SILICON
Loading...
Searching...
No Matches
circuitAutoplacer.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "circuitAutoplacer.hpp"
19
22
24
25#include <algorithm>
26#include <array>
27#include <chrono>
28#include <cmath>
29#include <cstddef>
30#include <cstdint>
31#include <limits>
32#include <map>
33#include <numeric>
34#include <optional>
35#include <ranges>
36#include <stdexcept>
37#include <tuple>
38#include <unordered_map>
39#include <utility>
40#include <vector>
41
42#include <QRectF>
43
44#include <libavoid/libavoid.h>
45#include <libavoid/qtgeomtypes.h>
46
47#include <core/circuit.hpp>
53
54namespace SILICON::ui {
55using namespace SILICON::core;
56
57namespace {
58
59 using ComponentMap = std::unordered_map<const Component*, GraphicalLogicComponent*>;
60 using OrientationMap = IoOrientationMap;
61 constexpr double COMPONENT_CLEARANCE = 2.0 * DiagramScene::GRID_SIZE;
62
63 // A single candidate already routes every connection. Bound the number of
64 // complete reroutes, including local refinements, as the design grows.
65 constexpr std::size_t ROUTING_WORK_BUDGET = 8192;
66
67 class ProgressRouter : public Avoid::Router {
68 public:
69 explicit ProgressRouter(const CircuitAutoplacerOptions& options)
70 : Avoid::Router(Avoid::OrthogonalRouting), options(options)
71 {
72 }
73
74 bool shouldContinueTransactionWithProgress(unsigned int, unsigned int, unsigned int,
75 double) override
76 {
77 const auto now = std::chrono::steady_clock::now();
78 if (now - lastCheck >= std::chrono::milliseconds(50)) {
79 lastCheck = now;
80 if (options.isCancelled && options.isCancelled())
81 cancelled = true;
82 }
83 return !cancelled;
84 }
85
86 private:
87 const CircuitAutoplacerOptions& options;
88 std::chrono::steady_clock::time_point lastCheck{};
89 bool cancelled = false;
90 };
91
92 QRectF movedComponentObstacle(GraphicalLogicComponent* component,
93 const QPointF& newPosition, const int padding,
94 const OrientationMap* orientations = nullptr)
95 {
96 const QPointF offset = newPosition - component->pos();
98 QRectF localBounds =
99 (orientations && orientations->contains(ioComponent))
100 ? ioComponent->collisionRectForPortSide(orientations->at(ioComponent))
101 : component->collisionRectForWires();
102 return component->mapToScene(localBounds)
103 .boundingRect()
104 .translated(offset)
105 .adjusted(-padding, -padding, padding, padding);
106 }
107
108 QPointF movedPortPosition(GraphicalLogicComponent* component, const Port* port,
109 const QPointF& newPosition,
110 const OrientationMap* orientations = nullptr)
111 {
113 QPoint localPosition =
114 (orientations && orientations->contains(ioComponent))
115 ? ioComponent->portPositionFor(orientations->at(ioComponent))
116 : port->getPosition();
117
118 return component->mapToScene(localPosition) + (newPosition - component->pos());
119 }
120
121 bool hasComponentClearance(const QRectF& candidate, std::span<const QRectF> accepted)
122 {
123 return detail::hasBoundsClearance(candidate, accepted, COMPONENT_CLEARANCE);
124 }
125
126 std::vector<GraphicalLogicComponent*>
127 orderedComponents(const GraphLayout::PlacementMap& placements, const bool ios)
128 {
129 std::vector<GraphicalLogicComponent*> result;
130 for (const auto& component : placements | std::views::keys) {
131 if (hasCategory(component, ItemCategory::IO) == ios)
132 result.push_back(component);
133 }
134 std::ranges::sort(result, [](const auto* lhs, const auto* rhs) {
135 if (lhs->getUiId() != rhs->getUiId())
136 return lhs->getUiId() < rhs->getUiId();
137 return lhs < rhs;
138 });
139 return result;
140 }
141
142 QPointF nearestClearPosition(GraphicalLogicComponent* component,
143 const QPointF& preferredPosition,
144 std::span<const QRectF> accepted)
145 {
146 const int grid = DiagramScene::GRID_SIZE;
147 for (int ring = 0;; ++ring) {
148 std::optional<std::pair<double, QPointF>> best;
149 for (int dx = -ring; dx <= ring; ++dx) {
150 const int dyMagnitude = ring - std::abs(dx);
151 const std::array dys =
152 dyMagnitude == 0 ? std::array{0, 0} : std::array{dyMagnitude, -dyMagnitude};
153 for (const int dy : dys) {
154 const QPointF position = preferredPosition + QPointF(dx * grid, dy * grid);
155 const QRectF bounds = movedComponentObstacle(component, position, 0);
156 if (!hasComponentClearance(bounds, accepted))
157 continue;
158
159 QRectF occupied = bounds;
160 for (const QRectF& other : accepted)
161 occupied = occupied.united(other);
162 const double area = occupied.width() * occupied.height();
163 if (!best || area < best->first
164 || (area == best->first
165 && std::pair{position.y(), position.x()}
166 < std::pair{best->second.y(), best->second.x()}))
167 best = std::pair{area, position};
168 }
169 }
170 if (best)
171 return DiagramScene::snapToGrid(best->second);
172 }
173 }
174
175 void separateLogicComponents(GraphLayout::PlacementMap& placements)
176 {
177 std::vector<QRectF> accepted;
178 for (GraphicalLogicComponent* component : orderedComponents(placements, false)) {
179 QPointF& position = placements.at(component);
180 position = nearestClearPosition(component, position, accepted);
181 accepted.push_back(movedComponentObstacle(component, position, 0));
182 }
183 }
184
185 void separateBoundaryIos(GraphLayout::PlacementMap& placements,
186 const OrientationMap& orientations, const int obstaclePadding)
187 {
188 std::vector<QRectF> accepted;
189 for (GraphicalLogicComponent* component : orderedComponents(placements, false))
190 accepted.push_back(movedComponentObstacle(component, placements.at(component), 0));
191
192 std::map<PortSide, std::vector<GraphicalIO*>> grouped;
193 for (GraphicalLogicComponent* component : orderedComponents(placements, true)) {
195
196 if (orientations.contains(ioComponent)) {
197 grouped[orientations.at(ioComponent)].push_back(ioComponent);
198 continue;
199 }
200
201 placements.at(ioComponent) =
202 nearestClearPosition(ioComponent, placements.at(ioComponent), accepted);
203 accepted.push_back(
204 movedComponentObstacle(ioComponent, placements.at(ioComponent), 0));
205 }
206
207 for (auto& [side, ios] : grouped) {
208 std::vector<detail::BoundaryIoLaneItem> laneItems;
209 laneItems.reserve(ios.size());
210 for (GraphicalIO* io : ios) {
211 const QPointF preferred = placements.at(io);
212 laneItems.push_back(
213 {.preferredPosition = preferred,
214 .preferredBounds = movedComponentObstacle(io, preferred, 0, &orientations),
215 .preferredPort =
216 io->mapToScene(io->portPositionFor(side)) + (preferred - io->pos()),
217 .stableOrder = io->getUiId()});
218 }
219
220 const auto lanePlacement =
221 detail::placeBoundaryIoInLanes(side, laneItems, accepted, COMPONENT_CLEARANCE,
222 obstaclePadding, DiagramScene::GRID_SIZE);
223 for (std::size_t i = 0; i < ios.size(); ++i) {
224 placements.at(ios[i]) = DiagramScene::snapToGrid(lanePlacement.positions[i]);
225 accepted.push_back(lanePlacement.bounds[i]);
226 }
227 }
228 }
229
230 bool componentsHaveClearance(const GraphLayout::PlacementMap& placements,
231 const OrientationMap& orientations)
232 {
233 std::vector<QRectF> accepted;
234 accepted.reserve(placements.size());
235 for (const auto& [component, position] : placements) {
236 const QRectF bounds = movedComponentObstacle(component, position, 0, &orientations);
237 if (!hasComponentClearance(bounds, accepted))
238 return false;
239 accepted.push_back(bounds);
240 }
241 return true;
242 }
243
244 // --- Logic / Graphical Port Mapping Helpers ------------------------------------------
245
246 struct RoutableConnection {
247 GraphicalLogicComponent* source;
248 GraphicalLogicComponent* target;
249 const Port* sourcePort;
250 const Port* targetPort;
251 Bus bus;
252 };
253
254 std::optional<RoutableConnection>
255 resolveConnection(const CircuitConnection& connection,
256 const ComponentMap& componentToGraphics)
257 {
258 // Skip incomplete logical edges early; every downstream helper assumes both ends
259 // exist and are represented in the placement result.
260 if (!connection.source || !connection.target)
261 return std::nullopt;
262
263 auto sourceGraphicsIt = componentToGraphics.find(connection.source.get());
264 auto targetGraphicsIt = componentToGraphics.find(connection.target.get());
265
266 if (sourceGraphicsIt == componentToGraphics.end()
267 || targetGraphicsIt == componentToGraphics.end())
268 return std::nullopt;
269
270 GraphicalLogicComponent* sourceGraphics = sourceGraphicsIt->second;
271 GraphicalLogicComponent* targetGraphics = targetGraphicsIt->second;
272
273 const auto sourcePorts = sourceGraphics->getOutputPorts();
274 const auto targetPorts = targetGraphics->getInputPorts();
275
276 // The circuit edge stores bus indices; resolve them back into actual graphical ports
277 // only if both components still expose those indices.
278 if (connection.sourceBusIndex >= sourcePorts.size()
279 || connection.targetBusIndex >= targetPorts.size())
280 return std::nullopt;
281
282 return RoutableConnection{.source = sourceGraphics,
283 .target = targetGraphics,
284 .sourcePort = sourcePorts[connection.sourceBusIndex],
285 .targetPort = targetPorts[connection.targetBusIndex],
286 .bus = connection.bus};
287 }
288
289 ComponentMap buildComponentMap(std::span<GraphicalLogicComponent* const> components)
290 {
291 ComponentMap result;
292 result.reserve(components.size());
293 for (GraphicalLogicComponent* component : components) {
294 if (component && component->getComponent())
295 result.emplace(component->getComponent().get(), component);
296 }
297 return result;
298 }
299
300 std::vector<RoutableConnection>
301 resolveConnections(const Circuit& circuit, const ComponentMap& componentToGraphics)
302 {
303 std::vector<RoutableConnection> result;
304 const auto connections = circuit.getConnections();
305 result.reserve(connections.size());
306
307 for (const CircuitConnection& connection : connections) {
308 if (auto resolved = resolveConnection(connection, componentToGraphics))
309 result.push_back(std::move(*resolved));
310 }
311 return result;
312 }
313
314 void compactOrderedFanIns(std::span<const RoutableConnection> connections,
315 GraphLayout::PlacementMap& placements)
316 {
317 struct OrderedSource {
318 GraphicalLogicComponent* component;
319 qreal targetCoordinate = 0.0;
320 qreal sourceCoordinate = 0.0;
321 std::size_t connectionCount = 0;
322 };
323 struct FanInGroup {
324 GraphicalLogicComponent* target;
325 PortSide side;
326 std::vector<OrderedSource> sources;
327 std::size_t connectionCount = 0;
328 };
329
330 constexpr std::array PORT_SIDES = {PortSide::LEFT, PortSide::RIGHT, PortSide::UP,
332 std::vector<FanInGroup> groups;
333
334 for (GraphicalLogicComponent* target : orderedComponents(placements, false)) {
335 for (const PortSide side : PORT_SIDES) {
336 std::vector<OrderedSource> sources;
337 std::size_t connectionCount = 0;
338 for (const RoutableConnection& connection : connections) {
339 if (connection.target != target || connection.targetPort->getDirection() != side
340 || connection.source == target || !placements.contains(connection.source)
341 || hasCategory(connection.source, ItemCategory::IO))
342 continue;
343
344 ++connectionCount;
345 auto source =
346 std::ranges::find_if(sources, [&](const OrderedSource& candidate) {
347 return candidate.component == connection.source;
348 });
349 if (source == sources.end()) {
350 sources.push_back({.component = connection.source});
351 source = std::prev(sources.end());
352 }
353
354 const QPointF targetPort =
355 movedPortPosition(target, connection.targetPort, placements.at(target));
356 const QPointF sourcePort = movedPortPosition(
357 connection.source, connection.sourcePort, placements.at(connection.source));
358 source->targetCoordinate += side == PortSide::LEFT || side == PortSide::RIGHT
359 ? targetPort.y()
360 : targetPort.x();
361 source->sourceCoordinate += side == PortSide::LEFT || side == PortSide::RIGHT
362 ? sourcePort.y()
363 : sourcePort.x();
364 ++source->connectionCount;
365 }
366
367 // Four or more ordered terminals indicate a bus selector, decoder, or similar
368 // high-fan-in block. OGDF lays out plain graph edges and cannot otherwise know
369 // that the terminal order is visually meaningful.
370 if (connectionCount >= 4 && sources.size() >= 3)
371 groups.push_back({.target = target,
372 .side = side,
373 .sources = std::move(sources),
374 .connectionCount = connectionCount});
375 }
376 }
377
378 std::ranges::sort(groups, [](const FanInGroup& lhs, const FanInGroup& rhs) {
379 if (lhs.connectionCount != rhs.connectionCount)
380 return lhs.connectionCount > rhs.connectionCount;
381 return lhs.target->getUiId() < rhs.target->getUiId();
382 });
383
384 std::unordered_set<GraphicalLogicComponent*> alreadyOrdered;
385 for (FanInGroup& group : groups) {
386 std::erase_if(group.sources, [&](const OrderedSource& source) {
387 return alreadyOrdered.contains(source.component);
388 });
389 if (group.sources.size() < 3)
390 continue;
391
392 std::ranges::sort(
393 group.sources, [](const OrderedSource& lhs, const OrderedSource& rhs) {
394 const qreal lhsCoordinate =
395 lhs.targetCoordinate / static_cast<qreal>(lhs.connectionCount);
396 const qreal rhsCoordinate =
397 rhs.targetCoordinate / static_cast<qreal>(rhs.connectionCount);
398 if (lhsCoordinate != rhsCoordinate)
399 return lhsCoordinate < rhsCoordinate;
400 return lhs.component->getUiId() < rhs.component->getUiId();
401 });
402
403 const bool verticalOrder =
404 group.side == PortSide::LEFT || group.side == PortSide::RIGHT;
406 proposals.reserve(group.sources.size());
407 for (const OrderedSource& source : group.sources) {
408 QPointF position = placements.at(source.component);
409 const qreal targetCoordinate =
410 source.targetCoordinate / static_cast<qreal>(source.connectionCount);
411 const qreal sourceCoordinate =
412 source.sourceCoordinate / static_cast<qreal>(source.connectionCount);
413 if (verticalOrder)
414 position.ry() += targetCoordinate - sourceCoordinate;
415 else
416 position.rx() += targetCoordinate - sourceCoordinate;
417 position = DiagramScene::snapToGrid(position);
418 proposals.emplace(source.component, position);
419 }
420
421 // Aligning a wide source directly with every terminal of a dense mux can make
422 // several source symbols overlap. A later generic separation pass then scatters
423 // them to arbitrary sides of the target and destroys the signal-flow layout.
424 // Treat the whole group as one transaction: only commit an ordered alignment when
425 // it remains clear of every component and stays outside the target's input side.
426 const QRectF targetBounds =
427 movedComponentObstacle(group.target, placements.at(group.target), 0);
428 bool valid = true;
429 std::vector<QRectF> accepted;
430 accepted.reserve(placements.size());
431 for (GraphicalLogicComponent* component : orderedComponents(placements, false)) {
432 const QPointF position = proposals.contains(component) ? proposals.at(component)
433 : placements.at(component);
434 const QRectF bounds = movedComponentObstacle(component, position, 0);
435 if (proposals.contains(component)
436 && !detail::boundsLieOutsideTarget(group.side, bounds, targetBounds,
437 COMPONENT_CLEARANCE)) {
438 valid = false;
439 break;
440 }
441 if (!hasComponentClearance(bounds, accepted)) {
442 valid = false;
443 break;
444 }
445 accepted.push_back(bounds);
446 }
447
448 if (!valid)
449 continue;
450
451 for (const auto& [component, position] : proposals) {
452 placements.at(component) = position;
453 alreadyOrdered.insert(component);
454 }
455 }
456 }
457
458 void stackSymmetricFeedbackPairs(std::span<const RoutableConnection> connections,
459 GraphLayout::PlacementMap& placements)
460 {
461 using Pair = std::pair<GraphicalLogicComponent*, GraphicalLogicComponent*>;
462 std::vector<Pair> alignedPairs;
463
464 for (const RoutableConnection& connection : connections) {
465 auto* first = connection.source;
466 auto* second = connection.target;
467 if (!first || !second || first == second || !placements.contains(first)
468 || !placements.contains(second) || !first->getComponent()
469 || !second->getComponent()
470 || first->getComponent()->typeName() != second->getComponent()->typeName())
471 continue;
472
473 const bool hasReverseConnection =
474 std::ranges::any_of(connections, [&](const RoutableConnection& candidate) {
475 return candidate.source == second && candidate.target == first;
476 });
477 if (!hasReverseConnection)
478 continue;
479
480 Pair pair = first->getUiId() < second->getUiId() ? Pair{first, second}
481 : Pair{second, first};
482 if (std::ranges::find(alignedPairs, pair) != alignedPairs.end())
483 continue;
484 alignedPairs.push_back(pair);
485
486 const QRectF firstBounds =
487 movedComponentObstacle(pair.first, placements.at(pair.first), 0);
488 const QRectF secondBounds =
489 movedComponentObstacle(pair.second, placements.at(pair.second), 0);
490 const qreal centerX = DiagramScene::snapToGrid(
491 (firstBounds.center().x() + secondBounds.center().x()) / 2.0);
492 const qreal pairCenterY = DiagramScene::snapToGrid(
493 (firstBounds.center().y() + secondBounds.center().y()) / 2.0);
494 const qreal requiredCenterDistance =
495 firstBounds.height() / 2.0 + secondBounds.height() / 2.0 + COMPONENT_CLEARANCE;
496 const qreal pairGrid = 2.0 * DiagramScene::GRID_SIZE;
497 const qreal centerDistance =
498 std::ceil(requiredCenterDistance / pairGrid) * pairGrid;
499
500 // A symmetric two-gate latch is conventionally drawn as a vertical pair. Keep
501 // both gate centers on the same x coordinate and separate their centers enough to
502 // preserve the mandatory two-grid component clearance.
503 const qreal firstCenterY = pairCenterY - centerDistance / 2.0;
504 const qreal secondCenterY = pairCenterY + centerDistance / 2.0;
505 placements.at(pair.first).rx() += centerX - firstBounds.center().x();
506 placements.at(pair.second).rx() += centerX - secondBounds.center().x();
507 placements.at(pair.first).ry() += firstCenterY - firstBounds.center().y();
508 placements.at(pair.second).ry() += secondCenterY - secondBounds.center().y();
509 placements.at(pair.first) = DiagramScene::snapToGrid(placements.at(pair.first));
510 placements.at(pair.second) = DiagramScene::snapToGrid(placements.at(pair.second));
511 }
512 }
513
514 PortSide oppositeSide(const PortSide side)
515 {
516 switch (side) {
517 case PortSide::LEFT: return PortSide::RIGHT;
518 case PortSide::RIGHT: return PortSide::LEFT;
519 case PortSide::UP: return PortSide::DOWN;
520 case PortSide::DOWN: return PortSide::UP;
521 }
522 std::unreachable();
523 }
524
525 GraphLayoutDirection layoutDirectionFor(const PortSide side)
526 {
527 switch (side) {
528 case PortSide::LEFT:
530 case PortSide::UP:
532 }
533 std::unreachable();
534 }
535
536 std::array<GraphLayoutDirection, 2>
537 preferredLayoutDirections(std::span<const RoutableConnection> connections,
538 const GraphLayoutDirection fallback)
539 {
542 const auto fallbackIt = std::ranges::find(directions, fallback);
543 std::ranges::rotate(directions, fallbackIt);
544
545 std::array<std::size_t, 2> votes{};
546 auto addVote = [&](const PortSide side) {
547 const auto direction = layoutDirectionFor(side);
548 const auto found = std::ranges::find(directions, direction);
549 ++votes[static_cast<std::size_t>(std::distance(directions.begin(), found))];
550 };
551
552 for (const auto& connection : connections) {
553 const bool sourceIsIo = hasCategory(connection.source, ItemCategory::IO);
554 const bool targetIsIo = hasCategory(connection.target, ItemCategory::IO);
555 if (!sourceIsIo || targetIsIo)
556 addVote(connection.sourcePort->getDirection());
557 if (!targetIsIo || sourceIsIo)
558 addVote(oppositeSide(connection.targetPort->getDirection()));
559 }
560
561 std::array<std::size_t, 2> order{};
562 std::iota(order.begin(), order.end(), 0);
563 std::ranges::stable_sort(order, [&](const std::size_t lhs, const std::size_t rhs) {
564 return votes[lhs] > votes[rhs];
565 });
566
567 std::array<GraphLayoutDirection, 2> result;
568 for (std::size_t i = 0; i < result.size(); ++i)
569 result[i] = directions[order[i]];
570 return result;
571 }
572
573 OrientationMap
574 preferredBoundaryIoOrientations(std::span<const RoutableConnection> connections)
575 {
576 constexpr std::array SIDE_PREFERENCE = {PortSide::RIGHT, PortSide::LEFT,
578 std::unordered_map<GraphicalIO*, std::array<std::size_t, SIDE_PREFERENCE.size()>>
579 votes;
580
581 auto addVote = [&](GraphicalIO* io, const Port* connectedPort) {
582 const PortSide preferredSide = oppositeSide(connectedPort->getDirection());
583 const auto vote = std::ranges::find(SIDE_PREFERENCE, preferredSide);
584 ++votes[io][static_cast<std::size_t>(std::distance(SIDE_PREFERENCE.begin(), vote))];
585 };
586
587 for (const auto& connection : connections) {
588 GraphicalIO* sourceIO =
590 GraphicalIO* targetIO =
592 if (sourceIO)
593 addVote(sourceIO, connection.targetPort);
594 if (targetIO)
595 addVote(targetIO, connection.sourcePort);
596 }
597
598 OrientationMap result;
599 for (const auto& [io, sideVotes] : votes) {
600 const auto winningVote = std::ranges::max_element(sideVotes);
601 result.emplace(io, SIDE_PREFERENCE[static_cast<std::size_t>(
602 std::distance(sideVotes.begin(), winningVote))]);
603 }
604 return result;
605 }
606
607 OrientationMap placeBoundaryIos(std::span<const RoutableConnection> connections,
608 GraphLayout::PlacementMap& placements)
609 {
610 struct IoNeighbor {
611 GraphicalLogicComponent* component;
612 const Port* port;
613 };
614 std::unordered_map<GraphicalIO*, std::vector<IoNeighbor>> neighbors;
615 for (const auto& connection : connections) {
616 GraphicalIO* sourceIO =
618 GraphicalIO* targetIO =
620 if (sourceIO)
621 neighbors[sourceIO].push_back({connection.target, connection.targetPort});
622 if (targetIO)
623 neighbors[targetIO].push_back({connection.source, connection.sourcePort});
624 }
625
626 OrientationMap orientations = preferredBoundaryIoOrientations(connections);
627 constexpr double GAP = 4.0 * DiagramScene::GRID_SIZE;
628
629 QRectF logicBounds;
630 bool hasLogicBounds = false;
631 for (const auto& [component, position] : placements) {
632 if (hasCategory(component, ItemCategory::IO))
633 continue;
634 const QRectF bounds = movedComponentObstacle(component, position, 0);
635 logicBounds = hasLogicBounds ? logicBounds.united(bounds) : bounds;
636 hasLogicBounds = true;
637 }
638
639 for (const auto& [io, connected] : neighbors) {
640 if (connected.empty() || !placements.contains(io))
641 continue;
642
643 QPointF connectedPortCenter;
644 QRectF connectedBounds;
645 bool hasBounds = false;
646 std::size_t connectedCount = 0;
647 for (const auto& [neighbor, neighborPort] : connected) {
648 if (!placements.contains(neighbor))
649 continue;
650 const QRectF rect = movedComponentObstacle(neighbor, placements.at(neighbor), 0);
651 connectedPortCenter +=
652 movedPortPosition(neighbor, neighborPort, placements.at(neighbor));
653 connectedBounds = hasBounds ? connectedBounds.united(rect) : rect;
654 hasBounds = true;
655 ++connectedCount;
656 }
657 if (!hasBounds)
658 continue;
659
660 connectedPortCenter /= static_cast<qreal>(connectedCount);
661 QPointF ioPosition = placements.at(io);
662 QRectF ioBounds = movedComponentObstacle(io, ioPosition, 0, &orientations);
663 const PortSide side = orientations.at(io);
664 const QRectF& placementBoundary = hasLogicBounds ? logicBounds : connectedBounds;
665
666 // Boundary symbols belong outside the complete logic block, not merely outside
667 // their directly connected gate. This prevents an input or output from being
668 // inserted between mutually connected latch gates and blocking their signal lanes.
669 switch (side) {
670 case PortSide::RIGHT:
671 ioPosition.rx() += placementBoundary.left() - GAP - ioBounds.right();
672 break;
673 case PortSide::LEFT:
674 ioPosition.rx() += placementBoundary.right() + GAP - ioBounds.left();
675 break;
676 case PortSide::DOWN:
677 ioPosition.ry() += placementBoundary.top() - GAP - ioBounds.bottom();
678 break;
679 case PortSide::UP:
680 ioPosition.ry() += placementBoundary.bottom() + GAP - ioBounds.top();
681 break;
682 }
683
684 // Align the proposed I/O port with the port(s) it connects to. This turns the
685 // common leaf-I/O case into a straight wire while fanout I/O aligns to the center
686 // of its targets instead of inheriting an arbitrary force-layout offset.
687 const QPointF proposedPort =
688 io->mapToScene(io->portPositionFor(side)) + (ioPosition - io->pos());
689 if (side == PortSide::LEFT || side == PortSide::RIGHT)
690 ioPosition.ry() += connectedPortCenter.y() - proposedPort.y();
691 else
692 ioPosition.rx() += connectedPortCenter.x() - proposedPort.x();
693
694 placements.at(io) = DiagramScene::snapToGrid(ioPosition);
695 orientations.emplace(io, side);
696 }
697 return orientations;
698 }
699
700 Avoid::ConnDirFlags portConnDir(const PortSide side)
701 {
702 switch (side) {
703 case PortSide::LEFT: return Avoid::ConnDirLeft;
704 case PortSide::RIGHT: return Avoid::ConnDirRight;
705 case PortSide::UP: return Avoid::ConnDirUp;
706 case PortSide::DOWN: return Avoid::ConnDirDown;
707 }
708 std::unreachable();
709 }
710
711 PortSide effectivePortSide(GraphicalLogicComponent* component, const Port* port,
712 const OrientationMap& orientations)
713 {
715 return orientations.contains(ioComponent) ? orientations.at(ioComponent)
716 : port->getDirection();
717 }
718
719 struct RoutingObstacle {
720 Avoid::ShapeRef* shape;
721 QRectF bounds;
722 };
723
724 using RoutingObstacleMap =
725 std::unordered_map<GraphicalLogicComponent*, RoutingObstacle>;
726
727 RoutingObstacleMap registerObstacles(Avoid::Router& router,
728 const GraphLayout::PlacementMap& placements,
729 const int padding,
730 const OrientationMap& orientations)
731 {
732 RoutingObstacleMap result;
733 result.reserve(placements.size());
734 for (const auto& [component, position] : placements) {
735 const QRectF rect =
736 movedComponentObstacle(component, position, padding, &orientations)
737 .normalized();
738 if (rect.isEmpty())
739 continue;
740
741 auto obstacle = Avoid::rectangleFromQRectF(rect);
742 // Router owns registered shapes, pins, junctions, and connectors.
743 auto* shape = new Avoid::ShapeRef(&router, obstacle);
744 result.emplace(component, RoutingObstacle{.shape = shape, .bounds = rect});
745 }
746 return result;
747 }
748
749 using NetKey = std::vector<std::uint64_t>;
750
751 NetKey netKey(const Bus& bus)
752 {
753 NetKey key;
754 key.reserve(bus.size());
755 for (const auto& wire : bus)
756 key.push_back(wire ? wire->getId() : 0);
757 return key;
758 }
759
760 struct PendingNet {
761 Bus bus;
762 std::vector<QPointF> terminals;
763 std::vector<std::vector<QPointF>> routes;
764 };
765
766 bool netRoutesAreComplete(const PendingNet& net)
767 {
768 if (net.routes.empty())
769 return false;
770
771 const bool containsEveryTerminal =
772 std::ranges::all_of(net.terminals, [&](const QPointF& terminal) {
773 return std::ranges::any_of(net.routes, [&](const auto& route) {
774 return pointOnOrthogonalRoute(terminal, route);
775 });
776 });
777 if (!containsEveryTerminal)
778 return false;
779
780 std::vector<bool> reached(net.routes.size());
781 reached.front() = true;
782 for (std::size_t pass = 1; pass < net.routes.size(); ++pass) {
783 bool changed = false;
784 for (std::size_t i = 0; i < net.routes.size(); ++i) {
785 if (reached[i])
786 continue;
787 for (std::size_t j = 0; j < net.routes.size(); ++j) {
788 if (reached[j] && orthogonalRoutesTouch(net.routes[i], net.routes[j])) {
789 reached[i] = true;
790 changed = true;
791 break;
792 }
793 }
794 }
795 if (!changed)
796 break;
797 }
798 return std::ranges::all_of(reached, std::identity{});
799 }
800
801 std::optional<std::vector<PendingNet>>
802 registerNets(Avoid::Router& router, std::span<const RoutableConnection> connections,
803 const GraphLayout::PlacementMap& placements,
804 const OrientationMap& orientations, const RoutingObstacleMap& obstacles,
805 const std::size_t routingOrder)
806 {
807 std::map<NetKey, std::vector<RoutableConnection>> groupedByKey;
808 for (const auto& connection : connections)
809 groupedByKey[netKey(connection.bus)].push_back(connection);
810
811 std::vector<std::vector<RoutableConnection>> grouped;
812 grouped.reserve(groupedByKey.size());
813 for (auto& netConnections : groupedByKey | std::views::values)
814 grouped.push_back(std::move(netConnections));
815 if (!grouped.empty()) {
816 const std::size_t offset = routingOrder % grouped.size();
817 std::ranges::rotate(grouped, grouped.begin() + static_cast<std::ptrdiff_t>(offset));
818 if ((routingOrder / grouped.size()) % 2 != 0)
819 std::ranges::reverse(grouped);
820 }
821
822 std::vector<PendingNet> result;
823 result.reserve(grouped.size());
824 unsigned int nextPinClassId = 1;
825
826 struct RegisteredNet {
827 PendingNet net;
828 Avoid::ConnRefList connectors;
829 std::optional<std::size_t> hyperedgeIndex;
830 };
831 std::vector<RegisteredNet> registered;
832 registered.reserve(grouped.size());
833 const bool useTerminalTrees = connections.size() > 1024;
834
835 for (auto& netConnections : grouped) {
836 using Terminal = std::pair<GraphicalLogicComponent*, const Port*>;
837 std::vector<Terminal> uniqueTerminals;
838 uniqueTerminals.reserve(netConnections.size() + 1);
839
840 auto appendTerminal = [&](GraphicalLogicComponent* component, const Port* port) {
841 const Terminal terminal{component, port};
842 if (std::ranges::find(uniqueTerminals, terminal) == uniqueTerminals.end())
843 uniqueTerminals.push_back(terminal);
844 };
845
846 for (const RoutableConnection& connection : netConnections) {
847 appendTerminal(connection.source, connection.sourcePort);
848 appendTerminal(connection.target, connection.targetPort);
849 }
850 if (uniqueTerminals.size() < 2)
851 continue;
852
853 Avoid::ConnEndList terminals;
854 PendingNet net{.bus = netConnections.front().bus, .terminals = {}, .routes = {}};
855 net.terminals.reserve(uniqueTerminals.size());
856 for (const auto& [component, port] : uniqueTerminals) {
857 const auto obstacle = obstacles.find(component);
858 if (obstacle == obstacles.end())
859 return std::nullopt;
860 const QPointF position =
861 movedPortPosition(component, port, placements.at(component), &orientations);
862 const PortSide side = effectivePortSide(component, port, orientations);
863 const unsigned int pinClassId = nextPinClassId++;
864 auto* pin = new Avoid::ShapeConnectionPin(
865 obstacle->second.shape, pinClassId,
866 position.x() - obstacle->second.bounds.left(),
867 position.y() - obstacle->second.bounds.top(), false, 0.0, portConnDir(side));
868 if (useTerminalTrees)
869 pin->setExclusive(false);
870 terminals.emplace_back(obstacle->second.shape, pinClassId);
871 net.terminals.push_back(DiagramScene::snapToGrid(position));
872 }
873 if (terminals.size() < 2)
874 return std::nullopt;
875
876 const bool direct = terminals.size() == 2;
877 RegisteredNet registration{
878 .net = std::move(net), .connectors = {}, .hyperedgeIndex = std::nullopt};
879 if (direct) {
880 auto* connector =
881 new Avoid::ConnRef(&router, terminals.front(), terminals.back());
882 connector->setRoutingType(Avoid::ConnType_Orthogonal);
883 registration.connectors.push_back(connector);
884 registered.push_back(std::move(registration));
885 continue;
886 }
887
888 if (useTerminalTrees) {
889 // A global Steiner-tree search explores the entire visibility graph for
890 // each fanout net. For large designs, route a Manhattan minimum spanning
891 // tree of the terminals instead. Shared pins keep every branch attached
892 // to the same electrical net while each obstacle search stays local.
893 const std::vector<Avoid::ConnEnd> ends(terminals.begin(), terminals.end());
894 std::vector<bool> reached(ends.size());
895 std::vector<qreal> distances(ends.size(), std::numeric_limits<qreal>::infinity());
896 std::vector<std::size_t> parents(ends.size());
897 distances.front() = 0;
898 for (std::size_t count = 0; count < ends.size(); ++count) {
899 std::size_t next = ends.size();
900 for (std::size_t terminal = 0; terminal < ends.size(); ++terminal)
901 if (!reached[terminal]
902 && (next == ends.size() || distances[terminal] < distances[next]))
903 next = terminal;
904 reached[next] = true;
905 if (count > 0) {
906 auto* connector =
907 new Avoid::ConnRef(&router, ends[parents[next]], ends[next]);
908 connector->setRoutingType(Avoid::ConnType_Orthogonal);
909 registration.connectors.push_back(connector);
910 }
911 for (std::size_t terminal = 0; terminal < ends.size(); ++terminal) {
912 const auto delta =
913 registration.net.terminals[next] - registration.net.terminals[terminal];
914 const qreal distance = std::abs(delta.x()) + std::abs(delta.y());
915 if (!reached[terminal] && distance < distances[terminal]) {
916 distances[terminal] = distance;
917 parents[terminal] = next;
918 }
919 }
920 }
921 registered.push_back(std::move(registration));
922 continue;
923 }
924
925 registration.hyperedgeIndex =
926 router.hyperedgeRerouter()->registerHyperedgeForRerouting(terminals);
927 registered.push_back(std::move(registration));
928 }
929
930 // A single transaction is essential: libavoid's nudger must see all distinct
931 // logical nets together to allocate separate collinear channels.
932 router.processTransaction();
933 if (router.transactionAborted())
934 return std::nullopt;
935
936 for (RegisteredNet& registration : registered) {
937 if (registration.hyperedgeIndex) {
938 const auto changes = router.hyperedgeRerouter()->newAndDeletedObjectLists(
939 *registration.hyperedgeIndex);
940 registration.connectors = changes.newConnectorList;
941 }
942 }
943
944 Avoid::ConnRefListVector routeGroups;
945 routeGroups.reserve(registered.size());
946 for (const RegisteredNet& registration : registered) {
947 // Lane conflicts must be checked in the same coordinates that will be
948 // committed. Snapping afterwards can collapse distinct fractional lanes.
949 for (auto* connector : registration.connectors) {
950 const auto points = extractOrthogonalRoute(*connector, DiagramScene::GRID_SIZE);
951 if (points.size() < 2)
952 continue;
953 Avoid::PolyLine snapped;
954 for (const QPointF point : points)
955 snapped.ps.emplace_back(point.x(), point.y());
956 connector->set_route(snapped);
957 }
958 routeGroups.push_back(registration.connectors);
959 }
960 if (!router.separateOrthogonalRouteGroups(routeGroups, DiagramScene::GRID_SIZE))
961 return std::nullopt;
962
963 for (RegisteredNet& registration : registered) {
964 registration.net.routes.reserve(registration.connectors.size());
965 for (Avoid::ConnRef* connector : registration.connectors) {
966 auto points = extractOrthogonalRoute(*connector, DiagramScene::GRID_SIZE);
967 if (points.size() < 2)
968 continue;
969 Q_ASSERT(isOrthogonalRoute(points));
970 registration.net.routes.push_back(std::move(points));
971 }
972
973 if (!netRoutesAreComplete(registration.net))
974 return std::nullopt;
975 result.push_back(std::move(registration.net));
976 }
977 return result;
978 }
979
980 std::optional<std::vector<RoutedWire>>
981 buildWires(std::vector<PendingNet> pendingNets, const CircuitAutoplacerOptions& options)
982 {
983 std::vector<RoutedWire> wires;
984 bool cancelled = false;
985 const auto progress = [&] {
986 cancelled = cancelled || (options.isCancelled && options.isCancelled());
987 return !cancelled;
988 };
989 for (PendingNet& net : pendingNets) {
990 if (!progress())
991 return std::nullopt;
992 auto merged = mergeOrthogonalRoutes(net.routes, progress);
993 if (cancelled)
994 return std::nullopt;
995 for (auto& points : merged)
996 wires.push_back(RoutedWire{.bus = net.bus, .points = std::move(points)});
997 }
998 return wires;
999 }
1000
1001 bool wireEndpointsPreserveNets(std::span<const RoutedWire> wires)
1002 {
1003 struct Span {
1004 qreal low, high;
1005 const Bus* bus;
1006 };
1007 std::map<qreal, std::vector<Span>> horizontal, vertical;
1008 for (const auto& wire : wires) {
1009 if (wire.points.size() < 2 || wire.points.front() == wire.points.back())
1010 return false;
1011 for (std::size_t i = 1; i < wire.points.size(); ++i) {
1012 const auto& a = wire.points[i - 1];
1013 const auto& b = wire.points[i];
1014 if (a.y() == b.y())
1015 horizontal[a.y()].push_back(
1016 {std::min(a.x(), b.x()), std::max(a.x(), b.x()), &wire.bus});
1017 else if (a.x() == b.x())
1018 vertical[a.x()].push_back(
1019 {std::min(a.y(), b.y()), std::max(a.y(), b.y()), &wire.bus});
1020 else
1021 return false;
1022 }
1023 }
1024 auto touchesOtherNet = [](const auto& lines, qreal coordinate, qreal position,
1025 const Bus& bus) {
1026 const auto line = lines.find(coordinate);
1027 return line != lines.end()
1028 && std::ranges::any_of(line->second, [&](const Span& span) {
1029 return span.low <= position && position <= span.high
1030 && *span.bus != bus;
1031 });
1032 };
1033 for (const auto& wire : wires)
1034 for (const auto point : {wire.points.front(), wire.points.back()})
1035 if (touchesOtherNet(horizontal, point.y(), point.x(), wire.bus)
1036 || touchesOtherNet(vertical, point.x(), point.y(), wire.bus))
1037 return false;
1038 return true;
1039 }
1040
1041 std::optional<CircuitAutoplacement>
1042 routePreparedCandidate(std::span<const RoutableConnection> connections,
1043 GraphLayout::PlacementMap placements,
1044 const CircuitAutoplacerOptions& options,
1045 const std::size_t routingOrder)
1046 {
1047 CircuitAutoplacement result;
1048 result.components = std::move(placements);
1049 result.ioPortOrientations = placeBoundaryIos(connections, result.components);
1050 separateBoundaryIos(result.components, result.ioPortOrientations,
1051 options.obstaclePadding);
1052 if (!componentsHaveClearance(result.components, result.ioPortOrientations))
1053 return std::nullopt;
1054
1055 ProgressRouter router(options);
1057 if (connections.size() > 1024) {
1058 // Separate the complete net groups below. Global crossing-penalty
1059 // rerouting compares every branch pair and is prohibitive at this size.
1060 router.setRoutingParameter(Avoid::fixedSharedPathPenalty, 0.0);
1061 router.setRoutingOption(Avoid::useWeightedAStar, true);
1062 router.setRoutingOption(Avoid::performOrthogonalNudging, false);
1063 }
1064 const auto obstacles = registerObstacles(
1065 router, result.components, options.obstaclePadding, result.ioPortOrientations);
1066 // Commit the obstacle visibility graph before adding the complete batch of nets.
1067 router.processTransaction();
1068 auto pendingNets = registerNets(router, connections, result.components,
1069 result.ioPortOrientations, obstacles, routingOrder);
1070 if (!pendingNets)
1071 return std::nullopt;
1072 auto wires = buildWires(std::move(*pendingNets), options);
1073 if (!wires)
1074 return std::nullopt;
1075 result.wires = std::move(*wires);
1076 // Merging changes segment endpoints. Validate the geometry the editor will
1077 // actually commit, where an endpoint touching another route joins its net.
1078 if (!wireEndpointsPreserveNets(result.wires))
1079 return std::nullopt;
1080 return result;
1081 }
1082
1083 std::optional<CircuitAutoplacement>
1084 routeCandidate(std::span<const RoutableConnection> connections,
1085 GraphLayout::PlacementMap placements,
1086 const CircuitAutoplacerOptions& options,
1087 const std::size_t routingOrder = 0)
1088 {
1089 stackSymmetricFeedbackPairs(connections, placements);
1090 separateLogicComponents(placements);
1091 compactOrderedFanIns(connections, placements);
1092 return routePreparedCandidate(connections, std::move(placements), options,
1093 routingOrder);
1094 }
1095
1096 void expandPlacements(GraphLayout::PlacementMap& placements, const int expansionLevel)
1097 {
1098 if (expansionLevel <= 0 || placements.empty())
1099 return;
1100
1101 QPointF center;
1102 for (const auto& position : placements | std::views::values)
1103 center += position;
1104 center /= static_cast<qreal>(placements.size());
1105 center = DiagramScene::snapToGrid(center);
1106
1107 const qreal factor = 1.0 + static_cast<qreal>(expansionLevel);
1108 for (auto& [_, position] : placements)
1109 position = DiagramScene::snapToGrid(center + (position - center) * factor);
1110 }
1111
1112 using PlacementScore = detail::AutoplacementQuality;
1113
1114 PlacementScore scorePlacement(std::span<const RoutableConnection> connections,
1115 const CircuitAutoplacement& placement)
1116 {
1117 // Component Bounds Calculation
1118 std::vector<QRectF> componentBounds;
1119 componentBounds.reserve(placement.components.size());
1120 std::optional<QRectF> layoutBounds;
1121
1122 for (const auto& [component, position] : placement.components) {
1123 const QRectF bounds =
1124 movedComponentObstacle(component, position, 0, &placement.ioPortOrientations);
1125
1126 componentBounds.push_back(bounds);
1127 layoutBounds = layoutBounds ? layoutBounds->united(bounds) : bounds;
1128 }
1129
1130 // Overlaps Calculation
1131 std::size_t overlaps = 0;
1132 for (const auto& [i, bound_a] : SILICON::views::enumerate(componentBounds)) {
1133 for (const auto& bound_b : componentBounds | std::views::drop(i + 1)) {
1134 if (!hasComponentClearance(bound_a, std::span(&bound_b, 1))) {
1135 ++overlaps;
1136 }
1137 }
1138 }
1139
1140 // Shared Segments and Crossing
1141 std::size_t sharedSegments = 0;
1142 std::size_t crossings = 0;
1143
1144 for (const auto& [i, wire_a] : SILICON::views::enumerate(placement.wires)) {
1145 for (const auto& [bus, points] : placement.wires | std::views::drop(i + 1)) {
1146 if (wire_a.bus == bus)
1147 continue;
1148
1149 if (orthogonalRoutesShareSegment(wire_a.points, points))
1150 ++sharedSegments;
1151 crossings += orthogonalRouteCrossingCount(wire_a.points, points);
1152 }
1153 }
1154
1155 // Prefer placements where the peer terminal lies in front of both connected ports.
1156 // Libavoid can legally route a connection that immediately doubles back around its
1157 // source or target, so route completeness alone does not distinguish a readable
1158 // signal-flow layout from a compact but backwards one.
1159 std::size_t directionViolations = 0;
1160 double wrongWayDistance = 0.0;
1161 for (const RoutableConnection& connection : connections) {
1162 if (!placement.components.contains(connection.source)
1163 || !placement.components.contains(connection.target))
1164 continue;
1165
1166 const QPointF sourcePort = movedPortPosition(
1167 connection.source, connection.sourcePort,
1168 placement.components.at(connection.source), &placement.ioPortOrientations);
1169 const QPointF targetPort = movedPortPosition(
1170 connection.target, connection.targetPort,
1171 placement.components.at(connection.target), &placement.ioPortOrientations);
1172 const qreal sourceViolation = detail::portDirectionViolationDistance(
1173 effectivePortSide(connection.source, connection.sourcePort,
1174 placement.ioPortOrientations),
1175 sourcePort, targetPort);
1176 const qreal targetViolation = detail::portDirectionViolationDistance(
1177 effectivePortSide(connection.target, connection.targetPort,
1178 placement.ioPortOrientations),
1179 targetPort, sourcePort);
1180 directionViolations += static_cast<std::size_t>(sourceViolation > 0.0)
1181 + static_cast<std::size_t>(targetViolation > 0.0);
1182 wrongWayDistance += sourceViolation + targetViolation;
1183 }
1184
1185 // Point calculation and Wire length
1186 std::size_t intermediatePoints = 0;
1187 double wireLength = 0.0;
1188
1189 for (const auto& [bus, points] : placement.wires) {
1190 if (points.size() > 2)
1191 intermediatePoints += points.size() - 2;
1192
1193 for (const QPointF& point : points) {
1194 const QRectF pointBounds(point, QSizeF(1.0, 1.0));
1195 layoutBounds = layoutBounds ? layoutBounds->united(pointBounds) : pointBounds;
1196 }
1197
1198 // Calculate Manhattan distance between adjacent pairs
1199 for (const auto& pair : points | SILICON::views::slide(2)) {
1200 const QPointF& p1 = pair[0];
1201 const QPointF& p2 = pair[1];
1202 wireLength += std::abs(p2.x() - p1.x()) + std::abs(p2.y() - p1.y());
1203 }
1204 }
1205
1206 // A bend is worth several grid steps, but never an arbitrarily long detour. This
1207 // keeps routes simple without allowing one fewer point to flatten a feedback circuit
1208 // into a huge loop around the whole diagram.
1209 const double routingCost = wireLength
1210 + intermediatePoints * 4.0 * DiagramScene::GRID_SIZE
1211 + 2.0 * wrongWayDistance;
1212
1213 const double area =
1214 layoutBounds ? layoutBounds->width() * layoutBounds->height() : 0.0;
1215
1216 return {.overlaps = overlaps,
1217 .directionViolations = directionViolations,
1218 .sharedSegments = sharedSegments,
1219 .crossings = crossings,
1220 .routingCost = routingCost,
1221 .area = area};
1222 }
1223
1224 bool verticalSide(const PortSide side)
1225 {
1226 return side == PortSide::UP || side == PortSide::DOWN;
1227 }
1228
1229 qreal medianCoordinate(std::vector<qreal> coordinates)
1230 {
1231 Q_ASSERT(!coordinates.empty());
1232 const auto middle =
1233 coordinates.begin() + static_cast<std::ptrdiff_t>(coordinates.size() / 2);
1234 std::ranges::nth_element(coordinates, middle);
1235 if (coordinates.size() % 2 != 0)
1236 return *middle;
1237
1238 const qreal lower =
1239 *std::ranges::max_element(std::ranges::subrange(coordinates.begin(), middle));
1240 return (lower + *middle) / 2.0;
1241 }
1242
1243 struct AlignmentTargets {
1244 std::vector<qreal> x;
1245 std::vector<qreal> y;
1246 };
1247
1248 std::unordered_map<GraphicalLogicComponent*, AlignmentTargets>
1249 alignmentTargets(std::span<const RoutableConnection> connections,
1250 const CircuitAutoplacement& placement)
1251 {
1252 std::unordered_map<GraphicalLogicComponent*, AlignmentTargets> targets;
1253
1254 for (const RoutableConnection& connection : connections) {
1255 if (!placement.components.contains(connection.source)
1256 || !placement.components.contains(connection.target))
1257 continue;
1258
1259 const PortSide sourceSide = effectivePortSide(
1260 connection.source, connection.sourcePort, placement.ioPortOrientations);
1261 const PortSide targetSide = effectivePortSide(
1262 connection.target, connection.targetPort, placement.ioPortOrientations);
1263 if (oppositeSide(sourceSide) != targetSide)
1264 continue;
1265
1266 const QPointF sourcePort = movedPortPosition(
1267 connection.source, connection.sourcePort,
1268 placement.components.at(connection.source), &placement.ioPortOrientations);
1269 const QPointF targetPort = movedPortPosition(
1270 connection.target, connection.targetPort,
1271 placement.components.at(connection.target), &placement.ioPortOrientations);
1272
1273 if (!hasCategory(connection.source, ItemCategory::IO)) {
1274 QPointF sourcePosition = placement.components.at(connection.source);
1275 if (verticalSide(sourceSide))
1276 targets[connection.source].x.push_back(sourcePosition.x() + targetPort.x()
1277 - sourcePort.x());
1278 else
1279 targets[connection.source].y.push_back(sourcePosition.y() + targetPort.y()
1280 - sourcePort.y());
1281 }
1282 if (!hasCategory(connection.target, ItemCategory::IO)) {
1283 QPointF targetPosition = placement.components.at(connection.target);
1284 if (verticalSide(targetSide))
1285 targets[connection.target].x.push_back(targetPosition.x() + sourcePort.x()
1286 - targetPort.x());
1287 else
1288 targets[connection.target].y.push_back(targetPosition.y() + sourcePort.y()
1289 - targetPort.y());
1290 }
1291 }
1292 return targets;
1293 }
1294
1295 void appendDistinctPosition(std::vector<QPointF>& positions, const QPointF position)
1296 {
1297 const QPointF snapped = DiagramScene::snapToGrid(position);
1298 if (std::ranges::find(positions, snapped) == positions.end())
1299 positions.push_back(snapped);
1300 }
1301
1302 std::vector<QPointF> refinementPositions(const QPointF& current,
1303 const AlignmentTargets& targets)
1304 {
1305 const std::optional<qreal> targetX =
1306 targets.x.empty() ? std::nullopt
1307 : std::optional<qreal>(medianCoordinate(targets.x));
1308 const std::optional<qreal> targetY =
1309 targets.y.empty() ? std::nullopt
1310 : std::optional<qreal>(medianCoordinate(targets.y));
1311
1312 std::vector<QPointF> positions;
1313 if (targetX) {
1314 appendDistinctPosition(positions, QPointF(*targetX, current.y()));
1315 appendDistinctPosition(positions,
1316 QPointF((current.x() + *targetX) / 2.0, current.y()));
1317 }
1318 if (targetY) {
1319 appendDistinctPosition(positions, QPointF(current.x(), *targetY));
1320 appendDistinctPosition(positions,
1321 QPointF(current.x(), (current.y() + *targetY) / 2.0));
1322 }
1323 if (targetX && targetY) {
1324 appendDistinctPosition(positions, QPointF(*targetX, *targetY));
1325 appendDistinctPosition(positions, (current + QPointF(*targetX, *targetY)) / 2.0);
1326 }
1327 std::erase(positions, DiagramScene::snapToGrid(current));
1328 return positions;
1329 }
1330
1332 refinePlacementWithRouting(std::span<const RoutableConnection> connections,
1334 const CircuitAutoplacerOptions& options,
1335 std::size_t routingOrder, std::size_t remainingAttempts)
1336 {
1337 constexpr int MAX_PASSES = 2;
1338 PlacementScore bestScore = scorePlacement(connections, best);
1339
1340 for (int pass = 0; pass < MAX_PASSES; ++pass) {
1341 bool improved = false;
1342 auto targets = alignmentTargets(connections, best);
1343 std::vector<GraphicalLogicComponent*> components;
1344 components.reserve(targets.size());
1345 for (GraphicalLogicComponent* component : targets | std::views::keys)
1346 components.push_back(component);
1347 std::ranges::sort(components, [](const auto* lhs, const auto* rhs) {
1348 if (lhs->getUiId() != rhs->getUiId())
1349 return lhs->getUiId() < rhs->getUiId();
1350 return lhs < rhs;
1351 });
1352
1353 for (GraphicalLogicComponent* component : components) {
1354 if (options.isCancelled && options.isCancelled())
1355 return best;
1356
1357 // Recompute after every accepted move: the useful alignment coordinate for the
1358 // next component may have moved with the net's opposite terminal.
1359 targets = alignmentTargets(connections, best);
1360 const auto target = targets.find(component);
1361 if (target == targets.end())
1362 continue;
1363
1364 const QPointF current = best.components.at(component);
1365 for (const QPointF proposalPosition :
1366 refinementPositions(current, target->second)) {
1367 if (remainingAttempts == 0)
1368 return best;
1369 --remainingAttempts;
1370 auto proposalPlacements = best.components;
1371 proposalPlacements[component] = proposalPosition;
1372 auto proposal = routePreparedCandidate(
1373 connections, std::move(proposalPlacements), options, routingOrder++);
1374 if (!proposal)
1375 continue;
1376
1377 const PlacementScore proposalScore = scorePlacement(connections, *proposal);
1378 if (proposalScore < bestScore) {
1379 best = std::move(*proposal);
1380 bestScore = proposalScore;
1381 improved = true;
1382 break;
1383 }
1384 }
1385 }
1386 if (!improved)
1387 break;
1388 }
1389 return best;
1390 }
1391} // namespace
1392
1394 const Circuit& circuit, std::span<GraphicalLogicComponent* const> components)
1395{
1396 const auto componentToGraphics = buildComponentMap(components);
1397 const auto connections = resolveConnections(circuit, componentToGraphics);
1398 return preferredBoundaryIoOrientations(connections);
1399}
1400
1403 std::span<GraphicalLogicComponent* const> components,
1404 const CircuitAutoplacerOptions& suppliedOptions)
1405{
1406 bool cancelled = false;
1407 auto options = suppliedOptions;
1408 options.isCancelled = [&] {
1409 cancelled =
1410 cancelled || (suppliedOptions.isCancelled && suppliedOptions.isCancelled());
1411 return cancelled;
1412 };
1413 if (options.isCancelled())
1414 return {.cancelled = true, .components = {}, .ioPortOrientations = {}, .wires = {}};
1415 const auto componentToGraphics = buildComponentMap(components);
1416 const auto resolvedConnections = resolveConnections(circuit, componentToGraphics);
1417 const auto attemptBudget = std::max<std::size_t>(
1418 1, ROUTING_WORK_BUDGET / std::max<std::size_t>(1, resolvedConnections.size()));
1419 const int candidateCount = static_cast<int>(
1420 std::min<std::size_t>(std::max(1, options.candidateCount), attemptBudget));
1421 std::size_t remainingAttempts = attemptBudget;
1422 if (options.progress)
1423 options.progress(0, candidateCount);
1424 const auto layoutDirections =
1425 preferredLayoutDirections(resolvedConnections, options.graphLayout.direction);
1426
1427 GraphLayoutOptions primaryLayoutOptions = options.graphLayout;
1428 if (primaryLayoutOptions.algorithm == GraphLayoutAlgorithm::Layered)
1429 primaryLayoutOptions.direction = layoutDirections.front();
1430 auto initialPlacements =
1431 GraphLayout::compute(circuit, components, primaryLayoutOptions);
1432
1434 std::optional<PlacementScore> bestScore;
1435
1436 for (int candidateIndex = 0; candidateIndex < candidateCount; ++candidateIndex) {
1437 if (options.isCancelled && options.isCancelled())
1438 break;
1439
1440 GraphLayout::PlacementMap placements;
1441 if (candidateIndex == 0) {
1442 placements = std::move(initialPlacements);
1443 } else {
1444 GraphLayoutOptions candidateOptions = options.graphLayout;
1445 if (options.graphLayout.algorithm == GraphLayoutAlgorithm::Layered
1446 && candidateIndex < static_cast<int>(layoutDirections.size())) {
1447 candidateOptions.direction =
1448 layoutDirections[static_cast<std::size_t>(candidateIndex)];
1449 } else {
1451 candidateOptions.randomSeed = candidateIndex;
1452 }
1453 placements = GraphLayout::compute(circuit, components, candidateOptions);
1454 }
1455
1456 auto candidate = routeCandidate(resolvedConnections, std::move(placements), options,
1457 static_cast<std::size_t>(candidateIndex));
1458 --remainingAttempts;
1459 if (!candidate) {
1460 if (options.progress)
1461 options.progress(candidateIndex + 1, candidateCount);
1462 continue;
1463 }
1464 const auto score = scorePlacement(resolvedConnections, *candidate);
1465 if (!bestScore || score < *bestScore) {
1466 best = std::move(*candidate);
1467 bestScore = score;
1468 }
1469
1470 if (options.progress)
1471 options.progress(candidateIndex + 1, candidateCount);
1472 }
1473
1474 // Constraint failures are search feedback, not a valid final result. If the graph
1475 // candidates all choose the same congested corridors, widen a deterministic base
1476 // placement and rotate the order in which libavoid fixes complete nets. Keep this
1477 // fallback bounded because a structurally unrepresentable topology cannot be fixed
1478 // by adding space.
1479 constexpr int MAX_FALLBACK_ROUTING_ATTEMPTS = 64;
1480 for (int routingAttempt = 0; !bestScore && remainingAttempts > 0
1481 && routingAttempt < MAX_FALLBACK_ROUTING_ATTEMPTS;
1482 ++routingAttempt) {
1483 if (options.isCancelled && options.isCancelled())
1484 break;
1485
1486 // Continue the normal candidate sequence rather than repeating and scaling the same
1487 // deterministic layered placement: try any remaining layered direction first, then
1488 // deterministic force-directed seeds.
1489 const int fallbackCandidateIndex = candidateCount + routingAttempt;
1490 GraphLayoutOptions fallbackLayoutOptions = options.graphLayout;
1491 if (fallbackCandidateIndex < static_cast<int>(layoutDirections.size())) {
1492 fallbackLayoutOptions.algorithm = GraphLayoutAlgorithm::Layered;
1493 fallbackLayoutOptions.direction =
1494 layoutDirections[static_cast<std::size_t>(fallbackCandidateIndex)];
1495 } else {
1496 fallbackLayoutOptions.algorithm = GraphLayoutAlgorithm::ForceDirected;
1497 fallbackLayoutOptions.randomSeed = fallbackCandidateIndex;
1498 }
1499
1500 auto placements = GraphLayout::compute(circuit, components, fallbackLayoutOptions);
1501 expandPlacements(placements, 1 + routingAttempt / 4);
1502 auto candidate =
1503 routeCandidate(resolvedConnections, std::move(placements), options,
1504 static_cast<std::size_t>(candidateCount + routingAttempt));
1505 --remainingAttempts;
1506 if (candidate) {
1507 best = std::move(*candidate);
1508 bestScore = scorePlacement(resolvedConnections, best);
1509 }
1510
1511 if (options.progress)
1512 options.progress(candidateCount, candidateCount);
1513 }
1514
1515 if (!bestScore && options.isCancelled && options.isCancelled())
1516 return {.cancelled = true, .components = {}, .ioPortOrientations = {}, .wires = {}};
1517 if (!bestScore) {
1519 "Circuit autoplacement could not produce a complete route");
1520 }
1521
1522 if (bestScore && remainingAttempts > 0
1523 && !(options.isCancelled && options.isCancelled())) {
1524 best = refinePlacementWithRouting(resolvedConnections, std::move(best), options,
1525 static_cast<std::size_t>(candidateCount),
1526 remainingAttempts);
1527 }
1528
1529 if (bestScore && options.progress)
1530 options.progress(candidateCount, candidateCount);
1531
1532 return best;
1533}
1534
1535} // namespace SILICON::ui
Represents a digital circuit as a directed graph of components.
Definition circuit.hpp:125
std::vector< CircuitConnection > getConnections() const
Gets concrete output-to-input logical connections for routing.
Definition circuit.cpp:423
Complete pure autoplacement result.
static IoOrientationMap boundaryIoOrientations(const core::Circuit &circuit, std::span< GraphicalLogicComponent *const > components)
Determines boundary I/O sides directly from connected component ports.
static CircuitAutoplacement compute(const core::Circuit &circuit, std::span< GraphicalLogicComponent *const > components, const CircuitAutoplacerOptions &options={})
Computes component placements and routed wire paths for a circuit.
static constexpr int GRID_SIZE
Grid cell size in scene units.
static QPoint snapToGrid(QPointF point)
Snaps a point to the grid.
static PlacementMap compute(const core::Circuit &circuit, std::span< GraphicalLogicComponent *const > components, const GraphLayoutOptions &options={})
Computes component placements for the subset represented by components.
std::unordered_map< GraphicalLogicComponent *, QPointF > PlacementMap
Map from graphical component to the computed scene position for that item.
const std::vector< Port * > & getOutputPorts() const
Borrows output ports; copy before replacing the component ports.
Abstract base class for all graphical Input and Output components.
Base class for logic-gate graphical components.
Represents a connection point on a component.
RTLIL::SigSpec port(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key, int expected)
bool orthogonalRoutesTouch(const std::span< const QPointF > first, const std::span< const QPointF > second)
Returns whether an endpoint of either route lies on the other route.
std::size_t orthogonalRouteCrossingCount(const std::span< const QPointF > first, const std::span< const QPointF > second)
Counts strict, perpendicular interior crossings between two routes.
void configureOrthogonalRouter(Avoid::Router &router, const qreal gridSize)
Applies SILICON's shared orthogonal-routing policy to a libavoid router.
std::vector< QPointF > extractOrthogonalRoute(Avoid::ConnRef &connector, const qreal gridSize)
Extracts, grid-snaps, and canonicalizes a libavoid display route.
bool isOrthogonalRoute(const std::span< const QPointF > points)
Returns whether every consecutive route segment is axis-aligned.
bool orthogonalRoutesShareSegment(const std::span< const QPointF > first, const std::span< const QPointF > second)
Returns true when two orthogonal polylines share a positive-length segment.
std::vector< std::vector< QPointF > > mergeOrthogonalRoutes(const std::vector< std::vector< QPointF > > &routes, const std::function< bool()> &progress)
Unions several routes of one net into maximal terminal-to-junction paths.
bool boundsLieOutsideTarget(const PortSide side, const QRectF &item, const QRectF &target, const qreal clearance)
BoundaryIoLaneResult placeBoundaryIoInLanes(const PortSide side, std::span< const BoundaryIoLaneItem > items, std::span< const QRectF > fixedObstacles, const qreal componentClearance, const qreal obstaclePadding, const qreal grid)
qreal portDirectionViolationDistance(const PortSide side, const QPointF &endpoint, const QPointF &peer)
bool hasBoundsClearance(const QRectF &candidate, const std::span< const QRectF > accepted, const qreal clearance)
bool hasCategory(const QGraphicsItem *item, ItemCategory cat)
Definition enums.hpp:49
GraphLayoutDirection
Signal-flow direction used for a layered layout.
std::unordered_map< GraphicalIO *, PortSide > IoOrientationMap
TargetType * category_cast(QGraphicsItem *item, ItemCategory expectedCategory)
Definition enums.hpp:60
constexpr auto slide
Json directions(std::initializer_list< std::pair< std::string_view, std::string_view > > values)
Definition helpers.hpp:36
Directed logical connection between one component output bus and one input bus.
Definition circuit.hpp:64
unsigned int sourceBusIndex
Output bus index on source.
Definition circuit.hpp:72
Component_ptr target
Component that owns the input bus.
Definition circuit.hpp:69
Bus bus
Logical bus carried by this connection.
Definition circuit.hpp:78
Component_ptr source
Component that owns the output bus.
Definition circuit.hpp:66
unsigned int targetBusIndex
Input bus index on target.
Definition circuit.hpp:75
GraphLayout::PlacementMap components
Computed scene positions for participating components.
Configuration for full circuit autoplacement and wire routing.
std::function< bool()> isCancelled
Optional cooperative cancellation check, also polled during routing. A candidate finishes routing bef...
Configuration for OGDF-based component placement.
int randomSeed
Deterministic seed used by force-directed candidates.
GraphLayoutAlgorithm algorithm
Placement family used to generate the candidate.
GraphLayoutDirection direction
Scene direction assigned to source-to-target ranks.
Scene-coordinate wire path produced by an automatic router.