This commit is contained in:
Mayank Mohapatra 2025-02-22 10:36:51 +00:00
parent 3c1be1ee2a
commit d00529c6f0

View file

@ -1,238 +1,261 @@
package d2cycle package d2cycle
import ( import (
"context" "context"
"math" "math"
"oss.terrastruct.com/d2/d2graph" "oss.terrastruct.com/d2/d2graph"
"oss.terrastruct.com/d2/lib/geo" "oss.terrastruct.com/d2/lib/geo"
"oss.terrastruct.com/d2/lib/label" "oss.terrastruct.com/d2/lib/label"
"oss.terrastruct.com/util-go/go2" "oss.terrastruct.com/util-go/go2"
) )
const ( const (
MIN_RADIUS = 200 MIN_RADIUS = 200
PADDING = 20 PADDING = 20
MIN_SEGMENT_LEN = 10 MIN_SEGMENT_LEN = 10
ARC_STEPS = 30 ARC_STEPS = 30
EPSILON = 1e-10 // Small value for floating point comparisons EPSILON = 1e-10 // Small value for floating point comparisons
) )
// Layout computes node positions and generates curved edge routes.
func Layout(ctx context.Context, g *d2graph.Graph, layout d2graph.LayoutGraph) error { func Layout(ctx context.Context, g *d2graph.Graph, layout d2graph.LayoutGraph) error {
objects := g.Root.ChildrenArray objects := g.Root.ChildrenArray
if len(objects) == 0 { if len(objects) == 0 {
return nil return nil
} }
for _, obj := range g.Objects { for _, obj := range g.Objects {
positionLabelsIcons(obj) positionLabelsIcons(obj)
} }
radius := calculateRadius(objects) radius := calculateRadius(objects)
positionObjects(objects, radius) positionObjects(objects, radius)
for _, edge := range g.Edges { for _, edge := range g.Edges {
createPreciseCircularArc(edge) createPreciseCircularArc(edge)
} }
return nil return nil
} }
func calculateRadius(objects []*d2graph.Object) float64 { func calculateRadius(objects []*d2graph.Object) float64 {
numObjects := float64(len(objects)) numObjects := float64(len(objects))
maxSize := 0.0 maxSize := 0.0
for _, obj := range objects { for _, obj := range objects {
size := math.Max(obj.Box.Width, obj.Box.Height) size := math.Max(obj.Box.Width, obj.Box.Height)
maxSize = math.Max(maxSize, size) maxSize = math.Max(maxSize, size)
} }
minRadius := (maxSize/2.0 + PADDING) / math.Sin(math.Pi/numObjects) minRadius := (maxSize/2.0 + PADDING) / math.Sin(math.Pi/numObjects)
return math.Max(minRadius, MIN_RADIUS) return math.Max(minRadius, MIN_RADIUS)
} }
func positionObjects(objects []*d2graph.Object, radius float64) { func positionObjects(objects []*d2graph.Object, radius float64) {
numObjects := float64(len(objects)) numObjects := float64(len(objects))
angleOffset := -math.Pi / 2 angleOffset := -math.Pi / 2
for i, obj := range objects { for i, obj := range objects {
angle := angleOffset + (2*math.Pi*float64(i)/numObjects) angle := angleOffset + (2*math.Pi*float64(i)/numObjects)
x := radius * math.Cos(angle) x := radius * math.Cos(angle)
y := radius * math.Sin(angle) y := radius * math.Sin(angle)
obj.TopLeft = geo.NewPoint( obj.TopLeft = geo.NewPoint(
x-obj.Box.Width/2, x-obj.Box.Width/2,
y-obj.Box.Height/2, y-obj.Box.Height/2,
) )
} }
} }
// createPreciseCircularArc computes a curved edge path that touches the node boundaries exactly.
func createPreciseCircularArc(edge *d2graph.Edge) { func createPreciseCircularArc(edge *d2graph.Edge) {
if edge.Src == nil || edge.Dst == nil { if edge.Src == nil || edge.Dst == nil {
return return
} }
srcCenter := edge.Src.Center() srcCenter := edge.Src.Center()
dstCenter := edge.Dst.Center() dstCenter := edge.Dst.Center()
// Calculate angles in the circular layout // Compute angles for the circular arc.
srcAngle := math.Atan2(srcCenter.Y, srcCenter.X) srcAngle := math.Atan2(srcCenter.Y, srcCenter.X)
dstAngle := math.Atan2(dstCenter.Y, dstCenter.X) dstAngle := math.Atan2(dstCenter.Y, dstCenter.X)
if dstAngle < srcAngle { if dstAngle < srcAngle {
dstAngle += 2 * math.Pi dstAngle += 2 * math.Pi
} }
arcRadius := math.Hypot(srcCenter.X, srcCenter.Y) arcRadius := math.Hypot(srcCenter.X, srcCenter.Y)
// Generate initial path points // Generate the initial arc path.
path := make([]*geo.Point, 0, ARC_STEPS+1) path := make([]*geo.Point, 0, ARC_STEPS+1)
for i := 0; i <= ARC_STEPS; i++ { for i := 0; i <= ARC_STEPS; i++ {
t := float64(i) / float64(ARC_STEPS) t := float64(i) / float64(ARC_STEPS)
angle := srcAngle + t*(dstAngle-srcAngle) angle := srcAngle + t*(dstAngle-srcAngle)
x := arcRadius * math.Cos(angle) x := arcRadius * math.Cos(angle)
y := arcRadius * math.Sin(angle) y := arcRadius * math.Sin(angle)
path = append(path, geo.NewPoint(x, y)) path = append(path, geo.NewPoint(x, y))
} }
// Find precise intersection points // Compute precise intersection points so the arrow touches the node boundaries.
srcIntersection := findPreciseBoxIntersection(edge.Src.Box, path[0], path[1]) // For the source, the segment goes from the center (inside) to the next point (outside).
dstIntersection := findPreciseBoxIntersection(edge.Dst.Box, path[len(path)-1], path[len(path)-2]) srcIntersection := findPreciseBoxIntersection(edge.Src.Box, path[0], path[1])
// For the destination, the segment goes from the center to the previous point (outside).
dstIntersection := findPreciseBoxIntersection(edge.Dst.Box, path[len(path)-1], path[len(path)-2])
// Update path endpoints with precise intersections // Update the endpoints with the snapped intersection points.
path[0] = srcIntersection path[0] = srcIntersection
path[len(path)-1] = dstIntersection path[len(path)-1] = dstIntersection
// Remove any points that might be inside the boxes // Trim intermediate points that still fall inside the boxes.
startIdx := 0 startIdx := 0
endIdx := len(path) - 1 endIdx := len(path) - 1
for i := 1; i < len(path); i++ {
if !boxContains(edge.Src.Box, path[i]) {
startIdx = i - 1
break
}
}
for i := len(path) - 2; i >= 0; i-- {
if !boxContains(edge.Dst.Box, path[i]) {
endIdx = i + 1
break
}
}
for i := 1; i < len(path)-1; i++ { edge.Route = path[startIdx : endIdx+1]
if boxContains(edge.Src.Box, path[i]) { edge.IsCurve = true
startIdx = i
}
if boxContains(edge.Dst.Box, path[i]) {
endIdx = i
break
}
}
edge.Route = path[startIdx:endIdx+1]
edge.IsCurve = true
} }
// findPreciseBoxIntersection returns the intersection point of the line (from p1 to p2) with the box boundary,
// snapped exactly to the nearest edge.
func findPreciseBoxIntersection(box *geo.Box, p1, p2 *geo.Point) *geo.Point { func findPreciseBoxIntersection(box *geo.Box, p1, p2 *geo.Point) *geo.Point {
// Define box edges as line segments // Define the four box edges.
edges := []geo.Segment{ edges := []geo.Segment{
// Top edge *geo.NewSegment(
*geo.NewSegment( geo.NewPoint(box.TopLeft.X, box.TopLeft.Y),
geo.NewPoint(box.TopLeft.X, box.TopLeft.Y), geo.NewPoint(box.TopLeft.X+box.Width, box.TopLeft.Y),
geo.NewPoint(box.TopLeft.X+box.Width, box.TopLeft.Y), ), // Top
), *geo.NewSegment(
// Right edge geo.NewPoint(box.TopLeft.X+box.Width, box.TopLeft.Y),
*geo.NewSegment( geo.NewPoint(box.TopLeft.X+box.Width, box.TopLeft.Y+box.Height),
geo.NewPoint(box.TopLeft.X+box.Width, box.TopLeft.Y), ), // Right
geo.NewPoint(box.TopLeft.X+box.Width, box.TopLeft.Y+box.Height), *geo.NewSegment(
), geo.NewPoint(box.TopLeft.X, box.TopLeft.Y+box.Height),
// Bottom edge geo.NewPoint(box.TopLeft.X+box.Width, box.TopLeft.Y+box.Height),
*geo.NewSegment( ), // Bottom
geo.NewPoint(box.TopLeft.X, box.TopLeft.Y+box.Height), *geo.NewSegment(
geo.NewPoint(box.TopLeft.X+box.Width, box.TopLeft.Y+box.Height), geo.NewPoint(box.TopLeft.X, box.TopLeft.Y),
), geo.NewPoint(box.TopLeft.X, box.TopLeft.Y+box.Height),
// Left edge ), // Left
*geo.NewSegment( }
geo.NewPoint(box.TopLeft.X, box.TopLeft.Y),
geo.NewPoint(box.TopLeft.X, box.TopLeft.Y+box.Height),
),
}
// Line segment from p1 to p2 // Construct the line from p1 (inside) to p2 (outside).
line := *geo.NewSegment(p1, p2) line := *geo.NewSegment(p1, p2)
var closestIntersection *geo.Point
minDist := math.MaxFloat64
// Find the intersection point closest to p1 // Find the intersection among the four edges that is closest to p1.
var closestIntersection *geo.Point for _, seg := range edges {
minDist := math.MaxFloat64 if intersection := findSegmentIntersection(line, seg); intersection != nil {
dist := math.Hypot(intersection.X-p1.X, intersection.Y-p1.Y)
if dist < minDist {
minDist = dist
closestIntersection = intersection
}
}
}
for _, edge := range edges { if closestIntersection != nil {
if intersection := findSegmentIntersection(line, edge); intersection != nil { return snapToBoundary(box, closestIntersection)
dist := math.Hypot( }
intersection.X-p1.X, return p1
intersection.Y-p1.Y,
)
if dist < minDist {
minDist = dist
closestIntersection = intersection
}
}
}
if closestIntersection != nil {
return closestIntersection
}
return p1
} }
// findSegmentIntersection computes the intersection between two line segments s1 and s2 using their parametric form.
func findSegmentIntersection(s1, s2 geo.Segment) *geo.Point { func findSegmentIntersection(s1, s2 geo.Segment) *geo.Point {
// Calculate the intersection of two line segments using parametric equations x1, y1 := s1.Start.X, s1.Start.Y
x1, y1 := s1.Start.X, s1.Start.Y x2, y2 := s1.End.X, s1.End.Y
x2, y2 := s1.End.X, s1.End.Y x3, y3 := s2.Start.X, s2.Start.Y
x3, y3 := s2.Start.X, s2.Start.Y x4, y4 := s2.End.X, s2.End.Y
x4, y4 := s2.End.X, s2.End.Y
denominator := (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4) denom := (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)
if math.Abs(denominator) < EPSILON { if math.Abs(denom) < EPSILON {
return nil return nil
} }
t := ((x1-x3)*(y3-y4) - (y1-y3)*(x3-x4)) / denominator t := ((x1-x3)*(y3-y4) - (y1-y3)*(x3-x4)) / denom
u := -((x1-x2)*(y1-y3) - (y1-y2)*(x1-x3)) / denominator u := -((x1-x2)*(y1-y3) - (y1-y2)*(x1-x3)) / denom
if t >= 0 && t <= 1 && u >= 0 && u <= 1 { if t >= 0 && t <= 1 && u >= 0 && u <= 1 {
x := x1 + t*(x2-x1) x := x1 + t*(x2-x1)
y := y1 + t*(y2-y1) y := y1 + t*(y2-y1)
return geo.NewPoint(x, y) return geo.NewPoint(x, y)
} }
return nil
return nil
} }
// snapToBoundary adjusts point p so that it lies exactly on the nearest boundary of box.
func snapToBoundary(box *geo.Box, p *geo.Point) *geo.Point {
left := box.TopLeft.X
right := box.TopLeft.X + box.Width
top := box.TopLeft.Y
bottom := box.TopLeft.Y + box.Height
dLeft := math.Abs(p.X - left)
dRight := math.Abs(p.X - right)
dTop := math.Abs(p.Y - top)
dBottom := math.Abs(p.Y - bottom)
if dLeft < dRight && dLeft < dTop && dLeft < dBottom {
return geo.NewPoint(left, p.Y)
} else if dRight < dLeft && dRight < dTop && dRight < dBottom {
return geo.NewPoint(right, p.Y)
} else if dTop < dBottom {
return geo.NewPoint(p.X, top)
} else {
return geo.NewPoint(p.X, bottom)
}
}
// boxContains returns true if point p is inside the box (using EPSILON for floating point tolerance).
func boxContains(b *geo.Box, p *geo.Point) bool { func boxContains(b *geo.Box, p *geo.Point) bool {
return p.X >= b.TopLeft.X-EPSILON && return p.X >= b.TopLeft.X-EPSILON &&
p.X <= b.TopLeft.X+b.Width+EPSILON && p.X <= b.TopLeft.X+b.Width+EPSILON &&
p.Y >= b.TopLeft.Y-EPSILON && p.Y >= b.TopLeft.Y-EPSILON &&
p.Y <= b.TopLeft.Y+b.Height+EPSILON p.Y <= b.TopLeft.Y+b.Height+EPSILON
} }
func positionLabelsIcons(obj *d2graph.Object) { func positionLabelsIcons(obj *d2graph.Object) {
if obj.Icon != nil && obj.IconPosition == nil { if obj.Icon != nil && obj.IconPosition == nil {
if len(obj.ChildrenArray) > 0 { if len(obj.ChildrenArray) > 0 {
obj.IconPosition = go2.Pointer(label.OutsideTopLeft.String()) obj.IconPosition = go2.Pointer(label.OutsideTopLeft.String())
if obj.LabelPosition == nil { if obj.LabelPosition == nil {
obj.LabelPosition = go2.Pointer(label.OutsideTopRight.String()) obj.LabelPosition = go2.Pointer(label.OutsideTopRight.String())
return return
} }
} else if obj.SQLTable != nil || obj.Class != nil || obj.Language != "" { } else if obj.SQLTable != nil || obj.Class != nil || obj.Language != "" {
obj.IconPosition = go2.Pointer(label.OutsideTopLeft.String()) obj.IconPosition = go2.Pointer(label.OutsideTopLeft.String())
} else { } else {
obj.IconPosition = go2.Pointer(label.InsideMiddleCenter.String()) obj.IconPosition = go2.Pointer(label.InsideMiddleCenter.String())
} }
} }
if obj.HasLabel() && obj.LabelPosition == nil { if obj.HasLabel() && obj.LabelPosition == nil {
if len(obj.ChildrenArray) > 0 { if len(obj.ChildrenArray) > 0 {
obj.LabelPosition = go2.Pointer(label.OutsideTopCenter.String()) obj.LabelPosition = go2.Pointer(label.OutsideTopCenter.String())
} else if obj.HasOutsideBottomLabel() { } else if obj.HasOutsideBottomLabel() {
obj.LabelPosition = go2.Pointer(label.OutsideBottomCenter.String()) obj.LabelPosition = go2.Pointer(label.OutsideBottomCenter.String())
} else if obj.Icon != nil { } else if obj.Icon != nil {
obj.LabelPosition = go2.Pointer(label.InsideTopCenter.String()) obj.LabelPosition = go2.Pointer(label.InsideTopCenter.String())
} else { } else {
obj.LabelPosition = go2.Pointer(label.InsideMiddleCenter.String()) obj.LabelPosition = go2.Pointer(label.InsideMiddleCenter.String())
} }
if float64(obj.LabelDimensions.Width) > obj.Width || if float64(obj.LabelDimensions.Width) > obj.Width ||
float64(obj.LabelDimensions.Height) > obj.Height { float64(obj.LabelDimensions.Height) > obj.Height {
if len(obj.ChildrenArray) > 0 { if len(obj.ChildrenArray) > 0 {
obj.LabelPosition = go2.Pointer(label.OutsideTopCenter.String()) obj.LabelPosition = go2.Pointer(label.OutsideTopCenter.String())
} else { } else {
obj.LabelPosition = go2.Pointer(label.OutsideBottomCenter.String()) obj.LabelPosition = go2.Pointer(label.OutsideBottomCenter.String())
} }
} }
} }
} }