载入中...
搜索中...
未找到
RoadConnection.cpp
浏览该文件的文档.
4
5#include <algorithm>
6#include <cmath>
7#include <map>
8#include <unordered_set>
9
11namespace {
12Result<void> invalidConnection(std::string message) {
13 return bakeFail<void>(DiagnosticCode::PreconditionViolation, std::move(message), "node.connection");
14}
15V3 rotate(V3 p, float degrees) {
16 const float radians = degrees * 0.017453292519943295f, c = std::cos(radians), s = std::sin(radians);
17 return {p.x * c + p.z * s, p.y, -p.x * s + p.z * c};
18}
19V3 world(V3 p, const RoadNode& node) { return rotate(p, node.connection.yawDegrees) + V3{node.x, node.y, node.z}; }
20V3 seamPoint(const RoadConnectionPort& port, const RoadProfilePoint& point) {
21 const V3 forward{port.forwardX, port.forwardY, port.forwardZ}, up{port.upX, port.upY, port.upZ};
22 return V3{port.x, port.y, port.z} + cross(up, forward) * point.side + up * point.up;
23}
24bool isFinite(V3 p) { return std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z); }
25bool isCoincident(V3 a, V3 b) { return length(a - b) <= 0.01f; }
26} // namespace
28 if (!std::isfinite(connection.yawDegrees)) return invalidConnection("connection yaw is not finite");
29 if (connection.ports.empty()) {
30 if (!connection.vertices.empty() || !connection.triangles.empty() || !connection.assetId.empty())
31 return invalidConnection("custom geometry needs explicit connection ports");
32 return Result<void>::success();
33 }
34 if (connection.assetId.empty() || connection.assetId.size() > 256u || connection.ports.size() > 64u ||
35 connection.vertices.size() < 3u || connection.vertices.size() > 65536u || connection.triangles.empty() ||
36 connection.triangles.size() > 131072u || !std::isfinite(connection.yawDegrees) ||
37 std::fabs(connection.yawDegrees) > 180.f)
38 return invalidConnection("custom connection identity, transform or mesh budget is invalid");
39 std::size_t seamPoints = 0;
40 for (const auto& port : connection.ports) seamPoints += port.section.size();
41 if (seamPoints > 64u * 128u || seamPoints * connection.vertices.size() > 8u * 1024u * 1024u)
42 return invalidConnection("connection seam validation exceeds work budget");
43 for (const auto& vertex : connection.vertices) {
44 const V3 position{vertex.x, vertex.y, vertex.z}, normal{vertex.nx, vertex.ny, vertex.nz};
45 if (!isFinite(position) || length(position) > 10000.f || !isFinite(normal) ||
46 std::fabs(length(normal) - 1.f) > 1e-3f || !std::isfinite(vertex.u) || !std::isfinite(vertex.v))
47 return invalidConnection("custom mesh vertex is invalid");
48 }
49 std::map<std::pair<std::uint32_t, std::uint32_t>, int> edges;
50 std::vector<bool> referenced(connection.vertices.size(), false);
51 for (const auto& triangle : connection.triangles) {
52 if (triangle.a >= connection.vertices.size() || triangle.b >= connection.vertices.size() ||
53 triangle.c >= connection.vertices.size() || triangle.material > RoadMaterial::TunnelPortalAsphalt)
54 return invalidConnection("custom mesh triangle index/material is invalid");
55 const auto& a = connection.vertices[triangle.a];
56 const auto& b = connection.vertices[triangle.b];
57 const auto& c = connection.vertices[triangle.c];
58 const V3 geometric = cross(V3{b.x - a.x, b.y - a.y, b.z - a.z}, V3{c.x - a.x, c.y - a.y, c.z - a.z});
59 if (length(geometric) < 1e-7f ||
60 dot(geometric, V3{a.nx + b.nx + c.nx, a.ny + b.ny + c.ny, a.nz + b.nz + c.nz}) <= 0.f)
61 return invalidConnection("custom mesh has degenerate or reversed triangles");
62 const std::uint32_t indices[]{triangle.a, triangle.b, triangle.c};
63 for (int i = 0; i < 3; ++i) {
64 referenced[indices[i]] = true;
65 auto key = std::minmax(indices[i], indices[(i + 1) % 3]);
66 if (++edges[{key.first, key.second}] > 2) return invalidConnection("custom mesh has a nonmanifold edge");
67 }
68 }
69 std::unordered_set<std::uint32_t> ids;
70 for (const auto& port : connection.ports) {
71 const V3 origin{port.x, port.y, port.z}, forward{port.forwardX, port.forwardY, port.forwardZ},
72 up{port.upX, port.upY, port.upZ};
73 if (port.id == 0 || !ids.insert(port.id).second || !isFinite(origin) || length(origin) < 0.01f ||
74 length(origin) > 10000.f || !isFinite(forward) || !isFinite(up) ||
75 std::fabs(length(forward) - 1.f) > 1e-4f || std::fabs(length(up) - 1.f) > 1e-4f ||
76 std::fabs(dot(forward, up)) > 1e-4f || dot(forward, origin) <= 0.f)
77 return invalidConnection("connection port frame must be outward and orthonormal");
78 auto section = validateSection(port.section, port.sectionClosed);
79 if (!section.ok()) return section;
80 std::vector<std::vector<std::uint32_t>> seamVertices;
81 for (const auto& point : port.section) {
82 const V3 position = seamPoint(port, point);
83 std::vector<std::uint32_t> matches;
84 for (std::size_t i = 0; i < connection.vertices.size(); ++i) {
85 const auto& vertex = connection.vertices[i];
86 if (referenced[i] && isCoincident(position, {vertex.x, vertex.y, vertex.z}) &&
87 (std::fabs(vertex.u) < .01f || std::fabs(vertex.u - 1.f) < .01f || std::fabs(vertex.v) < .01f ||
88 std::fabs(vertex.v - 1.f) < .01f))
89 matches.push_back(static_cast<std::uint32_t>(i));
90 }
91 if (matches.empty())
92 return invalidConnection(
93 "port section must coincide with referenced mesh boundary vertices and UV 0/1");
94 seamVertices.push_back(std::move(matches));
95 }
96 const std::size_t segmentCount = port.sectionClosed ? seamVertices.size() : seamVertices.size() - 1;
97 for (std::size_t i = 0; i < segmentCount; ++i) {
98 bool boundary = false;
99 for (auto a : seamVertices[i])
100 for (auto b : seamVertices[(i + 1) % seamVertices.size()]) {
101 const auto key = std::minmax(a, b);
102 const auto found = edges.find({key.first, key.second});
103 boundary = boundary || (found != edges.end() && found->second == 1);
104 }
105 if (!boundary) return invalidConnection("port segment is not an open mesh boundary");
106 }
107 }
108 return Result<void>::success();
109}
111 auto asset = validateConnectionAsset(node.connection);
112 if (!asset.ok()) return asset;
113 if (node.connection.ports.empty()) return Result<void>::success();
114 std::unordered_set<std::uint32_t> attached;
115 for (const auto& port : node.connection.ports) {
116 if (port.edgeId == 0) continue;
117 auto edge = network.edgeResult(port.edgeId);
118 if (!edge.ok()) return invalidConnection("connection port refers to a stale edge");
119 if ((edge.value().from != node.id && edge.value().to != node.id) || !attached.insert(port.edgeId).second)
120 return invalidConnection("connection port binds a nonincident or duplicate edge");
121 }
122 for (const auto& edge : network.edges())
123 if ((edge.from == node.id || edge.to == node.id) && !attached.contains(edge.id))
124 return invalidConnection("every incident road needs exactly one bound custom port");
125 return Result<void>::success();
126}
127float connectionSocketDistance(const RoadNode& node, const RoadEdge& edge, float pathLength) {
128 (void)pathLength;
129 for (const auto& port : node.connection.ports)
130 if (port.edgeId == edge.id) return length(V3{port.x, port.y, port.z});
131 return 0.f;
132}
135 if (!bindings.ok()) return bindings;
136 for (const auto& port : node.connection.ports) {
137 if (port.edgeId == 0) continue;
138 auto edge = network.edgeResult(port.edgeId);
139 if (!edge.ok()) return Result<void>::failure(edge.status());
140 auto path = edgeToSpline(edge.value());
141 if (!path.ok()) return Result<void>::failure(path.status());
142 auto pathLength = path.value().lengthResult(24);
143 if (!pathLength.ok()) return Result<void>::failure(pathLength.status());
144 const bool outgoing = edge.value().from == node.id;
145 const float distance = connectionSocketDistance(node, edge.value(), pathLength.value());
146 if (distance >= pathLength.value() - .01f)
147 return invalidConnection("custom socket consumes the full road length");
148 auto frame = path.value().travelFrameResult(outgoing ? distance : pathLength.value() - distance, "clamp", 24);
149 if (!frame.ok()) return Result<void>::failure(frame.status());
150 const auto& f = frame.value();
151 const V3 origin{f.sample.x, f.sample.y, f.sample.z}, side{f.sideX, f.sideY, f.sideZ}, up{f.upX, f.upY, f.upZ};
152 const V3 forward = V3{f.forwardX, f.forwardY, f.forwardZ} * (outgoing ? 1.f : -1.f);
153 if (!isCoincident(origin, world({port.x, port.y, port.z}, node)) ||
154 dot(forward, rotate({port.forwardX, port.forwardY, port.forwardZ}, node.connection.yawDegrees)) < .9999f ||
155 dot(up, rotate({port.upX, port.upY, port.upZ}, node.connection.yawDegrees)) < .9999f)
156 return invalidConnection("road spline position, grade or crossfall does not match custom port frame");
157 auto profile = makeRoadProfile(edge.value().style, edge.value().lanesForward, edge.value().lanesBackward);
158 if (!profile.ok()) return Result<void>::failure(profile.status());
159 if (profile.value().points.size() != port.section.size() || profile.value().closed != port.sectionClosed)
160 return invalidConnection("custom port section topology differs from road profile");
161 for (const auto& p : profile.value().points) {
162 const V3 roadPoint =
163 origin + side * scaledProfileSide(p.side, asphaltHalfWidth(edge.value()), f.sample.scaleX) + up * p.up;
164 const bool found = std::any_of(port.section.begin(), port.section.end(), [&](const auto& point) {
165 return isCoincident(roadPoint, world(seamPoint(port, point), node));
166 });
167 if (!found) return invalidConnection("custom port full section/width differs from the road socket");
168 }
169 }
170 return Result<void>::success();
171}
173 const RoadBakeOptions& options) {
174 auto seams = validateConnectionSeams(network, node);
175 if (!seams.ok()) return seams;
176 const std::size_t needed = node.connection.vertices.size() + node.connection.triangles.size() * 3u;
177 const std::size_t existing =
178 static_cast<std::size_t>(mesh.getVertexCount()) + static_cast<std::size_t>(mesh.getIndexCount());
179 if (existing > options.maximumMeshElements || needed > options.maximumMeshElements - existing)
180 return invalidConnection("custom connection exceeds mesh output budget");
181 const auto base = static_cast<std::uint32_t>(mesh.getVertexCount());
182 for (const auto& v : node.connection.vertices) {
183 const V3 p = world({v.x, v.y, v.z}, node), n = rotate({v.nx, v.ny, v.nz}, node.connection.yawDegrees);
184 mesh.addVertex(p.x, p.y, p.z, n.x, n.y, n.z, v.u, v.v);
185 }
186 for (const auto& tri : node.connection.triangles) {
187 mesh.setActiveGroup(roadMaterialGroup(tri.material));
188 mesh.addTriangle(base + tri.a, base + tri.b, base + tri.c);
189 }
190 return Result<void>::success();
191}
192} // namespace eve::procgen::road::detail
193
194namespace eve::procgen::road {
196 const int index = findNodeIndex(nodeId);
197 if (index < 0)
198 return Result<void>::failure(Diagnostic::error(DiagnosticCode::NotFound, "unknown connection node", "nodeId"));
199 auto candidate = *this;
200 candidate.nodes_[static_cast<std::size_t>(index)].connection = std::move(connection);
201 auto valid = candidate.validate();
202 if (!valid.ok()) return valid;
203 candidate.revision_ = revision_ + 1;
204 *this = std::move(candidate);
205 return Result<void>::success();
206}
207} // namespace eve::procgen::road
const std::string & s
float degrees
Definition CardTypes.cpp:38
glm::vec4 p[6]
std::string nodeId
SQObjectPtr key
Definition ECS.cpp:155
int triangle
Definition FluidSdf.cpp:554
std::string message
glm::vec3 n
Definition Grass.cpp:63
std::vector< std::uint32_t > indices
float v
HexVec3 up
std::int32_t c
float length
std::array< float, 3 > position
std::vector< Edge > edges
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
Texture * normal
OceanMeshSettings mesh
glm::dvec3 origin
ssq::Object frame
float f
std::vector< ParticleBakeMaterial > bindings
std::string path
Definition PlayHost.cpp:111
const RoadNode * node
bool found
const SquirrelValueOptions & options
CommandLogBoundary boundary
Anchor rule, see above.
uint32_t index
V forward
glm::vec3 point
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
const T & value() const &
Borrow the value from a const lvalue after checking success.
Definition Result.h:339
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
CPU triangle mesh from procedural mesh recipes (e.g. marching cubes). Positions/normals are xyz-packe...
Definition MeshBuild.h:20
Owning directed road graph with lane connectivity.
Definition RoadNetwork.h:19
const std::vector< RoadEdge > & edges() const noexcept
Edges.
Result< RoadEdge > edgeResult(std::uint32_t id) const
Return an owning edge snapshot. @cost Copies control points, custom sections and bounded interval/fac...
Result< void > setNodeConnection(std::uint32_t nodeId, RoadConnection connection)
Atomically attach or clear an owning custom connection mesh and its port bindings.
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
bool isFinite(float value)
True when finite.
SocketDirection rotate(SocketDirection direction, int degrees)
V3 cross(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:29
float asphaltHalfWidth(const RoadEdge &edge)
Module-private road bake implementation helper.
Definition RoadBake.cpp:100
float scaledProfileSide(float side, float asphaltHalf, float scale)
Module-private transverse width transform preserving fixed-width shoulders.
Definition RoadBake.cpp:114
Result< void > validateConnectionBindings(const RoadNetwork &network, const RoadNode &node)
Validate node-local edge bindings against the sole authoritative graph.
Result< SplinePath > edgeToSpline(const RoadEdge &edge)
Module-private road bake implementation helper.
Definition RoadBake.cpp:62
Result< void > validateSection(const std::vector< RoadProfilePoint > &points, bool closed)
Validate bounded simple section geometry and semantic material tags.
Result< void > validateConnectionAsset(const RoadConnection &connection)
Validate the owned asset, local frames, indexed topology and exact mesh boundary seams.
Result< void > bakeCustomConnection(MeshBuild &mesh, const RoadNetwork &network, const RoadNode &node, const RoadBakeOptions &options)
Append the validated custom connection mesh with its node transform.
float dot(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:28
Result< void > validateConnectionSeams(const RoadNetwork &network, const RoadNode &node)
Validate actual baked spline sockets against every full custom asset seam.
float connectionSocketDistance(const RoadNode &node, const RoadEdge &edge, float pathLength)
Return deterministic arc-distance to the bound custom socket (zero when absent).
Result< RoadProfile > makeRoadProfile(const RoadStyle &style, int lanesForward, int lanesBackward)
Build a mathematical road cross-section for the given lane counts.
const char * roadMaterialGroup(RoadMaterial material) noexcept
Map a material tag to the MeshBuild group name used by the baker. @ownership borrowed — returns a poi...
@ TunnelPortalAsphalt
Driving surface inside an authored tunnel portal footprint.
Options for baking a road network into mesh + navigation overlays.
Definition RoadBake.h:50
Owning custom junction asset snapshot; all geometry/ports share one node-local transform.
Definition RoadTypes.h:266
std::vector< RoadConnectionVertex > vertices
Definition RoadTypes.h:270
std::vector< RoadConnectionPort > ports
Empty selects the procedural junction, with no custom mesh.
Definition RoadTypes.h:272
std::vector< RoadConnectionTriangle > triangles
Definition RoadTypes.h:271
Directed centerline edge with optional reverse lanes.
Definition RoadTypes.h:286
Junction node owned by a road network.
Definition RoadTypes.h:275