Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions backend/app/api/v1/lego_assembly.py
Original file line number Diff line number Diff line change
Expand Up @@ -1324,9 +1324,22 @@ def _public_realm_recipe_for_zone(
validate_street_plan_centerline_wgs84(
source_geometry,
properties.get("plan_centerline"),
properties=properties,
)
)
if not centerline_is_valid:
from app.services.native_modular_bridge import is_modular_bridge

if is_modular_bridge(properties):
raise HTTPException(
status_code=422,
detail={
"code": "invalid_plan_centerline",
"message": "Keep the bridge footprint aligned with its current supported two-endpoint route.",
"zone_id": str(zone.id),
"kind": kind,
},
)
recovered_centerline = recover_street_plan_centerline_wgs84(source_geometry)
if recovered_centerline and validate_street_plan_centerline_wgs84(
source_geometry,
Expand Down
12 changes: 11 additions & 1 deletion backend/app/data/project_detail_models.json
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,16 @@
"detail-yyc-district-barrier-seventeenth-ave",
"detail-yyc-district-barrier-seventeenth-ave-single",
"detail-yyc-city-ghost-barrier",
"detail-yyc-city-ghost-barrier-pink"
"detail-yyc-city-ghost-barrier-pink",
"detail-yyc-scooter-corral-plain",
"detail-yyc-scooter-corral-foothills",
"detail-yyc-scooter-corral-chinook",
"detail-yyc-scooter-corral-river",
"detail-yyc-scooter-corral-mosaic",
"detail-yyc-scooter-corral-chevron",
"detail-yyc-scooter-corral-quilt",
"detail-yyc-scooter-corral-aspen",
"detail-yyc-scooter-corral-confetti",
"detail-yyc-scooter-corral-bird-lime"
]
}
1 change: 1 addition & 0 deletions backend/app/schemas/direct_3d_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"photomontage",
"development",
"atmospheric",
"movie-still",
"after-rain",
"autumn",
"winter",
Expand Down
2 changes: 2 additions & 0 deletions backend/app/services/direct_3d_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -3217,6 +3217,7 @@ def assess_reproject_output_sanity(
"photomontage": "a polished architectural photomontage integrated seamlessly into the photographed city",
"development": "a completed-development visualization with crisp facades, credible roofs and public realm",
"atmospheric": "warm atmospheric architectural photography with soft haze, directional light and planted depth",
"movie-still": "a live-action film still with believable light, gentle highlight roll-off and fine film grain",
"after-rain": "architectural photography after a shower, with diffuse daylight, damp paving and small broken reflections",
"autumn": "architectural photography in early autumn, with low sunlight and varied gold, copper and green deciduous foliage",
"winter": "convincing winter architectural photography with seasonal vegetation, snow and cold daylight",
Expand Down Expand Up @@ -3352,6 +3353,7 @@ def _presentation_prompt(
"photomontage",
"development",
"atmospheric",
"movie-still",
"after-rain",
"autumn",
"winter",
Expand Down
39 changes: 35 additions & 4 deletions backend/app/services/native_bridge_clearance.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,42 @@
_AREA_TOLERANCE_M2 = 1e-6


def validate_modular_bridge_footprint(geometry, properties):
"""Match a source bridge to its authored axis, even when width > span.

Generic road principal-axis recovery is not valid for these wide stair and
approach reservations. Retain the same 10 cm corridor tolerance as clearance.
"""
validate_specialist_properties(properties)
if not isinstance(geometry, Polygon) or geometry.is_empty or not geometry.is_valid or geometry.interiors:
raise ValueError("Keep a complete valid modular bridge footprint.")
profile = modular_bridge_profile(properties["road_selected_variant_id"])
route = properties["plan_centerline"]
if not isinstance(route, list):
raise ValueError("Modular bridge clearance requires its explicit saved two-endpoint coordinate array.")
origin = route[0]
sx = 111320 * math.cos(math.radians(origin[1]))

def local(point):
return ((point[0] - origin[0]) * sx, (point[1] - origin[1]) * 111320)

dx, dy = local(route[-1])
length = math.hypot(dx, dy)
ux, uy = dx / length, dy / length
half = profile["widthM"] / 2
occupied = Polygon(
[
(ux * along - uy * across, uy * along + ux * across)
for along, across in ((0, -half), (length, -half), (length, half), (0, half))
]
)
footprint = Polygon([local(point) for point in geometry.exterior.coords])
if not occupied.buffer(0.1).covers(footprint) or not footprint.buffer(0.1).covers(occupied):
raise ValueError("Keep the modular bridge footprint aligned with its current saved two-endpoint route.")


def _validate_bridge_pair(bridge_coordinates, bridge_properties, other_coordinates, other_properties):
validate_specialist_properties(bridge_properties)
validate_modular_bridge_footprint(Polygon(bridge_coordinates), bridge_properties)
profile = modular_bridge_profile(bridge_properties["road_selected_variant_id"])
route = bridge_properties["plan_centerline"]
if not isinstance(route, list):
Expand All @@ -41,9 +75,6 @@ def corridor(start, end):
)

occupied = corridor(0, length)
footprint = Polygon([local(point) for point in bridge_coordinates])
if not occupied.buffer(0.1).covers(footprint) or not footprint.buffer(0.1).covers(occupied):
raise ValueError("Keep the modular bridge footprint aligned with its current saved two-endpoint route.")
other = Polygon([local(point) for point in other_coordinates])
overlap = occupied.intersection(other)
if overlap.area <= _AREA_TOLERANCE_M2:
Expand Down
16 changes: 16 additions & 0 deletions backend/app/services/plan_geometry/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,8 @@ def recover_street_plan_centerline_wgs84(
def validate_street_plan_centerline_wgs84(
zone_wgs84: BaseGeometry,
value: Any,
*,
properties: dict[str, Any] | None = None,
) -> bool:
"""Whether saved centreline metadata still describes this street polygon.

Expand Down Expand Up @@ -421,6 +423,20 @@ def validate_street_plan_centerline_wgs84(
return False
coordinates.append((longitude, latitude))

# Source bridge reservations can be wider than their shortest valid span.
# Their exact two-point programme and full footprint, not the polygon's
# longest edge, define the travel axis. Ordinary road recovery stays strict.
from app.services.native_modular_bridge import is_modular_bridge

if is_modular_bridge(properties):
from app.services.native_bridge_clearance import validate_modular_bridge_footprint

try:
validate_modular_bridge_footprint(zone_wgs84, {**properties, "plan_centerline": value})
except (ValueError, TypeError, KeyError):
return False
return True

try:
centerline_wgs84 = LineString(coordinates)
except (TypeError, ValueError):
Expand Down
11 changes: 6 additions & 5 deletions backend/app/services/public_realm_lego.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
project_geometry,
)


PUBLIC_REALM_RECIPE_PROPERTY = "public_realm_lego"
PUBLIC_REALM_FALLBACK_PROPERTY = "public_realm_fallback"
PUBLIC_REALM_SCHEMA_VERSION = 1
Expand Down Expand Up @@ -2769,17 +2768,19 @@ def plan_public_realm_zone_recipe(
if is_street and props.get("plan_centerline") is not None:
from app.services.plan_geometry.generator import validate_street_plan_centerline_wgs84

if validate_street_plan_centerline_wgs84(geometry_wgs84, props["plan_centerline"]):
if validate_street_plan_centerline_wgs84(geometry_wgs84, props["plan_centerline"], properties=props):
centerline_metric = project_geometry(LineString(props["plan_centerline"]), transformer)
if is_modular_bridge(props):
from app.services.native_modular_bridge import modular_bridge_route_length

width = props["width"]
if centerline_metric is None:
raise ValueError("Modular bridge needs its current two-endpoint route inside the occupied footprint.")
ribbon = centerline_metric.buffer(width / 2, cap_style=2, join_style=2)
if not ribbon.buffer(0.1).covers(metric_geometry) or not metric_geometry.buffer(0.1).covers(ribbon):
raise ValueError("Keep the complete modular bridge footprint at its native width and route length.")
from app.services.native_bridge_clearance import validate_modular_bridge_footprint

# Match the source bridge's authored metric frame for both length and
# occupied width. UTM reprojection can shift a wide ring's edge >10 cm.
validate_modular_bridge_footprint(geometry_wgs84, props)
target = StreetSegmentTarget(
row_width_m=width, length_m=round(modular_bridge_route_length(props["plan_centerline"]), 3)
)
Expand Down
89 changes: 89 additions & 0 deletions backend/tests/test_bridge_drawn_centerline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""A source bridge's valid span may be shorter than its occupied width."""

import copy
import math
import uuid

import pytest
from fastapi import HTTPException
from geoalchemy2.shape import from_shape
from shapely.geometry import Polygon

from app.api.v1.lego_assembly import _public_realm_recipe_for_zone
from app.models.models import SiteZone
from app.services.native_modular_bridge import MODULAR_BRIDGE_IDENTITIES, modular_bridge_profile
from app.services.native_source_bridge import SOURCE_BRIDGE_LANES
from app.services.plan_geometry.generator import validate_street_plan_centerline_wgs84


def source(length=None, angle=0, variant="weathering_steel_v_footbridge_route_v1"):
profile = modular_bridge_profile(variant)
length = length or profile["program"]["minLengthM"] + 0.001
width = profile["widthM"]
sx = 111320 * math.cos(math.radians(51))

def point(along, across=0):
return [
-114 + (along * math.cos(angle) - across * math.sin(angle)) / sx,
51 + (along * math.sin(angle) + across * math.cos(angle)) / 111320,
]

polygon = Polygon([point(0, -width / 2), point(length, -width / 2), point(length, width / 2), point(0, width / 2)])
props = {
"road_selected_variant_id": variant,
"road_archetype_id": profile["sourceArchetypeId"],
"width": width,
"lane_count": SOURCE_BRIDGE_LANES.get(variant, 0),
"plan_centerline": [point(0), point(length)],
"plan_route_controls": [point(0), point(length)],
}
return polygon, props


@pytest.mark.parametrize("angle", [0, 0.7, math.pi / 2, math.pi])
def test_native_bridge_compiler_preserves_a_valid_shorter_than_width_authored_span(angle):
polygon, props = source(angle=angle)
before = copy.deepcopy(props)
zone = SiteZone(id=uuid.uuid4(), zone_type="road", geometry=from_shape(polygon, srid=4326), properties=props)
recipe = _public_realm_recipe_for_zone(zone, "street")
assert recipe["variant_id"] == props["road_selected_variant_id"]
assert recipe["target"]["row_width_m"] == 52
assert recipe["target"]["length_m"] == pytest.approx(48.987, abs=0.002)
assert zone.properties == before


@pytest.mark.parametrize("damage", ["shift", "width", "length", "bend", "missing", "nonfinite"])
def test_native_bridge_centerline_dispatch_rejects_stale_or_forged_geometry(damage):
polygon, props = source()
if damage == "shift":
props["plan_centerline"] = [[x + 0.0001, y] for x, y in props["plan_centerline"]]
elif damage == "width":
props["width"] = 51
elif damage == "length":
props["plan_centerline"][1][0] += 0.001
elif damage == "bend":
props["plan_centerline"].insert(1, [-114.0001, 51.0001])
elif damage == "missing":
props.pop("plan_centerline")
else:
props["plan_centerline"][0][0] = math.nan
assert not validate_street_plan_centerline_wgs84(polygon, props.get("plan_centerline"), properties=props)
zone = SiteZone(id=uuid.uuid4(), zone_type="road", geometry=from_shape(polygon, srid=4326), properties=props)
with pytest.raises(HTTPException) as exc:
_public_realm_recipe_for_zone(zone, "street")
assert exc.value.status_code == 422
assert "public_realm_lego" not in zone.properties


@pytest.mark.parametrize("variant", list(MODULAR_BRIDGE_IDENTITIES))
@pytest.mark.parametrize("bound", ["minLengthM", "maxLengthM"])
@pytest.mark.parametrize("angle", [0, 0.7, math.pi / 2, math.pi])
def test_bridge_minimum_and_maximum_spans_compile_in_the_authored_metric_frame(variant, bound, angle):
program = modular_bridge_profile(variant)["program"]
length = program[bound] + (0.001 if bound == "minLengthM" else -0.001)
polygon, props = source(length=length, angle=angle, variant=variant)
zone = SiteZone(id=uuid.uuid4(), zone_type="road", geometry=from_shape(polygon, srid=4326), properties=props)
recipe = _public_realm_recipe_for_zone(zone, "street")
assert recipe["variant_id"] == variant
assert recipe["target"]["length_m"] == pytest.approx(length, abs=0.001)
assert zone.properties["plan_centerline"] == props["plan_centerline"]
8 changes: 6 additions & 2 deletions backend/tests/test_direct_3d_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -2355,9 +2355,13 @@ def test_provider_first_prompts_use_one_concise_natural_design_lock():
@pytest.mark.parametrize("view_mode", ["aerial", "street"])
@pytest.mark.parametrize(
("style", "treatment"),
[("after-rain", "broken reflections"), ("autumn", "deciduous foliage")],
[
("movie-still", "gentle highlight roll-off"),
("after-rain", "broken reflections"),
("autumn", "deciduous foliage"),
],
)
def test_seasonal_presentation_keeps_the_source_camera(style, treatment, view_mode):
def test_photographic_preset_keeps_the_source_camera(style, treatment, view_mode):
request = _request(presentation_mode="scene", style=style, fidelity_policy="balanced")
prompt = _presentation_prompt(
"",
Expand Down
6 changes: 3 additions & 3 deletions backend/tests/test_project_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,15 +434,15 @@ async def test_claude_detail_packs_save_reload_and_preserve_legacy_details(monke
root = Path(__file__).resolve().parents[2]
choices = json.loads((root / "frontend/src/features/parks/detailCatalogueExtras.json").read_text(encoding="utf-8"))
choices = [c for c in choices if c.get("sourceKit") in {"calgary-details-v1", "prairie-foliage-v1"}]
assert len(choices) == 240
assert len(choices) == 250
placements = {"trees": [], "props": []}
for choice in choices:
field = "trees" if choice["kind"] == "tree" else "props"
placements[field].append(
{"id": choice["id"], "lng": -114.1, "lat": 51.05, "angle": 45, "variant": choice["id"]}
)
assert len(placements["trees"]) == 50
assert len(placements["props"]) == 190
assert len(placements["props"]) == 200
monkeypatch.setattr(endpoint, "check_project_permission", AsyncMock(return_value="editor"))
db, row = session({"other": {"keep": True}})
project_id = uuid.uuid4()
Expand All @@ -468,7 +468,7 @@ def test_expanded_catalogue_accepts_existing_kit_parts_and_matches_frontend():

root = Path(__file__).resolve().parents[2]
choices = json.loads((root / "frontend/src/features/parks/detailCatalogueExtras.json").read_text())
assert len(choices) == 395
assert len(choices) == 405
choices += json.loads((root / "frontend/src/features/parks/recoveredDetails.json").read_text())
choices += json.loads((root / "frontend/src/features/parks/trafficSafetyCatalogue.json").read_text())
# Local preview IDs must round-trip before their public picker gate is lifted.
Expand Down
Loading