28#include <unordered_set>
32#include <QGraphicsScene>
39using namespace SILICON::core;
47 try {
cancel(); }
catch (...) { }
71 throw std::invalid_argument(
"A committed wire route must be orthogonal and simple");
78 auto& pending =
manager->pendingEdits;
79 if (std::ranges::find(pending,
segmentId) == pending.end())
129 const auto it = std::ranges::find_if(
allSegments, [
id](
const auto* segment) {
130 return segment->getUiId() == id;
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});
160 std::map<uint64_t, size_t> incidences;
162 ++incidences[topology.firstVertex];
163 ++incidences[topology.lastVertex];
164 for (
const auto& [vertexId, position] : topology.junctions)
165 ++incidences[vertexId];
168 bool changed =
false;
169 for (
auto& [
id, vertex] :
vertices) {
170 auto ports = portsByPosition[{vertex.position.x(), vertex.position.y()}];
173 if (vertex.ports != ports || vertex.kind != kind) {
174 vertex.ports = std::move(ports);
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));
191 std::map<uint64_t, TopologyEdge> rebuilt;
193 topology.edgeIds.clear();
197 const auto route = segment->getScenePoints();
198 if (route.size() < 2)
200 std::vector<std::pair<uint64_t, QPointF>> ordered{{topology.firstVertex, route.front()}};
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
208 }) | std::ranges::to<std::vector>();
209 std::ranges::sort(onSpan, {}, [&](
const auto& junction) {
210 return QLineF(first, junction.second).length();
212 ordered.append_range(onSpan);
213 if (
static_cast<size_t>(i) + 2 == route.size())
214 ordered.emplace_back(topology.lastVertex, route.back());
216 ordered.emplace_back(0, last);
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);
226 if (piece.size() >= 2) {
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);
234 startVertex = endVertex;
236 topology.edgeIds = std::move(edgeIds);
238 edges = std::move(rebuilt);
245 std::vector<GraphicalWireSegment*> segments =
allSegments;
249 using PointKey = std::pair<qreal, qreal>;
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});
269 vertical[first.x()].push_back(
270 {std::min(first.y(), last.y()), std::max(first.y(), last.y()), i});
273 sceneRoutes.push_back(std::move(points));
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];
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);
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);
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]);
302 std::unordered_set<GraphicalWire*> assigned;
303 for (
const auto& group : groups) {
307 for (
auto* member : group)
308 if (
auto* candidate = member->getGraphicalWire();
309 candidate && !assigned.contains(candidate)
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);
319 std::erase_if(
managedWires, [](
const auto& wire) {
return wire->empty(); });
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];
336 for (std::size_t i = 0; i < segments.size(); ++i) {
337 const auto& points = sceneRoutes[i];
338 if (points.size() < 2)
341 vertexFor(points.front()), vertexFor(points.back()), {}, {}};
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())
350 .junctions.emplace_back(vertex, position);
361 const std::span<
const std::pair<uint64_t, QPointF>> translations)
363 if (std::ranges::any_of(translations, [](
const auto& entry) {
364 return !entry.second.isNull();
375 segment->detachFromWire();
379 wire->setManager(
nullptr);
403 for (
auto* segment : segments) {
407 scene.removeItem(segment);
408 segment->detachFromWire();
413 wire->setManager(
nullptr);
425 std::span<const RoutedWire> routedSegments)
430 std::map<std::vector<uint64_t>, std::shared_ptr<GraphicalWire>> wireByBus;
432 for (
const RoutedWire& routed : routedSegments) {
433 if (routed.points.size() < 2)
436 std::vector<uint64_t> key;
437 for (
const auto& bit : routed.bus)
438 key.push_back(bit ? bit->getId() : 0);
441 auto& wire = wireByBus[key];
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);
450 segment->setPoints(routed.points);
451 scene.addItem(segment);
452 segment->setGraphicalWire(wire.get());
462 auto wire = std::make_shared<GraphicalWire>(busSize);
463 wire->setManager(
this);
471 throw std::invalid_argument(
"removeWire() called with nullptr");
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;
482 throw std::invalid_argument(
"addSegment() called with null segment");
487 throw std::invalid_argument(
"A committed wire route must be orthogonal and simple");
501 throw std::invalid_argument(
"removeSegment() called with null segment");
513 throw std::invalid_argument(
"updateSegmentTopology() called with null segment");
514 if (!segment->
empty())
524 bool includeNeighborhood)
const
527 throw std::invalid_argument(
"calculateJunctions() called with null segment");
528 if (segment->
empty())
531 const auto neighborhood =
538 const std::span<GraphicalWireSegment* const> segments)
const
540 for (
auto* segment : segments) {
541 if (!segment || segment->empty() || !
segmentTopology.contains(segment->getUiId()))
544 segment->setFirstPointJunction(
546 segment->setLastPointJunction(
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
565 const QPointF localPt = seg->mapFromScene(scenePoint);
566 if (seg->isPointOnPath(localPt))
574std::vector<GraphicalWireSegment*>
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");
582 const auto colliding = segment->scene()->collidingItems(segment);
585 colliding | std::views::transform([](QGraphicsItem* item) {
591 | std::ranges::to<std::vector>();
593 neighbors.push_back(segment);
600 if (!segment || !other)
601 throw std::invalid_argument(
"segmentsTouching() called with null segment");
603 if (segment == other)
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
TopologyGraph topologyGraph
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)
Scene-coordinate wire path produced by an automatic router.