载入中...
搜索中...
未找到
RoadBakePlacements.cpp
浏览该文件的文档.
3
4#include <map>
5#include <tuple>
6#include "common/Capability.h"
7#include "common/Diagnostic.h"
11
12#include <algorithm>
13#include <array>
14#include <cmath>
15#include <functional>
16#include <limits>
17#include <unordered_map>
18#include <unordered_set>
19#include <utility>
20#include <vector>
21
23
25 const std::unordered_set<std::uint32_t>& activeJunctionNodes,
26 RoadFrameCache& frameCache) {
27 const bool needsTerrain = std::any_of(network.edges().begin(), network.edges().end(), [](const RoadEdge& edge) {
28 return (edge.style.sideTerrain.mode != RoadSideTerrainMode::None ||
29 edge.style.sideTerrain.alignment == RoadSideAlignment::TerrainNormal) &&
30 (edge.style.sideObjectsLeft || edge.style.sideObjectsRight);
31 });
32 auto* terrainQuery = options.placementWorldQuery;
33 if (needsTerrain && !terrainQuery) terrainQuery = eve::cap::query<eve::IProcgenWorldQuery>();
34 if (needsTerrain && !terrainQuery)
35 return bakeFail<void>(DiagnosticCode::Unsupported, "side-object terrain snapping requires IProcgenWorldQuery",
36 "sideTerrain");
37 std::size_t terrainWork = 0;
38 auto* assetBounds = options.placementAssetBounds;
39 const bool needsAssets = std::any_of(network.edges().begin(), network.edges().end(), [](const RoadEdge& edge) {
40 return edge.style.sideTerrain.asset.has_value() && (edge.style.sideObjectsLeft || edge.style.sideObjectsRight);
41 });
42 if (needsAssets && !assetBounds) assetBounds = eve::cap::query<eve::IProcgenAssetBounds>();
43 if (needsAssets && !assetBounds)
44 return bakeFail<void>(DiagnosticCode::Unsupported, "side-object prefab bounds require IProcgenAssetBounds",
45 "sideTerrain.assetRef");
46 std::map<std::tuple<eve::PersistentId, eve::PersistentId, eve::PrefabRootPose>, std::array<float, 6>>
47 resolvedAssets;
48 std::unordered_map<std::uint32_t, RoadSideTerrainRule> terrainRules;
49 std::unordered_map<std::uint32_t, std::array<float, 6>> edgeAssetBounds;
50 for (const auto& edge : network.edges()) {
51 auto rule = edge.style.sideTerrain;
52 if (rule.asset.has_value() && (edge.style.sideObjectsLeft || edge.style.sideObjectsRight)) {
53 const auto key = std::tuple{rule.asset->asset.id(), rule.asset->buildId, rule.asset->rootPose};
54 auto found = resolvedAssets.find(key);
55 if (found == resolvedAssets.end()) {
56 auto resolved = assetBounds->localBounds(rule.asset->asset, rule.asset->buildId, rule.asset->rootPose);
57 if (!resolved.ok()) return Result<void>::failure(resolved.status());
58 const auto& bounds = resolved.value();
59 for (unsigned axis = 0; axis < 3; ++axis)
60 if (!std::isfinite(bounds[axis]) || !std::isfinite(bounds[axis + 3]) ||
61 bounds[axis] > bounds[axis + 3] || std::fabs(bounds[axis]) > 10000.f ||
62 std::fabs(bounds[axis + 3]) > 10000.f)
63 return bakeFail<void>(DiagnosticCode::PreconditionViolation,
64 "asset provider returned invalid prefab bounds", "sideTerrain.assetRef");
65 found = resolvedAssets.emplace(key, bounds).first;
66 }
67 const auto& bounds = found->second;
68 rule.minSide = bounds[0];
69 rule.maxSide = bounds[3];
70 rule.minForward = bounds[2];
71 rule.maxForward = bounds[5];
72 edgeAssetBounds.emplace(edge.id, bounds);
73 }
74 terrainRules.emplace(edge.id, std::move(rule));
75 }
76 if (!std::isfinite(options.sideObjectSpacing) || options.sideObjectSpacing < 0.25f ||
77 !std::isfinite(options.sideObjectOffset) || options.sideObjectOffset < 0.f || options.maximumPlacements < 1)
78 return bakeFail<void>(DiagnosticCode::InvalidArgument, "road placement options are invalid", "placements");
79 if (!std::isfinite(options.sideObjectClearance) || options.sideObjectClearance < 0.f)
80 return bakeFail<void>(DiagnosticCode::InvalidArgument, "road side-object clearance is invalid",
81 "placements.clearance");
82
83 struct EdgeSource {
84 const RoadEdge* edge = nullptr;
86 float length = 0.f;
87 float halfWidth = 0.f;
88 float sideStart = 0.f;
89 float sideEnd = 0.f;
90 std::size_t sideCount = 0;
91 float sideFirst = 0.f, sideStep = 0.f;
92 int arcSamples = 32;
93 std::optional<RoadSurfacePolyline> surface;
94 };
95 std::unordered_map<std::uint32_t, std::vector<std::uint32_t>> adjacency;
96 for (const auto& node : network.nodes()) adjacency.emplace(node.id, std::vector<std::uint32_t>{});
97 for (const auto& edge : network.edges()) {
98 adjacency[edge.from].push_back(edge.to);
99 adjacency[edge.to].push_back(edge.from);
100 }
101
102 std::vector<std::vector<std::uint32_t>> roundabouts;
103 auto canonicalCycle = [](std::vector<std::uint32_t> cycle) {
104 const auto minimum = std::min_element(cycle.begin(), cycle.end());
105 std::rotate(cycle.begin(), minimum, cycle.end());
106 std::vector<std::uint32_t> reversed{cycle.front()};
107 for (auto it = cycle.rbegin(); it != cycle.rend() - 1; ++it) reversed.push_back(*it);
108 return reversed < cycle ? reversed : cycle;
109 };
110 for (const auto& node : network.nodes()) {
111 if (adjacency[node.id].size() != 3u) continue;
112 std::vector<std::uint32_t> path{node.id};
113 std::function<void(std::uint32_t)> visit = [&](std::uint32_t current) {
114 for (const auto next : adjacency[current]) {
115 if (next == path.front()) {
116 if (path.size() < 3u || path.size() > 12u) continue;
117 auto cycle = canonicalCycle(path);
118 if (std::find(roundabouts.begin(), roundabouts.end(), cycle) != roundabouts.end()) continue;
119 float centerX = 0.f, centerZ = 0.f, minY = std::numeric_limits<float>::max();
120 float maxY = -std::numeric_limits<float>::max();
121 bool valid = true;
122 int entryCount = 0;
123 for (const auto id : cycle) {
124 if (adjacency[id].size() < 2u || adjacency[id].size() > 3u) {
125 valid = false;
126 break;
127 }
128 if (adjacency[id].size() == 3u) ++entryCount;
129 auto value = network.nodeResult(id);
130 if (!value.ok()) {
131 valid = false;
132 break;
133 }
134 centerX += value.value().x;
135 centerZ += value.value().z;
136 minY = std::min(minY, value.value().y);
137 maxY = std::max(maxY, value.value().y);
138 }
139 if (!valid || entryCount < 3 || maxY - minY > 1.f) continue;
140 for (std::size_t i = 0; i < cycle.size(); ++i) {
141 const auto a = cycle[i];
142 const auto b = cycle[(i + 1u) % cycle.size()];
143 const auto ringEdge =
144 std::find_if(network.edges().begin(), network.edges().end(), [&](const RoadEdge& edge) {
145 return (edge.from == a && edge.to == b) || (edge.from == b && edge.to == a);
146 });
147 if (ringEdge == network.edges().end() || ringEdge->controlPoints.size() < 3u) {
148 valid = false;
149 break;
150 }
151 }
152 if (!valid) continue;
153 centerX /= static_cast<float>(cycle.size());
154 centerZ /= static_cast<float>(cycle.size());
155 float minRadius = std::numeric_limits<float>::max(), maxRadius = 0.f;
156 for (const auto id : cycle) {
157 const auto value = network.nodeResult(id).value();
158 const float dx = value.x - centerX, dz = value.z - centerZ;
159 const float radius = std::sqrt(dx * dx + dz * dz);
160 minRadius = std::min(minRadius, radius);
161 maxRadius = std::max(maxRadius, radius);
162 }
163 if (minRadius >= 1.f && maxRadius <= minRadius * 1.8f) roundabouts.push_back(std::move(cycle));
164 continue;
165 }
166 if (path.size() >= 12u || adjacency[next].size() < 2u || adjacency[next].size() > 3u ||
167 std::find(path.begin(), path.end(), next) != path.end())
168 continue;
169 path.push_back(next);
170 visit(next);
171 path.pop_back();
172 }
173 };
174 visit(node.id);
175 }
176 std::sort(roundabouts.begin(), roundabouts.end());
177 std::unordered_set<std::uint32_t> roundaboutNodes;
178 for (const auto& cycle : roundabouts)
179 for (const auto id : cycle) roundaboutNodes.insert(id);
180
181 std::vector<EdgeSource> sources;
182 sources.reserve(network.edges().size());
183 std::size_t required = 0;
184 for (const auto& cycle : roundabouts) {
185 required += 1u;
186 for (const auto id : cycle)
187 if (adjacency[id].size() == 3u) ++required;
188 }
189 for (const auto& node : network.nodes()) {
190 if (roundaboutNodes.contains(node.id)) continue;
191 const auto arms = static_cast<std::size_t>(
192 std::count_if(network.edges().begin(), network.edges().end(),
193 [&](const RoadEdge& edge) { return edge.from == node.id || edge.to == node.id; }));
194 if (arms >= 3u) required += arms == 3u ? 2u : 1u;
195 }
196 for (const auto& edge : network.edges()) {
197 auto spline = edgeToSpline(edge);
198 if (!spline.ok()) return Result<void>::failure(spline.status());
199 const int arcSamples = edge.style.sideObjectDistribution == RoadSideDistribution::LegacyCentered ? 32 : 512;
200 auto lengthResult = spline.value().lengthResult(arcSamples);
201 if (!lengthResult.ok()) return Result<void>::failure(lengthResult.status());
202 auto profile = makeRoadProfile(edge.style, edge.lanesForward, edge.lanesBackward);
203 if (!profile.ok()) return Result<void>::failure(profile.status());
204 std::optional<RoadSurfacePolyline> surface;
205 const bool followsSurface = edge.style.sidePlacement.pathSampling == RoadSidePathSampling::SurfaceSegments;
206 const auto retained = frameCache.surfaces.find(edge.id);
207 if (followsSurface && retained != frameCache.surfaces.end()) {
208 auto prepared = prepareSurfacePolyline(retained->second.frames);
209 if (!prepared.ok()) return Result<void>::failure(prepared.status());
210 surface = std::move(prepared).takeValue();
211 surface->firstVisible = retained->second.firstVisible;
212 surface->lastVisible = retained->second.lastVisible;
213 }
214 const float length = surface ? surface->length : lengthResult.value();
215 float sideStart = edge.style.sideObjectStartOffset;
216 float sideEnd = length - edge.style.sideObjectEndOffset;
217 if (!surface && activeJunctionNodes.contains(edge.from)) {
218 const auto node = network.nodeResult(edge.from);
219 if (!node.ok()) return Result<void>::failure(node.status());
220 sideStart = std::max(sideStart, junctionSocketDistance(network, node.value(), edge, length));
221 }
222 if (!surface && activeJunctionNodes.contains(edge.to)) {
223 const auto node = network.nodeResult(edge.to);
224 if (!node.ok()) return Result<void>::failure(node.status());
225 sideEnd = std::min(sideEnd, length - junctionSocketDistance(network, node.value(), edge, length));
226 }
227 if (surface) {
228 sideStart = std::max(sideStart, static_cast<float>(surface->distances[surface->firstVisible]));
229 sideEnd = std::min(sideEnd, static_cast<float>(surface->distances[surface->lastVisible]));
230 } else if (followsSurface) {
231 // Geometry intentionally omitted the whole edge inside its sockets; no visible facilities exist.
232 sideStart = sideEnd = 0.f;
233 }
234 sideEnd = std::max(sideStart, sideEnd);
235 const float placementLength = sideEnd - sideStart;
236 const auto distribution = edge.style.sideObjectDistribution;
237 const float firstSideDistance =
238 distribution == RoadSideDistribution::LegacyCentered ? options.sideObjectSpacing * .5f : 0.f;
239 float sideStep = options.sideObjectSpacing;
240 std::size_t sideSamples = 0;
241 if ((edge.style.sideObjectsLeft || edge.style.sideObjectsRight) && placementLength > firstSideDistance) {
242 const float ratio = (placementLength - firstSideDistance) / options.sideObjectSpacing;
243 if (!std::isfinite(ratio) || ratio > static_cast<float>(options.maximumPlacements))
244 return bakeFail<void>(DiagnosticCode::PreconditionViolation,
245 "road placement distribution exceeds budget", "placements");
246 if (distribution == RoadSideDistribution::Average) {
247 const float integral = std::floor(ratio), fraction = ratio - integral;
248 // Explicit nearest-even rounding is independent of process floating-point rounding mode.
249 const float rounded =
250 integral + ((fraction > .5f || (fraction == .5f && std::fmod(integral, 2.f) != 0.f)) ? 1.f : 0.f);
251 const auto intervals = static_cast<std::size_t>(std::max(1.f, rounded));
252 sideSamples = intervals + 1;
253 sideStep = placementLength / static_cast<float>(intervals) + .005f;
254 } else if (distribution == RoadSideDistribution::LegacyCentered)
255 sideSamples = static_cast<std::size_t>(std::floor(ratio)) + 1;
256 else
257 sideSamples = static_cast<std::size_t>(std::ceil(ratio));
258 }
259 const auto enabledSides =
260 edge.style.sidePlacement.reference == RoadSideReference::Center
261 ? static_cast<std::size_t>(edge.style.sideObjectsLeft || edge.style.sideObjectsRight)
262 : static_cast<std::size_t>(edge.style.sideObjectsLeft) +
263 static_cast<std::size_t>(edge.style.sideObjectsRight);
264 required += 2u + sideSamples * enabledSides;
265 if (required > static_cast<std::size_t>(options.maximumPlacements))
266 return bakeFail<void>(DiagnosticCode::PreconditionViolation, "road placement budget exceeded",
267 "placements");
268 sources.push_back({&edge, std::move(spline).takeValue(), length, profile.value().halfWidth, sideStart, sideEnd,
269 sideSamples, sideStart + firstSideDistance, sideStep, arcSamples, std::move(surface)});
270 }
271 placements.reserve(required);
272
273 for (const auto& cycle : roundabouts) {
274 float centerX = 0.f, centerY = 0.f, centerZ = 0.f;
275 for (const auto id : cycle) {
276 const auto node = network.nodeResult(id).value();
277 centerX += node.x;
278 centerY += node.y;
279 centerZ += node.z;
280 }
281 const float divisor = static_cast<float>(cycle.size());
282 centerX /= divisor;
283 centerY /= divisor;
284 centerZ /= divisor;
285 const std::uint32_t roundaboutId = cycle.front();
286 const auto entryCount = static_cast<std::int64_t>(
287 std::count_if(cycle.begin(), cycle.end(), [&](std::uint32_t id) { return adjacency[id].size() == 3u; }));
288 const auto pointNamespace = 0x524e444200000000ull | roundaboutId;
289 auto appendRoundaboutPoint = [&](const RoadNode& node, V3 heading, const char* role,
290 std::uint64_t ordinal) -> Result<void> {
291 const int row = placements.add(node.x, node.y, node.z);
292 placements.setNormal(row, 0.f, 1.f, 0.f);
293 placements.setYaw(row, std::atan2(heading.x, heading.z) * 57.2957795f);
294 placements.setPointSeed(row, deriveSeed(roundaboutId, std::string(role) + std::to_string(node.id)));
295 auto status = placements.trySetPointId(row, derivePointId(pointNamespace, ordinal));
296 if (!status.ok()) return status;
297 status = placements.trySetStringAttribute(row, "road_role", role);
298 if (!status.ok()) return status;
299 status = placements.trySetIntAttribute(row, "road_node_id", node.id);
300 if (!status.ok()) return status;
301 status = placements.trySetIntAttribute(row, "road_roundabout_id", roundaboutId);
302 if (!status.ok()) return status;
303 status = placements.trySetIntAttribute(row, "road_arm_count", entryCount);
304 if (!status.ok()) return status;
305 return placements.trySetVectorAttribute(row, "road_direction", heading.x, heading.y, heading.z);
306 };
307
308 RoadNode center;
309 center.x = centerX;
310 center.y = centerY;
311 center.z = centerZ;
312 auto status = appendRoundaboutPoint(center, V3{0.f, 0.f, 1.f}, "junction.roundabout.center", 1u);
313 if (!status.ok()) return status;
314 std::uint64_t entryOrdinal = 2u;
315 for (std::size_t i = 0; i < cycle.size(); ++i) {
316 const auto node = network.nodeResult(cycle[i]).value();
317 if (adjacency[node.id].size() != 3u) continue;
318 V3 heading{node.x - centerX, 0.f, node.z - centerZ};
319 for (const auto neighbor : adjacency[node.id]) {
320 if (std::find(cycle.begin(), cycle.end(), neighbor) != cycle.end()) continue;
321 const auto outside = network.nodeResult(neighbor).value();
322 heading = V3{outside.x - node.x, 0.f, outside.z - node.z};
323 break;
324 }
325 status = appendRoundaboutPoint(node, normalize(heading), "junction.roundabout.entry", entryOrdinal++);
326 if (!status.ok()) return status;
327 }
328 }
329
330 for (const auto& node : network.nodes()) {
331 if (roundaboutNodes.contains(node.id)) continue;
332 std::vector<V3> directions;
333 for (const auto& edge : network.edges()) {
334 auto appendDirection = [&](const RoadControlPoint& point) {
335 const V3 direction{point.x - node.x, 0.f, point.z - node.z};
336 if (dot(direction, direction) <= 1e-6f) return false;
337 directions.push_back(normalize(direction));
338 return true;
339 };
340 if (edge.from == node.id) {
341 for (std::size_t i = 1u; i < edge.controlPoints.size(); ++i)
342 if (appendDirection(edge.controlPoints[i])) break;
343 } else if (edge.to == node.id) {
344 for (std::size_t i = edge.controlPoints.size() - 1u; i-- > 0u;)
345 if (appendDirection(edge.controlPoints[i])) break;
346 }
347 }
348 if (directions.size() < 3u) continue;
349
350 int oppositePairs = 0;
351 for (std::size_t a = 0; a < directions.size(); ++a)
352 for (std::size_t b = a + 1u; b < directions.size(); ++b)
353 if (dot(directions[a], directions[b]) < -0.85f) ++oppositePairs;
354
355 const char* role = "junction.multi";
356 if (directions.size() == 3u) role = oppositePairs > 0 ? "junction.t" : "junction.y";
357 if (directions.size() == 4u) role = oppositePairs >= 2 ? "junction.x" : "junction.multi";
358
359 V3 heading{};
360 if (directions.size() == 3u && oppositePairs > 0) {
361 float leastOpposed = -2.f;
362 for (const auto& candidate : directions) {
363 float closest = 1.f;
364 for (const auto& other : directions) {
365 if (&candidate != &other) closest = std::min(closest, dot(candidate, other));
366 }
367 if (closest > leastOpposed) {
368 leastOpposed = closest;
369 heading = candidate;
370 }
371 }
372 } else {
373 heading = directions.front();
374 }
375
376 const int row = placements.add(node.x, node.y, node.z);
377 placements.setNormal(row, 0.f, 1.f, 0.f);
378 placements.setYaw(row, std::atan2(heading.x, heading.z) * 57.2957795f);
379 placements.setPointSeed(row, deriveSeed(node.id, role));
380 auto status = placements.trySetPointId(row, derivePointId(0x4a554e4300000000ull | node.id, 1u));
381 if (!status.ok()) return status;
382 status = placements.trySetStringAttribute(row, "road_role", role);
383 if (!status.ok()) return status;
384 status = placements.trySetIntAttribute(row, "road_node_id", node.id);
385 if (!status.ok()) return status;
386 status = placements.trySetIntAttribute(row, "road_arm_count", static_cast<std::int64_t>(directions.size()));
387 if (!status.ok()) return status;
388 status = placements.trySetIntAttribute(row, "road_side", 0);
389 if (!status.ok()) return status;
390 status = placements.trySetVectorAttribute(row, "road_direction", heading.x, heading.y, heading.z);
391 if (!status.ok()) return status;
392
393 if (directions.size() == 3u) {
394 const float islandDistance = std::max(1.f, node.junctionRadius * 0.45f);
395 const int islandRow =
396 placements.add(node.x + heading.x * islandDistance, node.y, node.z + heading.z * islandDistance);
397 placements.setNormal(islandRow, 0.f, 1.f, 0.f);
398 placements.setYaw(islandRow, std::atan2(heading.x, heading.z) * 57.2957795f);
399 constexpr const char* islandRole = "junction.channelizing.island";
400 placements.setPointSeed(islandRow, deriveSeed(node.id, islandRole));
401 status = placements.trySetPointId(islandRow, derivePointId(0x4a554e4300000000ull | node.id, 2u));
402 if (!status.ok()) return status;
403 status = placements.trySetStringAttribute(islandRow, "road_role", islandRole);
404 if (!status.ok()) return status;
405 status = placements.trySetIntAttribute(islandRow, "road_node_id", node.id);
406 if (!status.ok()) return status;
407 status = placements.trySetIntAttribute(islandRow, "road_arm_count", 3);
408 if (!status.ok()) return status;
409 status = placements.trySetFloatAttribute(islandRow, "road_distance", islandDistance);
410 if (!status.ok()) return status;
411 status = placements.trySetVectorAttribute(islandRow, "road_direction", heading.x, heading.y, heading.z);
412 if (!status.ok()) return status;
413 }
414 }
415
416 std::vector<V3> acceptedSidePoints;
417 for (const auto& source : sources) {
418 std::uint64_t ordinal = 1;
419 const auto pointNamespace = 0x524f414400000000ull | source.edge->id;
420 auto append = [&](float distance, float lateral, const char* role, int side,
421 bool avoidConflicts) -> Result<bool> {
422 auto frame = source.surface ? sampleSurfacePolyline(*source.surface, distance)
423 : source.spline.travelFrameResult(distance, "clamp", source.arcSamples);
424 if (!frame.ok()) return Result<bool>::failure(frame.status());
425 auto f = std::move(frame).takeValue();
426 if (!source.surface && distance > source.length) {
427 const float extension = distance - source.length;
428 f.sample.x += f.forwardX * extension;
429 f.sample.y += f.forwardY * extension;
430 f.sample.z += f.forwardZ * extension;
431 }
432 const auto& terrainRule = terrainRules.at(source.edge->id);
433 const bool hasAsset = side != 0 && terrainRule.asset.has_value();
434 const float placementYaw =
435 std::atan2(hasAsset ? -f.forwardX : f.forwardX, hasAsset ? -f.forwardZ : f.forwardZ);
436 const float profileSide = lateral;
437 lateral = scaledProfileSide(lateral, asphaltHalfWidth(*source.edge), f.sample.scaleX);
438 if (side != 0) lateral += source.edge->style.sidePlacement.lateralOffset;
439 V3 point{f.sample.x + f.sideX * lateral, f.sample.y + f.sideY * lateral, f.sample.z + f.sideZ * lateral};
440 if (source.surface) {
441 auto position =
442 sampleSurfaceProfilePoint(*source.surface, distance, profileSide, asphaltHalfWidth(*source.edge));
443 if (!position.ok()) return Result<bool>::failure(position.status());
444 point = position.value();
445 if (side != 0)
446 point = point + V3{f.sideX, f.sideY, f.sideZ} * source.edge->style.sidePlacement.lateralOffset;
447 }
448 ProcgenPoint pose;
449 pose.yaw = placementYaw * 57.2957795f;
450 pose.normalX = f.upX;
451 pose.normalY = f.upY;
452 pose.normalZ = f.upZ;
453 if (hasAsset || (side != 0 && terrainRule.mode != RoadSideTerrainMode::None)) {
454 pose.normalX = pose.normalZ = 0.f;
455 pose.normalY = 1.f;
456 }
457 if (side != 0 && source.edge->style.sideTerrain.alignment != RoadSideAlignment::None) {
458 V3 forward = normalize(V3{f.forwardX, f.forwardY, f.forwardZ});
459 V3 up{f.upX, f.upY, f.upZ};
460 const auto alignment = source.edge->style.sideTerrain.alignment;
461 if (alignment == RoadSideAlignment::TerrainNormal) {
462 auto normal = sideTerrainNormal(*terrainQuery, point.x, point.z, options, terrainWork);
463 if (!normal.ok()) return Result<bool>::failure(normal.status());
464 up = normal.value();
465 forward = forward - up * dot(forward, up);
466 if (length(forward) < 1e-6f) {
467 const V3 axis = std::fabs(up.x) < .9f ? V3{1, 0, 0} : V3{0, 0, 1};
468 forward = cross(axis, up);
469 }
471 } else if (alignment == RoadSideAlignment::PathForward) {
472 up = V3{0, 1, 0} - forward * forward.y;
473 if (length(up) < 1e-6f) up = V3{f.upX, f.upY, f.upZ};
474 }
476 if (hasAsset) forward = forward * -1.f; // Canonical admitted assets face local -Z.
477 const float pitch = -std::asin(std::clamp(forward.y, -1.f, 1.f));
478 float yaw = std::atan2(forward.x, forward.z), roll = 0.f;
479 if (std::fabs(std::cos(pitch)) < 1e-6f) {
480 const float sign = forward.y > 0.f ? -1.f : 1.f;
481 yaw = std::atan2(up.x * sign, up.z * sign);
482 } else {
483 const V3 right0{std::cos(yaw), 0, -std::sin(yaw)};
484 const V3 up0{std::sin(yaw) * std::sin(pitch), std::cos(pitch), std::cos(yaw) * std::sin(pitch)};
485 roll = std::atan2(-dot(up, right0), dot(up, up0));
486 }
487 pose.pitch = pitch * 57.2957795f;
488 pose.yaw = yaw * 57.2957795f;
489 pose.roll = roll * 57.2957795f;
490 pose.normalX = up.x;
491 pose.normalY = up.y;
492 pose.normalZ = up.z;
493 }
494 if (side != 0) pose.yaw += source.edge->style.sidePlacement.yawDegrees;
495 if (side != 0 && source.edge->style.sideTerrain.mode != RoadSideTerrainMode::None) {
496 auto height =
497 sideTerrainHeight(terrainRule, *terrainQuery, point.x, point.z, pose,
498 hasAsset ? &edgeAssetBounds.at(source.edge->id) : nullptr, options, terrainWork);
499 if (!height.ok()) return Result<bool>::failure(height.status());
500 point.y = height.value();
501 }
502 if (side != 0) point.y += source.edge->style.sidePlacement.verticalOffset;
503 if (avoidConflicts) {
504 for (const auto& other : sources) {
505 if (other.edge->id == source.edge->id) continue;
506 auto closest = other.surface ? closestSurfacePolyline(*other.surface, point.x, point.y, point.z)
507 : other.spline.closestPointResult(point.x, point.y, point.z, 32);
508 if (!closest.ok()) return Result<bool>::failure(closest.status());
509 const V3 delta{point.x - closest.value().x, point.y - closest.value().y,
510 point.z - closest.value().z};
511 if (length(delta) <
512 scaledProfileSide(other.halfWidth, asphaltHalfWidth(*other.edge), closest.value().scaleX) +
513 options.sideObjectClearance)
514 return Result<bool>::success(false);
515 }
516 for (const auto& accepted : acceptedSidePoints)
517 if (length(point - accepted) < options.sideObjectClearance) return Result<bool>::success(false);
518 }
519 const int row = placements.add(point.x, point.y, point.z);
520 if (hasAsset) {
521 const auto& bounds = edgeAssetBounds.at(source.edge->id);
522 placements.setBounds(row, bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]);
523 auto asset = placements.trySetStringAttribute(row, "asset", terrainRule.asset->asset.format());
524 if (!asset.ok()) return Result<bool>::failure(asset.status());
525 auto build =
526 placements.trySetStringAttribute(row, "asset_build_id", terrainRule.asset->buildId.format());
527 if (!build.ok()) return Result<bool>::failure(build.status());
528 auto rootPose = placements.trySetStringAttribute(
529 row, "asset_root_pose",
530 terrainRule.asset->rootPose == eve::PrefabRootPose::Authored ? "authored" : "placement");
531 if (!rootPose.ok()) return Result<bool>::failure(rootPose.status());
532 }
533 placements.setRotation(row, pose.pitch, pose.yaw, pose.roll);
534 placements.setNormal(row, pose.normalX, pose.normalY, pose.normalZ);
535 placements.setPointSeed(row, deriveSeed(source.edge->id, std::string(role) + std::to_string(ordinal)));
536 auto identified = placements.trySetPointId(row, derivePointId(pointNamespace, ordinal++));
537 if (!identified.ok()) return Result<bool>::failure(identified.status());
538 auto edgeId = placements.trySetIntAttribute(row, "road_edge_id", source.edge->id);
539 if (!edgeId.ok()) return Result<bool>::failure(edgeId.status());
540 auto pointRole = placements.trySetStringAttribute(row, "road_role", role);
541 if (!pointRole.ok()) return Result<bool>::failure(pointRole.status());
542 auto pointSide = placements.trySetIntAttribute(row, "road_side", side);
543 if (!pointSide.ok()) return Result<bool>::failure(pointSide.status());
544 auto along = placements.trySetFloatAttribute(row, "road_distance", distance);
545 if (!along.ok()) return Result<bool>::failure(along.status());
546 auto clearance = placements.trySetFloatAttribute(row, "road_clearance", options.sideObjectClearance);
547 if (!clearance.ok()) return Result<bool>::failure(clearance.status());
548 auto direction =
549 placements.trySetVectorAttribute(row, "road_direction", f.forwardX, f.forwardY, f.forwardZ);
550 if (!direction.ok()) return Result<bool>::failure(direction.status());
551 if (avoidConflicts) acceptedSidePoints.push_back(point);
552 return Result<bool>::success(true);
553 };
554
555 auto start = append(0.f, 0.f, "transition.start", 0, false);
556 if (!start.ok()) return Result<void>::failure(start.status());
557 auto end = append(source.length, 0.f, "transition.end", 0, false);
558 if (!end.ok()) return Result<void>::failure(end.status());
559 const auto reference = source.edge->style.sidePlacement.reference;
560 const float lateral = reference == RoadSideReference::Center ? 0.f
562 ? asphaltHalfWidth(*source.edge)
563 : source.halfWidth + options.sideObjectOffset;
564 float legacyDistance = source.sideFirst;
565 for (std::size_t index = 0; index < source.sideCount; ++index) {
566 const bool legacy = source.edge->style.sideObjectDistribution == RoadSideDistribution::LegacyCentered;
567 const float distance =
568 legacy ? legacyDistance : source.sideFirst + static_cast<float>(index) * source.sideStep;
569 if (legacy) {
570 // Preserve historical cumulative float additions and its open end, including its budget upper bound.
571 if (!(distance < source.sideEnd)) break;
572 legacyDistance += options.sideObjectSpacing;
573 }
574 // Author exclusions and junction sockets remain hard constraints; only a free road end extends.
575 if (source.sideEnd < source.length && distance > source.sideEnd) continue;
576 if (source.edge->style.sideObjectsLeft) {
577 auto left = append(distance, -lateral, "side.left", -1, true);
578 if (!left.ok()) return Result<void>::failure(left.status());
579 }
580 if (source.edge->style.sideObjectsRight &&
581 !(reference == RoadSideReference::Center && source.edge->style.sideObjectsLeft)) {
582 auto right = append(distance, lateral, "side.right", 1, true);
583 if (!right.ok()) return Result<void>::failure(right.status());
584 }
585 }
586 }
587 return detail::bakeTrafficControlPoints(placements, network, options);
588}
589
590} // namespace eve::procgen::road::detail
double z
double y
double x
Duration start
double lateral
eve::EntitySpatialPose pose
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
float yaw
Definition BushMesh.cpp:37
Stable, structured diagnostics shared by engine modules.
SQObjectPtr key
Definition ECS.cpp:155
float minimum[3]
wgpu::PopErrorScopeStatus status
float u
Definition Grass.cpp:233
float halfWidth
HexVec3 up
HexVec3 left
HexVec3 right
std::uint32_t height
float ratio
float length
JointPoint2D axis
std::array< float, 3 > position
bool required
std::vector< Edge > edges
std::map< std::string, std::vector< size_t > > adjacency
std::map< std::string, Node > nodes
std::string id
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
Texture * normal
ssq::Object frame
glm::dvec2 center
glm::dvec3 dx
glm::dvec3 dz
std::vector< std::pair< std::uint64_t, OceanBoatReceipt > > sources
size_t directions
float f
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
std::string build
RoadNetwork resolved
const RoadNode * node
RoadLaneDirection direction
SplinePath spline
bool found
std::string_view source
size_t end
double current
const SquirrelValueOptions & options
std::vector< TileLayer::Tileset::TerrainRule > terrainRules
V3 heading
Definition TreeMesh.cpp:429
float size
Definition TreeMesh.cpp:158
uint32_t index
float fraction
V forward
glm::vec3 point
int neighbor
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
Script-friendly collection of attributed 3D samples.
Definition PointSet.h:59
Owning multi-segment 3D spline with deterministic bounded sampling.
Definition SplinePath.h:118
Owning directed road graph with lane connectivity.
Definition RoadNetwork.h:19
const std::vector< RoadEdge > & edges() const noexcept
Edges.
const std::vector< RoadNode > & nodes() const noexcept
Nodes.
std::string extension(std::string_view name)
Extension.
eve::Result< T > Result
eve::Result< void > success()
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< SplineSample > closestSurfacePolyline(const RoadSurfacePolyline &path, float x, float y, float z)
Closest owned center sample for collision checks, linear in retained road rows.
Result< SplinePath > edgeToSpline(const RoadEdge &edge)
Module-private road bake implementation helper.
Definition RoadBake.cpp:62
Result< SplineFrameSample > sampleSurfacePolyline(const RoadSurfacePolyline &path, float distance)
Sample one owned frame by segment direction; endpoints extrapolate, widths clamp to endpoint values....
Result< V3 > sideTerrainNormal(eve::IProcgenWorldQuery &query, float x, float z, const RoadBakeOptions &options, std::size_t &work)
Borrow the center surface normal with the same network-wide projection budget; no retained provider.
float junctionSocketDistance(const RoadNetwork &network, const RoadNode &node, const RoadEdge &edge, float pathLength)
Module-private road bake implementation helper.
Definition RoadBake.cpp:146
Result< V3 > sampleSurfaceProfilePoint(const RoadSurfacePolyline &path, float distance, float side, float asphaltHalf)
Sample a profile-side offset from actual retained row vectors and widths, not a reconstructed normal....
Result< void > bakeTrafficControlPoints(PointSet &placements, const RoadNetwork &network, const RoadBakeOptions &options)
Result< void > bakePlacementPoints(PointSet &placements, const RoadNetwork &network, const RoadBakeOptions &options, const std::unordered_set< std::uint32_t > &activeJunctionNodes, RoadFrameCache &frameCache)
Module-private road bake implementation helper.
Result< RoadSurfacePolyline > prepareSurfacePolyline(std::span< const SplineFrameSample > frames)
Prepare a bounded piecewise road-center metric; rejects degenerate segments without publishing output...
Result< float > sideTerrainHeight(const RoadSideTerrainRule &rule, eve::IProcgenWorldQuery &query, float x, float z, const ProcgenPoint &pose, const std::array< float, 6 > *assetBounds, const RoadBakeOptions &options, std::size_t &work)
Bounded height-only projection; provider and options are borrowed synchronously, no callbacks retaine...
float dot(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:28
V3 normalize(V3 a)
Module-private road bake implementation helper.
Definition RoadBake.cpp:31
Result< RoadProfile > makeRoadProfile(const RoadStyle &style, int lanesForward, int lanesBackward)
Build a mathematical road cross-section for the given lane counts.
std::uint64_t derivePointId(std::uint64_t namespaceId, std::uint64_t ordinal)
Deterministically derive a non-zero stable point identity.
Definition PointSet.cpp:470
uint32_t deriveSeed(uint32_t parent, const std::string &scope)
Stable label-based seed derivation; independent pipeline branches do not perturb each other.
Definition PointSet.cpp:460
Result< void > accepted()
Build a successful write/validation result.
WidgetDesc row(std::vector< WidgetDesc > children, std::string id)
Horizontal elastic layout row.
Definition Widget.cpp:870
Options for baking a road network into mesh + navigation overlays.
Definition RoadBake.h:50
Directed centerline edge with optional reverse lanes.
Definition RoadTypes.h:286
glm::vec4 bounds