Files
orisys-app/shared/tests/test_scene3d_contracts.py
T
ykcheungab ef487098c9 feat(studio-3d): 限速、真实耗时统计、无位移复用资产几何,以及保护包密钥注入(阶段 9 上半)
- What:
  1. **显示限速真的生效**(R5):`ThreeDCoordinator.tick()` 用注入的单调时钟与
     `display_period_s() = 1/max_fps` 限制**合成启动**频率(窗口定时器仍是 16 ms,但"显示帧率"是给操作者的
     承诺,不是定时器的描述);声明边界(activate/begin_session/show_rest/隐藏)把预算清零,所以按下开始后的
     第一帧立刻合成。生产者侧改为**按需**跳过:`Scene3DView.submit_packet()` 在
     `coordinator.has_pending_frame()`(mailbox 里已有一帧等待)时不再构造快照——那是 O(H×W) 的拷贝,
     而 mailbox 只保留最新一帧,两次拷贝里必然丢一个;被跳过的数量计入新的 `skipped_producer`,
     与"显示跳帧"分开。**不丢任何本该显示的帧**(等待中的那一帧仍在)。
  2. **真实统计**:`RenderFrame.compose_ms`(composer 在构造帧之前测量并写入,不再读会被下一任务改写的
     `last_stats`);`GLRenderer` 的绘制计数改名为 `paint_calls`,`RenderStats.displayed_frames` 由
     **widget 按帧身份**统计(相机旋转/色标改动只是重画,不再是"多显示了一帧");`render_totals()` 增
     `compose_ms`/`latency_ms`(合成开始→被接受的单调耗时)/`paint_calls`/`skipped_producer`,并且
     `shown`/`compose_ms` 改从 widget 读(无 GL 的机器也能报告,之前只有画过才有数)。
  3. **无位移时复用资产几何**(R5 建议):`SceneComposer` 缓存 `asset_hash → (positions, normals)`;
     变形时照旧从形变后的位置重算法线,不变形时直接用资产自己的(只读、零拷贝)数组。20k 顶点实测:
     compose p50 **6.15 ms → 1.03 ms**(法线段 4.9 ms → 0.0001 ms,剩余是采样 1.01 ms);
     真实发布包(1032 顶点)compose p50 **0.50 ms → 0.17 ms**。
  4. **保护包密钥注入**(R4):新增 `scene3d/keys.py`——从 preference 读取
     `scene3d_verify_key`(验签公钥 PEM)/`scene3d_content_key_file` + `scene3d_content_key_id`
     (内容密钥,经 `protect.load_key_file`)/`scene3d_require_signature`(发布模式,拒绝无签名包),
     组装成 `SceneKeys` 交给 `SceneAssetLoader` → `load_package` → `PackagedAssetLoader.load(keys=…,
     verify_key_pem=…)`;`AppWindow._sync_3d_source()` 解析它并 `Mesh3dPanel.set_keys()`。
     缺失/不可读的密钥是**状态而不是崩溃**(`describe()` 里带原因),密钥材料永不进日志;
     `Mesh3dPanel.describe()` 的 scene 块记录 `keys`(布尔 + 路径)。
- Why: 审查报告 R5(`max_fps` 只被存储与显示、`draw()` 硬编码 `compose_ms=0.0`、`_displayed_frames` 把
  重画也算新帧、`SceneComposer.last_stats` 被显示链路完全未读)与 R4(底层支持签名/加密包,Studio 加载
  入口却从不传验签公钥与 KeyProvider,合法保护包打不开,只能发明文包或关掉校验)。R5 的另一半是
  "当前只有曲面着色、没有 displacement 时,composer 仍每帧重算法线并重新打包位置"——缓存后 20k 顶点
  降低到六分之一。
- Verification:
  · `test_scene3d_coordinator.py` +6:15 fps 的假时钟下 1.32 s 内只启动约 20 次合成(60 fps 对照 ≥55 次)、
  `display_period_s()` 跟随设置、结果延迟是真实单调差值、`has_pending_frame()` 随 mailbox 变化;
  `test_scene3d_live.py` +3:无位移时发布帧直接**就是**资产自己的(只读)数组、force_deform 但仍无位移时
  给出 `field_unavailable` 诊断、有标定位移时仍重算、`compose_ms` 属于该帧且不被下一次合成改写;
  `test_scene3d_view.py` +2:等待中的帧让生产者跳过第二个快照且取出后立即恢复、`render_totals()` 的
  compose 成本与延迟是真实值;新增 `test_scene3d_protected_package.py` 7 项:Studio 入口打开签名包、
  用 preference 里的内容密钥打开加密包、缺验签公钥 → `asset_auth_failed`、密钥文件缺失/无 key id →
  状态而非崩溃、发布模式拒绝无签名包而开发模式接受、`SceneAssetLoader` 把密钥交给 worker、面板携带密钥。
  · 全量:shared+apps 同一次运行 **588 项 0 失败 15 跳过**;真 GL 冒烟(`QT_QPA_PLATFORM=windows`)
  **14 项 0 失败**;ui_check 587 项 0 失败;locale_check 0 缺失。
  · 顺带修掉两个**既有的顺序依赖**真 GL 用例(不是本次引入:在上一提交上单跑同样失败):
  `test_the_producer_side_never_waits_for_the_gpu` 的收尾没有排空 mailbox(留下的一帧会被下一个测试
  上传),`test_an_automatic_colour_scale_follows_the_frame` 在渲染之前就断言"范围来自本帧",
  且用"不同颜色数"当自动量程的代理(对可见面积敏感)。现在前者排空并断言排空完成,后者先渲染再断言,
  判据改为**平均亮度**(固定 0..1000 把 3..7 压进 LUT 最暗的一小段,自动量程铺满整条色带)。
  · 性能报告(`.repro/perf-cpu-*-after-9.json`,`bench_scene.py --cpu-only`):合成 p50
  合成 poc 0.016 ms / 20k 顶点 1.03 ms / 真实包 0.17 ms;对比已提交的 `perf-report-windows-dev.json`
  (20k 6.15 ms、真实包 0.50 ms)。
- Not in this change: **画布布局第二批**(2D/3D 页签容器、参数抽屉、窄窗口回退、诊断抽屉)与曲线量程开关
  仍未做;阶段 9 的门禁部分(`soak_scene.py --minutes 120` GUI 模式、Jetson Orin Nano 与 QCS6490 上的
  `probe_gl/bench_scene/soak_scene` 报告)需要长时间运行与板卡,本轮未跑,结论不写"通过";
  签名私钥仍只在构建机(本提交只引入"读"的一半)。
2026-09-14 21:52:02 +08:00

540 lines
21 KiB
Python

"""The three-dimensional contracts, enforced without a GPU.
The skeleton's value is that the interfaces are executable: these tests are the
acceptance for the contract layer itself (stage 0 in
``docs/architecture/studio-3d-stages.md``). They run in the normal CPU test
environment — no Qt, no OpenGL, no camera — because the layer is what the
acquisition and worker threads will share.
"""
from __future__ import annotations
import sys
import threading
from pathlib import Path
import numpy as np
import pytest
from orisys_app_shared.scene3d import contracts as c
def _frame(**overrides):
scalar = np.zeros((3, 4), dtype=np.float32)
valid = np.ones((3, 4), dtype=bool)
frame = dict(
identity=c.FrameIdentity("live-1", 1, 7, 0.25, generation=1),
geometry_id="geom-abc",
field_domain_id="domain-xyz",
scalar=c.freeze(scalar, dtype=np.float32),
scalar_descriptor=c.FieldDescriptor("flow_magnitude", "px", "approximate", False),
valid=c.freeze(valid, dtype=np.bool_),
)
frame.update(overrides)
return c.SurfaceFieldFrame(**frame)
def _binding(vertices: int = 4):
indices = np.array(
[[0, 1, 5, 6], [1, 2, 6, 7], [4, 5, 9, 10], [5, 6, 10, 11]], dtype=np.int32
)[:vertices]
weights = np.full((vertices, 4), 0.25, dtype=np.float32)
return c.SurfaceBinding(
part_id="sensing_surface",
geometry_id="geom-abc",
field_domain_id="domain-xyz",
shape_hw=(3, 4),
sample_indices=c.freeze(indices, dtype=np.int32),
sample_weights=c.freeze(weights, dtype=np.float32),
)
def _part(role: str = "sensing", part_id: str = "sensing_surface", vertices: int = 4):
positions = np.zeros((vertices, 3), dtype=np.float32)
positions[:, 0] = np.arange(vertices, dtype=np.float32)
normals = np.tile(np.array([0.0, 0.0, 1.0], dtype=np.float32), (vertices, 1))
triangles = np.array([[0, 1, 2], [1, 2, 3]], dtype=np.uint32) if vertices >= 4 else np.zeros((0, 3), dtype=np.uint32)
return c.MeshPart(
part_id=part_id,
role=role,
positions_sensor_m=c.freeze(positions, dtype=np.float32),
normals_sensor=c.freeze(normals, dtype=np.float32),
triangles=c.freeze(triangles, dtype=np.uint32),
material=c.Material((0.5, 0.5, 0.5, 1.0), "diffuse", False),
)
def _assets(**overrides):
values = dict(
asset_id="finger-display",
asset_version="1.0.0",
asset_hash="hash",
geometry_id="geom-abc",
parts=(_part(),),
binding=_binding(),
camera_presets=(
c.CameraPreset("default", (0.0, -0.2, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 1.0), 0.7),
),
bounds_sensor_m=c.freeze(
np.array([[0.0, 0.0, 0.0], [1.0, 1.0, 0.0]], dtype=np.float32), dtype=np.float32
),
field_domain_id="domain-xyz",
shape_hw=(3, 4),
)
values.update(overrides)
return c.SceneAssets(**values)
# ------------------------------------------------------------------- freezing
def test_freeze_takes_ownership_and_locks_the_array():
"""A frozen dataclass does not freeze its arrays; freeze() has to."""
source = np.zeros((2, 2), dtype=np.float64)
frozen = c.freeze(source, dtype=np.float32)
assert frozen.dtype == np.float32
assert frozen.flags["C_CONTIGUOUS"]
assert not frozen.flags["WRITEABLE"]
with pytest.raises(ValueError):
frozen[0, 0] = 1.0
source[0, 0] = 5.0
assert frozen[0, 0] == 0.0, "the published array still shares the source buffer"
def test_a_writable_or_strided_array_is_refused():
writable = np.zeros((3, 4), dtype=np.float32)
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_surface_frame(_frame(scalar=writable))
assert excinfo.value.diagnostic.code == "field_domain_mismatch"
# Read-only but not contiguous: the second half of the same rule.
buffer = np.zeros((3, 8), dtype=np.float32)
strided = buffer[:, ::2]
strided.setflags(write=False)
assert not strided.flags["C_CONTIGUOUS"] and not strided.flags["WRITEABLE"]
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_surface_frame(_frame(scalar=strided))
assert "C-contiguous" in excinfo.value.diagnostic.message
# ---------------------------------------------------------------------- frame
def test_a_well_formed_frame_validates():
assert c.validate_surface_frame(_frame()) == ()
def test_a_frame_must_name_its_geometry_and_domain():
with pytest.raises(c.ThreeDError) as geometry:
c.validate_surface_frame(_frame(geometry_id=" "))
assert geometry.value.diagnostic.code == "geometry_mismatch"
with pytest.raises(c.ThreeDError) as domain:
c.validate_surface_frame(_frame(field_domain_id=""))
assert domain.value.diagnostic.code == "field_domain_mismatch"
def test_scalar_and_valid_must_agree_in_shape():
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_surface_frame(
_frame(valid=c.freeze(np.ones((3, 5), dtype=bool), dtype=np.bool_))
)
assert "disagree" in excinfo.value.diagnostic.message
def test_a_displacement_without_a_quality_is_refused():
displacement = c.freeze(np.zeros((3, 4, 3), dtype=np.float32), dtype=np.float32)
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_surface_frame(_frame(displacement_sensor_m=displacement))
assert "quality" in excinfo.value.diagnostic.message
ok = c.validate_surface_frame(
_frame(displacement_sensor_m=displacement, displacement_quality="approximate")
)
assert ok == ()
def test_a_non_finite_scalar_marked_valid_is_reported_not_silently_coloured():
scalar = np.zeros((3, 4), dtype=np.float32)
scalar[1, 1] = np.nan
warnings = c.validate_surface_frame(
_frame(scalar=c.freeze(scalar, dtype=np.float32))
)
assert [item.code for item in warnings] == ["field_unavailable"]
assert warnings[0].severity == "warning"
def test_an_unknown_linear_quantity_is_reported():
frame = _frame(
scalar_descriptor=c.FieldDescriptor("depth", "", "approximate", False)
)
assert [item.code for item in c.validate_surface_frame(frame)] == ["field_unavailable"]
# -------------------------------------------------------------------- binding
def test_a_binding_with_an_out_of_domain_index_is_refused():
indices = np.array([[0, 1, 5, 6], [1, 2, 6, 7], [4, 5, 9, 12], [5, 6, 10, 11]], dtype=np.int32)
binding = _binding()
broken = c.SurfaceBinding(
part_id=binding.part_id,
geometry_id=binding.geometry_id,
field_domain_id=binding.field_domain_id,
shape_hw=binding.shape_hw,
sample_indices=c.freeze(indices, dtype=np.int32),
sample_weights=binding.sample_weights,
)
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_binding(broken, vertices=4)
assert "outside the declared field domain" in excinfo.value.diagnostic.message
def test_unused_samples_must_be_minus_one_with_zero_weight():
indices = np.array([[0, 1, -2, -1], [1, 2, 6, 7], [4, 5, 9, 10], [5, 6, 10, 11]], dtype=np.int32)
binding = _binding()
broken = c.SurfaceBinding(
part_id=binding.part_id,
geometry_id=binding.geometry_id,
field_domain_id=binding.field_domain_id,
shape_hw=binding.shape_hw,
sample_indices=c.freeze(indices, dtype=np.int32),
sample_weights=binding.sample_weights,
)
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_binding(broken, vertices=4)
assert "unused samples must be -1" in excinfo.value.diagnostic.message
def test_weights_must_sum_to_one():
weights = np.full((4, 4), 0.2, dtype=np.float32)
binding = _binding()
broken = c.SurfaceBinding(
part_id=binding.part_id,
geometry_id=binding.geometry_id,
field_domain_id=binding.field_domain_id,
shape_hw=binding.shape_hw,
sample_indices=binding.sample_indices,
sample_weights=c.freeze(weights, dtype=np.float32),
)
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_binding(broken, vertices=4)
assert "do not sample exactly once" in excinfo.value.diagnostic.message
# ----------------------------------------------------------------------- mesh
def test_a_triangle_index_out_of_range_is_refused():
part = _part()
broken = c.MeshPart(
part_id=part.part_id,
role=part.role,
positions_sensor_m=part.positions_sensor_m,
normals_sensor=part.normals_sensor,
triangles=c.freeze(np.array([[0, 1, 9]], dtype=np.uint32), dtype=np.uint32),
material=part.material,
)
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_mesh_part(broken)
assert "out of range" in excinfo.value.diagnostic.message
def test_sensing_normals_must_be_unit_length():
part = _part()
broken = c.MeshPart(
part_id=part.part_id,
role=part.role,
positions_sensor_m=part.positions_sensor_m,
normals_sensor=c.freeze(np.full((4, 3), 2.0, dtype=np.float32), dtype=np.float32),
triangles=part.triangles,
material=part.material,
)
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_mesh_part(broken)
assert "unit length" in excinfo.value.diagnostic.message
# --------------------------------------------------------------------- assets
def test_a_scene_needs_exactly_one_sensing_part():
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_assets(_assets(parts=(_part("housing", "housing"),)))
assert "exactly one sensing part" in excinfo.value.diagnostic.message
def test_the_binding_must_belong_to_the_sensing_part():
# A housing part may sit beside the sensing one; the binding follows sensing.
assert c.validate_assets(_assets(parts=(_part(), _part("housing", "housing", 3)))) == ()
binding = _binding()
moved = c.SurfaceBinding(
part_id="housing",
geometry_id=binding.geometry_id,
field_domain_id=binding.field_domain_id,
shape_hw=binding.shape_hw,
sample_indices=binding.sample_indices,
sample_weights=binding.sample_weights,
)
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_assets(_assets(binding=moved))
assert "not the sensing part" in excinfo.value.diagnostic.message
def test_the_device_description_decides_whether_an_asset_fits():
expected = c.ExpectedGeometry("finger", "rev-b", "geom-abc", "domain-xyz", (3, 4))
assert c.validate_assets(_assets(), expected) == ()
def device(
geometry_id: str = "geom-abc",
field_domain_id: str = "domain-xyz",
shape_hw: tuple[int, int] = (3, 4),
) -> c.ExpectedGeometry:
return c.ExpectedGeometry("finger", "rev-b", geometry_id, field_domain_id, shape_hw)
cases = (
(device(geometry_id="geom-other"), "geometry_mismatch"),
(device(field_domain_id="domain-other"), "field_domain_mismatch"),
(device(shape_hw=(5, 5)), "field_domain_mismatch"),
)
for description, code in cases:
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_assets(_assets(), description)
assert excinfo.value.diagnostic.code == code
def test_an_unstated_device_identity_is_reported_not_matched():
"""An empty field is "the device cannot say", never "it matches"."""
device = c.ExpectedGeometry("finger", "", "", "domain-xyz", (3, 4), source_geometry_id="")
warnings = c.validate_assets(_assets(), device)
assert [item.code for item in warnings] == ["geometry_unverified"]
assert device.source_geometry_id == ""
def test_the_source_geometry_must_match_too():
"""Same size, same mapping, different surface: still not the same geometry."""
device = c.ExpectedGeometry(
"finger", "", "", "domain-xyz", (3, 4), source_geometry_id="src-1"
)
assert c.validate_assets(_assets(source_geometry_id="src-1"), device) == ()
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_assets(_assets(source_geometry_id="src-2"), device)
assert excinfo.value.diagnostic.code == "geometry_mismatch"
assert excinfo.value.diagnostic.details["device"] == "src-1"
# A package that predates the record: unverified, and said so.
warnings = c.validate_assets(_assets(), device)
assert [item.code for item in warnings] == ["geometry_unverified"]
def test_a_package_released_for_another_sensor_or_revision_is_refused():
device = c.ExpectedGeometry("finger", "rev-b", "geom-abc", "domain-xyz", (3, 4))
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_assets(_assets(compatible_sensor_model="box"), device)
assert excinfo.value.diagnostic.code == "geometry_mismatch"
with pytest.raises(c.ThreeDError) as excinfo:
c.validate_assets(
_assets(
compatible_sensor_model="finger",
compatible_hardware_revisions=("rev-a",),
),
device,
)
assert excinfo.value.diagnostic.code == "geometry_mismatch"
# ``*`` is "any revision", so it never refuses.
assert c.validate_assets(
_assets(
compatible_sensor_model="finger",
compatible_hardware_revisions=("*",),
),
device,
) == ()
# An unstated revision on the device side is not a mismatch either.
assert c.validate_assets(
_assets(
compatible_sensor_model="finger",
compatible_hardware_revisions=("rev-a",),
),
c.ExpectedGeometry("finger", "", "geom-abc", "domain-xyz", (3, 4)),
) == ()
def test_the_source_geometry_digest_is_stable_and_shape_checked():
from orisys_app_shared.scene3d.digest import source_geometry_digest
world = np.arange(3 * 4 * 3, dtype=np.float32).reshape(3, 4, 3)
assert source_geometry_digest(world) == source_geometry_digest(world.copy())
moved = world + 1.0
assert source_geometry_digest(moved) != source_geometry_digest(world)
with pytest.raises(c.ThreeDError) as excinfo:
source_geometry_digest(np.zeros((3, 4), dtype=np.float32))
assert excinfo.value.diagnostic.code == "geometry_mismatch"
def test_only_four_vertex_lod_counts_as_the_same_binding():
"""A new topology needs a new binding: 1032 and 1005 are not interchangeable."""
binding = _binding(vertices=3)
with pytest.raises(c.ThreeDError):
c.validate_assets(_assets(binding=binding, parts=(_part(vertices=4),)))
# -------------------------------------------------------------------- display
def test_display_settings_are_display_only_and_validated():
assert c.validate_display_settings(c.DisplaySettings()) == ()
with pytest.raises(c.ThreeDError):
c.validate_display_settings(c.DisplaySettings(display_gain=-1.0))
with pytest.raises(c.ThreeDError):
c.validate_display_settings(c.DisplaySettings(max_fps=0))
scale = c.ColorScale(
descriptor=c.FieldDescriptor("flow_magnitude", "px", "approximate", False),
lower=1.0,
upper=1.0,
lut_id="viridis",
mode="fixed",
)
with pytest.raises(c.ThreeDError):
c.validate_display_settings(c.DisplaySettings(color_scale=scale))
def test_the_reference_frame_claims_no_measurement():
descriptor = c.rest_descriptor()
assert descriptor.quantity == "unavailable"
assert descriptor.unit == "1"
assert descriptor.quality == "display_only"
# -------------------------------------------------------------------- mailbox
def test_the_mailbox_keeps_the_newest_frame_and_counts_the_rest():
box: c.LatestFrameMailbox[str] = c.LatestFrameMailbox()
assert box.take() is None
assert box.offer("a") == "accepted"
assert box.offer("b") == "replaced"
assert box.offer("c") == "replaced"
assert box.superseded_frames == 2
assert box.take() == "c"
assert box.take() is None, "taking must clear"
assert box.superseded_frames == 2, "taking is not superseding"
def test_the_mailbox_never_blocks_a_producer(monkeypatch):
"""The acquisition thread must not wait for the display: only references swap."""
offers = {"count": 0}
real_offer = c.LatestFrameMailbox.offer
def counting_offer(self, frame):
offers["count"] += 1
return real_offer(self, frame)
monkeypatch.setattr(c.LatestFrameMailbox, "offer", counting_offer)
box: c.LatestFrameMailbox[int] = c.LatestFrameMailbox()
taken: list[int] = []
def produce() -> None:
for index in range(500):
box.offer(index)
def consume() -> None:
for _ in range(200):
value = box.take()
if value is not None:
taken.append(value)
threads = [threading.Thread(target=produce), threading.Thread(target=consume)]
for thread in threads:
thread.start()
for thread in threads:
thread.join(timeout=5.0)
assert not thread.is_alive()
assert offers["count"] == 500
assert box.take() is not None or taken, "the producer's frames went nowhere"
def test_offering_nothing_is_a_programming_error():
box: c.LatestFrameMailbox[str] = c.LatestFrameMailbox()
with pytest.raises(ValueError):
box.offer(None)
# ------------------------------------------------------------------ identity
def test_identity_distinguishes_sources_and_generations():
first = c.FrameIdentity("live-A", 1, 0, 0.0, generation=1)
same = c.FrameIdentity("live-A", 1, 9, 0.3, generation=1)
other_source = c.FrameIdentity("rec-B", 1, 9, 0.3, generation=1)
other_generation = c.FrameIdentity("live-A", 1, 9, 0.3, generation=2)
assert first.is_from(same)
assert not first.is_from(other_source)
assert not first.is_from(other_generation)
# ------------------------------------------------------------------ skeleton
def test_the_contract_layer_imports_without_qt_or_opengl():
"""The acquisition thread imports this package; it must not drag Qt or GL in.
Checked in a **fresh interpreter**: asking ``sys.modules`` in this process only
proves what some earlier test happened to import (it failed once the studio tests
painted a widget before this file ran, which says nothing about the contract layer).
"""
import subprocess
import sys
script = (
"import sys;"
"import orisys_app_shared.scene3d.contracts as c;"
"print(','.join(m for m in ('OpenGL', 'PyQt5', 'cv2') if m in sys.modules))"
)
result = subprocess.run(
[sys.executable, "-c", script],
capture_output=True,
text=True,
timeout=120,
check=False,
)
assert result.returncode == 0, result.stderr
pulled = [name for name in result.stdout.strip().split(",") if name]
assert pulled == [], f"importing the contracts pulled in {pulled}"
def test_the_cpu_layer_is_importable_and_works_without_a_gpu():
"""The acquisition thread imports this package; it must not drag Qt or GL in.
Stages 2 and 3 filled in the CPU pieces, so this checks they are reachable and
usable here — the sampler and the composer run on a machine with no GPU, which
is the whole reason the contracts layer is separate from the view.
"""
from orisys_app_shared.scene3d import assets, composer, sampling, synthetic
scene = synthetic.poc_scene()
frame = _frame()
fields = sampling.sample_field(frame, _binding())
assert np.asarray(fields.scalar).shape == (4,)
composed = composer.SceneComposer().compose(
scene, c.SurfaceFieldFrame(
identity=frame.identity,
geometry_id=scene.geometry_id,
field_domain_id=scene.field_domain_id,
scalar=c.freeze(np.zeros(scene.shape_hw, dtype=np.float32), dtype=np.float32),
scalar_descriptor=c.FieldDescriptor("flow_magnitude", "px", "approximate", False),
valid=c.freeze(np.ones(scene.shape_hw, dtype=bool), dtype=np.bool_),
),
c.DisplaySettings(),
)
assert composed.scalar.shape == (9,)
# The loading facade is real too (stage 2), and the compiler refuses what it
# cannot honestly do: asking for encryption without key material, or without the
# crypto backend, must not produce a plain package that looks protected.
assert callable(assets.PackagedAssetLoader().load)
with pytest.raises(c.ThreeDError) as excinfo:
assets.SceneCompiler().compile(
scene,
None,
Path("unused.oryscene"),
c.CompileOptions(
asset_id="x",
version="0",
expected=synthetic.poc_expected(),
transform_sensor_from_glb=np.eye(4),
max_surface_vertices=0,
max_housing_triangles=1000,
signing_key_reference="build-key",
encryption_key_id="customer-1",
),
)
assert "key" in excinfo.value.diagnostic.message
assert excinfo.value.diagnostic.code == "asset_auth_failed"
def test_summarize_parts_counts_vertices_per_part():
counts = c.summarize_parts((_part(), _part("housing", "housing", 3)))
assert counts == {"sensing_surface": 4, "housing": 3}