Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

37.8 KB
Raw Blame
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Brep.Boolean;
using Aetheris.Kernel.Core.Brep.Features;
using Aetheris.Kernel.Core.Brep.Picking;
using Aetheris.Kernel.Core.Brep.Queries;
using Aetheris.Kernel.Core.Brep.Tessellation;
using Aetheris.Kernel.Core.Geometry;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Step242;
using Aetheris.Kernel.Core.Topology;
using Aetheris.Server.Contracts;
using Aetheris.Server.Documents;
using System.Security.Cryptography;
using System.Text;

namespace Aetheris.Server.Api;

public static class KernelEndpoints
{
    public static void MapKernelApi(this WebApplication app)
    {
        MapDocumentRoutes(app.MapGroup("/api/v1/documents"));
        MapDocumentRoutes(app.MapGroup("/api/documents"));
        app.MapPost("/api/v1/assemblies/display", (AssemblyDisplayRequestDto request) =>
            AssemblyDisplayService.TryBuild(request.Path, out var packet, out var error)
                ? ApiMappings.Ok(packet!)
                : ApiMappings.BadRequestFromMessage(error, "assemblies.display"));
    }

    private static void MapDocumentRoutes(RouteGroupBuilder documents)
    {
        documents.MapPost("/{documentId:guid}/measure", (Guid documentId, DocumentMeasurementRequest request, KernelDocumentStore store) =>
            WithDocument(store, documentId, document =>
            {
                try { return ApiMappings.Ok(new { revision = request.Revision, measurement = document.Measure(request.Revision, request.Measurement) }); }
                catch (Aetheris.Geometry.MeasurementException error) { return Results.BadRequest(new ApiResponseDto<object>(false, null,
                    [new DiagnosticDto(error.Code, "Error", error.Message, "Measurement")])); }
            }));
        documents.MapPost("", (DocumentCreateRequestDto? request, KernelDocumentStore store) =>
        {
            var created = store.Create(request?.Name);
            return ApiMappings.Ok(new DocumentCreateResponseDto(created.Id, created.Name, Volatile: true));
        });

        documents.MapPost("/{documentId:guid}/cadmata/fixtures/{fixtureId}", (Guid documentId, string fixtureId, KernelDocumentStore store) =>
            WithDocument(store, documentId, document =>
                CadmataFixtureService.TryLoad(fixtureId, document, out var fixture, out var error)
                    ? ApiMappings.Ok(fixture!)
                    : ApiMappings.BadRequestFromMessage(error, "cadmata.fixture")));

        documents.MapGet("/{documentId:guid}", (Guid documentId, KernelDocumentStore store) =>
        {
            if (!store.TryGet(documentId, out var document))
            {
                return ApiMappings.NotFound($"Document '{documentId}' was not found.", "documents.get");
            }

            var definitions = document.SnapshotDefinitions();
            var occurrences = document.SnapshotOccurrences().Values.OrderBy(o => o.OccurrenceId).ToArray();
            var bodyIds = occurrences.Select(o => o.OccurrenceId).ToArray();
            var occurrenceSummaries = occurrences.Select(o =>
            {
                var origin = o.Placement.Apply(new Point3D(0d, 0d, 0d));
                return new BodyOccurrenceSummaryDto(o.OccurrenceId, o.DefinitionId, o.Name, new Vector3Dto(origin.X, origin.Y, origin.Z));
            }).ToArray();

            return ApiMappings.Ok(new DocumentSummaryResponseDto(
                document.Id,
                document.Name,
                bodyIds.Length,
                bodyIds,
                definitions.Count,
                occurrenceSummaries, document.Revision));
        });

        documents.MapPost("/{documentId:guid}/bodies/primitives/box", (Guid documentId, BoxCreateRequestDto request, KernelDocumentStore store) =>
            WithDocument(store, documentId, document =>
            {
                var kernel = BrepPrimitives.CreateBox(request.Width, request.Height, request.Depth);
                if (!kernel.IsSuccess)
                {
                    return ApiMappings.KernelFailure(kernel.Diagnostics);
                }

                return ApiMappings.Ok(CreateBodyResponse(document, kernel.Value));
            }));

        documents.MapPost("/{documentId:guid}/bodies/primitives/cylinder", (Guid documentId, CylinderCreateRequestDto request, KernelDocumentStore store) =>
            WithDocument(store, documentId, document =>
            {
                var kernel = BrepPrimitives.CreateCylinder(request.Radius, request.Height);
                if (!kernel.IsSuccess)
                {
                    return ApiMappings.KernelFailure(kernel.Diagnostics);
                }

                return ApiMappings.Ok(CreateBodyResponse(document, kernel.Value));
            }));

        documents.MapPost("/{documentId:guid}/bodies/primitives/sphere", (Guid documentId, SphereCreateRequestDto request, KernelDocumentStore store) =>
            WithDocument(store, documentId, document =>
            {
                var kernel = BrepPrimitives.CreateSphere(request.Radius);
                if (!kernel.IsSuccess)
                {
                    return ApiMappings.KernelFailure(kernel.Diagnostics);
                }

                return ApiMappings.Ok(CreateBodyResponse(document, kernel.Value));
            }));

        documents.MapPost("/{documentId:guid}/operations/extrude", (Guid documentId, ExtrudeRequestDto request, KernelDocumentStore store) =>
            WithDocument(store, documentId, document =>
            {
                if (request.Profile is null)
                {
                    return ApiMappings.BadRequestFromMessage("Profile must be provided.", "operations.extrude");
                }

                var profile = PolylineProfile2D.Create(request.Profile.Select(p => new ProfilePoint2D(p.X, p.Y)).ToArray());
                if (!profile.IsSuccess)
                {
                    return ApiMappings.KernelFailure(profile.Diagnostics);
                }

                if (!TryCreateFrame(request.Origin, request.Normal, request.UAxis, out var frame, out var frameError))
                {
                    return frameError;
                }

                var kernel = BrepExtrude.Create(profile.Value, frame, request.Depth);
                if (!kernel.IsSuccess)
                {
                    return ApiMappings.KernelFailure(kernel.Diagnostics);
                }

                return ApiMappings.Ok(CreateBodyResponse(document, kernel.Value));
            }));

        documents.MapPost("/{documentId:guid}/operations/revolve", (Guid documentId, RevolveRequestDto request, KernelDocumentStore store) =>
            WithDocument(store, documentId, document =>
            {
                if (request.Profile is null)
                {
                    return ApiMappings.BadRequestFromMessage("Profile must be provided.", "operations.revolve");
                }

                if (!Direction3D.TryCreate(new Vector3D(request.AxisDirection.X, request.AxisDirection.Y, request.AxisDirection.Z), out var axisDirection))
                {
                    return ApiMappings.BadRequestFromMessage("AxisDirection must be non-zero and finite.", "operations.revolve");
                }

                if (!Direction3D.TryCreate(new Vector3D(request.UAxis.X, request.UAxis.Y, request.UAxis.Z), out var uAxis))
                {
                    return ApiMappings.BadRequestFromMessage("UAxis must be non-zero and finite.", "operations.revolve");
                }

                ExtrudeFrame3D frame;
                try
                {
                    frame = new ExtrudeFrame3D(
                        new Point3D(request.Origin.X, request.Origin.Y, request.Origin.Z),
                        axisDirection,
                        uAxis);
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    return ApiMappings.BadRequestFromMessage(ex.Message, "operations.revolve");
                }

                var angle = request.AngleRadians <= 0d ? 2d * double.Pi : request.AngleRadians;
                var kernel = BrepRevolve.Create(
                    request.Profile.Select(p => new ProfilePoint2D(p.X, p.Y)).ToArray(),
                    frame,
                    new RevolveAxis3D(new Point3D(request.Origin.X, request.Origin.Y, request.Origin.Z), axisDirection.ToVector()),
                    angle);

                if (!kernel.IsSuccess)
                {
                    return ApiMappings.KernelFailure(kernel.Diagnostics);
                }

                return ApiMappings.Ok(CreateBodyResponse(document, kernel.Value));
            }));

        documents.MapPost("/{documentId:guid}/operations/boolean", (Guid documentId, BooleanRequestDto request, KernelDocumentStore store) =>
            WithDocument(store, documentId, document =>
            {
                if (!document.TryGetBody(request.LeftBodyId, out var left))
                {
                    return ApiMappings.NotFound($"Body '{request.LeftBodyId}' was not found.", "operations.boolean");
                }

                if (!document.TryGetBody(request.RightBodyId, out var right))
                {
                    return ApiMappings.NotFound($"Body '{request.RightBodyId}' was not found.", "operations.boolean");
                }

                var kernel = request.Operation.ToLowerInvariant() switch
                {
                    "union" => BrepBoolean.Union(left, right),
                    "subtract" => BrepBoolean.Subtract(left, right),
                    "intersect" => BrepBoolean.Intersect(left, right),
                    _ => null,
                };

                if (kernel is null)
                {
                    return ApiMappings.BadRequestFromMessage("Operation must be one of: union, subtract, intersect.", "operations.boolean");
                }

                if (!kernel.IsSuccess)
                {
                    return ApiMappings.KernelFailure(kernel.Diagnostics);
                }

                return ApiMappings.Ok(CreateBodyResponse(document, kernel.Value));
            }))
            .WithDescription("Compatibility Boolean API for bounded recognized BRep families. Unsupported arbitrary body combinations return typed kernel rejections; this is not a general-purpose exact Boolean guarantee.");

        documents.MapPost("/{documentId:guid}/occurrences", (Guid documentId, CreateOccurrenceRequestDto request, KernelDocumentStore store) =>
            WithDocument(store, documentId, document =>
            {
                if (request.SourceOccurrenceId is null && request.DefinitionId is null)
                {
                    return ApiMappings.BadRequestFromMessage("Either SourceOccurrenceId or DefinitionId must be provided.", "documents.occurrences");
                }

                BodyOccurrence occurrence;
                var created = request.SourceOccurrenceId is Guid sourceOccurrenceId
                    ? document.TryCreateOccurrenceFromOccurrence(sourceOccurrenceId, out occurrence, request.Name)
                    : document.TryCreateOccurrence(request.DefinitionId!.Value, out occurrence, request.Name);

                if (!created)
                {
                    return ApiMappings.NotFound("Referenced occurrence or definition was not found.", "documents.occurrences");
                }

                return ApiMappings.Ok(new OccurrenceCreatedResponseDto(documentId, occurrence.OccurrenceId, occurrence.DefinitionId, occurrence.Name));
            }));


        documents.MapGet("/{documentId:guid}/definitions/{definitionId:guid}/export/step", (Guid documentId, Guid definitionId, KernelDocumentStore store) =>
            WithDocument(store, documentId, document =>
            {
                if (!document.TryGetDefinition(definitionId, out var definitionBody))
                {
                    return ApiMappings.NotFound($"Definition '{definitionId}' was not found.", "documents.definitions.export.step");
                }

                var exportResult = Step242Exporter.ExportBody(definitionBody, new Step242ExportOptions {
                    BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
                    ImportedRecoveryToleranceMillimetres = .1d
                });
                if (!exportResult.IsSuccess)
                {
                    return ApiMappings.KernelFailure(exportResult.Diagnostics);
                }

                var canonicalHash = ComputeCanonicalHash(exportResult.Value);

                return ApiMappings.Ok(new StepExportResponseDto(documentId, definitionId, exportResult.Value, canonicalHash, []));
            }));

        documents.MapPost("/{documentId:guid}/import/step", (Guid documentId, StepImportRequestDto request, KernelDocumentStore store) =>
            WithDocument(store, documentId, document =>
            {
                if (string.IsNullOrWhiteSpace(request.StepText))
                {
                    return ApiMappings.BadRequestFromMessage("StepText must be provided.", "documents.import.step");
                }

                var assemblyResult = Step242AssemblyImporter.Import(request.StepText);
                if (assemblyResult.IsSuccess)
                {
                    if (!AssemblyDisplayService.TryBuildStep(assemblyResult.Value, out var assemblyPacket, out var displayError))
                        return ApiMappings.BadRequestFromMessage(displayError, "documents.import.step.assembly.display");
                    var qualifications = assemblyPacket!.Definitions.Select(d => d.ImportQualification!).ToArray();
                    var definitionBodies = assemblyResult.Value.Definitions.Where(d => d.Geometry is not null).ToDictionary(d => d.StableId, d => d.Geometry!);
                    document.SetImportedMeasurementTargets(assemblyPacket.Occurrences.Where(o => o.DefinitionStableId is not null && definitionBodies.ContainsKey(o.DefinitionStableId))
                        .Select(o => new Aetheris.Geometry.MeasurementTarget(o.StableId, definitionBodies[o.DefinitionStableId!], Transform3D.FromRowMajor(o.WorldTransform))).ToArray());
                    var status = qualifications.Length == 0 ? "Failed" : qualifications.Max(q => q.Status).ToString();
                    return ApiMappings.Ok(new StepImportResponseDto(documentId, Guid.Empty, Guid.Empty,
                        assemblyPacket.Name, assemblyResult.Diagnostics.Select(ApiMappings.ToDiagnostic).ToArray(), AssemblyPresentation: assemblyPacket,
                        ImportStatus: status, ImportQualifications: qualifications, Revision: document.Revision));
                }
                if (assemblyResult.Diagnostics.All(diagnostic => diagnostic.Source != "Importer.Assembly.ProductStructure"))
                    return ApiMappings.KernelFailure(assemblyResult.Diagnostics);

                var importResult = Step242Importer.ImportBody(request.StepText);
                if (!importResult.IsSuccess)
                {
                    return ApiMappings.KernelFailure(importResult.Diagnostics);
                }

                var occurrenceName = string.IsNullOrWhiteSpace(request.Name) ? "Imported" : request.Name;
                var imported = document.AddDefinitionAndOccurrence(importResult.Value, occurrenceName);
                var semanticPresentation = CadmataStepSemanticBridge.Build(
                    request.StepText,
                    occurrenceName,
                    importResult.Value);
                return ApiMappings.Ok(new StepImportResponseDto(
                    documentId,
                    imported.DefinitionId,
                    imported.OccurrenceId,
                    occurrenceName,
                    importResult.Diagnostics.Select(ApiMappings.ToDiagnostic).ToArray(),
                    semanticPresentation,
                    ImportStatus: importResult.Value.ImportQualification?.Status.ToString() ?? "Inspectable",
                    ImportQualifications: importResult.Value.ImportQualification is { } qualification ? [qualification] : []));
            }));

        documents.MapPost("/{documentId:guid}/bodies/{bodyId:guid}/transform", (Guid documentId, Guid bodyId, TranslateBodyRequestDto request, KernelDocumentStore store) =>
            WithDocument(store, documentId, document =>
            {
                if (request.Translation is null)
                {
                    return ApiMappings.BadRequestFromMessage("Translation must be provided.", "documents.body");
                }

                if (!document.ApplyBodyTranslation(bodyId, new Vector3D(request.Translation.X, request.Translation.Y, request.Translation.Z), out _))
                {
                    return ApiMappings.NotFound($"Body '{bodyId}' was not found.", "documents.body");
                }

                document.TryGetOccurrence(bodyId, out var occurrence);
                return ApiMappings.Ok(new BodyTransformedResponseDto(documentId, bodyId, occurrence.DefinitionId, request.Translation));
            }));

        documents.MapPost("/{documentId:guid}/bodies/{bodyId:guid}/tessellate", (Guid documentId, Guid bodyId, TessellateRequestDto? request, KernelDocumentStore store) =>
            WithDocumentOccurrence(store, documentId, bodyId, (document, body) =>
            {
                var options = ApiMappings.BuildTessellationOptions(request?.Options);
                var kernel = BrepDisplayTessellator.TessellateBounded(body, options);
                if (!kernel.IsSuccess)
                {
                    return ApiMappings.KernelFailure(kernel.Diagnostics);
                }

                if (document.TryGetBodyTransform(bodyId, out var transform))
                {
                    return ApiMappings.Ok(ApiMappings.ToTessellationResponse(kernel.Value, transform));
                }

                return ApiMappings.Ok(ApiMappings.ToTessellationResponse(kernel.Value));
            }));

        documents.MapPost("/{documentId:guid}/bodies/{bodyId:guid}/display/prepare", (Guid documentId, Guid bodyId, DisplayPrepareRequestDto? request, KernelDocumentStore store) =>
            WithDocumentOccurrence(store, documentId, bodyId, (document, body) =>
            {
                var analyticPacket = AnalyticDisplayPacketBuilder.Build(body);
                var analyticDto = ApiMappings.ToAnalyticDisplayPacketResponse(analyticPacket);
                var lane = ResolveDisplayLane(analyticPacket);
                TessellationResponseDto? tessellationFallback = null;
                DisplayTessellationResult? boundedMeshResult = null;
                var displayDiagnostics = new List<DisplayDiagnosticDto>();
                var needsTrimmedAnalyticFallback = analyticDto.AnalyticFaces.Any(face =>
                    face.SurfaceKind == "Plane" && face.LoopCount > 1);

                if (lane is not "analytic-only" || needsTrimmedAnalyticFallback)
                {
                    var options = request?.TessellationOptions is null ? DisplayTessellationOptions.ForViewport(body)
                        : ApiMappings.BuildTessellationOptions(request.TessellationOptions);
                    var completeBoundedMesh = DisplayPreparationFallbackBuilder.Build(body, options);
                    boundedMeshResult = completeBoundedMesh.IsSuccess
                        ? completeBoundedMesh.Value
                        : BrepDisplayTessellator.TessellateBoundedPartial(body, options);

                    // Kernel tessellation reports skipped or degraded faces as warnings on an otherwise successful
                    // result. They used to be dropped here, so a face the kernel gave up on showed up as a silent hole.
                    if (completeBoundedMesh.IsSuccess)
                    {
                        displayDiagnostics.AddRange(completeBoundedMesh.Diagnostics
                            .Where(diagnostic => diagnostic.Severity != Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Info)
                            .Select(diagnostic => ToKernelWarningDisplayDiagnostic(body, diagnostic)));
                    }

                    tessellationFallback = document.TryGetBodyTransform(bodyId, out var fallbackTransform)
                        ? ApiMappings.ToTessellationResponse(boundedMeshResult, fallbackTransform)
                        : ApiMappings.ToTessellationResponse(boundedMeshResult);

                    // A patch with no triangles is a face the kernel skipped; treat it as absent so the face falls back
                    // to wireframe/diagnostic display instead of claiming to be a rendered mesh.
                    tessellationFallback = tessellationFallback with
                    {
                        FacePatches = tessellationFallback.FacePatches.Where(patch => patch.TriangleIndices.Count > 0).ToArray(),
                    };

                    if (!completeBoundedMesh.IsSuccess && boundedMeshResult.FaceDiagnostics is { Count: > 0 })
                    {
                        displayDiagnostics.AddRange(boundedMeshResult.FaceDiagnostics.Select(diagnostic => new DisplayDiagnosticDto(
                            diagnostic.Code,
                            diagnostic.Message,
                            diagnostic.FaceId?.Value,
                            diagnostic.SurfaceKind,
                            diagnostic.Phase,
                            "Use wire/proxy display or retry with explicit bounded mesh lowering.")));
                    }
                }

                var meshByFace = tessellationFallback?.FacePatches.ToDictionary(patch => patch.FaceId) ?? [];
                var wireByFace = body.Topology.Faces
                    .OrderBy(face => face.Id.Value)
                    .Select(face => (face.Id, Wire: TryBuildWirePatch(body, face.Id)))
                    .Where(item => item.Wire is not null)
                    .ToDictionary(item => item.Id.Value, item => item.Wire!);
                var analyticByFace = analyticDto.AnalyticFaces.ToDictionary(face => face.FaceId);
                var fallbackByFace = analyticDto.FallbackFaces.ToDictionary(face => face.FaceId);
                var diagnosticsByFace = displayDiagnostics
                    .Where(diagnostic => diagnostic.FaceId.HasValue)
                    .GroupBy(diagnostic => diagnostic.FaceId!.Value)
                    .ToDictionary(group => group.Key, group => (IReadOnlyList<DisplayDiagnosticDto>)group.ToArray());
                var faces = body.Topology.Faces.OrderBy(face => face.Id.Value).Select(face =>
                {
                    analyticByFace.TryGetValue(face.Id.Value, out var analyticFace);
                    meshByFace.TryGetValue(face.Id.Value, out var meshPatch);
                    fallbackByFace.TryGetValue(face.Id.Value, out var fallbackFace);
                    diagnosticsByFace.TryGetValue(face.Id.Value, out var faceDiagnostics);
                    wireByFace.TryGetValue(face.Id.Value, out var wirePatch);
                    var canUseWireFallback = analyticFace is null && meshPatch is null && faceDiagnostics is { Count: > 0 } && wirePatch is not null && wirePatch.Loops.Count > 0;
                    var status = analyticFace is not null ? "Analytic" : meshPatch is not null ? "Mesh" : canUseWireFallback ? "WireframeOnly" : faceDiagnostics is { Count: > 0 } ? "DiagnosticOnly" : "Omitted";
                    var patchKind = analyticFace is not null ? "AnalyticPatch" : meshPatch is not null ? "MeshPatch" : canUseWireFallback ? "WirePatch" : faceDiagnostics is { Count: > 0 } ? "DiagnosticPatch" : "DiagnosticPatch";
                    var materializationLane = analyticFace is not null ? "AnalyticPatch" : meshPatch is not null ? "BoundedMesh" : canUseWireFallback ? "WirePatch" : faceDiagnostics is { Count: > 0 } ? "BoundedMesh" : "DiagnosticOnly";
                    var combinedDiagnostics = canUseWireFallback
                        ? (faceDiagnostics ?? []).Concat([new DisplayDiagnosticDto("Viewer.Display.WireframeOnly", "Face fill materialization failed; boundary edges were emitted as preview wireframe DisplayIR.", face.Id.Value, analyticFace?.SurfaceKind ?? fallbackFace?.SurfaceKind, "BRepEdgeWireLowering", null)]).ToArray()
                        : faceDiagnostics ?? [];
                    return new DisplayFaceDto(
                        face.Id.Value,
                        analyticFace?.ShellId ?? fallbackFace?.ShellId,
                        analyticFace?.SurfaceKind ?? fallbackFace?.SurfaceKind,
                        status,
                        patchKind,
                        meshPatch,
                        analyticFace,
                        canUseWireFallback ? wirePatch : null,
                        materializationLane,
                        combinedDiagnostics,
                        AssemblyDisplayService.FaceSource(body, face.Id));
                }).ToArray();

                var status = faces.All(face => face.Status is "DiagnosticOnly" or "Omitted") ? "DiagnosticOnly" :
                    faces.Any(face => face.Status is "DiagnosticOnly" or "Omitted" or "WireframeOnly") ? "Partial" : "Complete";
                if (status is "Partial")
                {
                    displayDiagnostics.Insert(0, new DisplayDiagnosticDto("Viewer.Display.Partial", "Display preparation completed with one or more diagnostic-only or wireframe-only faces.", null, null, null, null));
                }

                var displayLanes = new List<DisplayLaneDto>();
                var analyticFaceCount = faces.Count(face => face.MaterializationLane == "AnalyticPatch");
                if (analyticFaceCount > 0)
                {
                    displayLanes.Add(new DisplayLaneDto("AnalyticPatch", "Complete", "BRep", "DisplayIR", null, "Default", null, analyticFaceCount, 0));
                }

                if (boundedMeshResult is not null)
                {
                    var boundedMeshDiagnostics = (boundedMeshResult.FaceDiagnostics?.Count ?? 0) + displayDiagnostics.Count(diagnostic => diagnostic.Phase == "FaceTessellation" && diagnostic.Code.StartsWith("Viewer.Tessellation", StringComparison.Ordinal));
                    var boundedMeshFaceCount = faces.Count(face => face.MaterializationLane == "BoundedMesh" && face.Status == "Mesh");
                    var boundedMeshStatus = boundedMeshDiagnostics > 0 ? (boundedMeshFaceCount > 0 ? "Partial" : "Failed") : "Complete";
                    displayLanes.Add(new DisplayLaneDto(
                        "BoundedMesh",
                        boundedMeshStatus,
                        "BRep",
                        "DisplayIR",
                        "BrepDisplayTessellator",
                        "Default",
                        5000,
                        boundedMeshFaceCount,
                        boundedMeshDiagnostics));
                }

                if (faces.Any(face => face.Status == "WireframeOnly"))
                {
                    displayLanes.Add(new DisplayLaneDto("WirePatch", "Partial", "BRep", "DisplayIR", "BRepEdgeWireLowering", "PreviewPolyline", null, faces.Count(face => face.Status == "WireframeOnly"), faces.Where(face => face.Status == "WireframeOnly").Sum(face => face.Diagnostics.Count)));
                }

                if (faces.Any(face => face.Status == "DiagnosticOnly"))
                {
                    displayLanes.Add(new DisplayLaneDto("DiagnosticOnly", status, "DisplayIR", "DisplayIR", null, "Diagnostic", null, faces.Count(face => face.Status == "DiagnosticOnly"), displayDiagnostics.Count));
                }

                var lanes = displayLanes.Select(displayLane => displayLane.Kind).ToArray();
                // Boundary sampling is available even when every support takes the analytic lane.
                // Mesh fallback is not the authority for whether topology lines exist.
                var topologyTransform = document.TryGetBodyTransform(bodyId, out var edgeTransform) ? edgeTransform : Transform3D.Identity;
                var topologyEdges = tessellationFallback?.EdgePolylines ?? wireByFace.Values.SelectMany(wire => wire.Loops).SelectMany(loop => loop.Edges)
                    .DistinctBy(edge => edge.EdgeId).Select(edge => {
                        var bound = body.Topology.GetEdge(new EdgeId(edge.EdgeId));
                        return new EdgePolylineDto(edge.EdgeId, edge.Points.Select(point => {
                            var world = topologyTransform.Apply(new Point3D(point.X, point.Y, point.Z));
                            return new Point3Dto(world.X, world.Y, world.Z);
                        }).ToArray(), bound.StartVertexId == bound.EndVertexId);
                    }).ToArray();
                return ApiMappings.Ok(new DisplayPreparationResponseDto(
                    lane,
                    analyticDto,
                    tessellationFallback,
                    status,
                    "BRep",
                    "DisplayIR",
                    lanes,
                    faces,
                    displayDiagnostics,
                    displayLanes,
                    topologyEdges));
            }));

        documents.MapPost("/{documentId:guid}/bodies/{bodyId:guid}/pick", (Guid documentId, Guid bodyId, PickRequestDto request, KernelDocumentStore store) =>
            WithDocumentOccurrence(store, documentId, bodyId, (document, body) =>
            {
                if (request.Direction is null)
                {
                    return ApiMappings.BadRequestFromMessage("Direction must be provided.", "bodies.pick");
                }

                if (!Direction3D.TryCreate(new Vector3D(request.Direction.X, request.Direction.Y, request.Direction.Z), out var direction))
                {
                    return ApiMappings.BadRequestFromMessage("Direction must be non-zero and finite.", "bodies.pick");
                }

                var ray = new Ray3D(new Point3D(request.Origin.X, request.Origin.Y, request.Origin.Z), direction);
                if (document.TryGetBodyTransform(bodyId, out var transform) && transform.TryInverse(out var inverse))
                {
                    ray = new Ray3D(inverse.Apply(ray.Origin), inverse.Apply(ray.Direction));
                }

                var kernel = BrepPicker.Pick(
                    body,
                    ray,
                    ApiMappings.BuildTessellationOptions(request.TessellationOptions),
                    ApiMappings.BuildPickOptions(request.PickOptions));

                if (!kernel.IsSuccess)
                {
                    return ApiMappings.KernelFailure(kernel.Diagnostics);
                }

                if (document.TryGetBodyTransform(bodyId, out transform))
                {
                    return ApiMappings.Ok(ApiMappings.ToPickResponse(kernel.Value, transform, bodyId));
                }

                return ApiMappings.Ok(ApiMappings.ToPickResponse(kernel.Value, bodyId));
            }));
    }

    private static string ComputeCanonicalHash(string stepText)
    {
        var utf8Bytes = Encoding.UTF8.GetBytes(stepText);
        var hash = SHA256.HashData(utf8Bytes);
        return Convert.ToHexString(hash).ToLowerInvariant();
    }

    private static IResult WithDocument(KernelDocumentStore store, Guid documentId, Func<DocumentSession, IResult> operation)
    {
        if (!store.TryGet(documentId, out var document))
        {
            return ApiMappings.NotFound($"Document '{documentId}' was not found.", "documents");
        }

        return operation(document);
    }

    private static IResult WithDocumentOccurrence(KernelDocumentStore store, Guid documentId, Guid bodyId, Func<DocumentSession, BrepBody, IResult> operation)
        => WithDocument(store, documentId, document =>
        {
            if (!document.TryGetBody(bodyId, out var body))
            {
                return ApiMappings.NotFound($"Body '{bodyId}' was not found.", "documents.body");
            }

            return operation(document, body);
        });

    private static BodyCreatedResponseDto CreateBodyResponse(DocumentSession document, BrepBody body)
    {
        var bodyIds = document.AddBody(body);
        return new BodyCreatedResponseDto(
            document.Id,
            bodyIds.OccurrenceId,
            bodyIds.DefinitionId,
            body.Topology.Faces.Count(),
            body.Topology.Edges.Count(),
            body.Topology.Vertices.Count());
    }

    private static bool TryCreateFrame(Point3Dto originDto, Vector3Dto normalDto, Vector3Dto uAxisDto, out ExtrudeFrame3D frame, out IResult error)
    {
        frame = default;
        error = Results.Empty;

        if (!Direction3D.TryCreate(new Vector3D(normalDto.X, normalDto.Y, normalDto.Z), out var normal))
        {
            error = ApiMappings.BadRequestFromMessage("Normal must be non-zero and finite.", "operations.extrude");
            return false;
        }

        if (!Direction3D.TryCreate(new Vector3D(uAxisDto.X, uAxisDto.Y, uAxisDto.Z), out var uAxis))
        {
            error = ApiMappings.BadRequestFromMessage("UAxis must be non-zero and finite.", "operations.extrude");
            return false;
        }

        try
        {
            frame = new ExtrudeFrame3D(new Point3D(originDto.X, originDto.Y, originDto.Z), normal, uAxis);
            return true;
        }
        catch (ArgumentOutOfRangeException ex)
        {
            error = ApiMappings.BadRequestFromMessage(ex.Message, "operations.extrude");
            return false;
        }
    }

    private static DisplayWirePatchDto? TryBuildWirePatch(Aetheris.Kernel.Core.Brep.BrepBody body, FaceId faceId)
    {
        var loops = new List<DisplayLoopDto>();
        var loopIds = body.GetLoopIds(faceId);
        for (var loopIndex = 0; loopIndex < loopIds.Count; loopIndex++)
        {
            var loopId = loopIds[loopIndex];
            var edges = new List<DisplayEdgeDto>();
            foreach (var coedgeId in body.GetCoedgeIds(loopId))
            {
                if (!body.Topology.TryGetCoedge(coedgeId, out var coedge) || coedge is null)
                {
                    continue;
                }

                edges.Add(BuildWireEdge(body, coedge.EdgeId));
            }

            if (edges.Count > 0)
            {
                loops.Add(new DisplayLoopDto(loopId.Value, loopIndex == 0 ? "Outer" : "Inner", edges));
            }
        }

        return loops.Count == 0 ? null : new DisplayWirePatchDto("WirePatch", "BRepEdges", "PreviewPolyline", loops);
    }

    private static DisplayEdgeDto BuildWireEdge(Aetheris.Kernel.Core.Brep.BrepBody body, EdgeId edgeId)
    {
        var points = new List<Point3Dto>();
        var diagnostics = new List<DisplayDiagnosticDto>();
        var sourceCurveKind = "Unknown";
        if (body.TryGetEdgeCurve(edgeId, out var curve) && curve is not null && body.Bindings.TryGetEdgeBinding(edgeId, out var binding))
        {
            sourceCurveKind = curve.Kind.ToString();
            var interval = binding.TrimInterval;
            var start = interval?.Start ?? 0d;
            var end = interval?.End ?? (curve.Kind == CurveGeometryKind.Circle3 ? 2d * double.Pi : 1d);
            if (curve.Kind == CurveGeometryKind.Line3 && curve.Line3 is { } line)
            {
                points.Add(ApiMappings.ToPointDto(line.Evaluate(start)));
                points.Add(ApiMappings.ToPointDto(line.Evaluate(end)));
            }
            else if (curve.Kind == CurveGeometryKind.Circle3 && curve.Circle3 is { } circle)
            {
                var samples = Math.Clamp((int)Math.Ceiling(Math.Abs(end - start) / (Math.PI / 12d)) + 1, 3, 33);
                for (var i = 0; i < samples; i++)
                {
                    var t = start + ((end - start) * i / (samples - 1));
                    points.Add(ApiMappings.ToPointDto(circle.Evaluate(t)));
                }
            }
            else
            {
                diagnostics.Add(new DisplayDiagnosticDto("Viewer.Wireframe.UnsupportedCurve", $"Wireframe preview does not sample edge curve kind '{curve.Kind}'.", null, null, "BRepEdgeWireLowering", "Keep face diagnostic visible; harden edge polyline sampler in a later milestone."));
            }
        }
        else
        {
            diagnostics.Add(new DisplayDiagnosticDto("Viewer.Wireframe.UnsupportedCurve", "Wireframe preview could not resolve an edge curve binding.", null, null, "BRepEdgeWireLowering", "Keep face diagnostic visible; inspect BRep edge bindings."));
        }

        if (points.Count == 0 && body.TryGetEdgeVertices(edgeId, out var startVertex, out var endVertex))
        {
            if (body.TryGetVertexPoint(startVertex, out var startPoint)) points.Add(ApiMappings.ToPointDto(startPoint));
            if (body.TryGetVertexPoint(endVertex, out var endPoint)) points.Add(ApiMappings.ToPointDto(endPoint));
        }

        return new DisplayEdgeDto(edgeId.Value, points, sourceCurveKind, points.Count, diagnostics);
    }

    private static DisplayDiagnosticDto ToKernelWarningDisplayDiagnostic(BrepBody body, Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic diagnostic)
    {
        int? faceId = null;
        string? surfaceKind = null;
        var match = System.Text.RegularExpressions.Regex.Match(diagnostic.Message, @"\bFace (\d+)\b");
        if (match.Success && int.TryParse(match.Groups[1].Value, out var parsedFaceId))
        {
            faceId = parsedFaceId;
            var face = body.Topology.Faces.FirstOrDefault(candidate => candidate.Id.Value == parsedFaceId);
            if (face is not null && body.TryGetFaceSurfaceGeometry(face.Id, out var surface) && surface is not null)
            {
                surfaceKind = surface.Kind.ToString();
            }
        }

        return new DisplayDiagnosticDto(
            diagnostic.Source ?? diagnostic.Code.ToString(),
            diagnostic.Message,
            faceId,
            surfaceKind,
            "FaceTessellation",
            "Face was skipped or degraded by kernel tessellation; check the trim loops and surface of this face.");
    }

    private static string ResolveDisplayLane(AnalyticDisplayPacket packet)
    {
        if (packet.AnalyticFaces.Count > 0 && packet.FallbackFaces.Count == 0)
        {
            return "analytic-only";
        }

        if (packet.AnalyticFaces.Count > 0)
        {
            return "mixed-fallback";
        }

        return "fallback-only";
    }
}