diff options
author | cel 🌸 <cel@blos.sm> | 2023-07-09 14:02:37 +0100 |
---|---|---|
committer | cel 🌸 <cel@blos.sm> | 2023-07-09 14:02:37 +0100 |
commit | ae7b7226c64e7b9ce62e045991c315040563fe5a (patch) | |
tree | abca4450641dee1a63150d45eeaf4fb3b6fb7676 /Scripts/Road.gd | |
parent | f1677fac1f7c7989a28d078498357c88f9f631f3 (diff) | |
download | 2023-ae7b7226c64e7b9ce62e045991c315040563fe5a.tar.gz 2023-ae7b7226c64e7b9ce62e045991c315040563fe5a.tar.bz2 2023-ae7b7226c64e7b9ce62e045991c315040563fe5a.zip |
road simplification via Ramer–Douglas–Peucker
Diffstat (limited to 'Scripts/Road.gd')
-rw-r--r-- | Scripts/Road.gd | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/Scripts/Road.gd b/Scripts/Road.gd new file mode 100644 index 0000000..e0b69a1 --- /dev/null +++ b/Scripts/Road.gd @@ -0,0 +1,48 @@ +extends Line2D + +var epsilon = 20 + +# Called when the node enters the scene tree for the first time. +func _ready(): + pass # Replace with function body. + + +# Called every frame. 'delta' is the elapsed time since the previous frame. +func _process(delta): + pass + +func simplify(): + points = simplify_rec(points, 5) + +func simplify_rec(pointArray: PackedVector2Array, epsilon: float): + var dmax = 0 + var index = -1 + if pointArray.size() < 3: + return pointArray + var end = pointArray.size() - 1 + for i in range(1, end-1): + var d = find_perpendicular_distance(pointArray[i], pointArray[0], pointArray[end]) + if d > dmax: + index = i + dmax = d + + if dmax > epsilon: + var recResults1 = simplify_rec(pointArray.slice(0, index), epsilon) + var recResults2 = simplify_rec(pointArray.slice(index, end), epsilon) + recResults1.append_array(recResults2) + return recResults1 + else: + return [pointArray[0], pointArray[end]] + +func find_perpendicular_distance(p: Vector2, p1: Vector2, p2: Vector2): + var result + var slope + var intercept + if p1.x == p2.x: + result = p.x - p1.x + else: + slope = (p2.y - p1.y) / (p2.x - p1.x) + intercept = p1.y - (slope * p1.x) + result = abs(slope * p.x - p.y + intercept) / sqrt(pow(slope, 2) + 1) + + return result |