diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index c5eec28..5973c6e 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -79,7 +79,7 @@ The following is the public MCP tool surface; the companion may perform several | `set_verbose` | `on` | | `log_marker` | `text` | | `paint_material` | `points`, `asset`, `size`, `layer`, `smooth`, `erase` | -| `set_trace_image` | `path`, `scale`, `opacity`, `center`, `clear` | +| `set_trace_image` | `path`, `scale`, `opacity`, `center`, `position`, `clear` | | `get_map_style` | — | | `set_map_style` | `building_wear`, `grid_style` | | `set_water_style` | `deep_color`, `shallow_color`, `blend_distance`, `border` | diff --git a/mod/battlemap-mcp-bridge/scripts/tools/mcp_bridge.gd b/mod/battlemap-mcp-bridge/scripts/tools/mcp_bridge.gd index 03ae2ad..df44635 100644 --- a/mod/battlemap-mcp-bridge/scripts/tools/mcp_bridge.gd +++ b/mod/battlemap-mcp-bridge/scripts/tools/mcp_bridge.gd @@ -1593,9 +1593,23 @@ func _set_trace_image(req : Dictionary) -> Dictionary: if bool(req.get("center", false)) and trace.has_method("Center"): trace.Center() applied["centered"] = true + # Where the image's centre sits, set rather than nudged, so a retried call + # lands in the same place. Dungeondraft saves it with the map. + if req.has("position"): + var at = req["position"] + if typeof(at) != TYPE_ARRAY or at.size() != 2: + _release_tool(trace, was_active) + return _err("'position' must be [x, y] in woxels") + var moved = Global.World.get("TraceImage") + if moved == null or not is_instance_valid(moved) or not (moved is Node2D) \ + or moved.get("texture") == null: + _release_tool(trace, was_active) + return _err("no trace image to position; load one with path first") + moved.position = Vector2(float(at[0]), float(at[1])) + applied["positioned"] = true _release_tool(trace, was_active) if applied.empty(): - return _err("give at least one of path, scale, opacity, center or clear") + return _err("give at least one of path, scale, opacity, center, position or clear") # Read back what is drawn, not what was asked: the Sprite, not the flag. var sprite = Global.World.get("TraceImage") var drawn := false @@ -1604,6 +1618,7 @@ func _set_trace_image(req : Dictionary) -> Dictionary: drawn = sprite.is_visible_in_tree() and sprite.texture != null if sprite.texture != null: size = [sprite.texture.get_width(), sprite.texture.get_height()] + applied["position"] = _vec(sprite.position) applied["visible"] = drawn applied["image_size"] = size return _ok(applied) diff --git a/server/battlemap_mcp/server.py b/server/battlemap_mcp/server.py index 80c15d6..ff06a5c 100644 --- a/server/battlemap_mcp/server.py +++ b/server/battlemap_mcp/server.py @@ -17,6 +17,7 @@ import io import json import logging +import math import os import random import re @@ -3353,6 +3354,7 @@ def set_trace_image( opacity: float | None = None, center: bool = False, clear: bool = False, + position: list[float] | None = None, ) -> dict: """Put a reference image under the map to trace over. Returns what applied. @@ -3368,6 +3370,12 @@ def set_trace_image( without drowning what you are drawing. center: centre the image on the map. clear: remove the trace image. + position: [x, y] in woxels (256 per grid square): where the image's + centre sits, applied after center and scale. Centre it, read the reply's + `position`, then set a position that puts a grid line drawn on the image + on a map grid line. It sets rather than nudges, so repeating the call is + harmless. A later center moves the image back to the map's centre and + discards it. Loading an image shows it and clear hides it. `visible` says whether it is drawn now and `image_size` is null if the image did not load. Exports never @@ -3386,6 +3394,10 @@ def set_trace_image( raise ValidationError(f"opacity must be between 0 and 1, got {opacity}") if scale is not None: require_positive(scale, "scale") + if position is not None and ( + len(position) != 2 or not all(math.isfinite(float(v)) for v in position) + ): + raise ValidationError(f"position must be [x, y], two finite woxel values, got {position}") params: dict = {} copied_from = None if path: @@ -3398,8 +3410,12 @@ def set_trace_image( params["center"] = True if clear: params["clear"] = True + if position is not None: + params["position"] = [float(v) for v in position] if not params: - raise ValidationError("give at least one of path, scale, opacity, center or clear") + raise ValidationError( + "give at least one of path, scale, opacity, center, position or clear" + ) result = bridge.request("set_trace_image", **params) if copied_from is not None: result["copied_from"] = copied_from diff --git a/server/tests/test_trace_position.py b/server/tests/test_trace_position.py new file mode 100644 index 0000000..adcc152 --- /dev/null +++ b/server/tests/test_trace_position.py @@ -0,0 +1,75 @@ +"""set_trace_image position: put the trace image where its grid lines up.""" + +from __future__ import annotations + +import math + +import pytest + +from battlemap_mcp import server +from battlemap_mcp.errors import ValidationError + + +@pytest.fixture +def sent(monkeypatch): + calls: list[tuple[str, dict]] = [] + + def request(command, **params): + calls.append((command, params)) + return {"position": params.get("position", [0, 0])} + + monkeypatch.setattr(server.bridge, "request", request) + return calls + + +def trace_params(sent): + [(command, params)] = sent + assert command == "set_trace_image" + return params + + +def test_position_is_sent_in_woxels(sent): + server.set_trace_image(position=[1953.3, 2114.6]) + assert trace_params(sent)["position"] == [1953.3, 2114.6] + + +# Models retry calls: a position, unlike a relative offset, lands in the same +# place however many times it is sent. +def test_repeating_a_position_sends_the_same_request(sent): + server.set_trace_image(position=[100.0, 200.0]) + server.set_trace_image(position=[100.0, 200.0]) + assert sent[0] == sent[1] + + +def test_position_omitted_when_not_given(sent): + server.set_trace_image(scale=2.0) + assert "position" not in trace_params(sent) + + +def test_position_alone_is_accepted(sent): + server.set_trace_image(position=[10.0, 20.0]) + assert trace_params(sent) == {"position": [10.0, 20.0]} + + +def test_position_goes_with_center_in_one_call(sent): + server.set_trace_image(center=True, position=[10.0, 20.0]) + assert trace_params(sent) == {"center": True, "position": [10.0, 20.0]} + + +@pytest.mark.parametrize("bad", [[math.nan, 0.0], [0.0, math.inf]]) +def test_position_must_be_finite(sent, bad): + with pytest.raises(ValidationError, match="position"): + server.set_trace_image(position=bad) + assert sent == [] + + +@pytest.mark.parametrize("bad", [[1.0], [1.0, 2.0, 3.0]]) +def test_position_needs_two_numbers(sent, bad): + with pytest.raises(ValidationError, match="position"): + server.set_trace_image(position=bad) + assert sent == [] + + +def test_relative_offsets_are_gone(): + with pytest.raises(TypeError): + server.set_trace_image(offset_x=10.0) # type: ignore[call-arg] diff --git a/server/tools/uat.py b/server/tools/uat.py index a4d0282..d78ae1c 100644 --- a/server/tools/uat.py +++ b/server/tools/uat.py @@ -3148,6 +3148,57 @@ def preview_unincluded_pack(): u.check("assets: a pack the map lacks previews but does not place", preview_unincluded_pack) +@group("trace_image") +def trace_image(u: Uat) -> None: + """The trace image goes where it is put, stays there on a retry, and saves.""" + import tempfile + + from PIL import Image + + def position_is_set_and_saved(): + st = u.c.request("get_status") + map_file = st.get("map_file") + if not map_file: + return "skipped: the map has never been saved, so it cannot be reopened" + target = [u.cx + 300.0, u.cy - 200.0] + with tempfile.TemporaryDirectory() as folder: + sketch = pathlib.Path(folder) / "uat-trace.png" + Image.new("RGB", (512, 512), (200, 200, 200)).save(sketch) + u.c.request("set_trace_image", path=str(sketch), center=True) + try: + first = u.c.request("set_trace_image", position=target) + again = u.c.request("set_trace_image", position=target) + assert first["position"] == target, f"placed at {first['position']}" + assert again["position"] == target, f"a retry moved it to {again['position']}" + centred = u.c.request("set_trace_image", center=True) + assert centred["position"] == st["map_center"], centred + u.c.request("set_trace_image", position=target) + u.c.request("save_map") + time.sleep(1.0) + assert u.wait_for_save(), "save did not finish" + u.c.request("open_map", path=map_file) + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + time.sleep(0.5) + try: + now = u.c.request("get_status") + except Exception: + continue + if now.get("map_open") and now.get("undo_depth") == 0: + break + back = u.c.request("set_trace_image", opacity=0.5) + assert back["position"] == target, f"reopened at {back['position']}" + finally: + u.c.request("set_trace_image", clear=True) + return f"at {target} after a retry and after save and reopen; center resets it" + + u.check( + "trace_image: position is set, safe to repeat, and survives save and reopen", + position_is_set_and_saved, + needs_dirty=True, + ) + + @group("lights") def lights(u: Uat) -> None: """A light with its object, a batch of lights, and light edits: one undo step each."""