Files
SpectraElement/HardwareControl.Core/Scanning/ScanCoordinateMapper.cs
T
2026-11-19 16:42:26 +08:00

66 lines
2.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
namespace HardwareControl.Core.Scanning
{
/// <summary>换算后的位移台绝对目标位置(mm)。</summary>
public readonly record struct StageTarget(int X, int Y);
/// <summary>
/// 相机像素坐标 → 位移台绝对坐标。
///
/// 约定(B 模式):
/// * 图像中心对应位移台坐标 (camera_x_offset, camera_y_offset);
/// * 激光位于位移台原点 (0,0);
/// * +X 使画面中的位移台向右,+Y 使画面中的位移台向上,图像 y 轴向下;
/// * 要把某个采样点送到激光下,目标位置 = -(该点在位移台坐标系中的坐标)。
/// </summary>
public static class ScanCoordinateMapper
{
public static StageTarget ToStageAbsolute(
int pixelX,
int pixelY,
int imageWidth,
int imageHeight,
double scalePxPerMm,
double offsetX,
double offsetY)
{
if (imageWidth <= 0 || imageHeight <= 0)
{
throw new HardwareException(
HardwareErrorKind.InvalidState,
"相机画面尺寸无效,无法换算采样点坐标");
}
if (scalePxPerMm <= 0)
{
throw new HardwareException(
HardwareErrorKind.InvalidState,
"标尺比例 camera_scale 无效,无法换算采样点坐标");
}
// 图像坐标相对画面中心的偏移(毫米):x 向右为正,y 向下为正。
var dx = (pixelX - imageWidth / 2.0) / scalePxPerMm;
var dy = (pixelY - imageHeight / 2.0) / scalePxPerMm;
// 点自身在位移台坐标系中的坐标:P = (offsetX + dx, offsetY - dy)。
// 要把 P 送到激光原点,位移台绝对位置 = -P。
var targetX = -offsetX - dx;
var targetY = -offsetY + dy;
return new StageTarget(RoundMm(targetX), RoundMm(targetY));
}
private static int RoundMm(double value)
{
var rounded = (int)Math.Round(value, MidpointRounding.AwayFromZero);
if (rounded is < short.MinValue or > short.MaxValue)
{
throw new HardwareException(
HardwareErrorKind.InvalidArgument,
$"换算后的位移台坐标 {rounded}mm 超出硬件范围");
}
return rounded;
}
}
}