maps

package
v0.0.0-...-95891f2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 46 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package maps provides the interactive maps addon for campaigns. This file embeds the plugin's SQL migrations and scripts so they are available in the compiled binary regardless of the runtime working directory.

map_widget_type.go registers "map" with the widget-binding framework: a widget_bindings row (widget_type="map") takes precedence over the legacy entity.map_id column, while an unbound entity still resolves via entity.map_id (the block closure's fallback).

marker_icons.go is Chronicle's canonical map-marker icon vocabulary.

Chronicle is authoritative for the marker icon set: a marker stores its icon as the canonical Font Awesome class string (e.g. "fa-castle"), and that same ID travels over the Foundry sync wire. The Foundry module keeps a translation table mapping each canonical ID to its own render mechanism, so the SAME ID means the SAME concept on both sides.

This file is the single source of truth: the editor's icon picker renders from it, and GET /campaigns/:id/maps/marker-icons exposes it so the Foundry module can align its translation table against a concrete contract.

Package maps provides interactive map support for campaigns. Campaigns can have multiple maps (world, region, city, dungeon). Each map has a background image and positioned pin markers that optionally link to entities.

Index

Constants

View Source
const (
	PinStyleDrop    = "drop"
	PinStyleSeal    = "seal"
	PinStyleFlag    = "flag"
	PinStyleDot     = "dot"
	PinStyleShield  = "shield"
	PinStyleTack    = "tack"
	PinStyleDiamond = "diamond"
	PinStylePlaque  = "plaque"

	PinSizeSmall  = "s"
	PinSizeMedium = "m"
	PinSizeLarge  = "l"

	PinLabelsAlways = "always"
	PinLabelsHover  = "hover"
	PinLabelsNever  = "never"

	GridNone   = "none"
	GridSquare = "square"
	GridHex    = "hex"

	OpenWhole = "whole"
	OpenLast  = "last"
	OpenSpot  = "spot"

	// DrawWhoOwners limits drawing to campaign owners; DrawWhoScribes (the
	// default, and the behaviour before this setting existed) also lets
	// scribes draw.
	DrawWhoOwners  = "owners"
	DrawWhoScribes = "scribes"

	// The hex layer's terrain art, shown to everyone who sees the map.
	// Detailed is the default and is not stored.
	HexArtRealistic = "real"
	HexArtDetailed  = "detailed"
	HexArtSimple    = "simple"
)

Allowed values for the enum-like settings. Kept as small sets so a stored value the renderer does not know can never exist.

View Source
const (
	// DrawingTypeArrow is a line from points[0] (tail) to points[1] (tip); the
	// viewer sizes the head from stroke_width.
	DrawingTypeArrow = "arrow"
	// DrawingTypeHighlight is a wide freehand stroke drawn translucent and
	// multiplied over the map; fill_alpha is its opacity.
	DrawingTypeHighlight = "highlight"
	// DrawingTypeStep is a numbered disc at points[0]; text_content holds the
	// number as decimal digits, stroke_color its fill.
	DrawingTypeStep = "step"
	// DrawingTypeCallout is a speech bubble whose tail points at points[0];
	// text_content is its text.
	DrawingTypeCallout = "callout"
)

The four annotation drawings. They share every rule of an ordinary drawing (visibility, layers, who may draw or delete, shadow and fog hiding, sync) and add their own shape and content limits below, checked on every write so a partial update cannot leave one the viewer cannot draw.

View Source
const (
	// DrawingTypeRoom is a walled space, drawn solid.
	DrawingTypeRoom = "room"
	// DrawingTypeArea is a zone with no walls, drawn dashed and tinted.
	DrawingTypeArea = "area"
	// DrawingTypeWater is a lake, river or sea, drawn tinted.
	DrawingTypeWater = "water"
	// DrawingTypeWall is a thick bar: a wall, fence or bridge.
	DrawingTypeWall = "wall"
	// DrawingTypeDanger is a hazard zone, tinted red. Only the map sketch
	// creates it; the Shapes palette keeps its signed four.
	DrawingTypeDanger = "danger"
)

The diagram boxes. Together with arrow (a line with a head) and callout (a speech bubble) they are the vocabulary of the Shapes tool, and of the AI map sketch that creates the same records. A box is two opposite corners in map percent, stored top-left first; text_content is its optional name (a wall has none). What a kind looks like is the viewer's decision, so it follows the light and dark themes: stroke_color and fill_color are accepted and checked like every annotation's but do not recolour these kinds.

View Source
const (
	// MaxDrawingTextRunes bounds the text of a label or speech bubble. The
	// column is TEXT, so without a bound one drawing could carry 64 KB that
	// every viewer downloads.
	MaxDrawingTextRunes = 500
	// MaxStepNumber caps a numbered step; three digits still fit the disc.
	MaxStepNumber = 999
)
View Source
const (
	TerrainPlains   = "plains"
	TerrainForest   = "forest"
	TerrainHills    = "hills"
	TerrainMountain = "mountain"
	TerrainWater    = "water"
	TerrainSwamp    = "swamp"
	TerrainDesert   = "desert"
	TerrainSnow     = "snow"
	TerrainTown     = "town"
	TerrainRoad     = "road"
	TerrainJungle   = "jungle"
	TerrainFarmland = "farmland"
	TerrainScrub    = "scrub"
	TerrainBadlands = "badlands"
	TerrainWaste    = "waste"
	TerrainVolcanic = "volcanic"
	TerrainCoast    = "coast"
	TerrainDeep     = "deep"
	TerrainIce      = "ice"
	TerrainCavern   = "cavern"
)

Terrain kinds a hex may carry. The set is an allowlist enforced here (the column is a plain VARCHAR) so a new kind is a code change, not a migration. It matches the viewer's palette; "road" is drawn as a line through its hexes rather than as a fill.

View Source
const (
	MaxHexBatch       = 500
	MaxHexNameRunes   = 120
	MaxHexNotesRunes  = 2000
	MaxHexCoord       = 399
	MaxHexCellsPerMap = 40000
)

Limits on what a hex may hold and what one request may change. The cell cap bounds a layer to roughly a 200 x 200 field so one map cannot grow without limit. MaxHexCoord is the highest valid column or row index, so a field is at most MaxHexCoord+1 (400) hexes along either axis; static/js/map_hexes.js clamps its field to the same MAX_HEX_AXIS so the client never offers a hex the server would refuse. A field of that size can hold more hexes than the cell cap, which only limits how many are painted.

View Source
const (
	DefaultMilesPerHex = 6
	DefaultMilesPerDay = 24
	MinTravelMiles     = 1
	MaxTravelMiles     = 1000
)

Travel figures for the trip planner. The columns are SMALLINT UNSIGNED; the ceiling keeps a typo from making every trip read as zero days, and the floor keeps the day maths from dividing by zero.

View Source
const (
	PartyWhoOwners  = "owners"
	PartyWhoScribes = "scribes"
)

Who may move the party, stored in display_settings hexes.party_who.

View Source
const (
	// MaxLinkTreeNodes caps how many maps one tree holds.
	MaxLinkTreeNodes = 300
	// MaxLinkTreeDepth caps how deep a branch goes.
	MaxLinkTreeDepth = 16
	// MaxTrailSteps caps how many maps a trail names before the current one.
	MaxTrailSteps = 16
)

Bounds on what one request may build. Links form a graph that can cycle (A opens B, B opens A); each map appears in the tree once, and these cap the work and the answer even on a campaign with very many links.

View Source
const (
	ShadowAlphaHint   = 0.5  // "A hint": something is there, hard to make out.
	ShadowAlphaHidden = 0.85 // "Almost nothing".
)

The two strengths a shadow can have, stored in the drawing's fill_alpha.

View Source
const DefaultFrame = "atlas"

DefaultFrame is what a campaign uses until its owner picks another.

View Source
const DefaultMarkerIcon = "fa-map-pin"

DefaultMarkerIcon is the fallback for a marker with no icon or an icon outside the canonical set (matches the renderers' "fa-map-pin" default).

View Source
const DrawingTypeImage = "image"

DrawingTypeImage marks a drawing that is a picture from the campaign's media placed on the map: two opposite corners, rotation, opacity in fill_alpha, and a media file plus crop that no other drawing type carries.

View Source
const DrawingTypeShadow = "shadow"

DrawingTypeShadow marks a drawing that players see as a drifting dark shadow instead of a shape. Pins and drawings lying under one are withheld from players on the server, so the shadow is a real secret, not a cover.

View Source
const HexMapWidth = 1000

HexMapWidth is the width, in map pixels, of a blank hex map made for AI Import. It matches the blank grid maps made there, so a grid size means the same number of pixels on both.

View Source
const HexPiecesPerTerrain = 12

HexPiecesPerTerrain is how many pieces (looks) the Realistic art offers for each terrain that has any; a hex's piece column picks one, and NULL ("Mix") lets the viewer pick a stable one from the hex's position. It must match the viewer's PIECES list in static/js/map_hex_art.js.

View Source
const MaxFogBatch = MaxHexBatch

MaxFogBatch caps how many hexes one reveal or hide request may name.

View Source
const MaxHexLineMask = 1<<6 - 1

MaxHexLineMask is the largest line value: six sides, one bit each.

View Source
const PluginSlug = "maps"

PluginSlug names this plugin in the registry and its static URL prefix.

View Source
const WhereItIsBlockType = "where_it_is"

WhereItIsBlockType is the entity page block's type key in saved layouts: an append-only namespace value, never rename.

View Source
const WidgetTypeMap = "map"

WidgetTypeMap is the persisted widget_type discriminator for maps — an append-only namespace value; never rename.

Variables

View Source
var FrameStyles = []FrameStyle{
	{"atlas", "Atlas", "A printed map plate: double rule, corner flourishes, grid letters and a title plate."},
	{"arcane", "Arcane", "A warded vellum: glowing runes in the margin that slowly breathe."},
	{"old", "Old", "A worn sea chart: stained parchment, a ragged edge and a wax seal."},
	{"modern", "Modern", "Clean and new: a plain rounded card, nothing in the way of the map."},
	{"futuristic", "Futuristic", "A tactical display: bracketed corners, scan lines and a live position readout."},
	{"gilded", "Gilded", "A gold picture frame for the map you want to show off."},
	{"blueprint", "Blueprint", "A draughtsman's sheet: blue paper, white rules, corner marks and a title block."},
	{"stone", "Stone", "A carved slab: speckled granite with a key pattern cut into the margin."},
	{"verdant", "Verdant", "A living border: a vine along the edges and ivy creeping in from the corners."},
	{"illuminated", "Illuminated", "A manuscript page: a red, blue and gold border and the map's first letter painted large."},
	{"corkboard", "Corkboard", "Pinned up for the investigation: a tack in each corner and the name typed on tape."},
	{"terminal", "Terminal", "An old monitor: rounded glass, amber scan lines and a status line."},
}

FrameStyles is the closed set of frames, in gallery order. Atlas is first because it is the default for every campaign that has not chosen.

View Source
var KindDefaults = []KindDisplay{
	{ID: "location", Label: "Places", Color: "#2563eb"},
	{ID: "danger", Label: "Danger", Color: "#dc2626"},
	{ID: "treasure", Label: "Treasure", Color: "#d97706"},
	{ID: "quest", Label: "Quests", Color: "#7c3aed"},
	{ID: "note", Label: "Notes", Color: "#0d9488"},
}

KindDefaults are the five pin kinds with their built-in labels and colours. The ids are the server's pin_category set (and the Foundry module's pin types), so this list is closed: a map can rename and recolour a kind but never add one.

View Source
var MeasureUnits = []string{"miles", "km", "feet", "leagues"}

The units a scale may be given in, and the bounds on it. The length cap is far beyond any world map in kilometres; it only keeps a typo from storing something absurd. The two ends must be apart, or every distance would be a division by zero.

View Source
var MigrationsFS embed.FS

MigrationsFS contains the embedded SQL migration files for the maps plugin.

View Source
var PinStyles = []PinStyle{
	{PinStyleDrop, "Drop"},
	{PinStyleSeal, "Seal"},
	{PinStyleFlag, "Flag"},
	{PinStyleDot, "Dot"},
	{PinStyleShield, "Shield"},
	{PinStyleTack, "Tack"},
	{PinStyleDiamond, "Diamond"},
	{PinStylePlaque, "Plaque"},
}

PinStyles is the closed set of pin shapes, in the order the Map settings sheet offers them. Drop is first because it is the default.

View Source
var StaticAssetsFS embed.FS

StaticAssetsFS holds the map scripts, served at /static/plugins/maps/. The widgets load on sight (ADR-063); the viewer fetches the rest on demand.

Functions

func AnchorHidesLayer

func AnchorHidesLayer(anchor *Drawing, role int) bool

AnchorHidesLayer reports whether the layer must be withheld from role because its picture is hidden from them. A hex field pinned to a DM-only picture would otherwise show players the outline, and any painted terrain, of something they are not meant to know exists.

func ClearForeignPictures

func ClearForeignPictures(ctx context.Context, store PictureRefStore, media MediaCampaignLookup) (int, error)

ClearForeignPictures clears every map background and token picture that names another campaign's media file. The write paths refuse such a file; this removes any stored before they did. Only a file that exists and belongs to a different campaign is cleared: a missing file shows nothing, and a file of no campaign is an avatar or backdrop, never campaign content. Idempotent, so it runs on every boot.

func CubeToOffset

func CubeToOffset(c Cube) (col, row int)

CubeToOffset converts cube coordinates back to offset (col, row).

func DrawingUnderShadow

func DrawingUnderShadow(areas []ShadowArea, d *Drawing) bool

DrawingUnderShadow: see MarkerUnderShadow.

func DrawingVisibleTo

func DrawingVisibleTo(d *Drawing, role int, userID string) bool

DrawingVisibleTo reports whether a viewer may read d by the rule ListDrawings applies in SQL: DM-equivalents see everything; anyone else never a dm_only drawing, nor one whose visibility_rules leave them out. Shadows are a separate check (IsDrawingShadowed).

func HexDistance

func HexDistance(a, b HexKey) int

HexDistance is the number of steps between two hexes.

func HexMapSize

func HexMapSize(cols, rows int) (width, height, gridSize int)

HexMapSize chooses the picture size and grid size of a blank map whose own hex field holds at least cols by rows hexes, with as little extra as the whole-number grid size allows.

The field's column count depends only on the grid size (the hex width is a fixed share of the map width), so the grid size is the largest one that still gives cols columns, and the height is then the shortest that gives rows rows. Both are read back through NewHexGeometry rather than re-derived, so the two cannot drift apart. The grid size stays within the range the map settings accept; when even the smallest cannot give cols columns (more than the viewer's limit) the smallest is used.

func IconColumns

func IconColumns() []database.IconColumn

IconColumns lists this plugin's stored icon columns and the default that replaces an unusable value, for the boot-time icon reconciler.

func IsValidFrame

func IsValidFrame(id string) bool

IsValidFrame reports whether id names one of the frames.

func IsValidHexArt

func IsValidHexArt(a string) bool

IsValidHexArt reports whether a is one of the terrain art styles.

func IsValidMarkerIcon

func IsValidMarkerIcon(id string) bool

IsValidMarkerIcon reports whether id is in the canonical vocabulary.

func IsValidMeasureUnit

func IsValidMeasureUnit(u string) bool

IsValidMeasureUnit reports whether u is one of the allowed units.

func IsValidPinStyle

func IsValidPinStyle(id string) bool

IsValidPinStyle reports whether id names one of the pin shapes.

func IsValidTerrain

func IsValidTerrain(t string) bool

IsValidTerrain reports whether t is one of the allowed terrain kinds.

func MarkerUnderShadow

func MarkerUnderShadow(areas []ShadowArea, mk *Marker) bool

MarkerUnderShadow and DrawingUnderShadow are the single-item forms of the rule for callers that gate one resource at a time (the event publisher and the by-id reads).

func MarkerVisibleTo

func MarkerVisibleTo(m *Marker, role int, userID string) bool

MarkerVisibleTo is DrawingVisibleTo for a marker: ListMarkers applies the same dm_only and visibility_rules predicate.

func NewMapWidgetType

func NewMapWidgetType(svc MapService) widgetbindings.WidgetType

NewMapWidgetType builds the map WidgetType for registration into the widget-binding registry at app startup.

func NormalizeMarkerIcon

func NormalizeMarkerIcon(id string) string

NormalizeMarkerIcon returns id when it's canonical, else DefaultMarkerIcon. Render-time safety net so an unknown/empty icon (e.g. from an out-of-date sync peer) degrades to the pin rather than a broken glyph.

func OnExploredFrontier

func OnExploredFrontier(explored func(HexKey) bool, k HexKey) bool

OnExploredFrontier reports whether k is explored or touches an explored hex: the only places a scribe may move the party. A scribe can then follow ground the party has already seen but cannot teleport it into the dark.

func ParseExpectedUpdatedAt

func ParseExpectedUpdatedAt(c *echo.Context) *time.Time

ParseExpectedUpdatedAt extracts the optional optimistic-concurrency token. Callers may send it via a JSON body field on DELETE requests (`{"expected_updated_at": "..."}`) or via the `expected_updated_at` query parameter — both are accepted because curl-style DELETE often avoids bodies. Invalid values fall through to nil (last-writer-wins) rather than 400 — the field is advisory.

func ParseTrailParam

func ParseTrailParam(raw string) []string

ParseTrailParam splits a ?from= value into ids. It bounds the input before splitting so an oversized query cannot cost more than a short one.

func PictureIsTurned

func PictureIsTurned(d *Drawing) bool

PictureIsTurned: see pictureIsTurned. The event publisher reads the map's frame only for these.

func PieceCount

func PieceCount(terrain string) int

PieceCount is how many pieces a terrain offers. A road is a line through its hexes and an unknown kind has no art, so neither has pieces.

func ReconcileOldRoadHexes

func ReconcileOldRoadHexes(ctx context.Context, store OldRoadStore) (maps int, hexes int, err error)

ReconcileOldRoadHexes turns every hex painted with the old road terrain into a land hex carrying a road line, one map per transaction, and returns how many maps and hexes it converted. It is idempotent because a converted map holds no road terrain any more, so a second run lists nothing and writes nothing. A failure on one map is logged and skipped so the rest still convert; the first such error is returned for the caller to log.

Which joins become exits is fixed by one rule: the kept lines have no loop of fewer than six hexes. Edges are taken from the lowest combined degree up (a spanning forest first, then any edge closing a loop of six or more), so at a bend whose end hexes also touch, the shortcut between them is considered last and the middle hex stays on the road rather than becoming a stub.

func RegisterDrawingRoutes

func RegisterDrawingRoutes(e *echo.Echo, dh *DrawingHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService, addonSvc addons.AddonService)

RegisterDrawingRoutes sets up API routes for drawings, tokens, layers, and fog. These are the real-time map collaboration endpoints used by both the Chronicle web UI and the Foundry VTT sync module.

func RegisterHexRoutes

func RegisterHexRoutes(e *echo.Echo, hh *HexHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService, addonSvc addons.AddonService)

RegisterHexRoutes sets up the hex layer's API. Painting is gated in HexService (owner or DM grant, or a scribe where the map's draw policy and fog allow), so the write route only requires membership: a DM-granted player is not a scribe by role and must still get through to the service.

func RegisterRoutes

func RegisterRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService, addonSvc addons.AddonService)

RegisterRoutes sets up all map-related routes. Map routes are scoped to a campaign and require membership. CRUD operations require Owner/Scribe role; viewing requires Player role.

func ShadowWithholdsImageOf

func ShadowWithholdsImageOf(areas []ShadowArea, d *Drawing, frame MapFrame) bool

ShadowWithholdsImageOf reports whether a shadow withholds the picture file of d, for the event publisher, whose payload carries the file id.

func TokenVisibleTo

func TokenVisibleTo(t *Token, role int) bool

TokenVisibleTo reports whether a viewer may read t by ListTokens' rule: a hidden token is for DM-equivalents only.

func UsableAnchor

func UsableAnchor(mapID string, d *Drawing) bool

UsableAnchor reports whether d can still carry a layer on mapID: it must exist, sit on this map and be a picture. The anchor column has no foreign key (so deleting a picture never cascades into painted terrain), which means a stale value is normal and is read as "the whole map", never as an error.

Types

type BindingCleaner

type BindingCleaner interface {
	OnInstanceDeleted(ctx context.Context, campaignID, widgetType, instanceID string) (int, error)
}

BindingCleaner sweeps a deleted instance's widget bindings. Implemented by widgetbindings.Service; injected via SetBindingCleaner. Optional — nil means "no binding framework wired" (Resolve's render-time guard skips and deletes orphaned bindings).

type CreateDrawingInput

type CreateDrawingInput struct {
	MapID       string
	LayerID     *string
	DrawingType string
	Points      json.RawMessage
	StrokeColor string
	StrokeWidth float64
	FillColor   *string
	FillAlpha   float64
	TextContent *string
	FontSize    *int
	Rotation    float64
	Visibility  string
	CreatedBy   string
	FoundryID   *string
	// ImageID, Crop and SortOrder are for "image" drawings only; any other
	// type that carries them is refused.
	ImageID   *string
	Crop      json.RawMessage
	SortOrder int
	// CallerRole is the caller's campaign role (permissions.Role*), used for
	// the map's "who can draw" gate. Not a data field; 0 is refused.
	CallerRole int
	// CallerIsDM is true for an owner or co-DM. Only they may create a shadow;
	// it is not a data field.
	CallerIsDM bool
	// Imported marks a drawing restored from a campaign export: a label's
	// text is cleaned to the current bounds instead of refused. Not a data
	// field.
	Imported bool
}

CreateDrawingInput is the validated input for creating a drawing.

type CreateFogInput

type CreateFogInput struct {
	MapID      string
	Points     json.RawMessage
	IsExplored bool
}

CreateFogInput is the validated input for creating a fog region.

type CreateLayerInput

type CreateLayerInput struct {
	MapID     string
	Name      string
	LayerType string
	SortOrder int
	IsVisible bool
	Opacity   float64
	IsLocked  bool
}

CreateLayerInput is the validated input for creating a layer.

type CreateMapInput

type CreateMapInput struct {
	CampaignID  string
	Name        string
	Description *string
	ImageID     *string
	ImageWidth  int
	ImageHeight int
}

CreateMapInput is the validated input for creating a map.

type CreateMarkerInput

type CreateMarkerInput struct {
	MapID       string
	Name        string
	Description *string
	X           float64
	Y           float64
	Icon        string
	Color       string
	PinCategory *string
	EntityID    *string
	// LinkedMapID is the map the new pin opens; nil or "" makes a plain pin.
	LinkedMapID     *string
	Visibility      string
	VisibilityRules *string
	CreatedBy       string
	FoundryID       *string
}

CreateMarkerInput is the validated input for placing a marker on a map.

type CreateTokenInput

type CreateTokenInput struct {
	MapID          string
	LayerID        *string
	EntityID       *string
	Name           string
	ImagePath      *string
	X              float64
	Y              float64
	Width          float64
	Height         float64
	Rotation       float64
	Scale          float64
	IsHidden       bool
	IsLocked       bool
	Bar1Value      *int
	Bar1Max        *int
	Bar2Value      *int
	Bar2Max        *int
	AuraRadius     *float64
	AuraColor      *string
	LightRadius    *float64
	LightDimRadius *float64
	LightColor     *string
	VisionEnabled  bool
	VisionRange    *float64
	Elevation      int
	StatusEffects  json.RawMessage
	Flags          json.RawMessage
	CreatedBy      string
	FoundryID      *string
}

CreateTokenInput is the validated input for placing a token on a map.

type Cube

type Cube struct{ X, Y, Z int }

Cube is a hex in cube coordinates.

func OffsetToCube

func OffsetToCube(col, row int) Cube

OffsetToCube converts offset (col, row) to cube coordinates.

type DisplaySettings

type DisplaySettings struct {
	Frame *FrameDisplay          `json:"frame,omitempty"`
	Pins  *PinDisplay            `json:"pins,omitempty"`
	Kinds map[string]KindDisplay `json:"kinds,omitempty"`
	Grid  *GridDisplay           `json:"grid,omitempty"`
	Open  *OpenDisplay           `json:"open,omitempty"`
	Draw  *DrawDisplay           `json:"draw,omitempty"`
	Hexes *HexesDisplay          `json:"hexes,omitempty"`
	// Measure is the map's scale for the Measure tool. Unlike the rest of the
	// document an owner or a member with DM access may write it
	// (MapService.SetMeasureScale), so it is its own group.
	Measure *MeasureDisplay `json:"measure,omitempty"`
	// Picture records the owner's answer to the empty map's "no picture yet"
	// prompt, so a map drawn from nothing stops asking on every device.
	Picture *PictureDisplay `json:"picture,omitempty"`
}

DisplaySettings is the stored per-map document. Every group is optional and every field within a group is optional: absent means "the default".

func MergeDisplaySettings

func MergeDisplaySettings(current *DisplaySettings, incoming json.RawMessage) (*DisplaySettings, error)

MergeDisplaySettings applies an incoming display_settings document to the stored one under the partial-update contract, at group granularity:

  • a group key that is absent keeps the stored group;
  • a group key that is an explicit null clears that group;
  • a group key with a value replaces that group, validated and normalised.

Groups, not individual fields, are the unit because the sheet edits a group at a time and sends only the groups the person touched; replacing a whole group is exact, while merging inside one would make "back to the default" impossible to say. The one exception is "hexes", which merges per field (absent keeps, null or the default clears, a value replaces): its two settings are written from different places by different people, so a save of one must never carry a stale copy of the other. Unknown top-level keys are dropped. The result is nil when nothing is left, so the column goes back to NULL.

func ParseDisplaySettings

func ParseDisplaySettings(raw *string) *DisplaySettings

ParseDisplaySettings reads the stored column. A document that fails to parse reads as "no settings" rather than failing the page: the column is written only through MergeDisplaySettings, so a bad value means hand-edited data and the map should still open on its defaults.

func (*DisplaySettings) IsEmpty

func (d *DisplaySettings) IsEmpty() bool

IsEmpty reports whether no group is set, i.e. the stored value should be NULL.

type DrawDisplay

type DrawDisplay struct {
	Who string `json:"who,omitempty"`
}

DrawDisplay is the draw gate. It is enforced on the server (see DrawingService), not only hidden in the UI.

type Drawing

type Drawing struct {
	ID          string          `json:"id"`
	MapID       string          `json:"map_id"`
	LayerID     *string         `json:"layer_id,omitempty"`
	DrawingType string          `json:"drawing_type"` // freehand, rectangle, ellipse, polygon, text, shadow (see shadow.go), image (drawing_image.go), arrow, highlight, step, callout (drawing_annotation.go)
	Points      json.RawMessage `json:"points"`       // Array of {x, y} coordinate pairs.
	StrokeColor string          `json:"stroke_color"`
	StrokeWidth float64         `json:"stroke_width"`
	FillColor   *string         `json:"fill_color,omitempty"`
	FillAlpha   float64         `json:"fill_alpha"`
	TextContent *string         `json:"text_content,omitempty"`
	FontSize    *int            `json:"font_size,omitempty"`
	Rotation    float64         `json:"rotation"`
	Visibility  string          `json:"visibility"` // everyone, dm_only
	// VisibilityRules mirrors Marker.VisibilityRules — per-player
	// allow/deny overrides. Must be selected and enforced by ListDrawings
	// (drawing_repository.go, matching ListMarkers) and by the WS publisher
	// (routes.go's mapEventPublisherAdapter), or a rule set on a drawing
	// silently does nothing.
	VisibilityRules *string `json:"visibility_rules,omitempty"`
	CreatedBy       *string `json:"created_by,omitempty"`
	FoundryID       *string `json:"foundry_id,omitempty"`
	// ImageID, Crop and SortOrder belong to "image" drawings (a picture placed
	// on the map): the campaign media file, the percentage trimmed from each
	// edge as {"t","r","b","l"}, and the stacking position among pictures.
	ImageID   *string         `json:"image_id,omitempty"`
	Crop      json.RawMessage `json:"crop,omitempty"`
	SortOrder int             `json:"sort_order"`
	CreatedAt time.Time       `json:"created_at"`
	UpdatedAt time.Time       `json:"updated_at"`
}

Drawing represents a freehand drawing, shape, or text annotation on a map. Coordinates use percentage-based positioning (0-100) for resolution independence. A "shadow" drawing is not a visible shape for players: it is an area whose contents the server withholds from them (see shadow.go).

type DrawingHandler

type DrawingHandler struct {
	// contains filtered or unexported fields
}

DrawingHandler processes HTTP requests for drawings, tokens, layers, and fog. All endpoints are scoped to a campaign and require the map to belong to that campaign.

func NewDrawingHandler

func NewDrawingHandler(mapSvc MapService, drawingSvc DrawingService) *DrawingHandler

NewDrawingHandler creates a new DrawingHandler.

func (*DrawingHandler) CreateDrawing

func (h *DrawingHandler) CreateDrawing(c *echo.Context) error

CreateDrawing creates a new drawing on a map. POST /api/v1/campaigns/:id/maps/:mid/drawings

func (*DrawingHandler) CreateFog

func (h *DrawingHandler) CreateFog(c *echo.Context) error

CreateFog creates a new fog region on a map. POST /api/v1/campaigns/:id/maps/:mid/fog

func (*DrawingHandler) CreateLayer

func (h *DrawingHandler) CreateLayer(c *echo.Context) error

CreateLayer creates a new layer on a map. POST /api/v1/campaigns/:id/maps/:mid/layers

func (*DrawingHandler) CreateToken

func (h *DrawingHandler) CreateToken(c *echo.Context) error

CreateToken places a new token on a map. POST /api/v1/campaigns/:id/maps/:mid/tokens

func (*DrawingHandler) DeleteDrawing

func (h *DrawingHandler) DeleteDrawing(c *echo.Context) error

DeleteDrawing removes a drawing. DELETE /api/v1/campaigns/:id/maps/:mid/drawings/:did

func (*DrawingHandler) DeleteFog

func (h *DrawingHandler) DeleteFog(c *echo.Context) error

DeleteFog removes a fog region. DELETE /api/v1/campaigns/:id/maps/:mid/fog/:fid

func (*DrawingHandler) DeleteLayer

func (h *DrawingHandler) DeleteLayer(c *echo.Context) error

DeleteLayer removes a layer. DELETE /api/v1/campaigns/:id/maps/:mid/layers/:lid

func (*DrawingHandler) DeleteToken

func (h *DrawingHandler) DeleteToken(c *echo.Context) error

DeleteToken removes a token. DELETE /api/v1/campaigns/:id/maps/:mid/tokens/:tid

func (*DrawingHandler) GetDrawing

func (h *DrawingHandler) GetDrawing(c *echo.Context) error

GetDrawing returns a single drawing by ID. GET /api/v1/campaigns/:id/maps/:mid/drawings/:did

func (*DrawingHandler) GetLayer

func (h *DrawingHandler) GetLayer(c *echo.Context) error

GetLayer returns a single layer by ID. GET /api/v1/campaigns/:id/maps/:mid/layers/:lid

func (*DrawingHandler) GetToken

func (h *DrawingHandler) GetToken(c *echo.Context) error

GetToken returns a single token by ID. GET /api/v1/campaigns/:id/maps/:mid/tokens/:tid

func (*DrawingHandler) ListDrawings

func (h *DrawingHandler) ListDrawings(c *echo.Context) error

ListDrawings returns all drawings for a map, filtered by the user's role. GET /api/v1/campaigns/:id/maps/:mid/drawings

func (*DrawingHandler) ListFog

func (h *DrawingHandler) ListFog(c *echo.Context) error

ListFog returns all fog regions for a map. GET /api/v1/campaigns/:id/maps/:mid/fog

func (*DrawingHandler) ListLayers

func (h *DrawingHandler) ListLayers(c *echo.Context) error

ListLayers returns all layers for a map. GET /api/v1/campaigns/:id/maps/:mid/layers

func (*DrawingHandler) ListTokens

func (h *DrawingHandler) ListTokens(c *echo.Context) error

ListTokens returns all tokens for a map, filtered by the user's role. GET /api/v1/campaigns/:id/maps/:mid/tokens

func (*DrawingHandler) ResetFog

func (h *DrawingHandler) ResetFog(c *echo.Context) error

ResetFog removes all fog regions for a map. POST /api/v1/campaigns/:id/maps/:mid/fog/reset

func (*DrawingHandler) UpdateDrawing

func (h *DrawingHandler) UpdateDrawing(c *echo.Context) error

UpdateDrawing updates an existing drawing. PUT /api/v1/campaigns/:id/maps/:mid/drawings/:did

func (*DrawingHandler) UpdateLayer

func (h *DrawingHandler) UpdateLayer(c *echo.Context) error

UpdateLayer updates a layer's properties. PUT /api/v1/campaigns/:id/maps/:mid/layers/:lid

func (*DrawingHandler) UpdateToken

func (h *DrawingHandler) UpdateToken(c *echo.Context) error

UpdateToken updates a token's properties. PUT /api/v1/campaigns/:id/maps/:mid/tokens/:tid

func (*DrawingHandler) UpdateTokenPosition

func (h *DrawingHandler) UpdateTokenPosition(c *echo.Context) error

UpdateTokenPosition updates only the position of a token (optimized for drag). PATCH /api/v1/campaigns/:id/maps/:mid/tokens/:tid/position

type DrawingRepository

type DrawingRepository interface {
	// Drawing CRUD.
	CreateDrawing(ctx context.Context, d *Drawing) error
	GetDrawing(ctx context.Context, id string) (*Drawing, error)
	UpdateDrawing(ctx context.Context, d *Drawing) error
	DeleteDrawing(ctx context.Context, id string) error
	// ListDrawings filters by role AND userID (S1): a non-owner only sees
	// drawings whose visibility_rules admit userID, matching ListMarkers'
	// signature and semantics exactly.
	ListDrawings(ctx context.Context, mapID string, role int, userID string) ([]Drawing, error)
	// ListShadows returns every shadow drawing on a map regardless of its own
	// visibility: a shadow hides what is under it from everyone who cannot see
	// the shadow's author's view, so the rule must not depend on whether this
	// particular viewer was allowed to receive the shadow itself.
	ListShadows(ctx context.Context, mapID string) ([]Drawing, error)

	// Token CRUD.
	CreateToken(ctx context.Context, t *Token) error
	GetToken(ctx context.Context, id string) (*Token, error)
	UpdateToken(ctx context.Context, t *Token, cols []TokenColumn) error
	UpdateTokenPosition(ctx context.Context, id string, x, y float64) error
	DeleteToken(ctx context.Context, id string) error
	ListTokens(ctx context.Context, mapID string, role int) ([]Token, error)

	// Layer CRUD.
	CreateLayer(ctx context.Context, l *Layer) error
	GetLayer(ctx context.Context, id string) (*Layer, error)
	UpdateLayer(ctx context.Context, l *Layer) error
	DeleteLayer(ctx context.Context, id string) error
	ListLayers(ctx context.Context, mapID string) ([]Layer, error)

	// Fog CRUD.
	CreateFog(ctx context.Context, f *FogRegion) error
	GetFog(ctx context.Context, id string) (*FogRegion, error)
	DeleteFog(ctx context.Context, id string) error
	ListFog(ctx context.Context, mapID string) ([]FogRegion, error)
	ResetFog(ctx context.Context, mapID string) error
}

DrawingRepository defines persistence for map drawings, tokens, layers, and fog.

func NewDrawingRepository

func NewDrawingRepository(db *sql.DB) DrawingRepository

NewDrawingRepository creates a new drawing repository.

type DrawingService

type DrawingService interface {
	// Drawing CRUD.
	//
	// CreateDrawing and UpdateDrawing enforce the map's "who can draw" setting
	// from the caller's campaign role (input.CallerRole / the role argument), so
	// the rule holds for the web UI, the sync API and imports alike. A role of 0
	// is refused: an unresolved caller never draws.
	CreateDrawing(ctx context.Context, input CreateDrawingInput) (*Drawing, error)
	GetDrawing(ctx context.Context, id string) (*Drawing, error)
	// mapID on the write methods is the authorization boundary from the URL
	// path: the object must belong to that map, mirroring the read-path guard
	// (audit-R2 Finding 2 — IDOR).
	//
	// isDM (owner or co-DM, CampaignContext.CanAuthorDmOnly) is separate from
	// role: only a DM may create, change or delete a shadow, while role keeps
	// driving the "who can draw" gate unchanged.
	//
	// UpdateDrawing follows DeleteDrawing's ownership rule: owners and DM
	// access change any drawing, a scribe only the ones actorID created.
	UpdateDrawing(ctx context.Context, id, mapID, actorID string, role int, isDM bool, input UpdateDrawingInput) error
	DeleteDrawing(ctx context.Context, id, mapID string, expectedUpdatedAt *time.Time, actorID string, role int, isDM bool) error
	// ListDrawings also withholds, from viewers subject to shadow hiding,
	// non-shadow drawings lying wholly under a shadow area.
	ListDrawings(ctx context.Context, mapID string, role int, userID string) ([]Drawing, error)
	// IsDrawingShadowed answers the same question for one drawing fetched by
	// id, so a by-id read cannot reveal what the list withholds.
	IsDrawingShadowed(ctx context.Context, d *Drawing, role int) (bool, error)
	// WithholdImages returns the drawings with the picture file removed, for a
	// viewer subject to fog or shadows, from the picture a fogged hex layer is
	// pinned to, from every picture reaching into unexplored hexes and from
	// every picture overlapping a shadow. Those files show land the viewer may
	// not see, so they never reach them; the drawing itself stays so the
	// viewer can still place the hexes by its box.
	WithholdImages(ctx context.Context, mapID string, role int, ds []Drawing) ([]Drawing, error)
	// WithholdsPictureFile reports whether mediaID is the file of a picture on
	// mapID that WithholdImages withholds, so the media server can refuse the
	// file itself to the same viewers (MapService.IsShadowedMapImage).
	WithholdsPictureFile(ctx context.Context, mapID, mediaID string) (bool, error)

	// Token CRUD. isDM on the writes is CampaignContext.CanAuthorDmOnly: anyone
	// else is answered NotFound for a token they may not see (hidden, or under
	// unexplored hexes), the same as for a token that does not exist.
	CreateToken(ctx context.Context, input CreateTokenInput) (*Token, error)
	GetToken(ctx context.Context, id string) (*Token, error)
	UpdateToken(ctx context.Context, id, mapID string, isDM bool, input UpdateTokenInput) error
	UpdateTokenPosition(ctx context.Context, id, mapID string, isDM bool, input UpdateTokenPositionInput) error
	DeleteToken(ctx context.Context, id, mapID string, expectedUpdatedAt *time.Time) error
	// ListTokens also withholds, from viewers subject to fog, tokens standing
	// in unexplored hexes.
	ListTokens(ctx context.Context, mapID string, role int) ([]Token, error)
	// IsTokenHidden answers, for one token fetched by id, whether role may not
	// see it, so a by-id read cannot reveal what the list withholds.
	IsTokenHidden(ctx context.Context, t *Token, role int) (bool, error)

	// Layer CRUD.
	CreateLayer(ctx context.Context, input CreateLayerInput) (*Layer, error)
	GetLayer(ctx context.Context, id string) (*Layer, error)
	UpdateLayer(ctx context.Context, id, mapID string, input UpdateLayerInput) error
	DeleteLayer(ctx context.Context, id, mapID string, expectedUpdatedAt *time.Time) error
	ListLayers(ctx context.Context, mapID string) ([]Layer, error)

	// Fog CRUD.
	CreateFog(ctx context.Context, input CreateFogInput) (*FogRegion, error)
	// mapID is the authorization boundary from the URL path: the fog region
	// must belong to that map (SEC-IDOR-4), mirroring DeleteDrawing/Token/Layer.
	DeleteFog(ctx context.Context, id, mapID string) error
	ListFog(ctx context.Context, mapID string) ([]FogRegion, error)
	ResetFog(ctx context.Context, mapID string) error

	// ShadowAreas makes every DrawingService a ShadowLookup, checked at compile
	// time where it is wired.
	ShadowAreas(ctx context.Context, mapID string) ([]ShadowArea, error)

	// Wiring.
	SetEventPublisher(pub MapEventPublisher)
	SetMapLookup(fn func(ctx context.Context, mapID string) (string, error))
	// SetDrawPolicyLookup wires the per-map "who can draw" value (DrawWhoOwners
	// or DrawWhoScribes). Unwired, every map uses the default (scribes).
	SetDrawPolicyLookup(fn func(ctx context.Context, mapID string) (string, error))
	// SetMediaVerifier wires the check that a picture's media file belongs to
	// the map's campaign. Unwired, picture writes are refused.
	SetMediaVerifier(v MediaVerifier)
	// SetHexFogLookup wires the hex fog, so drawings under unexplored hexes are
	// withheld like those under a shadow. Unwired, no fog is known.
	SetHexFogLookup(l HexFogLookup)
	// SetMapFrameLookup wires a map's recorded image size, so a turned picture
	// is judged against shadows exactly. Unwired, every turned picture on a
	// map with a shadow is withheld.
	SetMapFrameLookup(fn func(ctx context.Context, mapID string) (w, h int, err error))
	// MapFrame returns the frame the viewer draws mapID in; zero when unknown.
	MapFrame(ctx context.Context, mapID string) MapFrame
}

DrawingService defines business logic for drawings, tokens, layers, and fog.

Mutation methods (Update*, Delete*) accept an optional optimistic- concurrency token. Layer and fog gain UpdatedAt on migration 006 so they participate in the same pattern as drawings/tokens. Fog mutations are short-lived and don't expose an Update path; only Delete carries the token in case a "delete this fog you saw at time T" call races a concurrent reset.

func NewDrawingService

func NewDrawingService(repo DrawingRepository) DrawingService

NewDrawingService creates a new drawing service.

type EntityVisibilityGate

type EntityVisibilityGate interface {
	FilterViewableEntityIDs(ctx context.Context, campaignID string, entityIDs []string, role int, userID string) (map[string]bool, error)
}

EntityVisibilityGate resolves which of a set of entity IDs a viewer (role + userID) may see, applying the entities plugin's own canonical visibility policy (default is_private, custom per-subject grants, tag grants). Wraps entities.EntityService.FilterViewableEntityIDs — the same seam armory, media, npcs, sessions and the relations widget use — so a marker naming a dm_only/private entity never leaks that entity's name/icon to a viewer who could not otherwise see it.

type FogMask

type FogMask struct {
	Version  uint64
	Geo      HexGeometry
	MapW     float64
	MapH     float64
	Explored map[HexKey]bool
	// AnchorID is the picture the layer is pinned to, or "" when it covers the
	// whole map. A pinned layer hides only land inside that picture.
	AnchorID string
}

FogMask is what hides unexplored land from a viewer below CanSeeDmOnly: the field's geometry and the explored set at one layer version. It is built only when fog is on and the grid is hexes, so a nil mask always means "nothing is fogged".

func (*FogMask) CoversMapPicture

func (f *FogMask) CoversMapPicture() bool

CoversMapPicture reports whether the map's own background picture is under the fog. A layer pinned to a picture drawing leaves the background alone: it is that drawing's file that is the secret.

func (*FogMask) HidesDrawing

func (f *FogMask) HidesDrawing(d *Drawing) bool

HidesDrawing reports whether a drawing lies wholly in unexplored hexes, the same rule shadows use: one that merely touches explored land stays, because hiding it would also hide the part players may see. An unparseable drawing is hidden, failing closed. Shadows pass (players need them to draw the smoke) and so does the picture the layer is pinned to: the client needs its box to place the hexes, and its file is withheld separately.

func (*FogMask) HidesMarker

func (f *FogMask) HidesMarker(mk *Marker) bool

HidesMarker reports whether a pin sits in an unexplored hex.

func (*FogMask) HidesPoint

func (f *FogMask) HidesPoint(xPct, yPct float64) bool

HidesPoint reports whether a point given in map percentages (0-100) lies in an unexplored hex.

func (*FogMask) HidesToken

func (f *FogMask) HidesToken(t *Token) bool

HidesToken reports whether a token sits in an unexplored hex, by the same point rule as a pin.

func (*FogMask) WithholdsImageOf

func (f *FogMask) WithholdsImageOf(d *Drawing) bool

WithholdsImageOf reports whether the picture file of drawing d must not be sent to a viewer: it is the picture a fogged layer is pinned to, or a picture whose box reaches into any unexplored hex. A picture shows land as pixels, so unlike a line it cannot "merely touch" the fog; the drawing itself still goes out (as a placeholder) wherever HidesDrawing lets it. A picture whose box cannot be read is withheld, failing closed.

type FogRegion

type FogRegion struct {
	ID         string          `json:"id"`
	MapID      string          `json:"map_id"`
	Points     json.RawMessage `json:"points"` // Polygon vertices.
	IsExplored bool            `json:"is_explored"`
	CreatedAt  time.Time       `json:"created_at"`
	UpdatedAt  time.Time       `json:"updated_at"`
}

FogRegion represents a revealed/hidden area of fog of war.

type FrameDisplay

type FrameDisplay struct {
	Style string `json:"style,omitempty"`
	Tint  *bool  `json:"tint,omitempty"`
}

FrameDisplay overrides the campaign frame for one map. An empty Style means "follow the campaign style"; Tint is a pointer so "unset" (on, the default) and an explicit off are distinguishable.

type FrameStyle

type FrameStyle struct {
	ID          string
	Label       string
	Description string
}

FrameStyle is one of the frames drawn around the map on the map page.

type GridDisplay

type GridDisplay struct {
	Type     string `json:"type,omitempty"`
	Size     int    `json:"size,omitempty"`
	Strength int    `json:"strength,omitempty"`
}

GridDisplay is the grid overlay, drawn in map coordinates so it scales with zoom. Size is measured as if the map were 1000 wide, so the same number looks the same on a 600px sketch and a 6000px poster.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler processes HTTP requests for the maps plugin.

func NewHandler

func NewHandler(svc MapService) *Handler

NewHandler creates a new maps Handler.

func (*Handler) CreateMapAPI

func (h *Handler) CreateMapAPI(c *echo.Context) error

CreateMapAPI creates a new map. POST /campaigns/:id/maps

func (*Handler) CreateMapForm

func (h *Handler) CreateMapForm(c *echo.Context) error

CreateMapForm handles map creation from a form POST. POST /campaigns/:id/maps/new

func (*Handler) CreateMarkerAPI

func (h *Handler) CreateMarkerAPI(c *echo.Context) error

CreateMarkerAPI places a new marker on a map. POST /campaigns/:id/maps/:mid/markers

func (*Handler) DeleteMapAPI

func (h *Handler) DeleteMapAPI(c *echo.Context) error

DeleteMapAPI moves a map, with its pins, to the campaign Trash. DELETE /campaigns/:id/maps/:mid

func (*Handler) DeleteMarkerAPI

func (h *Handler) DeleteMarkerAPI(c *echo.Context) error

DeleteMarkerAPI deletes a marker. DELETE /campaigns/:id/maps/:mid/markers/:mkid

func (*Handler) GetMapMetaAPI

func (h *Handler) GetMapMetaAPI(c *echo.Context) error

GetMapMetaAPI returns the public-capable JSON the embeddable map widget needs (image id + dimensions + visibility-filtered markers) so map-widget / entity-map blocks render on public campaigns without the /api/v1 (Foundry / API-key) path. Role/visibility filtering matches ListMarkersAPI and is empty-userID safe (anonymous public visitors). GET /campaigns/:id/maps/:mid/meta

func (*Handler) Index

func (h *Handler) Index(c *echo.Context) error

Index lists all maps for a campaign, or redirects to the first map. GET /campaigns/:id/maps

func (*Handler) LinkTreeAPI

func (h *Handler) LinkTreeAPI(c *echo.Context) error

LinkTreeAPI returns the campaign's linked maps as this viewer can follow them. The service builds it from the viewer's own marker lists, so a link on a pin hidden from them is never in it. GET /campaigns/:id/maps/link-tree

func (*Handler) ListMarkersAPI

func (h *Handler) ListMarkersAPI(c *echo.Context) error

ListMarkersAPI returns all markers for a map as JSON. GET /campaigns/:id/maps/:mid/markers

func (*Handler) MarkerIconsAPI

func (h *Handler) MarkerIconsAPI(c *echo.Context) error

MarkerIconsAPI returns Chronicle's canonical map-marker icon vocabulary. Chronicle is authoritative for the icon set; this endpoint is the contract the Foundry sync module reads to align its translation table, so the same icon ID renders the same concept on both sides. Static catalog (no per-campaign state) but campaign-scoped + Player-gated to match the rest of the maps API surface.

func (*Handler) PlayerImage

func (h *Handler) PlayerImage(c *echo.Context) error

PlayerImage serves the map's picture with its shadowed areas smudged into the pixels, for viewers who must not receive the original. It is registered beside the map page with the same access check, and any failure to produce the copy is an error, never the original. GET /campaigns/:id/maps/:mid/player-image

func (*Handler) PutMeasureScaleAPI

func (h *Handler) PutMeasureScaleAPI(c *echo.Context) error

PutMeasureScaleAPI sets or removes the map's scale for the Measure tool. The body is {"scale": {a, b, length, unit}} to set it or {"scale": null} to remove it; a body without "scale" changes nothing and is refused, so a stray request can never clear a scale. Who may write is decided in the service (owner or DM grant). PUT /campaigns/:id/maps/:mid/measure

func (*Handler) SetCampaignFrameAPI

func (h *Handler) SetCampaignFrameAPI(c *echo.Context) error

SetCampaignFrameAPI stores the campaign-wide map frame, chosen on the Customize page's Maps tab (Owner only, enforced by the route). It answers an HTMX request with the refreshed section so "Saved" shows in place, and a plain request with 204 so the endpoint is also usable without the page. PUT /campaigns/:id/maps/frame-style

func (*Handler) SetMemberLister

func (h *Handler) SetMemberLister(ml campaigns.MemberLister)

SetMemberLister wires the campaign member list (post-construction, as the other plugins that show member names do).

func (*Handler) Show

func (h *Handler) Show(c *echo.Context) error

Show renders a single map with its markers in a Leaflet.js viewer. GET /campaigns/:id/maps/:mid

func (*Handler) UpdateMapAPI

func (h *Handler) UpdateMapAPI(c *echo.Context) error

UpdateMapAPI updates a map's metadata. PUT /campaigns/:id/maps/:mid

func (*Handler) UpdateMarkerAPI

func (h *Handler) UpdateMarkerAPI(c *echo.Context) error

UpdateMarkerAPI updates an existing marker. PUT /campaigns/:id/maps/:mid/markers/:mkid

func (*Handler) Viewer

func (h *Handler) Viewer(c *echo.Context) error

Viewer renders the bare framed viewer (no page chrome) that the focus view fetches when a map preview on another page is opened. GET /campaigns/:id/maps/:mid/viewer

It is registered in the same group, with the same access check, as Show and builds its data through the same mapViewData, so what a viewer receives here (role-filtered markers, tool gates, resolved frame) is by construction what the map page gives them; there is no second copy of the rules to drift.

type HexActor

type HexActor struct {
	UserID string
	Role   int
	IsDM   bool
}

HexActor is who is writing, as the handler resolved it. IsDM is the owner-or-DM-grant capability (CanAuthorDmOnly); Role is the member's actual role, which is what the "who can draw" gate compares, so a DM grant does not have to be a scribe to paint.

type HexCell

type HexCell struct {
	Col     int     `json:"col"`
	Row     int     `json:"row"`
	Terrain *string `json:"terrain"`
	Piece   *int    `json:"piece"`
	// Road, River and Trail are the sides each line leaves the hex through,
	// one bit per neighbour in Neighbors() order. nil is no such line; 0 is the
	// line on the hex with no exits. They lie on top of the terrain.
	Road      *int      `json:"road,omitempty"`
	River     *int      `json:"river,omitempty"`
	Trail     *int      `json:"trail,omitempty"`
	Name      string    `json:"name"`
	Notes     *string   `json:"notes"`
	Explored  bool      `json:"explored"`
	UpdatedBy *string   `json:"-"`
	UpdatedAt time.Time `json:"-"`
}

HexCell is one painted or annotated hex. Only hexes someone has touched have a row. Name and Notes are plain text: they are stored as typed and escaped by whatever renders them.

func VisibleCells

func VisibleCells(layer HexLayer, cells []HexCell, role int) []HexCell

VisibleCells returns the cells role may receive. role is the viewer's VisibilityRole, so a co-DM grant already arrives promoted to owner.

With fog off everyone sees everything. With fog on, only whoever passes CanSeeDmOnly sees every row; everyone else, scribes included, gets explored rows only and nothing that hints at the rest. Scribes are filtered on purpose: an unexplored hex is a secret from the whole table, and a scribe can write on the map without being the DM.

Lines ride on their hex's row, so a hidden row hides its lines. A filtered viewer's line exits are also clipped to the rows they are sent: an exit toward an unexplored or absent hex would reveal that the line continues into the fog. Every read of cells for a client goes through here so none can skip the clipping.

type HexCellWrite

type HexCellWrite struct {
	Col, Row   int
	TerrainSet bool
	Terrain    *string // nil with TerrainSet clears
	NameSet    bool
	Name       string // "" with NameSet clears
	NotesSet   bool
	Notes      *string // nil with NotesSet clears
	PieceSet   bool
	Piece      *int // nil with PieceSet means "Mix"
	// Each line is a six-bit side mask; nil with its Set flag removes the line.
	RoadSet  bool
	Road     *int
	RiverSet bool
	River    *int
	TrailSet bool
	Trail    *int
}

HexCellWrite is one cell change as the repository applies it. Each Set flag says whether the caller named that field: only named fields are written, so a write that mentions one field cannot disturb another, and the merge happens in a single statement instead of a read followed by a write that a second painter could slip between.

type HexEventPublisher

type HexEventPublisher interface {
	PublishHexChanged(campaignID, mapID string, version uint64, partyPath []HexKey)
}

HexEventPublisher announces that a map's hexes changed. It carries a version and, when it is safe, the party's path, never any cell contents: clients refetch the filtered read, so the audience rules live in one place.

type HexFogCell

type HexFogCell struct {
	Col int
	Row int
}

HexFogCell names one hex in a reveal or hide request.

type HexFogLookup

type HexFogLookup interface {
	FogMask(ctx context.Context, mapID string) (*FogMask, error)
}

HexFogLookup returns the fog mask of a map, or nil when nothing is fogged. Implemented by the hex service, which owns the layer; pins, drawings, the event publisher and the picture renderer only apply the mask.

type HexGeometry

type HexGeometry struct {
	R, Ox, Oy  float64
	Cols, Rows int
}

HexGeometry places the hex field on the map in map pixels. R is the corner radius; hex width is sqrt(3)*R and rows are 1.5*R apart. (Ox, Oy) is the centre of hex (0, 0). Cols and Rows bound the field.

func NewAnchoredHexGeometry

func NewAnchoredHexGeometry(gridSize, boxX, boxY, boxW, boxH float64) HexGeometry

NewAnchoredHexGeometry lays the field inside a picture's box (boxX, boxY, boxW, boxH in map pixels) instead of over the whole map. gridSize is measured as if the picture were 1000 wide, so every length scales with the box: resize the picture and the hexes grow with it, with the same columns, rows and keys. Hex (0, 0) is the first hex that fits whole at the box's top-left, and the field stops before a hex would cross the right or bottom edge, so nothing spills off the picture. static/js/map_hexes.js builds the same field (anchoredGeometry) in a box 1000 wide and scales it.

func NewHexGeometry

func NewHexGeometry(gridSize float64, mapW, mapH float64) HexGeometry

NewHexGeometry lays the field over the whole map picture. gridSize is the stored grid.size, measured as if the map were 1000 wide, so the same number looks the same on any picture; the field starts with hex (0, 0) centred on the map's top-left corner and covers the same range the plain hex grid draws.

func (HexGeometry) Center

func (g HexGeometry) Center(col, row int) (x, y float64)

Center is the centre of hex (col, row) in map pixels.

func (HexGeometry) HexAtPoint

func (g HexGeometry) HexAtPoint(x, y float64) (col, row int, ok bool)

HexAtPoint returns the hex under a map point, or ok=false when the point falls outside the field. It rounds in cube space so the result is exact on hex borders rather than approximated with rectangles.

func (HexGeometry) PointInUnexplored

func (g HexGeometry) PointInUnexplored(explored map[HexKey]bool, x, y float64) bool

PointInUnexplored reports whether a map point (pixels) lies inside a hex of the field that is not explored. A point outside the field is not hidden: the layer says nothing about land it does not cover.

func (HexGeometry) Width

func (g HexGeometry) Width() float64

Width is a hex's width.

type HexHandler

type HexHandler struct {
	// contains filtered or unexported fields
}

HexHandler serves the hex layer's JSON API. It binds, calls the service and renders; who may see or write what is decided in HexService.

func NewHexHandler

func NewHexHandler(svc HexService) *HexHandler

NewHexHandler creates a new HexHandler.

func (*HexHandler) GetHexes

func (h *HexHandler) GetHexes(c *echo.Context) error

GetHexes returns the map's hex layer with the cells the viewer may receive. GET /campaigns/:id/maps/:mid/hexes

func (*HexHandler) PatchHexCells

func (h *HexHandler) PatchHexCells(c *echo.Context) error

PatchHexCells changes a batch of hexes. Absent keys keep, null clears. PATCH /campaigns/:id/maps/:mid/hexes/cells

func (*HexHandler) PostHexFog

func (h *HexHandler) PostHexFog(c *echo.Context) error

PostHexFog reveals or hides hexes, or hides them all. A body of {"reset": true} hides every hex; otherwise {cells, explored} names them. POST /campaigns/:id/maps/:mid/hexes/fog

func (*HexHandler) PutHexLayer

func (h *HexHandler) PutHexLayer(c *echo.Context) error

PutHexLayer changes the layer row. The body is partial: an absent anchor_drawing_id keeps, null means the whole map, an id pins the hexes to that picture; an absent fog_enabled keeps, null or false turns fog off; an absent miles_per_hex or miles_per_day keeps, null restores the default; an absent art keeps, null restores Detailed. PUT /campaigns/:id/maps/:mid/hexes/layer

func (*HexHandler) PutHexParty

func (h *HexHandler) PutHexParty(c *echo.Context) error

PutHexParty moves the party to a hex and returns the path it walked. PUT /campaigns/:id/maps/:mid/hexes/party

type HexKey

type HexKey struct {
	Col int `json:"col"`
	Row int `json:"row"`
}

HexKey identifies a hex by its offset coordinates.

func HexLine

func HexLine(a, b HexKey) []HexKey

HexLine lists the hexes from a to b inclusive, interpolating in cube space and rounding like JavaScript's Math.round so the server's path is the same line the viewer draws for its walking animation (hexLine in map_hexes.js).

func Neighbors

func Neighbors(col, row int) [6]HexKey

Neighbors returns the six hexes around (col, row), east first and turning clockwise. Results may have negative coordinates at the field's edge; the caller decides whether those exist.

func RevealZone

func RevealZone(path []HexKey, cols, rows int) []HexKey

RevealZone returns every hex within one step of any hex on path, each once, in first-seen order. The server derives it from the path it computed itself, so a client can never name which hexes a move reveals. cols and rows clip the result to the field so a move at the edge never stores a hex that cannot exist.

type HexLayer

type HexLayer struct {
	MapID           string    `json:"map_id"`
	AnchorDrawingID *string   `json:"anchor_drawing_id"`
	FogEnabled      bool      `json:"fog_enabled"`
	PartyCol        *int      `json:"party_col"`
	PartyRow        *int      `json:"party_row"`
	MilesPerHex     int       `json:"miles_per_hex"`
	MilesPerDay     int       `json:"miles_per_day"`
	Version         uint64    `json:"version"`
	UpdatedAt       time.Time `json:"updated_at"`
}

HexLayer is the per-map hex settings row. A map without a row has an implicit layer at version 0 (see DefaultHexLayer); the row appears on the first write. Fields past the cells are carried now so later slices (fog, party, travel, pinning to a picture) need no schema change.

func DefaultHexLayer

func DefaultHexLayer(mapID string) HexLayer

DefaultHexLayer is the layer of a map nobody has painted yet.

func VisiblePartyLayer

func VisiblePartyLayer(layer HexLayer, cells []HexCell, role int) HexLayer

VisiblePartyLayer returns the layer as role may receive it. With fog on, a viewer below CanSeeDmOnly gets no party position while the party stands on an unexplored hex. A move always reveals the hexes it ends on, so this should never trigger; it fails closed for a reset, a hand-edited row or a race, so the party token can never point at land the viewer has not been shown.

type HexLayerView

type HexLayerView struct {
	Layer   HexLayer  `json:"layer"`
	Cells   []HexCell `json:"cells"`
	Version uint64    `json:"version"`
	Hidden  bool      `json:"hidden"`
	Art     string    `json:"art,omitempty"`
}

HexLayerView is what a viewer receives: the layer and only the cells their role may see. Hidden is true when the layer's picture is hidden from this viewer; the layer then carries no anchor and no cells, and the client draws no hexes at all rather than falling back to the whole map.

Art is the map's terrain style, sent here as well as with the page so a change reaches every open viewer with the next read. It is empty for a hidden layer.

type HexLayerWriteResult

type HexLayerWriteResult struct {
	Version         uint64  `json:"version"`
	AnchorDrawingID *string `json:"anchor_drawing_id"`
	FogEnabled      bool    `json:"fog_enabled"`
	MilesPerHex     int     `json:"miles_per_hex"`
	MilesPerDay     int     `json:"miles_per_day"`
	Art             string  `json:"art,omitempty"`
}

HexLayerWriteResult is the outcome of a layer change.

type HexPictures

type HexPictures interface {
	// GetPicture returns a drawing by id, or nil when it does not exist.
	GetPicture(ctx context.Context, id string) (*Drawing, error)
	// IsShadowed reports whether a shadow wholly covers the picture for a
	// viewer of this role, using the same rule that withholds drawings.
	IsShadowed(ctx context.Context, d *Drawing, role int) (bool, error)
	// ClearRotation turns a picture upright. Hexes do not turn, so a picture
	// carrying them must not either. expected is the picture's UpdatedAt as the
	// caller read it, so a concurrent edit to the picture is a conflict.
	ClearRotation(ctx context.Context, mapID, id string, actor HexActor, expected time.Time) error
}

HexPictures is the hex layer's view of the map's pictures. It is narrow on purpose: the layer may read one picture and straighten it, nothing else.

func NewHexPictures

func NewHexPictures(svc DrawingService) HexPictures

NewHexPictures adapts the drawing service, so a rotation reset goes through the same write path (and the same live update to other viewers) as an edit from the picture bar.

type HexRepository

type HexRepository interface {
	// GetLayer returns the map's layer row, or nil with no error when nothing
	// has been written yet.
	GetLayer(ctx context.Context, mapID string) (*HexLayer, error)
	// ListCells returns every stored cell of a map, unfiltered. Role filtering
	// is the service's job (VisibleCells), never the query's.
	ListCells(ctx context.Context, mapID string) ([]HexCell, error)
	// GetCells returns the stored cells among keys, indexed by position.
	GetCells(ctx context.Context, mapID string, keys []HexKey) (map[HexKey]HexCell, error)
	// CountCells returns how many cells a map stores.
	CountCells(ctx context.Context, mapID string) (int, error)
	// SetAnchor points the layer at a picture (nil: the whole map), creating the
	// layer row on first use, bumps the version and returns it. Only the anchor
	// column is touched, so it cannot disturb fog, the party or the miles.
	SetAnchor(ctx context.Context, mapID string, anchor *string) (uint64, error)
	// ApplyCells writes the changes and bumps the layer's version in one
	// transaction, creating the layer row on first use, deleting any touched cell
	// that ends up empty, and returns the new
	// version. The layer row is touched first so concurrent writers to one map
	// queue behind it and every version is unique.
	ApplyCells(ctx context.Context, mapID, userID string, writes []HexCellWrite) (uint64, error)
	// ListExplored returns the position of every explored hex, which is all the
	// fog filters need; it never reads names or notes.
	ListExplored(ctx context.Context, mapID string) ([]HexKey, error)
	// SetFog turns fog of war on or off, creating the layer row on first use,
	// bumps the version and returns it. Only the fog column is touched.
	SetFog(ctx context.Context, mapID string, enabled bool) (uint64, error)
	// SetTravel changes the miles per hex and per day, creating the layer row
	// on first use, bumps the version and returns it. A nil figure keeps its
	// column, so changing one never writes the other.
	SetTravel(ctx context.Context, mapID string, perHex, perDay *int) (uint64, error)
	// BumpVersion raises the layer's version (creating the row on first use)
	// and returns it, for a change stored elsewhere that viewers must hear
	// about, such as the map's terrain art.
	BumpVersion(ctx context.Context, mapID string) (uint64, error)
	// SetExplored marks hexes explored or unexplored and bumps the version, in
	// one transaction. Hiding a hex that carries nothing else removes its row so
	// it stops counting against the map's cell cap.
	SetExplored(ctx context.Context, mapID, userID string, keys []HexKey, explored bool) (uint64, error)
	// ResetExplored hides every hex of the map and bumps the version.
	ResetExplored(ctx context.Context, mapID, userID string) (uint64, error)
	// ApplyParty moves the party to `to` and marks reveal explored, in one
	// transaction, and returns the new version. expectedFrom is where the caller
	// computed its path from (nil: never placed); if the stored position differs
	// the move is a Conflict, so two movers cannot both reveal along stale paths.
	ApplyParty(ctx context.Context, mapID, userID string, expectedFrom *HexKey, to HexKey, reveal []HexKey) (uint64, error)
}

HexRepository defines persistence for hex layers and their cells.

func NewHexRepository

func NewHexRepository(db *sql.DB) HexRepository

NewHexRepository creates a new hex repository.

type HexService

type HexService interface {
	// GetLayer returns the layer with the cells the role may see. role is the
	// viewer's VisibilityRole.
	GetLayer(ctx context.Context, campaignID, mapID string, role int) (*HexLayerView, error)
	// PatchCells applies a batch of partial cell changes.
	PatchCells(ctx context.Context, campaignID, mapID string, actor HexActor, entries []UpdateHexCellInput) (*HexWriteResult, error)
	// UpdateLayer changes the layer row (today: which picture it covers) and
	// returns the new version. Owner or DM access only.
	UpdateLayer(ctx context.Context, campaignID, mapID string, actor HexActor, in UpdateHexLayerInput) (*HexLayerWriteResult, error)
	// RevealFog marks hexes explored or unexplored. Owner or DM access only.
	RevealFog(ctx context.Context, campaignID, mapID string, actor HexActor, cells []HexFogCell, explored bool) (*HexWriteResult, error)
	// ResetFog hides every hex again. Owner or DM access only.
	ResetFog(ctx context.Context, campaignID, mapID string, actor HexActor) (*HexWriteResult, error)
	// MoveParty moves the party, revealing radius 1 along the path the server
	// computes. Who may is the map's hexes.party_who setting.
	MoveParty(ctx context.Context, campaignID, mapID string, actor HexActor, to HexFogCell) (*PartyMoveResult, error)
	// FogMask makes the hex service a HexFogLookup for pins, drawings, events
	// and the map picture.
	FogMask(ctx context.Context, mapID string) (*FogMask, error)
	// SetPictures wires the lookup behind the anchor checks.
	SetPictures(p HexPictures)
	// SetEventPublisher wires the live-update publisher. Unwired, writes still
	// succeed and clients pick changes up on their next read.
	SetEventPublisher(pub HexEventPublisher)
	// SetMapLoader wires the lookup of a whole map, which the fog needs for the
	// picture's size, the grid size and the party rule. Unwired, the fog fails
	// closed and only owners and DMs may move the party.
	SetMapLoader(fn func(ctx context.Context, mapID string) (*Map, error))
	// SetPictureInvalidator wires the drop of cached map-picture answers, called
	// with the campaign id when fog changes who may fetch the original.
	SetPictureInvalidator(fn func(campaignID string))
	// SetMapLookup wires the map-to-campaign lookup behind the IDOR check.
	SetMapLookup(fn func(ctx context.Context, mapID string) (string, error))
	// SetDrawPolicyLookup wires the map's "who can draw" value.
	SetDrawPolicyLookup(fn func(ctx context.Context, mapID string) (string, error))
	// SetArtWriter wires the save of the map's terrain art into its display
	// settings. Unwired, a request to change the art fails.
	SetArtWriter(fn func(ctx context.Context, mapID, art string) error)
}

HexService is the hex layer's business logic.

func NewHexService

func NewHexService(repo HexRepository) HexService

NewHexService creates a new hex service.

type HexWriteResult

type HexWriteResult struct {
	Version uint64 `json:"version"`
	Updated int    `json:"updated"`
}

HexWriteResult is the outcome of a batch.

type HexesDisplay

type HexesDisplay struct {
	PartyWho string `json:"party_who,omitempty"`
	Art      string `json:"art,omitempty"`
}

HexesDisplay holds the hex layer's settings. PartyWho is enforced on the server (HexService.MoveParty), not only hidden in the UI. "Everyone" is not offered: letting a player move the party would let them uncover land. Art is the terrain style everyone sees; owners set it in Map settings and DM grants from the Paint mode, so this group merges per field (see MergeDisplaySettings): saving one never resets the other.

type KindDisplay

type KindDisplay struct {
	ID    string `json:"id,omitempty"`
	Label string `json:"label,omitempty"`
	Color string `json:"color,omitempty"`
}

KindDisplay renames and recolours one of the five pin kinds for this map. ID is set only on the resolved copy, never stored: the map key is the id.

type Layer

type Layer struct {
	ID        string    `json:"id"`
	MapID     string    `json:"map_id"`
	Name      string    `json:"name"`
	LayerType string    `json:"layer_type"` // background, drawing, token, gm, fog
	SortOrder int       `json:"sort_order"`
	IsVisible bool      `json:"is_visible"`
	Opacity   float64   `json:"opacity"`
	IsLocked  bool      `json:"is_locked"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Layer organizes map content into z-ordered groups (background, drawing, token, gm, fog).

func VisibleLayers

func VisibleLayers(layers []Layer, role int) []Layer

VisibleLayers is the layer list a viewer of that role may see: a "gm" layer is the Director's own.

type LinkMapOption

type LinkMapOption struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	ThumbURL string `json:"thumb_url,omitempty"`
}

LinkMapOption is a map the pin form's "Opens map" chooser offers.

type LinkNode

type LinkNode struct {
	ID       string     `json:"id"`
	Name     string     `json:"name"`
	ThumbURL string     `json:"thumb_url,omitempty"`
	Via      *LinkVia   `json:"via,omitempty"`
	Children []LinkNode `json:"children,omitempty"`
	// contains filtered or unexported fields
}

LinkNode is one map in the tree of linked maps.

func (LinkNode) ThumbSource

func (n LinkNode) ThumbSource() (mediaID string, playerURL string)

ThumbSource returns the viewer's version of the node's picture: the player copy's address, or the original's media id, or neither.

type LinkTree

type LinkTree struct {
	Roots []LinkNode `json:"roots"`
	// Count is how many maps the tree holds.
	Count int `json:"count"`
	// Truncated is set when a bound stopped the tree from holding every link.
	Truncated bool `json:"truncated"`
}

LinkTree is the campaign's linked maps as one viewer can follow them. Roots are maps no visible link leads to, then one map per group reachable only through a cycle; a map reached twice is listed under the first map that reaches it.

type LinkVia

type LinkVia struct {
	Visibility   string   `json:"visibility"`
	AllowedUsers []string `json:"allowed_users,omitempty"`
	DeniedUsers  []string `json:"denied_users,omitempty"`
}

LinkVia says who can follow the link that leads to a node: the visibility and rules of the pin carrying it. Sent only to viewers who can see DM-only content, the only ones the tree tells who else can follow.

type Map

type Map struct {
	ID          string  `json:"id"`
	CampaignID  string  `json:"campaign_id"`
	Name        string  `json:"name"`
	Description *string `json:"description,omitempty"`
	ImageID     *string `json:"image_id,omitempty"`
	// PlayerImageURL replaces ImageID for a viewer who must not receive the
	// original (a map with a shadow): the address of the picture with the shadows
	// smudged in. Never stored; set only by MapService.ForViewer.
	PlayerImageURL string `json:"image_url,omitempty"`
	// PlayerImageAPIURL is the sync API address of the player copy, set on maps
	// the sync API returns when the map has a shadow, for every key: an owner key
	// still reads the original, but must hand players this copy instead.
	PlayerImageAPIURL string `json:"player_image_url,omitempty"`
	ImageWidth        int    `json:"image_width"`
	ImageHeight       int    `json:"image_height"`
	// BackgroundColor optionally overrides the default theme-following
	// canvas color (bg-surface-alt, which adapts to dark/light via CSS
	// vars) with a fixed CSS color (e.g. "#000000"). Nil means "follow
	// theme" — the renderer falls back to the Tailwind class.
	BackgroundColor *string `json:"background_color,omitempty"`
	// Display is the per-map display settings (frame override, pins, grid,
	// opening view, draw gate); nil means every default. See display_settings.go.
	Display   *DisplaySettings `json:"display_settings,omitempty"`
	SortOrder int              `json:"sort_order"`
	CreatedAt time.Time        `json:"created_at"`
	UpdatedAt time.Time        `json:"updated_at"`

	// Eager-loaded (populated by service, not every query).
	Markers []Marker `json:"markers,omitempty"`
}

Map is an interactive map with a background image and positioned markers.

func (*Map) DrawWho

func (m *Map) DrawWho() string

DrawWho returns the effective draw gate for the map: owners only, or the default of owners and scribes.

func (*Map) GetCampaignID

func (m *Map) GetCampaignID() string

GetCampaignID returns the campaign this map belongs to. Implements middleware.CampaignScoped for generic IDOR protection.

func (*Map) HasImage

func (m *Map) HasImage() bool

HasImage returns true if the map has a background image set, either the original or the player copy that stands in for it.

func (*Map) HexArt

func (m *Map) HexArt() string

HexArt returns the map's terrain art style, Detailed unless the map picked another.

func (*Map) PartyWho

func (m *Map) PartyWho() string

PartyWho returns who may move the party: owners only, or the default of owners and scribes. An owner or DM grant always may.

type MapEventPublisher

type MapEventPublisher interface {
	PublishDrawingEvent(eventType string, campaignID string, drawing *Drawing)
	PublishTokenEvent(eventType string, campaignID string, token *Token)
	// PublishTokenPositionEvent carries isHidden so the fast-drag path gates
	// hidden tokens the same way PublishTokenEvent does — a GM-only token's
	// live position must not reach non-GM clients while it's being dragged.
	// mapID lets the publisher apply the hex fog to the new position.
	PublishTokenPositionEvent(campaignID, mapID, tokenID string, x, y float64, isHidden bool)
	PublishLayerEvent(eventType string, campaignID string, layer *Layer)
	PublishFogEvent(eventType string, campaignID, mapID string, region *FogRegion)
	PublishMarkerEvent(eventType string, campaignID string, marker *Marker)
}

MapEventPublisher emits domain events when map resources change. Implemented by the WebSocket EventBus adapter in routes.go.

type MapFrame

type MapFrame struct {
	W, H float64
}

MapFrame is a map's size in map units (the pixels of its image), the space the viewer draws in. A picture turns in this space, not in percentages, so a turned picture can only be placed on a map whose frame is known.

type MapListData

type MapListData struct {
	CampaignID string
	Maps       []Map
	IsOwner    bool
	IsScribe   bool
	CSRFToken  string
	// CampaignFrame is the campaign-wide frame the list cards wear in small form.
	CampaignFrame string
}

MapListData holds all data needed to render the map list page.

type MapRepository

type MapRepository interface {
	// Map CRUD.
	CreateMap(ctx context.Context, m *Map) error
	GetMap(ctx context.Context, id string) (*Map, error)
	UpdateMap(ctx context.Context, m *Map) error
	DeleteMap(ctx context.Context, id string) error
	ListMaps(ctx context.Context, campaignID string) ([]Map, error)

	// The campaign Trash (map_trash_repository.go). Every read above leaves
	// a trashed map out; DeleteMap is the purge's final delete.
	TrashMap(ctx context.Context, campaignID, id string, at time.Time) error
	RestoreMap(ctx context.Context, campaignID, id string) error
	ListTrashedMaps(ctx context.Context, campaignID string) ([]TrashedMap, error)
	ListMapsTrashedBefore(ctx context.Context, cutoff time.Time) ([]TrashedMap, error)
	SearchMaps(ctx context.Context, campaignID, query string) ([]Map, error)

	// Campaign-wide map look. GetCampaignFrame returns "" when the campaign has
	// never chosen, so the caller applies the default in one place.
	GetCampaignFrame(ctx context.Context, campaignID string) (string, error)
	SetCampaignFrame(ctx context.Context, campaignID, frame string) error

	// Marker CRUD.
	CreateMarker(ctx context.Context, mk *Marker) error
	GetMarker(ctx context.Context, id string) (*Marker, error)
	UpdateMarker(ctx context.Context, mk *Marker) error
	DeleteMarker(ctx context.Context, id string) error
	ListMarkers(ctx context.Context, mapID string, role int, userID string) ([]Marker, error)
	// ListLinkSourceMaps returns the ids of the campaign's maps that carry at
	// least one pin opening another map, unfiltered: the caller reads each
	// map's pins through the viewer's own marker filtering.
	ListLinkSourceMaps(ctx context.Context, campaignID string) ([]string, error)
	// ListMapsPinningEntity returns the ids of the campaign's maps that carry
	// a pin on entityID, and ListMapsLinkingTo those that carry a pin opening
	// mapID, both unfiltered and in the campaign's map order: the caller reads
	// each map's pins through the viewer's own marker filtering.
	ListMapsPinningEntity(ctx context.Context, campaignID, entityID string) ([]string, error)
	ListMapsLinkingTo(ctx context.Context, campaignID, mapID string) ([]string, error)
}

MapRepository defines persistence operations for maps and markers.

func NewMapRepository

func NewMapRepository(db *sql.DB) MapRepository

NewMapRepository creates a new MariaDB-backed map repository.

type MapService

type MapService interface {
	// Map CRUD.
	CreateMap(ctx context.Context, input CreateMapInput) (*Map, error)
	GetMap(ctx context.Context, id string) (*Map, error)
	UpdateMap(ctx context.Context, id string, input UpdateMapInput) error
	// DeleteMap moves a map, with its pins, to the campaign Trash.
	DeleteMap(ctx context.Context, id string, expectedUpdatedAt *time.Time) error
	ListMaps(ctx context.Context, campaignID string) ([]Map, error)

	// RestoreMap, ListTrashedMaps and PurgeTrashedMaps are the maps side of
	// the campaign Trash.
	RestoreMap(ctx context.Context, campaignID, id string) error
	ListTrashedMaps(ctx context.Context, campaignID string) ([]TrashedMap, error)
	PurgeTrashedMaps(ctx context.Context, cutoff time.Time) (int, error)
	SearchMaps(ctx context.Context, campaignID, query string) ([]map[string]string, error)

	// Map look. GetCampaignFrame returns the campaign-wide frame (the default
	// when the campaign has never chosen); SetCampaignFrame validates and
	// stores it; ResolveDisplay is a map's settings with every default filled,
	// including the campaign frame it follows.
	GetCampaignFrame(ctx context.Context, campaignID string) (string, error)
	SetCampaignFrame(ctx context.Context, campaignID, frame string) error
	ResolveDisplay(ctx context.Context, m *Map) (ResolvedDisplay, error)
	// SetMeasureScale stores (or, with a nil scale, removes) the map's scale
	// for the Measure tool. canSet is the owner-or-DM-grant capability
	// (CampaignContext.CanAuthorDmOnly): the rest of the display settings are
	// owner-only, but a DM sets the scale too, so this is its own gate.
	SetMeasureScale(ctx context.Context, campaignID, mapID string, canSet bool, scale json.RawMessage) (*MeasureDisplay, error)

	// Marker CRUD. UpdateMarker and DeleteMarker take canAuthorDmOnly (Owner
	// or a co-DM grant, campaigns.CampaignContext.CanAuthorDmOnly) so a
	// caller who cannot author dm_only content gets the same NotFound a
	// missing id would give when the stored marker is dm_only, regardless of
	// which fields the request touches.
	CreateMarker(ctx context.Context, input CreateMarkerInput) (*Marker, error)
	GetMarker(ctx context.Context, id string) (*Marker, error)
	UpdateMarker(ctx context.Context, id string, input UpdateMarkerInput, canAuthorDmOnly bool) error
	DeleteMarker(ctx context.Context, id string, expectedUpdatedAt *time.Time, canAuthorDmOnly bool, actorID string, role int) error
	// ListMarkers takes campaignID so non-owner results can be narrowed by
	// EntityVisibilityGate: the marker's own visibility is repo-filtered, but
	// a linked entity's visibility is a separate check the caller must supply.
	ListMarkers(ctx context.Context, campaignID, mapID string, role int, userID string) ([]Marker, error)
	// IsMarkerShadowed reports whether a viewer of this role must not receive
	// the marker because it lies under a shadow area. By-id reads use it so
	// they cannot reveal what ListMarkers withholds.
	IsMarkerShadowed(ctx context.Context, mk *Marker, role int) (bool, error)

	// Linked maps (a pin that opens another map). ResolveTrail turns the ids
	// a viewer followed (?from=) into the trail shown above mapID, keeping
	// only maps of the campaign; it is display only and grants nothing.
	// LinkTree is the campaign's linked maps as this viewer can follow them,
	// built from ListMarkers for the viewer so hidden pins add nothing.
	ResolveTrail(ctx context.Context, campaignID, mapID string, from []string) ([]TrailStep, error)
	LinkTree(ctx context.Context, campaignID string, role int, userID string) (*LinkTree, error)
	// WhereIs is an entity's place in the maps, closest first: the map it is
	// pinned on, then the map holding a pin that opens it, out to the top,
	// plus the other maps it is pinned on. Every pin is read for this viewer.
	WhereIs(ctx context.Context, campaignID, entityID string, role int, userID string) (*WhereLadder, error)

	// ForViewer returns the map as a viewer of this (promoted visibility) role
	// may receive it. For anyone who is not owner/DM-equivalent and a map with a
	// shadow, the original image id is removed and the address of the player copy
	// (the picture with the shadows smudged into the pixels) is set instead.
	// Every handler that sends a map to a user passes it through here.
	ForViewer(ctx context.Context, m *Map, role int) (*Map, error)
	ForViewerList(ctx context.Context, ms []Map, role int) ([]Map, error)
	// PlayerImage renders (or reads from cache) the player copy of the map's
	// picture as JPEG. It errors rather than ever returning the original.
	PlayerImage(ctx context.Context, m *Map) ([]byte, error)
	// PlayerImageVersion is the version of the map's player copy, or "" when the
	// map has no picture or no shadow (players then see the original).
	PlayerImageVersion(ctx context.Context, m *Map) (string, error)
	// IsShadowedMapImage tells the media plugin whether a file is the picture of
	// a map that has a shadow or whole-map fog, or a picture drawing whose file
	// the hex fog withholds (media.MapImageGuard); IsMapPicture whether it is
	// the picture of any map at all, or such a withheld picture.
	IsShadowedMapImage(ctx context.Context, campaignID, mediaID string) (bool, error)
	IsMapPicture(ctx context.Context, campaignID, mediaID string) (bool, error)

	// Wiring.
	SetEventPublisher(pub MapEventPublisher)
	// SetShadowLookup is on the interface (not reached by type assertion) so a
	// wiring that stops matching fails to compile instead of silently showing
	// players every pin.
	SetShadowLookup(l ShadowLookup)
	// SetPlayerImageSource is on the interface for the same reason.
	SetPlayerImageSource(src MediaImageSource, cacheDir string)
	// SetHexFogLookup is on the interface for the same reason: without it every
	// player would see every pin and the whole picture under unexplored hexes.
	SetHexFogLookup(l HexFogLookup)
	// SetPictureFileLookup wires the check that a file is a picture drawing the
	// fog or a shadow withholds. With a fog lookup wired and this one not, the
	// media guard refuses every campaign file rather than serve one under the fog.
	SetPictureFileLookup(l PictureFileLookup)
	// SetMediaVerifier wires the check that a map's background is a picture of
	// the map's own campaign. Unwired, a background can't be set at all.
	SetMediaVerifier(v MediaVerifier)
}

MapService defines business logic for the maps plugin.

Mutation methods that mutate row-level state (Update*, Delete*) accept an optional expectedUpdatedAt token for optimistic concurrency. Pass nil for last-writer-wins; pass the caller's last-known UpdatedAt to trigger 409 Conflict if the row has been modified since.

func NewMapService

func NewMapService(repo MapRepository) MapService

NewMapService creates a MapService backed by the given repository.

type MapViewData

type MapViewData struct {
	CampaignID string
	Map        *Map
	Markers    []Marker
	IsScribe   bool
	// IsOwner gates the Map settings sheet: the PUT behind it is Owner-only,
	// so offering it to a scribe could only end in a refusal.
	IsOwner bool
	// IsDM is the owner or a co-DM. Only they see under shadows and get the
	// shadow tool; a scribe is hidden like a player.
	IsDM bool
	// UserID is the viewer's own id (empty when anonymous). The page uses it
	// only to key the per-person "where I left off" view in the browser.
	UserID string
	// Display is the resolved look of this map. The zero value is replaced by
	// defaults at render (see DisplayOrDefault), so a caller that builds
	// MapViewData by hand never has to fill it.
	Display ResolvedDisplay
	// Trail is the path the viewer followed to reach this map (the validated
	// ?from= ids), ending with this map. Display only: it never grants access.
	// Empty when the viewer did not arrive by a link.
	Trail []TrailStep
	// LinkMaps are the maps a pin on this map may open, offered by the pin
	// form's "Opens map" chooser. Filled only for viewers who can edit pins.
	LinkMaps []LinkMapOption
	// MemberNames maps user ids to display names so the badge can name the
	// players a pin's rules allow. Filled only for viewers who can see
	// DM-only content, the only ones shown those names.
	MemberNames map[string]string
}

MapViewData holds all data needed to render a single map page.

func (MapViewData) CanDraw

func (d MapViewData) CanDraw() bool

CanDraw reports whether this viewer gets the drawing tools: a scribe or above, and an owner when the map restricts drawing to owners. This only decides what is offered; DrawingService enforces the rule on the server.

func (MapViewData) CanMoveParty

func (d MapViewData) CanMoveParty() bool

CanMoveParty reports whether this viewer is offered the Party tool. It mirrors HexService.requirePartyMover: an owner or DM grant always, a scribe unless the map keeps the party to owners, a player never.

func (MapViewData) CanPaintHexes

func (d MapViewData) CanPaintHexes() bool

CanPaintHexes reports whether this viewer is offered Paint in the Hexes tool. It mirrors HexService.requireWriter exactly: an owner or DM grant always, a scribe only when the map lets scribes draw, a player never. It is not CanDraw because a DM-granted player is below scribe, so CanDraw hides a tool the server would let them use.

func (MapViewData) CanShadow

func (d MapViewData) CanShadow() bool

CanShadow reports whether this viewer gets the "Hide under shadow" tool: a DM who can draw on this map. Offering only; DrawingService enforces it.

func (MapViewData) DisplayOrDefault

func (d MapViewData) DisplayOrDefault() ResolvedDisplay

DisplayOrDefault returns Display, or the all-defaults resolution when the caller did not set one.

type Marker

type Marker struct {
	ID          string  `json:"id"`
	MapID       string  `json:"map_id"`
	Name        string  `json:"name"`
	Description *string `json:"description,omitempty"`
	X           float64 `json:"x"`
	Y           float64 `json:"y"`
	Icon        string  `json:"icon"`
	Color       string  `json:"color"`
	PinCategory *string `json:"pin_category,omitempty"` // location, danger, treasure, quest, note.
	EntityID    *string `json:"entity_id,omitempty"`
	// LinkedMapID is the map this pin opens: another map of the same
	// campaign, never the pin's own. Who may follow it is the pin's own
	// visibility; maps have no "who can see" setting of their own.
	LinkedMapID     *string   `json:"linked_map_id,omitempty"`
	Visibility      string    `json:"visibility"`
	VisibilityRules *string   `json:"visibility_rules,omitempty"`
	CreatedBy       *string   `json:"created_by,omitempty"`
	FoundryID       *string   `json:"foundry_id,omitempty"`
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`

	// Joined fields for display (populated by some queries).
	EntityName string `json:"entity_name,omitempty"`
	EntityIcon string `json:"entity_icon,omitempty"`
	// LinkedMapName is the name of the map LinkedMapID opens, for the badge
	// and the "Open <map>" button. It rides on the marker, so it reaches
	// exactly the viewers the marker itself reaches.
	LinkedMapName string `json:"linked_map_name,omitempty"`
}

Marker is a pin placed on a map at percentage coordinates (0-100). Optionally links to an entity and supports per-player visibility via visibility_rules (same pattern as timelines/calendar events).

func (*Marker) IsDMOnly

func (m *Marker) IsDMOnly() bool

IsDMOnly returns true if this marker is only visible to the DM.

type MarkerIcon

type MarkerIcon struct {
	ID       string `json:"id"`       // canonical Font Awesome class, e.g. "fa-castle"
	Label    string `json:"label"`    // human concept, e.g. "Castle"
	Category string `json:"category"` // picker group, e.g. "Fortifications"
}

MarkerIcon is one entry in the canonical vocabulary. ID is the stable Font Awesome class persisted on markers + sent over sync; Label is the human concept; Category groups the picker.

func MarkerIconCatalog

func MarkerIconCatalog() []MarkerIcon

MarkerIconCatalog returns a copy of the canonical icon vocabulary in display order. Copy (not the package slice) so callers can't mutate the source.

type MarkerIconGroup

type MarkerIconGroup struct {
	Category string       `json:"category"`
	Icons    []MarkerIcon `json:"icons"`
}

MarkerIconGroup is a category and its icons, for grouped rendering.

func MarkerIconGroups

func MarkerIconGroups() []MarkerIconGroup

MarkerIconGroups returns the catalog grouped by category, preserving the catalog's first-seen category order (so the picker is stable).

type MeasureDisplay

type MeasureDisplay struct {
	A      MeasurePoint `json:"a"`
	B      MeasurePoint `json:"b"`
	Length float64      `json:"length"`
	Unit   string       `json:"unit"`
}

MeasureDisplay is a picture map's scale: two points the owner dragged between (percent of the picture, like pins, so a bigger upload of the same map keeps its scale) and the real length of that line. Storing the line rather than a units-per-pixel figure keeps it independent of the picture's resolution. Hex maps do not use it: they measure in hexes.

type MeasurePoint

type MeasurePoint struct {
	X float64 `json:"x"`
	Y float64 `json:"y"`
}

MeasurePoint is one end of the scale line, in percent of the picture.

type MediaCampaignLookup

type MediaCampaignLookup interface {
	MediaCampaign(ctx context.Context, mediaID string) (campaignID string, found bool, err error)
}

MediaCampaignLookup answers which campaign a media file belongs to; found is false for an unknown id, and campaignID is "" for a file of no campaign.

type MediaImageSource

type MediaImageSource interface {
	ReadImage(ctx context.Context, campaignID, mediaID string) ([]byte, error)
}

MediaImageSource reads the original bytes of a campaign's picture. Implemented in app over the media plugin, so maps never touches media's storage or repository.

type MediaVerifier

type MediaVerifier interface {
	// ImageInCampaign is true only when the file exists, is an image and
	// belongs to the campaign. A missing file is a clean false, not an error.
	ImageInCampaign(ctx context.Context, mediaID, campaignID string) (bool, error)
}

MediaVerifier answers whether a media file may be used as a picture on a campaign's map. It is a seam so this plugin never reads the media plugin's repository; the app wires an adapter over the media service.

type NoopMapEventPublisher

type NoopMapEventPublisher struct{}

NoopMapEventPublisher is a no-op implementation for tests.

func (NoopMapEventPublisher) PublishDrawingEvent

func (NoopMapEventPublisher) PublishDrawingEvent(string, string, *Drawing)

func (NoopMapEventPublisher) PublishFogEvent

func (NoopMapEventPublisher) PublishFogEvent(string, string, string, *FogRegion)

func (NoopMapEventPublisher) PublishLayerEvent

func (NoopMapEventPublisher) PublishLayerEvent(string, string, *Layer)

func (NoopMapEventPublisher) PublishMarkerEvent

func (NoopMapEventPublisher) PublishMarkerEvent(string, string, *Marker)

func (NoopMapEventPublisher) PublishTokenEvent

func (NoopMapEventPublisher) PublishTokenEvent(string, string, *Token)

func (NoopMapEventPublisher) PublishTokenPositionEvent

func (NoopMapEventPublisher) PublishTokenPositionEvent(string, string, string, float64, float64, bool)

type OldRoadConversion

type OldRoadConversion struct {
	Col, Row int
	Road     int
	Terrain  *string
}

OldRoadConversion is the new state of one old road hex: its road mask and the land that replaces the road terrain (nil when no land can be inferred). The hex's piece is cleared, since the old road had none.

func PlanOldRoadConversion

func PlanOldRoadConversion(cells []HexCell) []OldRoadConversion

PlanOldRoadConversion computes the conversion of every old road hex among cells, in row-then-column order. It is pure so the rule is testable without a database.

type OldRoadStore

type OldRoadStore interface {
	// ListMapIDsWithOldRoads returns the maps that still hold a hex whose
	// terrain is the old road.
	ListMapIDsWithOldRoads(ctx context.Context) ([]string, error)
	// ConvertMap reads the map's cells, applies plan's result and bumps the
	// layer version, in one transaction, and returns how many hexes changed.
	ConvertMap(ctx context.Context, mapID string, plan func([]HexCell) []OldRoadConversion) (int, error)
}

OldRoadStore is the persistence surface ReconcileOldRoadHexes needs.

func NewOldRoadStore

func NewOldRoadStore(db *sql.DB) OldRoadStore

NewOldRoadStore returns the MariaDB-backed OldRoadStore.

type OpenDisplay

type OpenDisplay struct {
	Mode string   `json:"mode,omitempty"`
	X    *float64 `json:"x,omitempty"`
	Y    *float64 `json:"y,omitempty"`
	Zoom *float64 `json:"zoom,omitempty"`
}

OpenDisplay is where the map opens. X and Y are percent of the image (like marker coordinates) and Zoom is levels relative to the whole-map view, so a stored spot means the same on every screen size.

type PartyMoveResult

type PartyMoveResult struct {
	Version uint64   `json:"version"`
	Path    []HexKey `json:"path"`
}

PartyMoveResult is the outcome of moving the party. Path runs from the old position to the new one inclusive (just the new one on first placement); every hex on it is explored by the time it is returned.

type PictureDisplay

type PictureDisplay struct {
	Blank bool `json:"blank,omitempty"`
}

PictureDisplay is the owner's choice to keep a map without a picture. Only true is stored; false is the default.

type PictureFileLookup

type PictureFileLookup interface {
	WithholdsPictureFile(ctx context.Context, mapID, mediaID string) (bool, error)
}

PictureFileLookup reports whether a file is a picture on a map whose image the hex fog or a shadow withholds from viewers below CanSeeDmOnly. Implemented by the drawing service.

type PictureRef

type PictureRef struct {
	ID         string
	CampaignID string
	Value      string
}

PictureRef is one stored picture reference: a map's background or a token's picture, with the campaign of the map that holds it.

type PictureRefStore

type PictureRefStore interface {
	ListMapBackgrounds(ctx context.Context) ([]PictureRef, error)
	ListTokenPictures(ctx context.Context) ([]PictureRef, error)
	ClearMapBackground(ctx context.Context, mapID, expected string) (bool, error)
	ClearTokenPicture(ctx context.Context, tokenID, expected string) (bool, error)
}

PictureRefStore reads and clears stored picture references for ClearForeignPictures. A clear names the value it expects, so a picture changed since the listing is left alone.

func NewPictureRefStore

func NewPictureRefStore(db *sql.DB) PictureRefStore

NewPictureRefStore creates a PictureRefStore backed by MariaDB.

type PinDisplay

type PinDisplay struct {
	Style  string `json:"style,omitempty"`
	Size   string `json:"size,omitempty"`
	Labels string `json:"labels,omitempty"`
}

PinDisplay is the marker shape drawn around the Font Awesome icon, its size, and when the pin's name shows on the map.

type PinStyle

type PinStyle struct {
	ID    string
	Label string
}

PinStyle is one of the shapes a map draws its pins in.

type ResolvedDisplay

type ResolvedDisplay struct {
	// Frame is the frame actually drawn: the map's own pick, else the campaign's.
	Frame string `json:"frame"`
	// FrameSource is "map" when this map overrides the campaign style, else "campaign".
	FrameSource string `json:"frame_source"`
	// CampaignFrame is the campaign style, so the sheet can label "Campaign style (Atlas)".
	CampaignFrame string        `json:"campaign_frame"`
	Tint          bool          `json:"tint"`
	PinStyle      string        `json:"pin_style"`
	PinSize       string        `json:"pin_size"`
	PinLabels     string        `json:"pin_labels"`
	Kinds         []KindDisplay `json:"kinds"`
	GridType      string        `json:"grid_type"`
	GridSize      int           `json:"grid_size"`
	GridStrength  int           `json:"grid_strength"`
	OpenMode      string        `json:"open_mode"`
	OpenX         float64       `json:"open_x"`
	OpenY         float64       `json:"open_y"`
	OpenZoom      float64       `json:"open_zoom"`
	DrawWho       string        `json:"draw_who"`
	PartyWho      string        `json:"party_who"`
	// Measure is the map's scale, or null while nobody has set one. It is not
	// secret: everyone who can see the map measures with it.
	Measure *MeasureDisplay `json:"measure"`
	// KeepBlank is true once the owner answered the "no picture yet" prompt
	// with Not now, so the page never shows it again for this map.
	KeepBlank bool `json:"keep_blank"`
}

ResolvedDisplay is the display settings with every default filled in, in the shape the page script reads. Resolving server-side keeps the defaults in one place instead of repeating them in JavaScript.

func ResolveDisplay

func ResolveDisplay(m *Map, campaignFrame string) ResolvedDisplay

ResolveDisplay fills every default for a map. campaignFrame is the campaign-wide style; an invalid or empty value falls back to the default so a stale row can never leave the page without a frame.

type ShadowArea

type ShadowArea struct {
	MinX, MinY, MaxX, MaxY float64
	Strength               float64
}

ShadowArea is a shadow's box in map percentages (0-100), already ordered so Min <= Max. Corners are normalised on parse because a person can drag a box from any corner to its opposite. Strength is one of the two normalised strengths; the player copy of the map picture needs it to know how dark to smudge the area.

func (ShadowArea) Contains

func (a ShadowArea) Contains(x, y float64) bool

Contains reports whether the point lies inside the box. Edges count as inside: a pin sitting exactly on the border must not be left showing.

type ShadowLookup

type ShadowLookup interface {
	ShadowAreas(ctx context.Context, mapID string) ([]ShadowArea, error)
}

ShadowLookup returns the shadow areas of a map. Implemented by the drawing service, which owns drawings; the map service only applies the rule to pins.

type Token

type Token struct {
	ID             string          `json:"id"`
	MapID          string          `json:"map_id"`
	LayerID        *string         `json:"layer_id,omitempty"`
	EntityID       *string         `json:"entity_id,omitempty"`
	Name           string          `json:"name"`
	ImagePath      *string         `json:"image_path,omitempty"`
	X              float64         `json:"x"` // Percentage 0-100.
	Y              float64         `json:"y"`
	Width          float64         `json:"width"` // Grid units.
	Height         float64         `json:"height"`
	Rotation       float64         `json:"rotation"`
	Scale          float64         `json:"scale"`
	IsHidden       bool            `json:"is_hidden"` // GM-only visibility.
	IsLocked       bool            `json:"is_locked"`
	Bar1Value      *int            `json:"bar1_value,omitempty"`
	Bar1Max        *int            `json:"bar1_max,omitempty"`
	Bar2Value      *int            `json:"bar2_value,omitempty"`
	Bar2Max        *int            `json:"bar2_max,omitempty"`
	AuraRadius     *float64        `json:"aura_radius,omitempty"`
	AuraColor      *string         `json:"aura_color,omitempty"`
	LightRadius    *float64        `json:"light_radius,omitempty"`
	LightDimRadius *float64        `json:"light_dim_radius,omitempty"`
	LightColor     *string         `json:"light_color,omitempty"`
	VisionEnabled  bool            `json:"vision_enabled"`
	VisionRange    *float64        `json:"vision_range,omitempty"`
	Elevation      int             `json:"elevation"`
	SortOrder      int             `json:"sort_order"`
	StatusEffects  json.RawMessage `json:"status_effects,omitempty"`
	Flags          json.RawMessage `json:"flags,omitempty"`
	FoundryID      *string         `json:"foundry_id,omitempty"`
	CreatedBy      *string         `json:"created_by,omitempty"`
	CreatedAt      time.Time       `json:"created_at"`
	UpdatedAt      time.Time       `json:"updated_at"`
}

Token represents a character, NPC, or object placed on a map. Tokens optionally link to Chronicle entities for cross-referencing.

type TokenColumn

type TokenColumn string

TokenColumn names a map_tokens column a partial update may write. It is a closed set so a column name never comes from request data.

type TrailStep

type TrailStep struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

TrailStep is one map on the trail at the top of the viewer.

type TrashedMap

type TrashedMap struct {
	ID         string
	CampaignID string
	Name       string
	DeletedAt  time.Time
}

TrashedMap is a map as the campaign Trash lists it.

type UpdateDrawingInput

type UpdateDrawingInput struct {
	Points      patch.Field[json.RawMessage]
	StrokeColor patch.Field[string]
	StrokeWidth patch.Field[float64]
	FillColor   patch.Field[string]
	FillAlpha   patch.Field[float64]
	TextContent patch.Field[string]
	FontSize    patch.Field[int]
	Rotation    patch.Field[float64]
	Visibility  patch.Field[string]
	// ImageID may only change to another media file of the map's campaign;
	// Crop null clears the crop. Both apply to "image" drawings only.
	ImageID           patch.Field[string]
	Crop              patch.Field[json.RawMessage]
	SortOrder         patch.Field[int]
	ExpectedUpdatedAt *time.Time
}

UpdateDrawingInput is the validated input for updating a drawing. ExpectedUpdatedAt is the optimistic-concurrency token (optional) and is NOT a data field, so it stays a plain pointer.

PARTIAL update: absent preserves, explicit null clears, present replaces (see .ai/conventions.md's partial-update contract; same shape as UpdateTokenInput). A caller sending only {points} to reshape a freehand stroke must not wipe fill, text content, font size or rotation.

type UpdateHexCellInput

type UpdateHexCellInput struct {
	Col     int
	Row     int
	Terrain patch.Field[string]
	Piece   patch.Field[int]
	// Road, River and Trail are line side masks (0..MaxHexLineMask, bit i is
	// neighbour i of Neighbors()); null removes the line from the hex.
	Road  patch.Field[int]
	River patch.Field[int]
	Trail patch.Field[int]
	Name  patch.Field[string]
	Notes patch.Field[string]
}

UpdateHexCellInput is one entry of a hex batch. Col and Row name the hex and are required; every other field is presence-aware: absent keeps the stored value, an explicit null clears it, a present value replaces it. A paint stroke sends terrain and piece only, so it cannot touch a hex's name or notes. Piece picks one of the terrain's looks (0..PieceCount-1); null is "Mix", where the viewer picks a stable look from the hex's position.

type UpdateHexLayerInput

type UpdateHexLayerInput struct {
	AnchorDrawingID patch.Field[string]
	FogEnabled      patch.Field[bool]
	MilesPerHex     patch.Field[int]
	MilesPerDay     patch.Field[int]
	Art             patch.Field[string]
}

UpdateHexLayerInput is a partial change to the layer row: an absent field keeps, an explicit null clears, a present value replaces. Null on the anchor means "the whole map"; null on fog_enabled means off; null on a travel figure restores its default. A value outside MinTravelMiles..MaxTravelMiles is refused. Art is the map's terrain style (display_settings hexes.art), here so a DM grant, who cannot save the map's settings, can change it from the Paint mode; null restores the default.

type UpdateLayerInput

type UpdateLayerInput struct {
	Name              string
	SortOrder         patch.Field[int]
	IsVisible         patch.Field[bool]
	Opacity           patch.Field[float64]
	IsLocked          patch.Field[bool]
	ExpectedUpdatedAt *time.Time
}

UpdateLayerInput is the validated input for updating a layer. ExpectedUpdatedAt is the optimistic-concurrency token (optional) and is NOT a data field, so it stays a plain pointer.

PARTIAL update: absent preserves, explicit null clears, present replaces (see .ai/conventions.md's partial-update contract). A SortOrder-only PUT must not silently reset the other patch.Field members' visibility/lock state.

Name is deliberately left a plain string: UpdateLayer only ever assigns it when the caller sends a non-empty value, so an absent/blank name is already preserved.

type UpdateMapInput

type UpdateMapInput struct {
	Name              string
	Description       patch.Field[string]
	ImageID           patch.Field[string]
	ImageWidth        patch.Field[int]
	ImageHeight       patch.Field[int]
	BackgroundColor   *string
	DisplaySettings   patch.Field[json.RawMessage]
	ExpectedUpdatedAt *time.Time
}

UpdateMapInput is the validated input for updating a map.

PARTIAL update: absent preserves, explicit null clears, present replaces (see .ai/conventions.md). ImageID, ImageWidth, ImageHeight and Description use patch.Field[T], not a plain *T, so a rename-only PUT can't unlink the image or wipe the description.

BackgroundColor stays a plain *string: nil = unchanged, pointer-to-empty = clear the override, any other value = set it — that sentinel, not a JSON null, is the contract the caller and service use.

DisplaySettings is group-level partial too (MergeDisplaySettings): the whole key absent preserves, null clears every group, and an object replaces only the groups it names (a group set to null clears just that group).

Name is a plain string; UpdateMap 400s on a blank merged name so an absent name fails loudly rather than overwriting silently.

ExpectedUpdatedAt is the optional optimistic-concurrency token: non-nil rejects with 409 if UpdatedAt has advanced past it (internal/concurrency.Check); omitted falls back to last-writer-wins. Not a data field, so plain pointer.

type UpdateMarkerInput

type UpdateMarkerInput struct {
	Name              patch.Field[string]
	Description       patch.Field[string]
	X                 patch.Field[float64]
	Y                 patch.Field[float64]
	Icon              patch.Field[string]
	Color             patch.Field[string]
	PinCategory       patch.Field[string]
	EntityID          patch.Field[string]
	LinkedMapID       patch.Field[string]
	Visibility        patch.Field[string]
	VisibilityRules   patch.Field[string]
	FoundryID         patch.Field[string]
	ExpectedUpdatedAt *time.Time
}

UpdateMarkerInput is the validated input for updating a marker. ExpectedUpdatedAt is the optimistic-concurrency token (optional) and is NOT a data field — it is the caller's last-known version, so it stays a plain pointer.

Everything else is a patch.Field: this is a PARTIAL update (see .ai/conventions.md) — an ABSENT key preserves the stored value, an EXPLICIT null clears it, a present value replaces it. pin_category and visibility_rules (access-control data) must survive an edit or drag PUT that omits them, and foundry_id must survive a web edit that omits it — the web form never sends foundry_id, but syncapi can still clear it via an explicit null.

type UpdateTokenInput

type UpdateTokenInput struct {
	Name              string
	ImagePath         patch.Field[string]
	X                 patch.Field[float64]
	Y                 patch.Field[float64]
	Width             patch.Field[float64]
	Height            patch.Field[float64]
	Rotation          patch.Field[float64]
	Scale             patch.Field[float64]
	IsHidden          patch.Field[bool]
	IsLocked          patch.Field[bool]
	Bar1Value         patch.Field[int]
	Bar1Max           patch.Field[int]
	Bar2Value         patch.Field[int]
	Bar2Max           patch.Field[int]
	AuraRadius        patch.Field[float64]
	AuraColor         patch.Field[string]
	LightRadius       patch.Field[float64]
	LightDimRadius    patch.Field[float64]
	LightColor        patch.Field[string]
	VisionEnabled     patch.Field[bool]
	VisionRange       patch.Field[float64]
	Elevation         patch.Field[int]
	StatusEffects     patch.Field[json.RawMessage]
	Flags             patch.Field[json.RawMessage]
	ExpectedUpdatedAt *time.Time
}

UpdateTokenInput is the validated input for updating a token. ExpectedUpdatedAt is the optimistic-concurrency token (optional) and is NOT a data field, so it stays a plain pointer.

PARTIAL update: absent preserves, explicit null clears, present replaces (see .ai/conventions.md's partial-update contract). Every field uses patch.Field[T] rather than a plain *T, since a plain pointer bound from JSON can't distinguish "key omitted" from "key sent null" — a drag PUT carrying only {x, y} must not zero IsHidden, HP bars, or aura/light/vision.

Name is the one field deliberately left a plain string: UpdateToken only assigns it when the caller sends a non-empty value, so an absent/blank name is already preserved without patch.Field.

type UpdateTokenPositionInput

type UpdateTokenPositionInput struct {
	X                 patch.Field[float64] `json:"x"`
	Y                 patch.Field[float64] `json:"y"`
	ExpectedUpdatedAt *time.Time           `json:"expected_updated_at"`
}

UpdateTokenPositionInput is a lightweight update for token position only. ExpectedUpdatedAt is the optimistic-concurrency token (optional). Drag pipelines that fire many position updates per second can simply omit it and accept last-writer-wins; deliberate "drop here" actions can include it to detect cross-user collisions.

X and Y are presence-aware: a body naming one axis moves the token along that axis only, instead of snapping the other to 0. Both columns are NOT NULL, so an explicit null also preserves.

type VisibilityRules

type VisibilityRules struct {
	AllowedUsers []string `json:"allowed_users,omitempty"`
	DeniedUsers  []string `json:"denied_users,omitempty"`
}

VisibilityRules defines per-user visibility overrides for map content. Follows the same pattern as timelines and calendar events.

func ParseVisibilityRules

func ParseVisibilityRules(raw *string) *VisibilityRules

ParseVisibilityRules parses the JSON visibility rules into a VisibilityRules struct.

func (*VisibilityRules) Allows

func (v *VisibilityRules) Allows(userID string) bool

Allows reports whether userID may see content gated by these rules, under the non-owner branch of a visibility check — Owners bypass VisibilityRules entirely (ListMarkers/ListDrawings) and never call this. A nil receiver always allows.

Must mirror the SQL predicate in repository.go's ListMarkers and drawing_repository.go's ListDrawings byte-for-byte, and the WebSocket hub's per-recipient gate (internal/websocket's Message.AudienceAllows, duplicated there since that package can't import a plugin's types) — all three must stay in lockstep or content becomes visible over one channel and not another.

The default for a user named in NEITHER list depends on whether AllowedUsers is in use: empty means "everyone except DeniedUsers" (default-allow); non-empty is a strict allowlist (default-deny).

A non-empty DeniedUsers also excludes an anonymous (empty) userID — permissions.DeniesAnonymous, ADR-049 — since a logged-out visitor can't be proven not to be the player the list names.

type WhereAlso

type WhereAlso struct {
	Map    Map
	DMOnly bool
}

WhereAlso is a map the entity is pinned on that the ladder does not pass through.

type WhereLadder

type WhereLadder struct {
	Steps []WhereStep
	Also  []WhereAlso
	// Truncated is set when the depth bound, a cap on visible maps or the read
	// budget kept the ladder or the Also list from being complete.
	Truncated bool
}

WhereLadder is the entity's place in the maps, closest first.

type WhereStep

type WhereStep struct {
	// Map is the viewer's version of the map (players get the player-safe
	// picture), so a thumbnail built from it cannot leak an original.
	Map Map
	// HasPin is set when PinX/PinY (percent of the picture) mark a spot to
	// outline: the entity's own pin on the first step, otherwise the pin on
	// this map that opens the closer step.
	HasPin     bool
	PinX, PinY float64
	// DMOnly is set when players cannot reach this step. Only a viewer who can
	// see DM-only content ever receives such a step.
	DMOnly bool
}

WhereStep is one map on the ladder.

Jump to

Keyboard shortcuts

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