Metadata-Version: 2.4
Name: mudhub-worldbuilder
Version: 0.8.0
Summary: File-based visual world builder for Evennia: YAML areas, idempotent sync, web map editor, blueprints, behaviours, world map and area converters.
Author: MUDHub
License-Expression: BSD-3-Clause
Project-URL: Homepage, https://mudhub.club/game/repository/#contribs
Keywords: evennia,mud,worldbuilding,area,builder,contrib
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: Django
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Games/Entertainment :: Multi-User Dungeons (MUD)
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: evennia>=4
Requires-Dist: pyyaml
Provides-Extra: xyzgrid
Requires-Dist: scipy; extra == "xyzgrid"
Dynamic: license-file

# MUDHub Worldbuilder

A universal, file-based world builder for any [Evennia](https://www.evennia.com) game,
shipped as a pip-installable contrib: YAML area files, an idempotent sync engine,
in-game room features, a web map editor, blueprints, mobile behaviours and resets,
a world map with XYZGrid / wilderness / Mudlet support, and converters for old
Diku-family area files. Version 0.8.0, BSD-3-Clause. See CHANGELOG.md.

## Install

Needs Python 3.10+ and Evennia 4 or newer, in the venv your game runs from.

1. Install the package (the wheel from the MUDHub repository, or from source):

   ```
   pip install mudhub_worldbuilder-0.8.0-py3-none-any.whl
   # optional, for XYZGrid import/export:
   pip install "mudhub_worldbuilder-0.8.0-py3-none-any.whl[xyzgrid]"
   ```

2. Settings (`server/conf/settings.py`). Nothing is required; the defaults are
   shown. No `INSTALLED_APPS` change and no migrations of its own.

   ```python
   WORLDBUILDER_AREAS_DIR = os.path.join(GAME_DIR, "world", "areas")
   ```

3. Commands: add the cmdset to your character cmdset in
   `commands/default_cmdsets.py`:

   ```python
   from mudhub_worldbuilder.commands import WorldbuilderCmdSet

   class CharacterCmdSet(default_cmds.CharacterCmdSet):
       def at_cmdset_creation(self):
           super().at_cmdset_creation()
           self.add(WorldbuilderCmdSet)
   ```

4. Web editor: one line in `web/urls.py`, inside `urlpatterns`:

   ```python
   path("worldbuilder/", include("mudhub_worldbuilder.web.urls")),
   ```

5. `evennia migrate` (only Evennia's own tables: the package has no models),
   then `evennia start` (or `evennia reload` on a running game). On a new game
   `evennia start` asks for the superuser first; for a scripted setup set
   `EVENNIA_SUPERUSER_USERNAME`, `EVENNIA_SUPERUSER_PASSWORD` (and optionally
   `EVENNIA_SUPERUSER_EMAIL`) in the environment. Create the superuser before
   using `evennia shell` on a new game.

6. Try the sample castle: copy it into your areas folder and apply it
   (needs the Builder permission; the superuser has it):

   ```
   python -c "import mudhub_worldbuilder, os; print(os.path.join(os.path.dirname(mudhub_worldbuilder.__file__), 'sample_areas'))"
   mkdir -p world/areas && cp -r <that folder>/castle world/areas/
   ```

   Log in (telnet or the webclient) and run `@area validate castle`,
   `@area plan castle`, `@area apply castle`, then `@area list`.
   The editor is at `http://localhost:4001/worldbuilder/` (4001 is Evennia's
   default web port; use your game's). Log in on the website first
   (`/auth/login/`); the castle shows in the area list and opens in the map editor.

Checked for 0.8.0 on a brand-new Evennia 6.1 game in a clean venv: wheel
install, steps 2 to 6, castle applied (re-plan shows it unchanged), area list,
editor page and API load all served.

## Area format (Ranvier-style YAML)

```
world/areas/
  world.yml                       # optional: area origins + world links (phase 6)
  castle/
    area.yml     id, title, status (draft|review|published), owners[], builders[],
                 zlevels, reset_interval, default_room_type, entry
    rooms.yml    [{id, name, desc, xyz, room_type, details{}, states{night:..,winter:..},
                   attrs{}, exits{dir: {to: "area:id", kind: plain|door|gate|curtain|window,
                                         desc, aliases, typeclass, attrs}}}]
    objects.yml  prototype dicts + id, prototype_parent, placement: background|foreground
    mobiles.yml  prototype dicts + id
    resets.yml   [{room, prototype, max, chance}]
```

Ids are namespaced strings (`castle:101`); bare ids are qualified with the area
namespace. Files never contain dbrefs. Values must be JSON-safe; `$protfunc(...)`
strings are stored verbatim and only evaluated on the spawned object.
See `mudhub_worldbuilder/sample_areas/castle` (13 rooms, 3 z-levels, gate, doors,
curtain, a window, a sittable background bench, foreground objects, a guard).

## Engine (plain Python - wrap it in any API)

```python
from mudhub_worldbuilder import api
spec = api.load_area("world/areas/castle")
api.validate_area(spec)      # errors/warnings: duplicate ids, dangling exits, unreachable
                             # rooms, missing prototypes, >4 foreground objects ...
api.plan_area(spec)          # dry run: create/update/delete/undelete/unchanged per id
api.apply_area(spec)         # idempotent upsert; soft-delete removed entities
api.export_area("castle", "out/castle")   # DB -> YAML (round trip)
api.list_room_types()
```

* Every entity is tagged `area_vnum=<id>`, `wb_area=<namespace>`, `wb_kind=<kind>`;
  instances also get `from_prototype`; rooms with xyz get xyzgrid-compatible
  `room_x/y/z_coordinate` tags.
* **Strictly per area**: plan/apply for area A only touches objects tagged
  `wb_area=A`; a file that defines another namespace's room is refused. Other
  areas' rooms are only looked up (read-only) as exit destinations.
* Removed rooms/objects are soft-deleted (`wb_status=deleted`, moved to the
  "Worldbuilder Holding" room) and revived in place if they come back. Exits
  hold nothing and are removed/rebuilt.
* `owners`/`builders`/`status` in `area.yml` are stored and exported; permission
  enforcement (head builder vs per-area builders) is left to the hosting layer.

## Room types

Auto-discovered: any typeclass subclassing `WorldbuilderRoom` or carrying a
`worldbuilder_room_type` class attribute (with optional `worldbuilder_fields`).
Built in: `default`, `indoors`, `outdoors`, `underground`, `water`. Override or
add via `settings.WORLDBUILDER_ROOM_TYPES = {"name": "path.to.Typeclass"}`.
Extra discovery modules: `WORLDBUILDER_DISCOVER_MODULES` (default `["typeclasses.rooms"]`).

## Builder command

Add `mudhub_worldbuilder.commands.WorldbuilderCmdSet` to your character cmdset:
`@area list | types | validate <id> | plan <id> | apply <id> | export <id>`
(lock `perm(Builder)`). Folders: `WORLDBUILDER_AREAS_DIR` (default
`<game>/world/areas`), exports go to `WORLDBUILDER_EXPORT_DIR` (default
`<areas>/_export`) so source files are never overwritten.

## In play (phase 2)

Add `WorldbuilderCmdSet` (builder + play) or just `WorldbuilderPlayCmdSet` to the
character cmdset:

* `open/close <exit>`, `lock/unlock <exit>` (needs an item spawned from the exit's
  `key_prototype`). Exit attrs: `noun`, `closed`, `locked`, `key_prototype`,
  `blinds`. State is shared with the paired exit on the other side and shown in
  the exit list ("a closed oak door north") and `look <exit>`. File values of
  `closed`/`locked` are the *initial* state: re-applying never resets played state.
* Windows: `look [through] window` shows the room beyond (first sentence of its
  desc + visible characters/foreground objects); `close blinds` blocks the view
  from both sides; windows cannot be walked through.
* Furniture (`capacity`/`seats`, `postures: [sit, lie]`): `sit/lie on <x>`,
  `stand`; occupants are shown in the room text. Background furniture is scenery
  (not listed, but `look bench` works, also via room details); foreground
  furniture is listed.
* Room states: `desc_<state>` for explicit room states (Tags `room_state`), time
  of day (morning/afternoon/evening/night + day/night) and season; details can be
  `{default: .., night: ..}`.
* `render_room(room_or_yaml, viewer=None, screenreader=False)` returns exactly the
  player's `look` text (also from a rooms.yml dict, for the editor preview); the
  screen-reader variant has no colour codes and one sentence per line.

Optional contrib: rooms subclass Evennia's `ExtendedRoom` when importable (its
`desc`/`detail`/`roomstate` builder commands then work, and descs go through its
funcparser). All worldbuilder state/detail/time/season logic is our own and
uses the same storage, so it falls back to plain `DefaultRoom` unchanged.
Nothing else depends on optional contribs.

## Web editor (phase 3)

One line in your game's `web/urls.py`:

```python
path("worldbuilder/", include("mudhub_worldbuilder.web.urls")),
```

No INSTALLED_APPS change. Pages: area list (status, owners, counts, validation
badge) and a per-area editor: SVG map per z level (grid snap, drag to move,
shift-drag or Link mode between rooms creates an exit pair with the direction
picked from relative position, up/down and cross-area exits shown as markers),
inspector for rooms / exits / objects / area, live preview through `render_room`
(normal and screen reader), and Save (writes YAML, status draft), Validate,
Plan, Apply (status published), Export. JSON API under `api/<area>/<action>/`,
CSRF protected.

Permissions (`mudhub_worldbuilder/web/permissions.py`, swappable with
`WORLDBUILDER_PERMISSION_MODULE`): Builder perm to view; editing needs the
user to be listed in `owners`/`builders` (when those lists are non-empty);
applying needs `owners` or a head builder (Developer perm). Only head builders
can change owners/builders. Note: saving rewrites the YAML files, so comments
in hand-written files are not preserved.

## Blueprints (phase 4)

Parameterised layout templates in `mudhub_worldbuilder/blueprints/*.yml` (more
folders via `WORLDBUILDER_BLUEPRINT_DIRS`). Built in: `small_castle` (floors 1-3,
towers 0-4, gatehouse with portcullis, optional locked cellar), `modern_apartment`
(bedrooms 1-4, storey, view city/river/park, lockable front door, balcony with a
kitchen window onto it), `sprawling_estate` (size small/medium/large: manor house
indoors plus walled grounds with lodge gates, stables, gardens, orchard, pond,
lake and deer park) and `hedge_labyrinth` (seeded W x H perfect maze, centre
fountain, background hedges, a `behavior: wander` gardener with a `region`).

Format: `parameters` (int with min/max, bool, choice, str; all with defaults),
`text` (per-option tables, e.g. `style: {granite: {stone: grey granite}}`),
`vars`, optional `generator: {hook: module.func}` (python returning rooms/links/
objects/mobiles/resets/vars), then area-format `rooms`, `links` (two-way exit
pairs), `objects`, `mobiles`, `resets` with LOCAL ids and relative xyz. Any list
item may carry `when: <expr>` and `each: {var: <list expr>}`; strings are
templates (`${expr}`, a small safe expression language, no attribute access or
arbitrary calls).

Stamping maps every local id to `<area>:<prefix>_<local>`, offsets xyz by the
origin, refuses explicit prefixes that collide (an automatic prefix is made
unique: `maze`, `maze2`, ...), warns about map-cell overlaps, records the stamp
in `area.yml` (`stamps:`) and saves the area as a draft. Nothing is applied.

```python
api.list_blueprints(); api.generate_blueprint(api.load_blueprint("hedge_labyrinth"), {"seed": 4})
new_spec, report = api.stamp_blueprint(spec, "small_castle", {"floors": 3}, (10, 0, 0),
                                       prefix=None, link="gate:north")
api.stamp_area_dir("world/areas/gardens", "hedge_labyrinth", {"width": 9}, (0, 0, 0))
```

Command: `@blueprint list | show <id> | stamp <id> into <area> at x,y,z
[param=value ...] [prefix=..] [link=<room>:<dir>]`. Web editor: "Stamp blueprint"
opens a dialog with the parameter form, a live mini-preview per level, origin
fields and "Pick on map" (a dashed ghost follows the pointer; red cells overlap
existing rooms). Mobile `behavior`/`region`/`home` are copied to attributes
(`behavior`, `region`, `home_room`) on apply; the runtime arrives in phase 5.

## Mobile behaviours and resets (phase 5)

Mobiles get a routine from their prototype; a reset entry may override it for
one spawn point (`behavior`, `behavior_params`, `region`, `home`):

```yaml
# mobiles.yml
- id: gardener
  key: old gardener
  behavior: wander            # idle | wander | patrol | schedule | tend | greeter | shopkeeper
  region: [maze_1, maze_2]    # room ids, "area" (default) or "tag:<tag>"
  home: maze_centre
  behavior_params: {every: 20, emotes: ["snips a stray sprig."], return_home: true}
- id: guard
  behavior: patrol
  behavior_params: {route: [gate, hall, tower], mode: pingpong}    # or loop
- id: cook
  behavior: schedule
  behavior_params: {entries: ["morning kitchen stirs the pot.", "12-14 hall serves lunch.", "night cellar sleeps."]}
- id: weeder
  behavior: tend
  behavior_params: {tag: flowerbed, tasks: ["pulls a weed."]}   # rooms with attrs: {tags: [flowerbed]}
# resets.yml
- {room: shop, prototype: keeper, max: 1, chance: 100, behavior: shopkeeper}
```

Movement never leaves the area and never passes a closed door, window or a
failing traverse lock. `@area behaviors` lists the registry with parameters
(the web editor builds its Mobiles form from it). Games add behaviours by
subclassing `mudhub_worldbuilder.behaviors.Behavior` and decorating it with
`@register_behavior`, or via `WORLDBUILDER_BEHAVIORS = {"name": "path.Class"}`
(modules in `WORLDBUILDER_BEHAVIOR_MODULES` are imported first).

Runtime: apply creates one ticker Script per area (`wb_tick_<area>`, every
`WORLDBUILDER_TICK_INTERVAL` = 5 s); it ticks every mobile in the area and
each behaviour paces itself with `every`. While no player is in the area the
behaviours sleep (`pause_when_empty: false` in area.yml to keep them going).
`runtime.tick_area(ns, rng=..., now=..., hour=...)` takes an injected rng and
clock for tests.

Resets: every `reset_interval` seconds (and on `@area reset <id>`) missing
reset instances are respawned up to `max`, rolling `chance`, with the same
`area_vnum` ids so sync stays idempotent. Rooms with players are skipped
(`reset_skip_occupied: false` to allow). `reset_doors: true` restores doors to
their file state on reset. `@area list` shows each area's reset status.

## World map, XYZGrid, wilderness and Mudlet (phase 6)

### world.yml

```yaml
areas:
  castle: {origin: [0, 0, 0]}      # area local xyz + origin = world xyz
  moors:  {origin: [-30, 4, 0]}
links:
  - id: castle-moors               # optional (default "<from>><dir>")
    from: castle:100
    dir: west
    to: moors:pass
    back_dir: east                 # default: opposite of dir; "" = one way
    kind: plain                    # plain | door | gate | curtain
    status: proposed               # proposed | approved
    proposed_by: alice             # written by the web UI
```

`api.load_world(root)`, `validate_world(world, specs)`, `plan_world(world)`,
`apply_world(world)` (in `mudhub_worldbuilder.world`). Only **approved** links
are built. Link exits are owned by the world layer (tags `wb_area=_world`,
`wb_kind=worldlink`, id `<room>><dir>`): applying an area never touches them,
applying the world never touches anything else, and area exports never contain
them. Applying is idempotent; unapproving or deleting a link removes its exits;
a link side whose room is not built, or whose room already has an area exit in
that direction, is skipped with a warning. Area ids starting with `_` are
reserved. (The phase 1 behaviour of folding world.yml links into area exits is
gone: `load_world_areas` just loads the areas.)

### World view (web)

`/worldbuilder/world/`: every area as a box on the world map (placed by its
origin, dashed while draft), room dots, links (amber dashed = proposed, green =
approved). Drag a box to move the area, then Save layout (writes origins).
Click a room dot and then another to fill the link form, or pick rooms from the
lists; Propose link needs edit rights on the source area. Approve / Unapprove
and Apply approved links are for head builders (Developer perm); an approved
link can only be removed by a head builder. Per-area download buttons: Mudlet
JSON and XYZGrid module per z level. API: `world/api/<action>/` with
`load | save_layout | add_link | remove_link | set_status | apply | mudlet |
xyz_export | xyz_import | terrain | terrain_save`.

### XYZGrid interop (`mudhub_worldbuilder.xyzgrid_interop`)

* `export_zlevel(spec, z)` returns the source of an XYZGrid map module
  (`MAP` string drawn from room coordinates, empty `LEGEND` = default symbols,
  `PROTOTYPES` per (X, Y) with `XYZRoom` typeclass, key, desc, details and
  `wb_source_id`, and `XYMAP_DATA`). Coordinates are shifted so the level
  starts at 0,0. One-cell compass exits become `- | / \ x`, one-way N/S/E/W
  become `^ v > <`; up/down, longer jumps and windows are reported as warnings.
* `import_map(module_or_dict, ns, z=0, zcoord=None)` parses a map with the
  contrib's own parser and returns rooms `<ns>:x<X>_y<Y>` with xyz `[X, Y, z]`
  (compatible with xyzgrid's `room_x/y/z_coordinate` tags), names, descs and
  exits; nodes that lead to other maps are reported. `merge_into_spec` adds them
  to an area (re-import updates the same ids) and records the zcoord name as the
  zlevel label. Web: `xyz_import` (head builder only, takes a module path).
* The contrib needs scipy. Without it `xyzgrid_status()` returns
  `(False, "XYZGrid interop is disabled: ...")`, both functions raise
  `XYZGridUnavailable`, and the web buttons are disabled with that message.

### Wilderness areas

```yaml
# area.yml
id: moors
type: wilderness
wilderness:
  rows: ["MMM=MMM", "M..=..M", "M~~=TTM"]  # first row = north edge, x = column
  start: [3, 1]
  brushes: {}            # optional overrides: {"T": {name, desc, passable, color}}
  landmarks:
    - {at: [3, 0], room: pass, dir: south, back: north, name: Mountain pass}
```

Brushes: `.` plains, `T` forest, `^` hills, `=` road, `M` mountains and `~`
water (not passable), blank = off the map. Landmarks are real rooms from
rooms.yml. Applying the area stores the terrain on the area record, creates
the contrib's `WildernessScript` (`wb_wild_<area>`) with a generated
`WorldbuilderMapProvider` (passability, location names, terrain descs) and an
exit `back` in each landmark room leading onto the grid. In the virtual room
at a landmark's cell an exit `dir` leads into the landmark room. Rooms stay
virtual: only terrain and landmarks are stored. Re-applying updates terrain
live. `wilderness.enter(obj, ns, coords=None)` puts something on the grid.
Link a landmark room to the rest of the world with a world link. Web: the
Terrain page (`/worldbuilder/area/<id>/terrain/`) paints with brushes, resizes
the grid, places landmarks and the start cell, and saves as draft. See
`sample_areas/moors`.

### Mudlet map export (`mudhub_worldbuilder.mudlet`)

`mudlet.export_json(specs, path=None, world=None, extra_links=())` writes the
JSON map format read by Mudlet's `loadJsonMap()` (4.11+). Field names follow
Mudlet's own writer (TMap/TArea/TRoom `writeJson*`): `formatVersion` 1.0,
`areaCount`, `roomCount`, `labelCount`, `defaultAreaName`,
`anonymousAreaName`, `areas[]` (`id`, `name`, `roomCount`, `rooms`, `userData`),
rooms (`id`, `name`, `coordinates` [x, y, z], `environment`, `exits` with
`name` + `exitId` and `door` open/closed/locked, `userData` with `wb_id`).
Standard directions use Mudlet's names, other exits become special exits,
windows are left out. A whole-world export adds area origins and approved
world links. Web: "Mudlet map (world)" and per-area buttons on the World view.

## Converting old area files (phase 7)

`mudhub_worldbuilder.convert` reads Diku-family area files and writes a draft
area folder. The reader knows what each field means for its engine, converts
the handful of datapoints that matter and keeps everything else verbatim.

| format | files | notes |
| --- | --- | --- |
| `rom` | ROM 2.4 / OLC `.are` (`#AREADATA` or `#AREA {lv} Author Title~`) | letter or numeric flags |
| `merc` | Merc 2.x `.are` | numeric flags, no race line |
| `smaug` | SMAUG / Dark Legacy `.are` (`#AUTHOR`, `#RANGES`, ...) | mudprogs set aside |
| `diku` | Diku/Circle `.wld .mob .obj .zon` (a folder or one of the files) | |
| `pbox-json` | pbox JSON area packages (`world/importers` output) | |

Mapping: room name/desc, sector -> `room_type` (+ `attrs.sector`), room flags
-> `attrs.tags`, exits with doors (`kind: door`, `noun`, `key_prototype` when
the key object is in the area), extra descriptions -> `details`, mobiles
(`m<vnum>`: key = short desc, aliases, desc, `attrs.room_desc/level/sex/race/
alignment`), objects (`o<vnum>`: `attrs.item_type/wear/weight/value/level`, no
`take` flag -> `get:false()`), resets M/O -> `resets.yml` (duplicates fold into
`max`), G/E/P -> `attrs.carries/wears/contains` (partial: spawning those needs a
game hook), D -> initial door state, area header -> `area.yml` (title, levels,
`source_vnums`, reset interval). Exits to vnums outside the file are set aside
and listed as decisions (make them world links).

Every area gets two extra files (ignored by `load_area`):

* `_unconverted.yml`: `[{key, where: "file:line", field, raw, status, reason}]`,
  the source text of everything not converted (stats, values, affects, progs,
  shops, specials, unknown flags, external exits, unusable resets).
* `_conversion.yml`: source format/path, md5 + sha256, converter + version,
  timestamps, licence signals, a summary and per field
  (`rooms/3001/name`, `mobiles/m3000/attrs.level`, `area//title`,
  `resets/*/list`) `{status: converted|partial|unconverted|ignored|human,
  version, hash}`.

Re-converting (`reconvert(area_dir)`, `@area reconvert <id>`, or converting the
same file into the same folder again) fills fields that are still unconverted,
upgrades fields written by an older converter version, and never touches a
field whose current value no longer matches the hash written at conversion
(human edit, kept and marked `human_edited`) or an entity a human deleted.

```python
from mudhub_worldbuilder import convert
res = convert.convert_area("old/midgaard.are", "world/areas/midgaard")  # fmt="auto"
print(convert.report_text(res))     # came across / set aside / needs a decision
convert.reconvert("world/areas/midgaard")
```

Licence metadata in `area.yml`: `authors[]`, `license` (SPDX, `LicenseRef-*`
or `unknown`), `source_codebase`, `origin` (stock | third-party | original |
clean-room | unverified), `credits`, `commercial_ok`. Well-known stock areas
(Midgaard, Limbo, Mud School, Moria, Thalos, ...) are fingerprinted by file
hash, file name, vnum range, title and stock header authors (two signals) and
marked `origin: stock` with the codebase licence (non-commercial); anything
else is `unverified` / `unknown`. `convert.can_publish_public(meta)` refuses
unknown licences, stock or unverified origins and `commercial_ok` other than
true; any public library publisher must call it. (General information, not
legal advice.)

Command: `@area convert <path> [--format auto|rom|merc|smaug|diku|pbox-json]
[--as <id>]` (relative paths are read from `WORLDBUILDER_IMPORT_DIR`, default
`<areas>/_import`; absolute paths need Developer) and `@area reconvert <id>`.
Web: `/worldbuilder/import/` ("Import area file" on the area list) uploads one
file (or the Circle file set), converts it as a draft and shows the report.
Re-uploading into an existing converted area re-converts it (edit rights
needed); an existing hand-made area id is refused.

## Development

`devgame/` is a throwaway Evennia game (ports 4800-4804, localhost only) used
only for tests. `./tests/run.sh` runs `tests/test_*.py` (engine, play, web, blueprints, behaviors, world, convert) against its sqlite DB
(first time: `cd devgame && evennia migrate`). The XYZGrid tests need scipy:
without it they test the disabled path; `WB_TEST_PYDEPS=/dir/with/numpy+scipy`
adds such a folder to `sys.path` for the real interop tests.

License: BSD-3-Clause.
