Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add M16 backend kernel host API with in-memory documents
Yuechen Lia86db4edec43
diff --git a/Aetheris.Server.Tests/Aetheris.Server.Tests.csproj b/Aetheris.Server.Tests/Aetheris.Server.Tests.csprojnew file mode 100644index 00000000..0ff99127--- /dev/null+++ b/Aetheris.Server.Tests/Aetheris.Server.Tests.csproj@@ -0,0 +1,23 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <TargetFramework>net8.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <IsPackable>false</IsPackable>+ </PropertyGroup>++ <ItemGroup>+ <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.24" />+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />+ <PackageReference Include="xunit" Version="2.9.2" />+ <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />+ </ItemGroup>++ <ItemGroup>+ <Using Include="Xunit" />+ </ItemGroup>++ <ItemGroup>+ <ProjectReference Include="..\Aetheris.Server\Aetheris.Server.csproj" />+ </ItemGroup>+</Project>diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.csnew file mode 100644index 00000000..75ebb044--- /dev/null+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs@@ -0,0 +1,114 @@+using System.Net;+using System.Net.Http.Json;+using Aetheris.Server.Contracts;+using Microsoft.AspNetCore.Mvc.Testing;++namespace Aetheris.Server.Tests;++public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFactory<Program>>+{+ private readonly HttpClient _client;++ public KernelApiIntegrationTests(WebApplicationFactory<Program> factory)+ {+ _client = factory.CreateClient();+ }++ [Fact]+ public async Task CreateDocument_CreateBox_TessellateAndPick_Succeeds()+ {+ var document = await CreateDocumentAsync();++ var boxResponse = await _client.PostAsJsonAsync(+ $"/api/documents/{document.DocumentId}/bodies/primitives/box",+ new BoxCreateRequestDto(2, 2, 2));+ boxResponse.EnsureSuccessStatusCode();++ var boxBody = await boxResponse.Content.ReadFromJsonAsync<BodyCreatedResponseDto>();+ Assert.NotNull(boxBody);++ var tessellationResponse = await _client.PostAsJsonAsync(+ $"/api/documents/{document.DocumentId}/bodies/{boxBody!.BodyId}/tessellate",+ new TessellateRequestDto(null));+ tessellationResponse.EnsureSuccessStatusCode();++ var tessellation = await tessellationResponse.Content.ReadFromJsonAsync<TessellationResponseDto>();+ Assert.NotNull(tessellation);+ Assert.NotEmpty(tessellation!.FacePatches);++ var pickResponse = await _client.PostAsJsonAsync(+ $"/api/documents/{document.DocumentId}/bodies/{boxBody.BodyId}/pick",+ new PickRequestDto(+ new Point3Dto(0, 0, 5),+ new Vector3Dto(0, 0, -1),+ TessellationOptions: null,+ PickOptions: new PickOptionsDto(NearestOnly: true, IncludeBackfaces: null, EdgeTolerance: null, SortTieTolerance: null, MaxDistance: null)));+ pickResponse.EnsureSuccessStatusCode();++ var pick = await pickResponse.Content.ReadFromJsonAsync<PickResponseDto>();+ Assert.NotNull(pick);+ Assert.Single(pick!.Hits);+ }++ [Fact]+ public async Task UnsupportedBoolean_ReturnsStructuredError()+ {+ var document = await CreateDocumentAsync();+ var left = await CreateBoxAsync(document.DocumentId, 1, 1, 1);+ var right = await CreateBoxAsync(document.DocumentId, 1, 1, 1);++ var extrudeResponse = await _client.PostAsJsonAsync(+ $"/api/documents/{document.DocumentId}/operations/extrude",+ new ExtrudeRequestDto(+ [new ProfilePoint2Dto(-0.5, -0.5), new ProfilePoint2Dto(0.5, -0.5), new ProfilePoint2Dto(0.5, 0.5), new ProfilePoint2Dto(-0.5, 0.5)],+ new Point3Dto(4, 0, 0),+ new Vector3Dto(0, 0, 1),+ new Vector3Dto(1, 0, 0),+ 1));+ extrudeResponse.EnsureSuccessStatusCode();++ var moved = await extrudeResponse.Content.ReadFromJsonAsync<BodyCreatedResponseDto>();+ Assert.NotNull(moved);++ var booleanResponse = await _client.PostAsJsonAsync(+ $"/api/documents/{document.DocumentId}/operations/boolean",+ new BooleanRequestDto(left.BodyId, moved!.BodyId, "union"));++ Assert.Equal(HttpStatusCode.UnprocessableEntity, booleanResponse.StatusCode);+ var error = await booleanResponse.Content.ReadFromJsonAsync<ErrorResponseDto>();+ Assert.NotNull(error);+ Assert.Contains(error!.Diagnostics, d => d.Code == "NotImplemented");+ }++ [Fact]+ public async Task MissingDocumentAndBody_ReturnNotFound()+ {+ var missingDocId = Guid.NewGuid();+ var missingBodyId = Guid.NewGuid();++ var docResponse = await _client.GetAsync($"/api/documents/{missingDocId}");+ Assert.Equal(HttpStatusCode.NotFound, docResponse.StatusCode);++ var created = await CreateDocumentAsync();+ var bodyResponse = await _client.PostAsJsonAsync(+ $"/api/documents/{created.DocumentId}/bodies/{missingBodyId}/tessellate",+ new TessellateRequestDto(null));+ Assert.Equal(HttpStatusCode.NotFound, bodyResponse.StatusCode);+ }++ private async Task<DocumentCreateResponseDto> CreateDocumentAsync()+ {+ var response = await _client.PostAsJsonAsync("/api/documents", new DocumentCreateRequestDto("test"));+ response.EnsureSuccessStatusCode();+ var payload = await response.Content.ReadFromJsonAsync<DocumentCreateResponseDto>();+ return payload!;+ }++ private async Task<BodyCreatedResponseDto> CreateBoxAsync(Guid documentId, double w, double h, double d)+ {+ var response = await _client.PostAsJsonAsync($"/api/documents/{documentId}/bodies/primitives/box", new BoxCreateRequestDto(w, h, d));+ response.EnsureSuccessStatusCode();+ var body = await response.Content.ReadFromJsonAsync<BodyCreatedResponseDto>();+ return body!;+ }+}diff --git a/Aetheris.Server/Aetheris.Server.csproj b/Aetheris.Server/Aetheris.Server.csprojindex a180c757..e17ed5b7 100644--- a/Aetheris.Server/Aetheris.Server.csproj+++ b/Aetheris.Server/Aetheris.Server.csproj@@ -4,23 +4,15 @@<TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings>- <SpaRoot>..\aetheris.client</SpaRoot>- <SpaProxyLaunchCommand>npm run dev</SpaProxyLaunchCommand>- <SpaProxyServerUrl>https://localhost:63354</SpaProxyServerUrl></PropertyGroup><ItemGroup><PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.24" />- <PackageReference Include="Microsoft.AspNetCore.SpaProxy">- <Version>8.*-*</Version>- </PackageReference><PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" /></ItemGroup><ItemGroup>- <ProjectReference Include="..\aetheris.client\aetheris.client.esproj">- <ReferenceOutputAssembly>false</ReferenceOutputAssembly>- </ProjectReference>+ <ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" /></ItemGroup></Project>diff --git a/Aetheris.Server/Api/ApiMappings.cs b/Aetheris.Server/Api/ApiMappings.csnew file mode 100644index 00000000..924befdb--- /dev/null+++ b/Aetheris.Server/Api/ApiMappings.cs@@ -0,0 +1,112 @@+using Aetheris.Kernel.Core.Brep.Picking;+using Aetheris.Kernel.Core.Brep.Tessellation;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Results;+using Aetheris.Server.Contracts;+using Microsoft.AspNetCore.Http.HttpResults;++namespace Aetheris.Server.Api;++public static class ApiMappings+{+ public static IResult KernelFailure(IReadOnlyList<KernelDiagnostic> diagnostics)+ {+ var mapped = diagnostics.Select(ToDiagnostic).ToArray();+ var statusCode = ResolveStatusCode(diagnostics);+ return Results.Json(new ErrorResponseDto(mapped), statusCode: statusCode);+ }++ public static DiagnosticDto ToDiagnostic(KernelDiagnostic diagnostic)+ => new(diagnostic.Code.ToString(), diagnostic.Severity.ToString(), diagnostic.Message, diagnostic.Source);++ public static int ResolveStatusCode(IReadOnlyList<KernelDiagnostic> diagnostics)+ {+ if (diagnostics.Count == 0)+ {+ return StatusCodes.Status400BadRequest;+ }++ return diagnostics.Max(static d => d.Code switch+ {+ KernelDiagnosticCode.InternalError => StatusCodes.Status500InternalServerError,+ KernelDiagnosticCode.NotImplemented => StatusCodes.Status422UnprocessableEntity,+ KernelDiagnosticCode.ValidationFailed => StatusCodes.Status422UnprocessableEntity,+ KernelDiagnosticCode.InvalidArgument => StatusCodes.Status400BadRequest,+ KernelDiagnosticCode.ToleranceConflict => StatusCodes.Status400BadRequest,+ _ => StatusCodes.Status400BadRequest,+ });+ }++ public static IResult NotFound(string message, string source)+ {+ var diagnostic = new KernelDiagnostic(KernelDiagnosticCode.InvalidArgument, KernelDiagnosticSeverity.Error, message, source);+ return Results.NotFound(new ErrorResponseDto([ToDiagnostic(diagnostic)]));+ }++ public static Point3Dto ToPointDto(Point3D point) => new(point.X, point.Y, point.Z);++ public static Vector3Dto ToVectorDto(Vector3D vector) => new(vector.X, vector.Y, vector.Z);++ public static TessellationResponseDto ToTessellationResponse(DisplayTessellationResult result)+ => new(+ result.FacePatches.Select(p => new FacePatchDto(+ p.FaceId.Value,+ p.Positions.Select(ToPointDto).ToArray(),+ p.Normals.Select(ToVectorDto).ToArray(),+ p.TriangleIndices.ToArray())).ToArray(),+ result.EdgePolylines.Select(e => new EdgePolylineDto(+ e.EdgeId.Value,+ e.Points.Select(ToPointDto).ToArray(),+ e.IsClosed)).ToArray());++ public static PickResponseDto ToPickResponse(IReadOnlyList<PickHit> hits)+ => new(hits.Select(h => new PickHitDto(+ h.T,+ ToPointDto(h.Point),+ h.Normal is null ? null : ToVectorDto(h.Normal.Value.ToVector()),+ h.EntityKind.ToString(),+ h.FaceId?.Value,+ h.EdgeId?.Value,+ h.BodyId?.Value,+ h.SourcePatchIndex,+ h.SourcePrimitiveIndex)).ToArray());++ public static BadRequest<ErrorResponseDto> BadRequestFromMessage(string message, string source)+ => TypedResults.BadRequest(new ErrorResponseDto([new DiagnosticDto(+ KernelDiagnosticCode.InvalidArgument.ToString(),+ KernelDiagnosticSeverity.Error.ToString(),+ message,+ source)]));++ public static DisplayTessellationOptions? BuildTessellationOptions(TessellationOptionsDto? options)+ {+ if (options is null)+ {+ return null;+ }++ var baseOptions = DisplayTessellationOptions.Default;+ return new DisplayTessellationOptions(+ options.AngularToleranceRadians ?? baseOptions.AngularToleranceRadians,+ options.ChordTolerance ?? baseOptions.ChordTolerance,+ options.MinimumSegments ?? baseOptions.MinimumSegments,+ options.MaximumSegments ?? baseOptions.MaximumSegments);+ }++ public static PickQueryOptions? BuildPickOptions(PickOptionsDto? options)+ {+ if (options is null)+ {+ return null;+ }++ var defaults = PickQueryOptions.Default;+ return new PickQueryOptions(+ options.NearestOnly ?? defaults.NearestOnly,+ options.IncludeBackfaces ?? defaults.IncludeBackfaces,+ options.EdgeTolerance ?? defaults.EdgeTolerance,+ options.SortTieTolerance ?? defaults.SortTieTolerance,+ options.MaxDistance ?? defaults.MaxDistance);+ }+}diff --git a/Aetheris.Server/Api/KernelEndpoints.cs b/Aetheris.Server/Api/KernelEndpoints.csnew file mode 100644index 00000000..2049c295--- /dev/null+++ b/Aetheris.Server/Api/KernelEndpoints.cs@@ -0,0 +1,266 @@+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.Tessellation;+using Aetheris.Kernel.Core.Math;+using Aetheris.Server.Contracts;+using Aetheris.Server.Documents;++namespace Aetheris.Server.Api;++public static class KernelEndpoints+{+ public static void MapKernelApi(this WebApplication app)+ {+ var documents = app.MapGroup("/api/documents");++ documents.MapPost("", (DocumentCreateRequestDto? request, KernelDocumentStore store) =>+ {+ var created = store.Create(request?.Name);+ return Results.Ok(new DocumentCreateResponseDto(created.Id, created.Name, Volatile: true));+ });++ 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 bodyIds = document.SnapshotBodies().Keys.OrderBy(id => id).ToArray();+ return Results.Ok(new DocumentSummaryResponseDto(document.Id, document.Name, bodyIds.Length, bodyIds));+ });++ 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 Results.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 Results.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 Results.Ok(CreateBodyResponse(document, kernel.Value));+ }));++ documents.MapPost("/{documentId:guid}/operations/extrude", (Guid documentId, ExtrudeRequestDto request, KernelDocumentStore store) =>+ WithDocument(store, documentId, document =>+ {+ 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 Results.Ok(CreateBodyResponse(document, kernel.Value));+ }));++ documents.MapPost("/{documentId:guid}/operations/revolve", (Guid documentId, RevolveRequestDto request, KernelDocumentStore store) =>+ WithDocument(store, documentId, document =>+ {+ 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 Results.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 Results.Ok(CreateBodyResponse(document, kernel.Value));+ }));++ documents.MapPost("/{documentId:guid}/bodies/{bodyId:guid}/tessellate", (Guid documentId, Guid bodyId, TessellateRequestDto? request, KernelDocumentStore store) =>+ WithDocumentBody(store, documentId, bodyId, body =>+ {+ var options = ApiMappings.BuildTessellationOptions(request?.Options);+ var kernel = BrepDisplayTessellator.Tessellate(body, options);+ if (!kernel.IsSuccess)+ {+ return ApiMappings.KernelFailure(kernel.Diagnostics);+ }++ return Results.Ok(ApiMappings.ToTessellationResponse(kernel.Value));+ }));++ documents.MapPost("/{documentId:guid}/bodies/{bodyId:guid}/pick", (Guid documentId, Guid bodyId, PickRequestDto request, KernelDocumentStore store) =>+ WithDocumentBody(store, documentId, bodyId, body =>+ {+ 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);+ var kernel = BrepPicker.Pick(+ body,+ ray,+ ApiMappings.BuildTessellationOptions(request.TessellationOptions),+ ApiMappings.BuildPickOptions(request.PickOptions));++ if (!kernel.IsSuccess)+ {+ return ApiMappings.KernelFailure(kernel.Diagnostics);+ }++ return Results.Ok(ApiMappings.ToPickResponse(kernel.Value));+ }));+ }++ 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 WithDocumentBody(KernelDocumentStore store, Guid documentId, Guid bodyId, Func<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(body);+ });++ private static BodyCreatedResponseDto CreateBodyResponse(DocumentSession document, BrepBody body)+ {+ var bodyId = document.AddBody(body);+ return new BodyCreatedResponseDto(+ document.Id,+ bodyId,+ 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;+ }+ }+}diff --git a/Aetheris.Server/Contracts/ApiContracts.cs b/Aetheris.Server/Contracts/ApiContracts.csnew file mode 100644index 00000000..28804d55--- /dev/null+++ b/Aetheris.Server/Contracts/ApiContracts.cs@@ -0,0 +1,68 @@+namespace Aetheris.Server.Contracts;++public sealed record DiagnosticDto(string Code, string Severity, string Message, string? Source);++public sealed record ErrorResponseDto(IReadOnlyList<DiagnosticDto> Diagnostics);++public sealed record DocumentCreateRequestDto(string? Name);++public sealed record DocumentCreateResponseDto(Guid DocumentId, string? Name, bool Volatile);++public sealed record DocumentSummaryResponseDto(Guid DocumentId, string? Name, int BodyCount, IReadOnlyList<Guid> BodyIds);++public sealed record BodyCreatedResponseDto(Guid DocumentId, Guid BodyId, int FaceCount, int EdgeCount, int VertexCount);++public sealed record Point3Dto(double X, double Y, double Z);++public sealed record Vector3Dto(double X, double Y, double Z);++public sealed record ProfilePoint2Dto(double X, double Y);++public sealed record BoxCreateRequestDto(double Width, double Height, double Depth);++public sealed record CylinderCreateRequestDto(double Radius, double Height);++public sealed record SphereCreateRequestDto(double Radius);++public sealed record ExtrudeRequestDto(+ IReadOnlyList<ProfilePoint2Dto> Profile,+ Point3Dto Origin,+ Vector3Dto Normal,+ Vector3Dto UAxis,+ double Depth);++public sealed record RevolveRequestDto(+ IReadOnlyList<ProfilePoint2Dto> Profile,+ Point3Dto Origin,+ Vector3Dto AxisDirection,+ Vector3Dto UAxis,+ double AngleRadians = 0d);++public sealed record BooleanRequestDto(Guid LeftBodyId, Guid RightBodyId, string Operation);++public sealed record TessellationOptionsDto(double? AngularToleranceRadians, double? ChordTolerance, int? MinimumSegments, int? MaximumSegments);++public sealed record TessellateRequestDto(TessellationOptionsDto? Options);++public sealed record TessellationResponseDto(IReadOnlyList<FacePatchDto> FacePatches, IReadOnlyList<EdgePolylineDto> EdgePolylines);++public sealed record FacePatchDto(int FaceId, IReadOnlyList<Point3Dto> Positions, IReadOnlyList<Vector3Dto> Normals, IReadOnlyList<int> TriangleIndices);++public sealed record EdgePolylineDto(int EdgeId, IReadOnlyList<Point3Dto> Points, bool IsClosed);++public sealed record PickOptionsDto(bool? NearestOnly, bool? IncludeBackfaces, double? EdgeTolerance, double? SortTieTolerance, double? MaxDistance);++public sealed record PickRequestDto(Point3Dto Origin, Vector3Dto Direction, TessellationOptionsDto? TessellationOptions, PickOptionsDto? PickOptions);++public sealed record PickResponseDto(IReadOnlyList<PickHitDto> Hits);++public sealed record PickHitDto(+ double T,+ Point3Dto Point,+ Vector3Dto? Normal,+ string EntityKind,+ int? FaceId,+ int? EdgeId,+ int? BodyId,+ int? SourcePatchIndex,+ int? SourcePrimitiveIndex);diff --git a/Aetheris.Server/Documents/DocumentSession.cs b/Aetheris.Server/Documents/DocumentSession.csnew file mode 100644index 00000000..5c13380d--- /dev/null+++ b/Aetheris.Server/Documents/DocumentSession.cs@@ -0,0 +1,60 @@+using Aetheris.Kernel.Core.Brep;++namespace Aetheris.Server.Documents;++public sealed class DocumentSession+{+ private readonly Dictionary<Guid, BrepBody> _bodies = new();+ private readonly object _sync = new();++ public DocumentSession(Guid id, string? name = null)+ {+ Id = id;+ Name = name;+ }++ public Guid Id { get; }++ public string? Name { get; }++ public IReadOnlyDictionary<Guid, BrepBody> SnapshotBodies()+ {+ lock (_sync)+ {+ return _bodies.ToDictionary(static kvp => kvp.Key, static kvp => kvp.Value);+ }+ }++ public Guid AddBody(BrepBody body)+ {+ var bodyId = Guid.NewGuid();+ lock (_sync)+ {+ _bodies[bodyId] = body;+ }++ return bodyId;+ }++ public bool TryGetBody(Guid bodyId, out BrepBody body)+ {+ lock (_sync)+ {+ return _bodies.TryGetValue(bodyId, out body!);+ }+ }++ public bool ReplaceBody(Guid bodyId, BrepBody body)+ {+ lock (_sync)+ {+ if (!_bodies.ContainsKey(bodyId))+ {+ return false;+ }++ _bodies[bodyId] = body;+ return true;+ }+ }+}diff --git a/Aetheris.Server/Documents/KernelDocumentStore.cs b/Aetheris.Server/Documents/KernelDocumentStore.csnew file mode 100644index 00000000..176effb3--- /dev/null+++ b/Aetheris.Server/Documents/KernelDocumentStore.cs@@ -0,0 +1,26 @@+namespace Aetheris.Server.Documents;++public sealed class KernelDocumentStore+{+ private readonly Dictionary<Guid, DocumentSession> _documents = new();+ private readonly object _sync = new();++ public DocumentSession Create(string? name = null)+ {+ var session = new DocumentSession(Guid.NewGuid(), name);+ lock (_sync)+ {+ _documents[session.Id] = session;+ }++ return session;+ }++ public bool TryGet(Guid documentId, out DocumentSession session)+ {+ lock (_sync)+ {+ return _documents.TryGetValue(documentId, out session!);+ }+ }+}diff --git a/Aetheris.Server/Program.cs b/Aetheris.Server/Program.csindex d0be8351..a366ed74 100644--- a/Aetheris.Server/Program.cs+++ b/Aetheris.Server/Program.cs@@ -1,49 +1,22 @@+using Aetheris.Server.Api;+using Aetheris.Server.Documents;+var builder = WebApplication.CreateBuilder(args);-// Add services to the container.-// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbucklebuilder.Services.AddEndpointsApiExplorer();builder.Services.AddSwaggerGen();+builder.Services.AddSingleton<KernelDocumentStore>();var app = builder.Build();-app.UseDefaultFiles();-app.UseStaticFiles();--// Configure the HTTP request pipeline.if (app.Environment.IsDevelopment()){app.UseSwagger();app.UseSwaggerUI();}-app.UseHttpsRedirection();--var summaries = new[]-{- "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"-};--app.MapGet("/weatherforecast", () =>-{- var forecast = Enumerable.Range(1, 5).Select(index =>- new WeatherForecast- (- DateOnly.FromDateTime(DateTime.Now.AddDays(index)),- Random.Shared.Next(-20, 55),- summaries[Random.Shared.Next(summaries.Length)]- ))- .ToArray();- return forecast;-})-.WithName("GetWeatherForecast")-.WithOpenApi();--app.MapFallbackToFile("/index.html");+app.MapKernelApi();app.Run();-internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)-{- public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);-}+public partial class Program;diff --git a/Aetheris.slnx b/Aetheris.slnxindex 83ea3bf6..8918a77a 100644--- a/Aetheris.slnx+++ b/Aetheris.slnx@@ -1,9 +1,6 @@<Solution>- <Project Path="aetheris.client/aetheris.client.esproj">- <Build />- <Deploy />- </Project><Project Path="Aetheris.Server/Aetheris.Server.csproj" />+ <Project Path="Aetheris.Server.Tests/Aetheris.Server.Tests.csproj" /><Project Path="Aetheris.Kernel.Core/Aetheris.Kernel.Core.csproj" /><Project Path="Aetheris.Kernel.Core.Tests/Aetheris.Kernel.Core.Tests.csproj" /></Solution>diff --git a/docs/milestones.md b/docs/milestones.mdindex f922a694..6db14bc2 100644--- a/docs/milestones.md+++ b/docs/milestones.md@@ -135,3 +135,12 @@- [x] Default backface handling is culling (`IncludeBackfaces = false`), with opt-in backface inclusion.- [x] Add focused unit tests for face hits/misses, edge tolerance behavior, face-vs-edge precedence, nearest-only determinism, and structured diagnostics for malformed input.- [x] Explicitly defer UI/backend integration, interaction tools, acceleration structures, and caching/performance optimizations.++## M16 — ASP.NET Backend Kernel Host v1 (Local API)++- [x] Add a minimal in-memory document store for local backend kernel sessions (volatile, process-lifetime only).+- [x] Introduce explicit backend DTO contracts for document, modeling, tessellation, and picking endpoints without exposing raw kernel internals as API contracts.+- [x] Expose local HTTP endpoints for document lifecycle, primitive creation (box/cylinder/sphere), extrude/revolve subset operations, narrow M13 boolean operations, display tessellation, and picking.+- [x] Add deterministic kernel diagnostic-to-HTTP mapping with structured error payloads for invalid, unsupported, validation, and missing-resource paths.+- [x] Add focused integration tests for core happy paths and deterministic error behavior.+- [x] Defer frontend integration details and API versioning to M17+.