添加RTT算法

This commit is contained in:
张梦南 2025-06-02 19:49:45 +08:00
parent 5d2b4d951a
commit 66cb6a9fe3

144
RTT/RTT.m Normal file
View File

@ -0,0 +1,144 @@
function path = rtt(map, start, goal)
maxIterations = 5000;
stepSize = 5;
goalThreshold = 5; %
mapSize = size(map);
%
tree.nodes = start;
tree.parents = 0;
for i = 1:maxIterations
%
randPoint = sampler(mapSize, goal);
%
[nearestIdx, nearestPoint] = find_nearest(tree.nodes, randPoint);
%
newPoint = local_planner(map, nearestPoint, randPoint, stepSize);
%
if isempty(newPoint)
continue;
end
%
tree.nodes = [tree.nodes; newPoint];
tree.parents = [tree.parents; nearestIdx];
%
if norm(newPoint - goal) < goalThreshold
tree.nodes = [tree.nodes; goal];
tree.parents = [tree.parents; size(tree.nodes, 1) - 1];
path = make_path(tree);
return;
end
end
%
path = [];
end
function point = sampler(mapSize, goal)
% 10%90%
if rand() < 0.1
point = goal;
else
point = round([rand()*mapSize(1), rand()*mapSize(2)]);
%
point(1) = max(min(point(1), mapSize(1)), 1);
point(2) = max(min(point(2), mapSize(2)), 1);
end
end
function [idx, nearest] = find_nearest(nodes, point)
% point
dists = vecnorm(nodes - point, 2, 2);
[~, idx] = min(dists);
nearest = nodes(idx, :);
end
function newPoint = local_planner(map, nearestPoint, randPoint, stepSize)
% 沿
direction = randPoint - nearestPoint;
if norm(direction) == 0
newPoint = [];
return;
end
direction = direction / norm(direction);
newPoint = round(nearestPoint + direction * stepSize);
%
if newPoint(1) < 1 || newPoint(2) < 1 || ...
newPoint(1) > size(map, 1) || newPoint(2) > size(map, 2)
newPoint = [];
return;
end
% (线)
if isCollision(map, nearestPoint, newPoint)
newPoint = [];
return;
end
end
function collision = isCollision(map, p1, p2)
% 使Bresenham
linePts = bresenham(p1, p2);
collision = false;
for i = 1:size(linePts,1)
pt = linePts(i,:);
if map(pt(1), pt(2)) == 1
collision = true;
return;
end
end
end
function pts = bresenham(p1, p2)
% Bresenham线
x1 = p1(1); y1 = p1(2);
x2 = p2(1); y2 = p2(2);
dx = abs(x2 - x1); dy = abs(y2 - y1);
sx = sign(x2 - x1); sy = sign(y2 - y1);
err = dx - dy;
pts = [];
while true
pts = [pts; x1, y1];
if x1 == x2 && y1 == y2
break;
end
e2 = 2*err;
if e2 > -dy
err = err - dy;
x1 = x1 + sx;
end
if e2 < dx
err = err + dx;
y1 = y1 + sy;
end
end
end
function path = make_path(tree)
%
path = tree.nodes(end, :);
idx = size(tree.nodes, 1);
while tree.parents(idx) ~= 0
idx = tree.parents(idx);
path = [tree.nodes(idx, :); path];
end
%
if ~isempty(path)
disp('');
for i = 1:size(path, 1)
fprintf('(%d, %d)\n', path(i, 2), path(i, 1));
end
else
disp('');
end
end