SILICON
Loading...
Searching...
No Matches
wireManager.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 "wireManager.hpp"
19
20#include <algorithm>
21#include <array>
22#include <cstdint>
23#include <map>
24#include <numeric>
25#include <ranges>
26#include <set>
27#include <stdexcept>
28#include <unordered_set>
29#include <utility>
30
31
32#include <QGraphicsScene>
33#include <QLineF>
37
38namespace SILICON::ui {
39using namespace SILICON::core;
40
42 : manager(&owner), segmentId(editedSegment->getUiId()), originalPoints(editedSegment->getPoints())
43{}
44
46{
47 try { cancel(); } catch (...) { /* Destructors must not throw. */ }
48}
49
51{
52 if (!manager)
53 return;
54 if (auto* segment = manager->registeredSegment(segmentId))
55 segment->setPoints(originalPoints);
56 manager = nullptr;
57}
58
60{
61 if (!manager)
62 return;
63 auto* segment = manager->registeredSegment(segmentId);
64 if (!segment) {
65 manager = nullptr;
66 return;
67 }
68 if (segment->getPoints().size() < 2 || !isOrthogonalRoute(segment->getPoints())
69 || orthogonalRouteSelfIntersects(segment->getPoints())) {
70 cancel();
71 throw std::invalid_argument("A committed wire route must be orthogonal and simple");
72 }
73 if (segment->getPoints() == originalPoints) {
74 manager = nullptr;
75 return;
76 }
77 Batch batch(*manager);
78 auto& pending = manager->pendingEdits;
79 if (std::ranges::find(pending, segmentId) == pending.end())
80 pending.push_back(segmentId);
81 batch.commit();
82 manager = nullptr;
83}
84
86{
87 if (!batchDepth)
88 return;
89 if (batchDepth > 1) {
90 --batchDepth;
91 return;
92 }
93 const bool geometryChanged = std::exchange(rebuildPending, false) || !pendingEdits.empty();
94 if (geometryChanged)
96 pendingEdits.clear();
97 batchDepth = 0;
98 const auto changes = static_cast<Change>(pendingChanges
99 | (geometryChanged ? static_cast<uint8_t>(Change::Geometry) : 0));
100 pendingChanges = 0;
101 notify(changes);
102}
103
104void WireManager::notify(const Change change) const
105{
106 if (change == Change::None)
107 return;
108 if (batchDepth) {
109 pendingChanges |= static_cast<uint8_t>(change);
110 return;
111 }
112 if (onChanged)
113 onChanged(change);
114}
115
117{
118 if (batchDepth)
119 --batchDepth;
120 if (!batchDepth) {
121 pendingEdits.clear();
122 rebuildPending = false;
123 pendingChanges = 0;
124 }
125}
126
128{
129 const auto it = std::ranges::find_if(allSegments, [id](const auto* segment) {
130 return segment->getUiId() == id;
131 });
132 return it == allSegments.end() ? nullptr : *it;
133}
134
135uint64_t WireManager::createVertex(const QPointF position, const VertexKind kind)
136{
137 const uint64_t id = nextVertexId++;
138 TopologyVertex vertex{id, position, kind, {}};
139 // Rebuild creates vertices in a batch and refreshPortAnchors binds all ports
140 // afterwards. Fetching the entire scene's ports for each vertex is quadratic.
141 vertices.emplace(id, vertex);
142 return id;
143}
144
145const WireManager::SegmentTopology& WireManager::topologyFor(const uint64_t segmentId) const
146{
147 const auto it = segmentTopology.find(segmentId);
148 static const SegmentTopology empty;
149 return it == segmentTopology.end() ? empty : it->second;
150}
151
153{
154 const auto anchors = portAnchors ? portAnchors() : std::vector<PortAnchor>{};
155 std::map<std::pair<qreal, qreal>, std::vector<PortReference>> portsByPosition;
156 for (const auto& anchor : anchors)
157 portsByPosition[{anchor.position.x(), anchor.position.y()}].push_back(
158 {anchor.componentId, anchor.portIndex, anchor.output});
159
160 std::map<uint64_t, size_t> incidences;
161 for (const auto& topology : segmentTopology | std::views::values) {
162 ++incidences[topology.firstVertex];
163 ++incidences[topology.lastVertex];
164 for (const auto& [vertexId, position] : topology.junctions)
165 ++incidences[vertexId];
166 }
167
168 bool changed = false;
169 for (auto& [id, vertex] : vertices) {
170 auto ports = portsByPosition[{vertex.position.x(), vertex.position.y()}];
171 const auto kind = !ports.empty() ? VertexKind::Port
172 : (incidences[id] > 1 ? VertexKind::Junction : VertexKind::FreeEndpoint);
173 if (vertex.ports != ports || vertex.kind != kind) {
174 vertex.ports = std::move(ports);
175 vertex.kind = kind;
176 changed = true;
177 }
178 }
179 if (changed) {
181 }
182}
183
185{
186 topologyGraph.clear();
187 std::map<uint64_t, VertexDescriptor> descriptors;
188 for (const auto id : vertices | std::views::keys)
189 descriptors.emplace(id, boost::add_vertex(id, topologyGraph));
190
191 std::map<uint64_t, TopologyEdge> rebuilt;
192 for (auto& [segmentId, topology] : segmentTopology) {
193 topology.edgeIds.clear();
194 const auto* segment = registeredSegment(segmentId);
195 if (!segment)
196 continue;
197 const auto route = segment->getScenePoints();
198 if (route.size() < 2)
199 continue;
200 std::vector<std::pair<uint64_t, QPointF>> ordered{{topology.firstVertex, route.front()}};
201 for (const auto [i, endpoints] : route | SILICON::views::adjacent<2>
202 | SILICON::views::enumerate) {
203 const auto& [first, last] = endpoints;
204 const std::array span{first, last};
205 auto onSpan = topology.junctions | std::views::filter([&](const auto& junction) {
206 return junction.second != first
207 && core::pointOnOrthogonalRoute(junction.second, span);
208 }) | std::ranges::to<std::vector>();
209 std::ranges::sort(onSpan, {}, [&](const auto& junction) {
210 return QLineF(first, junction.second).length();
211 });
212 ordered.append_range(onSpan);
213 if (static_cast<size_t>(i) + 2 == route.size())
214 ordered.emplace_back(topology.lastVertex, route.back());
215 else
216 ordered.emplace_back(0, last);
217 }
218 uint64_t startVertex = ordered.front().first;
219 std::vector<QPointF> piece{ordered.front().second};
220 std::vector<uint64_t> edgeIds;
221 for (const auto& [endVertex, point] : ordered | std::views::drop(1)) {
222 if (piece.back() != point)
223 piece.push_back(point);
224 if (!endVertex)
225 continue;
226 if (piece.size() >= 2) {
227 const uint64_t id = nextEdgeId++;
228 rebuilt.emplace(id, TopologyEdge{id, segmentId, startVertex, endVertex,
230 boost::add_edge(descriptors.at(startVertex), descriptors.at(endVertex), id, topologyGraph);
231 edgeIds.push_back(id);
232 }
233 piece = {point};
234 startVertex = endVertex;
235 }
236 topology.edgeIds = std::move(edgeIds);
237 }
238 edges = std::move(rebuilt);
239 vertexDescriptors = std::move(descriptors);
240}
241
243{
244 Batch batch(*this);
245 std::vector<GraphicalWireSegment*> segments = allSegments;
246 std::ranges::sort(segments, {}, &GraphicalWireSegment::getUiId);
247 // Contacts require a route endpoint. Index horizontal and vertical spans so
248 // each endpoint only examines spans on its own coordinates, not every route.
249 using PointKey = std::pair<qreal, qreal>;
250 struct Span {
251 qreal first, last;
252 std::size_t segment;
253 };
254 std::map<qreal, std::vector<Span>> horizontal, vertical;
255 std::map<PointKey, std::set<std::size_t>> contactsAt;
256 std::vector<std::vector<QPointF>> sceneRoutes;
257 sceneRoutes.reserve(segments.size());
258 for (std::size_t i = 0; i < segments.size(); ++i) {
259 auto points = segments[i]->getScenePoints();
260 if (points.size() >= 2) {
261 contactsAt[{points.front().x(), points.front().y()}].insert(i);
262 contactsAt[{points.back().x(), points.back().y()}].insert(i);
263 for (std::size_t j = 1; j < points.size(); ++j) {
264 const auto first = points[j - 1], last = points[j];
265 if (first.y() == last.y())
266 horizontal[first.y()].push_back(
267 {std::min(first.x(), last.x()), std::max(first.x(), last.x()), i});
268 else
269 vertical[first.x()].push_back(
270 {std::min(first.y(), last.y()), std::max(first.y(), last.y()), i});
271 }
272 }
273 sceneRoutes.push_back(std::move(points));
274 }
275 std::vector<std::size_t> components(segments.size());
276 std::iota(components.begin(), components.end(), 0);
277 auto root = [&components](std::size_t index) {
278 while (components[index] != index) {
279 components[index] = components[components[index]];
280 index = components[index];
281 }
282 return index;
283 };
284 for (auto& [point, touching] : contactsAt) {
285 const auto collect = [&](const auto& lines, qreal coordinate, qreal position) {
286 if (const auto line = lines.find(coordinate); line != lines.end())
287 for (const auto& span : line->second)
288 if (span.first <= position && position <= span.last)
289 touching.insert(span.segment);
290 };
291 collect(horizontal, point.second, point.first);
292 collect(vertical, point.first, point.second);
293 for (const auto index : touching) {
294 const auto first = root(*touching.begin()), second = root(index);
295 components[std::max(first, second)] = std::min(first, second);
296 }
297 }
298 std::vector<std::vector<GraphicalWireSegment*>> groups(segments.size());
299 for (std::size_t i = 0; i < segments.size(); ++i)
300 groups[root(i)].push_back(segments[i]);
301
302 std::unordered_set<GraphicalWire*> assigned;
303 for (const auto& group : groups) {
304 if (group.empty())
305 continue;
306 GraphicalWire* wire = nullptr;
307 for (auto* member : group)
308 if (auto* candidate = member->getGraphicalWire();
309 candidate && !assigned.contains(candidate)
310 && (!wire || candidate->getSegments().size() > wire->getSegments().size()))
311 wire = candidate;
312 if (!wire)
313 wire = createWire(group.front()->getGraphicalWire()
314 ? group.front()->getGraphicalWire()->getBusSize() : 1).get();
315 assigned.insert(wire);
316 for (auto* member : group)
317 member->setGraphicalWire(wire);
318 }
319 std::erase_if(managedWires, [](const auto& wire) { return wire->empty(); });
320
321 vertices.clear();
322 edges.clear();
323 topologyGraph.clear();
324 vertexDescriptors.clear();
325 segmentTopology.clear();
326 nextVertexId = 1;
327 nextEdgeId = 1;
328 std::map<std::pair<qreal, qreal>, uint64_t> vertexAt;
329 const auto vertexFor = [&](const QPointF point) {
330 const auto key = std::pair{point.x(), point.y()};
331 auto& id = vertexAt[key];
332 if (!id)
333 id = createVertex(point);
334 return id;
335 };
336 for (std::size_t i = 0; i < segments.size(); ++i) {
337 const auto& points = sceneRoutes[i];
338 if (points.size() < 2)
339 continue;
340 segmentTopology[segments[i]->getUiId()] = {
341 vertexFor(points.front()), vertexFor(points.back()), {}, {}};
342 }
343 for (const auto& [point, touching] : contactsAt) {
344 const QPointF position(point.first, point.second);
345 const auto vertex = vertexAt.at(point);
346 for (const auto index : touching) {
347 const auto& route = sceneRoutes[index];
348 if (position != route.front() && position != route.back())
349 segmentTopology.at(segments[index]->getUiId())
350 .junctions.emplace_back(vertex, position);
351 }
352 }
357 batch.commit();
358}
359
361 const std::span<const std::pair<uint64_t, QPointF>> translations)
362{
363 if (std::ranges::any_of(translations, [](const auto& entry) {
364 return !entry.second.isNull();
365 }))
367 return true;
368}
369
371{
372 // Detach segments without side-effects (avoids creating new wires during
373 // teardown, which would leave dangling pointers after managedWires is cleared).
374 for (auto* segment : allSegments) {
375 segment->detachFromWire();
376 }
377
378 for (auto& wire : managedWires) {
379 wire->setManager(nullptr);
380 }
381
382 allSegments.clear();
383 managedWires.clear();
384 vertices.clear();
385 edges.clear();
386 topologyGraph.clear();
387 vertexDescriptors.clear();
388 segmentTopology.clear();
389 pendingEdits.clear();
390 rebuildPending = false;
391 pendingChanges = 0;
392 batchDepth = 0;
393}
394
395void WireManager::clearSegments(QGraphicsScene& scene)
396{
397 pendingEdits.clear();
398 rebuildPending = false;
399 pendingChanges = 0;
400 batchDepth = 0;
401 auto segments = std::exchange(allSegments, {});
402
403 for (auto* segment : segments) {
404 if (!segment)
405 continue;
406
407 scene.removeItem(segment);
408 segment->detachFromWire();
409 delete segment;
410 }
411
412 for (auto& wire : managedWires) {
413 wire->setManager(nullptr);
414 }
415
416 managedWires.clear();
417 vertices.clear();
418 edges.clear();
419 topologyGraph.clear();
420 vertexDescriptors.clear();
421 segmentTopology.clear();
422}
423
424void WireManager::replaceSegments(QGraphicsScene& scene,
425 std::span<const RoutedWire> routedSegments)
426{
427 clearSegments(scene);
428 Batch batch(*this);
429
430 std::map<std::vector<uint64_t>, std::shared_ptr<GraphicalWire>> wireByBus;
431
432 for (const RoutedWire& routed : routedSegments) {
433 if (routed.points.size() < 2)
434 continue;
435
436 std::vector<uint64_t> key;
437 for (const auto& bit : routed.bus)
438 key.push_back(bit ? bit->getId() : 0);
439 // A bus is its complete ordered bit vector. Sharing the first bit does not
440 // make two differently sized or differently ordered buses the same net.
441 auto& wire = wireByBus[key];
442 if (!wire) {
443 wire = createWire(
444 static_cast<unsigned int>(std::max<std::size_t>(routed.bus.size(), 1)));
445 if (routed.bus.size() > 0)
446 wire->setBus(routed.bus);
447 }
448
449 auto* segment = new GraphicalWireSegment(routed.points.front());
450 segment->setPoints(routed.points);
451 scene.addItem(segment);
452 segment->setGraphicalWire(wire.get());
453 addSegment(segment, false);
454 }
455
457 batch.commit();
458}
459
460std::shared_ptr<GraphicalWire> WireManager::createWire(unsigned int busSize)
461{
462 auto wire = std::make_shared<GraphicalWire>(busSize);
463 wire->setManager(this);
464 managedWires.push_back(wire);
465 return wire;
466}
467
469{
470 if (!wire)
471 throw std::invalid_argument("removeWire() called with nullptr");
472 if (!wire->getSegments().empty())
473 throw std::logic_error("removeWire() called without detaching the segments first");
474 std::erase_if(managedWires, [wire](const auto& managed) {
475 return managed.get() == wire;
476 });
477}
478
479void WireManager::addSegment(GraphicalWireSegment* segment, const bool updateTopology)
480{
481 if (!segment)
482 throw std::invalid_argument("addSegment() called with null segment");
483 if (std::ranges::find(allSegments, segment) != allSegments.end())
484 return;
485 if (segment->getPoints().size() < 2 || !isOrthogonalRoute(segment->getPoints())
487 throw std::invalid_argument("A committed wire route must be orthogonal and simple");
488
489 allSegments.push_back(segment);
490 if (!segment->getGraphicalWire()) {
491 auto wire = createWire(1);
492 segment->setGraphicalWire(wire.get());
493 }
494 if (updateTopology)
496}
497
499{
500 if (!segment)
501 throw std::invalid_argument("removeSegment() called with null segment");
502 std::erase(allSegments, segment);
503 std::erase(pendingEdits, segment->getUiId());
504 if (batchDepth)
505 rebuildPending = true;
506 else
508}
509
511{
512 if (!segment)
513 throw std::invalid_argument("updateSegmentTopology() called with null segment");
514 if (!segment->empty())
516}
517
522
524 bool includeNeighborhood) const
525{
526 if (!segment)
527 throw std::invalid_argument("calculateJunctions() called with null segment");
528 if (segment->empty())
529 return;
530
531 const auto neighborhood =
532 includeNeighborhood ? segmentNeighbors(segment) : std::vector{segment};
533
534 calculateJunctionsFor(neighborhood);
535}
536
538 const std::span<GraphicalWireSegment* const> segments) const
539{
540 for (auto* segment : segments) {
541 if (!segment || segment->empty() || !segmentTopology.contains(segment->getUiId()))
542 continue;
543 const auto& topology = segmentTopology.at(segment->getUiId());
544 segment->setFirstPointJunction(
545 boost::degree(vertexDescriptors.at(topology.firstVertex), topologyGraph) >= 3);
546 segment->setLastPointJunction(
547 boost::degree(vertexDescriptors.at(topology.lastVertex), topologyGraph) >= 3);
548 }
549}
550
551// --- Query -----------------------------------------------------------------------------
552
555 const GraphicalWireSegment* ignoredSegment) const
556{
557 if (allSegments.empty() || !allSegments.front()->scene())
558 return nullptr;
559 const QRectF query(scenePoint - QPointF(5, 5), QSizeF(10, 10));
560 for (auto* item : allSegments.front()->scene()->items(query)) {
562 if (!seg || seg == ignoredSegment
563 || std::ranges::find(allSegments, seg) == allSegments.end())
564 continue;
565 const QPointF localPt = seg->mapFromScene(scenePoint);
566 if (seg->isPointOnPath(localPt))
567 return seg;
568 }
569 return nullptr;
570}
571
572// --- Helpers ---------------------------------------------------------------------------
573
574std::vector<GraphicalWireSegment*>
576{
577 if (!segment)
578 throw std::invalid_argument("segmentNeighbors() called with null segment");
579 if (!segment->scene())
580 throw std::logic_error("segmentNeighbors() called on segment not in a scene");
581
582 const auto colliding = segment->scene()->collidingItems(segment);
583
584 auto neighbors =
585 colliding | std::views::transform([](QGraphicsItem* item) {
587 })
588 | std::views::filter([&](const GraphicalWireSegment* sibling) {
589 return sibling && segmentsTouching(segment, sibling);
590 })
591 | std::ranges::to<std::vector>();
592
593 neighbors.push_back(segment);
594 return neighbors;
595}
596
598 const GraphicalWireSegment* other)
599{
600 if (!segment || !other)
601 throw std::invalid_argument("segmentsTouching() called with null segment");
602
603 if (segment == other)
604 return false;
605 if (segment->empty() || other->empty())
606 return false;
607
608 return orthogonalRoutesTouch(segment->getScenePoints(), other->getScenePoints());
609}
610
611} // namespace SILICON::ui
The visible, selectable polyline wire on the diagram scene.
GraphicalWire * getGraphicalWire() const
Gets the logical wire.
const std::vector< QPointF > & getPoints() const
Gets all points of the segment.
bool empty() const
Checks if segment has only one point.
void setGraphicalWire(GraphicalWire *newWire)
Sets the logical wire, optionally propagating to touching siblings.
std::vector< QPointF > getScenePoints() const
Gets all points mapped into scene coordinates.
Logical wire entity that groups segments sharing the same bus.
const std::unordered_set< GraphicalWireSegment * > & getSegments() const
Gets all segments belonging to this wire.
void commit()
Finishes the batch, rebuilding topology and notifying at the outermost level.
void cancel()
Restores the original local route if the segment is still registered.
std::vector< QPointF > originalPoints
Edit(WireManager &manager, GraphicalWireSegment *segment)
Captures a registered segment's original local route for a preview edit.
~Edit() noexcept
Cancels an uncommitted edit and suppresses exceptions during cleanup.
void commit()
Validates the preview route and queues its topology rebuild.
void addSegment(GraphicalWireSegment *segment, bool updateTopology=true)
void calculateJunctions() const
void replaceSegments(QGraphicsScene &scene, std::span< const RoutedWire > routedSegments)
Replaces all managed graphical wire segments with routed segments.
static bool segmentsTouching(const GraphicalWireSegment *segment, const GraphicalWireSegment *other)
GraphicalWireSegment * segmentAtPoint(QPointF scenePoint, const GraphicalWireSegment *ignoredSegment=nullptr) const
std::vector< GraphicalWireSegment * > allSegments
void finishBatch()
Finishes one batch level and flushes pending edits and changes at the outermost level.
void notifyTopologyChanged() const
Force execute the callback natively mapped to topological splits, merges, or drags.
void removeSegment(GraphicalWireSegment *segment)
void rebuildTopologyEdges()
Rebuilds graph edges by splitting each segment route at its electrical vertices.
std::vector< uint64_t > pendingEdits
std::vector< std::shared_ptr< GraphicalWire > > managedWires
static std::vector< GraphicalWireSegment * > segmentNeighbors(GraphicalWireSegment *segment)
void discardBatch() noexcept
Drops one batch level and clears pending work when no batch remains.
TopologyVertexMap vertices
std::map< uint64_t, SegmentTopology > segmentTopology
const SegmentTopology & topologyFor(uint64_t segmentId) const
Borrows segment topology until rebuilt; missing segments return an empty topology.
std::shared_ptr< GraphicalWire > createWire(unsigned int busSize=1)
GraphicalWireSegment * registeredSegment(uint64_t id) const
Returns the registered segment with the given identifier, or nullptr.
void calculateJunctionsFor(std::span< GraphicalWireSegment *const > segments) const
Updates endpoint junction flags for the supplied registered segments.
void refreshPortAnchors()
Refreshes port references after components enter or leave the scene.
std::map< uint64_t, VertexDescriptor > vertexDescriptors
void updateSegmentTopology(GraphicalWireSegment *segment)
void removeWire(GraphicalWire *wire)
void rebuildFromGeometry()
Derives electrical groups, junctions, and port vertices from segment geometry.
PortAnchorProvider portAnchors
void notify(Change change) const
Delivers change flags to the callback or accumulates them in an active batch.
uint64_t createVertex(QPointF position, VertexKind kind=VertexKind::FreeEndpoint)
Creates a topology vertex and attaches matching port anchors.
void clearSegments(QGraphicsScene &scene)
Deletes all managed graphical wire segments from scene.
bool commitSegmentTranslations(std::span< const std::pair< uint64_t, QPointF > > translations)
Rebuilds connectivity after segment positions have been translated.
ChangeCallback onChanged
Callback invoked when wire topology changes (splits, merges, drags).
std::vector< QPointF > canonicalizeOrthogonalRoute(std::vector< QPointF > points)
Removes consecutive duplicates and redundant collinear interior points.
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.
bool orthogonalRouteSelfIntersects(const std::span< const QPointF > points)
Detects crossings, touches, or retraced portions within one route.
bool pointOnOrthogonalRoute(const QPointF point, const std::span< const QPointF > route)
Returns whether point lies on an orthogonal polyline.
bool isOrthogonalRoute(const std::span< const QPointF > points)
Returns whether every consecutive route segment is axis-aligned.
TargetType * category_cast(QGraphicsItem *item, ItemCategory expectedCategory)
Definition enums.hpp:60
constexpr auto adjacent
Scene-coordinate wire path produced by an automatic router.