123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971 |
- using UnityEngine;
- using System.Collections.Generic;
- namespace Pathfinding.RVO.Sampled {
- using Pathfinding;
- using Pathfinding.RVO;
- using Pathfinding.Util;
-
-
-
-
-
-
- public class Agent : IAgent {
-
- internal float radius, height, desiredSpeed, maxSpeed, agentTimeHorizon, obstacleTimeHorizon;
- internal bool locked = false;
- RVOLayer layer, collidesWith;
- int maxNeighbours;
- internal Vector2 position;
- float elevationCoordinate;
- Vector2 currentVelocity;
-
- Vector2 desiredTargetPointInVelocitySpace;
- Vector2 desiredVelocity;
- Vector2 nextTargetPoint;
- float nextDesiredSpeed;
- float nextMaxSpeed;
- Vector2 collisionNormal;
- bool manuallyControlled;
- bool debugDraw;
- #region IAgent Properties
-
- public Vector2 Position { get; set; }
-
- public float ElevationCoordinate { get; set; }
-
- public Vector2 CalculatedTargetPoint { get; private set; }
-
- public float CalculatedSpeed { get; private set; }
-
- public bool Locked { get; set; }
-
- public float Radius { get; set; }
-
- public float Height { get; set; }
-
- public float AgentTimeHorizon { get; set; }
-
- public float ObstacleTimeHorizon { get; set; }
-
- public int MaxNeighbours { get; set; }
-
- public int NeighbourCount { get; private set; }
-
- public RVOLayer Layer { get; set; }
-
- public RVOLayer CollidesWith { get; set; }
-
- public bool DebugDraw {
- get {
- return debugDraw;
- }
- set {
- debugDraw = value && simulator != null && !simulator.Multithreading;
- }
- }
-
- public float Priority { get; set; }
-
- public System.Action PreCalculationCallback { private get; set; }
- #endregion
- #region IAgent Methods
-
- public void SetTarget (Vector2 targetPoint, float desiredSpeed, float maxSpeed) {
- maxSpeed = System.Math.Max(maxSpeed, 0);
- desiredSpeed = System.Math.Min(System.Math.Max(desiredSpeed, 0), maxSpeed);
- nextTargetPoint = targetPoint;
- nextDesiredSpeed = desiredSpeed;
- nextMaxSpeed = maxSpeed;
- }
-
- public void SetCollisionNormal (Vector2 normal) {
- collisionNormal = normal;
- }
-
- public void ForceSetVelocity (Vector2 velocity) {
-
-
- nextTargetPoint = CalculatedTargetPoint = position + velocity * 1000;
- nextDesiredSpeed = CalculatedSpeed = velocity.magnitude;
- manuallyControlled = true;
- }
- #endregion
-
- internal Agent next;
- float calculatedSpeed;
- Vector2 calculatedTargetPoint;
-
-
-
-
-
- internal Simulator simulator;
- List<Agent> neighbours = new List<Agent>();
- List<float> neighbourDists = new List<float>();
- List<ObstacleVertex> obstaclesBuffered = new List<ObstacleVertex>();
- List<ObstacleVertex> obstacles = new List<ObstacleVertex>();
- const float DesiredVelocityWeight = 0.1f;
-
- const float WallWeight = 5;
- public List<ObstacleVertex> NeighbourObstacles {
- get {
- return null;
- }
- }
- public Agent (Vector2 pos, float elevationCoordinate) {
- AgentTimeHorizon = 2;
- ObstacleTimeHorizon = 2;
- Height = 5;
- Radius = 5;
- MaxNeighbours = 10;
- Locked = false;
- Position = pos;
- ElevationCoordinate = elevationCoordinate;
- Layer = RVOLayer.DefaultAgent;
- CollidesWith = (RVOLayer)(-1);
- Priority = 0.5f;
- CalculatedTargetPoint = pos;
- CalculatedSpeed = 0;
- SetTarget(pos, 0, 0);
- }
-
-
-
-
-
-
-
-
-
- public void BufferSwitch () {
-
- radius = Radius;
- height = Height;
- maxSpeed = nextMaxSpeed;
- desiredSpeed = nextDesiredSpeed;
- agentTimeHorizon = AgentTimeHorizon;
- obstacleTimeHorizon = ObstacleTimeHorizon;
- maxNeighbours = MaxNeighbours;
-
-
- locked = Locked && !manuallyControlled;
- position = Position;
- elevationCoordinate = ElevationCoordinate;
- collidesWith = CollidesWith;
- layer = Layer;
- if (locked) {
-
- desiredTargetPointInVelocitySpace = position;
- desiredVelocity = currentVelocity = Vector2.zero;
- } else {
- desiredTargetPointInVelocitySpace = nextTargetPoint - position;
-
-
-
- currentVelocity = (CalculatedTargetPoint - position).normalized * CalculatedSpeed;
-
- desiredVelocity = desiredTargetPointInVelocitySpace.normalized*desiredSpeed;
- if (collisionNormal != Vector2.zero) {
- collisionNormal.Normalize();
- var dot = Vector2.Dot(currentVelocity, collisionNormal);
-
- if (dot < 0) {
-
- currentVelocity -= collisionNormal * dot;
- }
-
- collisionNormal = Vector2.zero;
- }
- }
- }
- public void PreCalculation () {
- if (PreCalculationCallback != null) {
- PreCalculationCallback();
- }
- }
- public void PostCalculation () {
-
- if (!manuallyControlled) {
- CalculatedTargetPoint = calculatedTargetPoint;
- CalculatedSpeed = calculatedSpeed;
- }
- List<ObstacleVertex> tmp = obstaclesBuffered;
- obstaclesBuffered = obstacles;
- obstacles = tmp;
- manuallyControlled = false;
- }
-
- public void CalculateNeighbours () {
- neighbours.Clear();
- neighbourDists.Clear();
- if (MaxNeighbours > 0 && !locked) simulator.Quadtree.Query(position, maxSpeed, agentTimeHorizon, radius, this);
- NeighbourCount = neighbours.Count;
- }
-
- static float Sqr (float x) {
- return x*x;
- }
-
-
-
-
- internal float InsertAgentNeighbour (Agent agent, float rangeSq) {
-
- if (this == agent || (agent.layer & collidesWith) == 0) return rangeSq;
-
- float dist = (agent.position - position).sqrMagnitude;
- if (dist < rangeSq) {
- if (neighbours.Count < maxNeighbours) {
- neighbours.Add(null);
- neighbourDists.Add(float.PositiveInfinity);
- }
-
- int i = neighbours.Count-1;
- if (dist < neighbourDists[i]) {
- while (i != 0 && dist < neighbourDists[i-1]) {
- neighbours[i] = neighbours[i-1];
- neighbourDists[i] = neighbourDists[i-1];
- i--;
- }
- neighbours[i] = agent;
- neighbourDists[i] = dist;
- }
- if (neighbours.Count == maxNeighbours) {
- rangeSq = neighbourDists[neighbourDists.Count-1];
- }
- }
- return rangeSq;
- }
-
- static Vector3 FromXZ (Vector2 p) {
- return new Vector3(p.x, 0, p.y);
- }
-
- static Vector2 ToXZ (Vector3 p) {
- return new Vector2(p.x, p.z);
- }
-
-
-
-
-
-
-
- Vector2 To2D (Vector3 p, out float elevation) {
- if (simulator.movementPlane == MovementPlane.XY) {
- elevation = -p.z;
- return new Vector2(p.x, p.y);
- } else {
- elevation = p.y;
- return new Vector2(p.x, p.z);
- }
- }
- static void DrawVO (Vector2 circleCenter, float radius, Vector2 origin) {
- float alpha = Mathf.Atan2((origin - circleCenter).y, (origin - circleCenter).x);
- float gamma = radius/(origin-circleCenter).magnitude;
- float delta = gamma <= 1.0f ? Mathf.Abs(Mathf.Acos(gamma)) : 0;
- Draw.Debug.CircleXZ(FromXZ(circleCenter), radius, Color.black, alpha-delta, alpha+delta);
- Vector2 p1 = new Vector2(Mathf.Cos(alpha-delta), Mathf.Sin(alpha-delta)) * radius;
- Vector2 p2 = new Vector2(Mathf.Cos(alpha+delta), Mathf.Sin(alpha+delta)) * radius;
- Vector2 p1t = -new Vector2(-p1.y, p1.x);
- Vector2 p2t = new Vector2(-p2.y, p2.x);
- p1 += circleCenter;
- p2 += circleCenter;
- Debug.DrawRay(FromXZ(p1), FromXZ(p1t).normalized*100, Color.black);
- Debug.DrawRay(FromXZ(p2), FromXZ(p2t).normalized*100, Color.black);
- }
-
-
-
-
-
-
- internal struct VO {
- Vector2 line1, line2, dir1, dir2;
- Vector2 cutoffLine, cutoffDir;
- Vector2 circleCenter;
- bool colliding;
- float radius;
- float weightFactor;
- float weightBonus;
- Vector2 segmentStart, segmentEnd;
- bool segment;
-
-
-
-
-
-
- public VO (Vector2 center, Vector2 offset, float radius, float inverseDt, float inverseDeltaTime) {
-
- this.weightFactor = 1;
- weightBonus = 0;
-
- Vector2 globalCenter;
- circleCenter = center*inverseDt + offset;
- this.weightFactor = 4*Mathf.Exp(-Sqr(center.sqrMagnitude/(radius*radius))) + 1;
-
- if (center.magnitude < radius) {
- colliding = true;
-
-
- line1 = center.normalized * (center.magnitude - radius - 0.001f) * 0.3f * inverseDeltaTime;
- dir1 = new Vector2(line1.y, -line1.x).normalized;
- line1 += offset;
- cutoffDir = Vector2.zero;
- cutoffLine = Vector2.zero;
- dir2 = Vector2.zero;
- line2 = Vector2.zero;
- this.radius = 0;
- } else {
- colliding = false;
- center *= inverseDt;
- radius *= inverseDt;
- globalCenter = center+offset;
-
-
- var cutoffDistance = center.magnitude - radius + 0.001f;
- cutoffLine = center.normalized * cutoffDistance;
- cutoffDir = new Vector2(-cutoffLine.y, cutoffLine.x).normalized;
- cutoffLine += offset;
- float alpha = Mathf.Atan2(-center.y, -center.x);
- float delta = Mathf.Abs(Mathf.Acos(radius/center.magnitude));
- this.radius = radius;
-
-
- line1 = new Vector2(Mathf.Cos(alpha+delta), Mathf.Sin(alpha+delta));
-
-
- dir1 = new Vector2(line1.y, -line1.x);
-
- line2 = new Vector2(Mathf.Cos(alpha-delta), Mathf.Sin(alpha-delta));
-
-
- dir2 = new Vector2(line2.y, -line2.x);
- line1 = line1 * radius + globalCenter;
- line2 = line2 * radius + globalCenter;
- }
- segmentStart = Vector2.zero;
- segmentEnd = Vector2.zero;
- segment = false;
- }
-
-
-
-
- public static VO SegmentObstacle (Vector2 segmentStart, Vector2 segmentEnd, Vector2 offset, float radius, float inverseDt, float inverseDeltaTime) {
- var vo = new VO();
-
- vo.weightFactor = 1;
-
- vo.weightBonus = Mathf.Max(radius, 1)*40;
- var closestOnSegment = VectorMath.ClosestPointOnSegment(segmentStart, segmentEnd, Vector2.zero);
-
- if (closestOnSegment.magnitude <= radius) {
- vo.colliding = true;
- vo.line1 = closestOnSegment.normalized * (closestOnSegment.magnitude - radius) * 0.3f * inverseDeltaTime;
- vo.dir1 = new Vector2(vo.line1.y, -vo.line1.x).normalized;
- vo.line1 += offset;
- vo.cutoffDir = Vector2.zero;
- vo.cutoffLine = Vector2.zero;
- vo.dir2 = Vector2.zero;
- vo.line2 = Vector2.zero;
- vo.radius = 0;
- vo.segmentStart = Vector2.zero;
- vo.segmentEnd = Vector2.zero;
- vo.segment = false;
- } else {
- vo.colliding = false;
- segmentStart *= inverseDt;
- segmentEnd *= inverseDt;
- radius *= inverseDt;
- var cutoffTangent = (segmentEnd - segmentStart).normalized;
- vo.cutoffDir = cutoffTangent;
- vo.cutoffLine = segmentStart + new Vector2(-cutoffTangent.y, cutoffTangent.x) * radius;
- vo.cutoffLine += offset;
-
-
- var startSqrMagnitude = segmentStart.sqrMagnitude;
- var normal1 = -VectorMath.ComplexMultiply(segmentStart, new Vector2(radius, Mathf.Sqrt(Mathf.Max(0, startSqrMagnitude - radius*radius)))) / startSqrMagnitude;
- var endSqrMagnitude = segmentEnd.sqrMagnitude;
- var normal2 = -VectorMath.ComplexMultiply(segmentEnd, new Vector2(radius, -Mathf.Sqrt(Mathf.Max(0, endSqrMagnitude - radius*radius)))) / endSqrMagnitude;
- vo.line1 = segmentStart + normal1 * radius + offset;
- vo.line2 = segmentEnd + normal2 * radius + offset;
-
- vo.dir1 = new Vector2(normal1.y, -normal1.x);
- vo.dir2 = new Vector2(normal2.y, -normal2.x);
- vo.segmentStart = segmentStart;
- vo.segmentEnd = segmentEnd;
- vo.radius = radius;
- vo.segment = true;
- }
- return vo;
- }
-
-
-
-
-
- public static float SignedDistanceFromLine (Vector2 a, Vector2 dir, Vector2 p) {
- return (p.x - a.x) * (dir.y) - (dir.x) * (p.y - a.y);
- }
-
-
-
-
-
- public Vector2 ScaledGradient (Vector2 p, out float weight) {
- var grad = Gradient(p, out weight);
- if (weight > 0) {
- const float Scale = 2;
- grad *= Scale * weightFactor;
- weight *= Scale * weightFactor;
- weight += 1 + weightBonus;
- }
- return grad;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public Vector2 Gradient (Vector2 p, out float weight) {
- if (colliding) {
-
-
- float l1 = SignedDistanceFromLine(line1, dir1, p);
-
- if (l1 >= 0) {
- weight = l1;
- return new Vector2(-dir1.y, dir1.x);
- } else {
- weight = 0;
- return new Vector2(0, 0);
- }
- }
- float det3 = SignedDistanceFromLine(cutoffLine, cutoffDir, p);
- if (det3 <= 0) {
- weight = 0;
- return Vector2.zero;
- } else {
-
- float det1 = SignedDistanceFromLine(line1, dir1, p);
- float det2 = SignedDistanceFromLine(line2, dir2, p);
- if (det1 >= 0 && det2 >= 0) {
-
-
-
-
-
- Vector2 gradient;
-
- if (Vector2.Dot(p - line1, dir1) > 0 && Vector2.Dot(p - line2, dir2) < 0) {
- if (segment) {
-
- if (det3 < radius) {
- var closestPointOnLine = (Vector2)VectorMath.ClosestPointOnSegment(segmentStart, segmentEnd, p);
- var dirFromCenter = p - closestPointOnLine;
- float distToCenter;
- gradient = VectorMath.Normalize(dirFromCenter, out distToCenter);
-
- weight = radius - distToCenter;
- return gradient;
- }
- } else {
- var dirFromCenter = p - circleCenter;
- float distToCenter;
- gradient = VectorMath.Normalize(dirFromCenter, out distToCenter);
-
- weight = radius - distToCenter;
- return gradient;
- }
- }
- if (segment && det3 < det1 && det3 < det2) {
- weight = det3;
- gradient = new Vector2(-cutoffDir.y, cutoffDir.x);
- return gradient;
- }
-
-
- if (det1 < det2) {
- weight = det1;
- gradient = new Vector2(-dir1.y, dir1.x);
- } else {
- weight = det2;
- gradient = new Vector2(-dir2.y, dir2.x);
- }
- return gradient;
- }
- weight = 0;
- return Vector2.zero;
- }
- }
- }
-
-
-
-
-
-
- internal class VOBuffer {
- public VO[] buffer;
- public int length;
- public void Clear () {
- length = 0;
- }
- public VOBuffer (int n) {
- buffer = new VO[n];
- length = 0;
- }
- public void Add (VO vo) {
- if (length >= buffer.Length) {
- var nbuffer = new VO[buffer.Length * 2];
- buffer.CopyTo(nbuffer, 0);
- buffer = nbuffer;
- }
- buffer[length++] = vo;
- }
- }
- internal void CalculateVelocity (Pathfinding.RVO.Simulator.WorkerContext context) {
- if (manuallyControlled) {
- return;
- }
- if (locked) {
- calculatedSpeed = 0;
- calculatedTargetPoint = position;
- return;
- }
-
- var vos = context.vos;
- vos.Clear();
- GenerateObstacleVOs(vos);
- GenerateNeighbourAgentVOs(vos);
- bool insideAnyVO = BiasDesiredVelocity(vos, ref desiredVelocity, ref desiredTargetPointInVelocitySpace, simulator.symmetryBreakingBias);
- if (!insideAnyVO) {
-
-
-
-
-
-
-
-
-
- calculatedTargetPoint = desiredTargetPointInVelocitySpace + position;
- calculatedSpeed = desiredSpeed;
- if (DebugDraw) Draw.Debug.CrossXZ(FromXZ(calculatedTargetPoint), Color.white);
- return;
- }
- Vector2 result = Vector2.zero;
- result = GradientDescent(vos, currentVelocity, desiredVelocity);
- if (DebugDraw) Draw.Debug.CrossXZ(FromXZ(result+position), Color.white);
-
- calculatedTargetPoint = position + result;
- calculatedSpeed = Mathf.Min(result.magnitude, maxSpeed);
- }
- static Color Rainbow (float v) {
- Color c = new Color(v, 0, 0);
- if (c.r > 1) { c.g = c.r - 1; c.r = 1; }
- if (c.g > 1) { c.b = c.g - 1; c.g = 1; }
- return c;
- }
- void GenerateObstacleVOs (VOBuffer vos) {
- var range = maxSpeed * obstacleTimeHorizon;
-
- for (int i = 0; i < simulator.obstacles.Count; i++) {
- var obstacle = simulator.obstacles[i];
- var vertex = obstacle;
-
- do {
-
- if (vertex.ignore || (vertex.layer & collidesWith) == 0) {
- vertex = vertex.next;
- continue;
- }
-
- float elevation1, elevation2;
- var p1 = To2D(vertex.position, out elevation1);
- var p2 = To2D(vertex.next.position, out elevation2);
- Vector2 dir = (p2 - p1).normalized;
-
-
- float dist = VO.SignedDistanceFromLine(p1, dir, position);
- if (dist >= -0.01f && dist < range) {
- float factorAlongSegment = Vector2.Dot(position - p1, p2 - p1) / (p2 - p1).sqrMagnitude;
-
- var segmentY = Mathf.Lerp(elevation1, elevation2, factorAlongSegment);
-
- var sqrDistToSegment = (Vector2.Lerp(p1, p2, factorAlongSegment) - position).sqrMagnitude;
-
-
-
- if (sqrDistToSegment < range*range && (simulator.movementPlane == MovementPlane.XY || (elevationCoordinate <= segmentY + vertex.height && elevationCoordinate+height >= segmentY))) {
- vos.Add(VO.SegmentObstacle(p2 - position, p1 - position, Vector2.zero, radius * 0.01f, 1f / ObstacleTimeHorizon, 1f / simulator.DeltaTime));
- }
- }
- vertex = vertex.next;
- } while (vertex != obstacle && vertex != null && vertex.next != null);
- }
- }
- void GenerateNeighbourAgentVOs (VOBuffer vos) {
- float inverseAgentTimeHorizon = 1.0f/agentTimeHorizon;
-
-
- Vector2 optimalVelocity = currentVelocity;
- for (int o = 0; o < neighbours.Count; o++) {
- Agent other = neighbours[o];
-
- if (other == this)
- continue;
-
- float maxY = System.Math.Min(elevationCoordinate + height, other.elevationCoordinate + other.height);
- float minY = System.Math.Max(elevationCoordinate, other.elevationCoordinate);
-
- if (maxY - minY < 0) {
- continue;
- }
- float totalRadius = radius + other.radius;
-
- Vector2 voBoundingOrigin = other.position - position;
- float avoidanceStrength;
- if (other.locked || other.manuallyControlled) {
- avoidanceStrength = 1;
- } else if (other.Priority > 0.00001f || Priority > 0.00001f) {
- avoidanceStrength = other.Priority / (Priority + other.Priority);
- } else {
-
-
- avoidanceStrength = 0.5f;
- }
-
-
-
-
- Vector2 otherOptimalVelocity = Vector2.Lerp(other.currentVelocity, other.desiredVelocity, 2*avoidanceStrength - 1);
- var voCenter = Vector2.Lerp(optimalVelocity, otherOptimalVelocity, avoidanceStrength);
- vos.Add(new VO(voBoundingOrigin, voCenter, totalRadius, inverseAgentTimeHorizon, 1 / simulator.DeltaTime));
- if (DebugDraw)
- DrawVO(position + voBoundingOrigin * inverseAgentTimeHorizon + voCenter, totalRadius * inverseAgentTimeHorizon, position + voCenter);
- }
- }
- Vector2 GradientDescent (VOBuffer vos, Vector2 sampleAround1, Vector2 sampleAround2) {
- float score1;
- var minima1 = Trace(vos, sampleAround1, out score1);
- if (DebugDraw) Draw.Debug.CrossXZ(FromXZ(minima1 + position), Color.yellow, 0.5f);
-
-
-
-
-
-
-
-
-
-
- float score2;
- Vector2 minima2 = Trace(vos, sampleAround2, out score2);
- if (DebugDraw) Draw.Debug.CrossXZ(FromXZ(minima2 + position), Color.magenta, 0.5f);
- return score1 < score2 ? minima1 : minima2;
- }
-
-
-
-
-
-
-
-
-
-
-
-
- static bool BiasDesiredVelocity (VOBuffer vos, ref Vector2 desiredVelocity, ref Vector2 targetPointInVelocitySpace, float maxBiasRadians) {
- var desiredVelocityMagn = desiredVelocity.magnitude;
- var maxValue = 0f;
- for (int i = 0; i < vos.length; i++) {
- float value;
-
-
-
- vos.buffer[i].Gradient(desiredVelocity, out value);
- maxValue = Mathf.Max(maxValue, value);
- }
-
- var inside = maxValue > 0;
-
- if (desiredVelocityMagn < 0.001f) {
- return inside;
- }
-
-
-
- var angle = Mathf.Min(maxBiasRadians, maxValue / desiredVelocityMagn);
- desiredVelocity += new Vector2(desiredVelocity.y, -desiredVelocity.x) * angle;
- targetPointInVelocitySpace += new Vector2(targetPointInVelocitySpace.y, -targetPointInVelocitySpace.x) * angle;
- return inside;
- }
-
- Vector2 EvaluateGradient (VOBuffer vos, Vector2 p, out float value) {
- Vector2 gradient = Vector2.zero;
- value = 0;
-
- for (int i = 0; i < vos.length; i++) {
- float w;
- var grad = vos.buffer[i].ScaledGradient(p, out w);
- if (w > value) {
- value = w;
- gradient = grad;
- }
- }
-
- var dirToDesiredVelocity = desiredVelocity - p;
- var distToDesiredVelocity = dirToDesiredVelocity.magnitude;
- if (distToDesiredVelocity > 0.0001f) {
- gradient += dirToDesiredVelocity * (DesiredVelocityWeight/distToDesiredVelocity);
- value += distToDesiredVelocity * DesiredVelocityWeight;
- }
-
-
- var sqrSpeed = p.sqrMagnitude;
- if (sqrSpeed > desiredSpeed*desiredSpeed) {
- var speed = Mathf.Sqrt(sqrSpeed);
- if (speed > maxSpeed) {
- const float MaxSpeedWeight = 3;
- value += MaxSpeedWeight * (speed - maxSpeed);
- gradient -= MaxSpeedWeight * (p/speed);
- }
-
-
-
- float scale = 2*DesiredVelocityWeight;
- value += scale * (speed - desiredSpeed);
- gradient -= scale * (p/speed);
- }
- return gradient;
- }
-
-
-
-
-
-
- Vector2 Trace (VOBuffer vos, Vector2 p, out float score) {
-
- float stepSize = Mathf.Max(radius, 0.2f * desiredSpeed);
- float bestScore = float.PositiveInfinity;
- Vector2 bestP = p;
-
- const int MaxIterations = 50;
- for (int s = 0; s < MaxIterations; s++) {
- float step = 1.0f - (s/(float)MaxIterations);
- step = Sqr(step) * stepSize;
- float value;
- var gradient = EvaluateGradient(vos, p, out value);
- if (value < bestScore) {
- bestScore = value;
- bestP = p;
- }
-
- gradient.Normalize();
- gradient *= step;
- Vector2 prev = p;
- p += gradient;
- if (DebugDraw) Debug.DrawLine(FromXZ(prev + position), FromXZ(p + position), Rainbow(s*0.1f) * new Color(1, 1, 1, 1f));
- }
- score = bestScore;
- return bestP;
- }
- }
- }
|