Repository navigation
Expand file tree
/
Copy pathEntryPoint.cs
More file actions
322 lines (277 loc) · 16.2 KB
/
Copy pathEntryPoint.cs
File metadata and controls
322 lines (277 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
using Rage;
using Rage.Native;
using System;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
[assembly: Rage.Attributes.Plugin("KeepRight", Description = "Make the vehicles driving in front of you in the left lane on the highway change lanes", Author = "SSStuart", PrefersSingleInstance = true, SupportUrl = "https://ssstuart.net/discord")]
namespace KeepRight
{
public static class EntryPoint
{
public static string pluginName = "KeepRight";
public static string pluginVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
public static Localization l10n = new Localization();
private static bool isKeyButtonDefined = false;
private static int checkDelayMs = 2000;
private static int hornWeight = 0;
private static int lastHornWeight = 0;
public static void Main()
{
Game.LogTrivial($"{pluginName} plugin v{pluginVersion} has been loaded.");
UpdateChecker.CheckForUpdates();
Settings.LoadSettings();
isKeyButtonDefined = Settings.CHECK_KEY != Keys.None || Settings.CHECK_CONT_BUTTON != ControllerButtons.None;
float checkFrequency = !isKeyButtonDefined ? Settings.CHECK_FREQUENCY : 2;
checkDelayMs = (int)(1 / checkFrequency) * 1000;
if (isKeyButtonDefined)
{
GameFiber.StartNew(delegate
{
while (true)
{
if (((Settings.CHECK_KEY != Keys.None && Game.IsKeyDown(Settings.CHECK_KEY)) || (Settings.CHECK_CONT_BUTTON != ControllerButtons.None && Game.IsControllerButtonDown(Settings.CHECK_CONT_BUTTON)))
&& Game.LocalPlayer.Character.Exists() && Game.LocalPlayer.Character.IsInAnyVehicle(false) && Game.LocalPlayer.Character.CurrentVehicle.Speed > 2)
CheckForVehicles();
GameFiber.Yield();
}
});
}
else
{
if (Settings.CHECK_FREQUENCY == 0 || Settings.CHECK_FREQUENCY > 100)
{
Game.LogTrivial("Plugin stopped! Check frequency is " + (Settings.CHECK_FREQUENCY == 0 ? "too low" : "too high"));
return;
}
GameFiber.StartNew(delegate
{
while (true)
{
if (Game.LocalPlayer.Character.Exists() && Game.LocalPlayer.Character.IsInAnyVehicle(false) && Game.LocalPlayer.Character.CurrentVehicle.Speed > 2)
{
CheckForVehicles();
}
lastHornWeight = hornWeight;
hornWeight = 0;
GameFiber.Wait(checkDelayMs);
}
});
GameFiber.StartNew(delegate
{
while (true)
{
if (Game.LocalPlayer.Character.IsInAnyVehicle(false) && Game.LocalPlayer.IsPressingHorn)
hornWeight++;
GameFiber.Wait(100);
}
});
}
}
private static void CheckForVehicles()
{
Vehicle[] drivingVehiclesInFront = World.GetEntities(GetEntitiesFlags.ConsiderGroundVehicles | GetEntitiesFlags.ExcludeEmptyVehicles | GetEntitiesFlags.ExcludePlayerVehicle | (Settings.ENABLE_FOR_OTHER_EMERGENCY_VEHICLES ? 0 : GetEntitiesFlags.ExcludeEmergencyVehicles)).Cast<Vehicle>().ToArray();
drivingVehiclesInFront = drivingVehiclesInFront.Where((vehicle) => DoesVehicleMeetCriteria(vehicle)).ToArray();
foreach (Vehicle vehicle in drivingVehiclesInFront)
{
if (!vehicle.Exists() || !vehicle.HasDriver)
continue;
Vector3 nodeCheckPos = vehicle.GetOffsetPositionFront(10);
NativeFunction.Natives.GET_CLOSEST_VEHICLE_NODE_WITH_HEADING(
nodeCheckPos.X, nodeCheckPos.Y, nodeCheckPos.Z,
out Vector3 nodePos, out float _, 0, 3.0f, 0f);
vehicle.Metadata.KR_isGoingRight = true;
GameFiber.StartNew(delegate
{
// Random delay to avoid triggering the lane change at a fixed frequency
GameFiber.Sleep(MathHelper.GetRandomInteger(0, checkDelayMs));
if (!DoesVehicleMeetCriteria(vehicle))
return;
NativeFunction.Natives.GET_CLOSEST_VEHICLE_NODE_WITH_HEADING(
nodeCheckPos.X, nodeCheckPos.Y, nodeCheckPos.Z,
out nodePos, out float nodeHeading, 0, 3.0f, 0f);
NativeFunction.Natives.GET_ROAD_BOUNDARY_USING_HEADING(
nodeCheckPos.X, nodeCheckPos.Y, nodeCheckPos.Z,
vehicle.Heading, out Vector3 roadBoundPos);
NativeFunction.Natives.GET_VEHICLE_NODE_PROPERTIES(
nodePos.X, nodePos.Y, nodePos.Z,
out int _, out int flags);
bool isInJunction = (flags & (1 << 7)) != 0;
if (isInJunction)
{
vehicle.Metadata.KR_timeout = Game.GameTime + 5000;
return;
}
bool isOnHighway = (flags & (1 << 6)) != 0;
bool isOnLeftSideOfRoad = vehicle.GetPositionOffset(nodePos).X > 0;
bool doesLaneToRightExist = vehicle.GetPositionOffset(roadBoundPos).X > 5;
bool isRightLaneOccupied = World.TraceBox(vehicle.GetOffsetPosition(new Vector3(4, 0, 0)), vehicle.Orientation, new Vector3(2, vehicle.Length + vehicle.Speed, 3), TraceFlags.IntersectVehicles, vehicle).Hit;
if (isRightLaneOccupied && Settings.ACCELERATE_IF_CANT_CHANGE_LANES)
{
vehicle.Metadata.KR_timeout = Game.GameTime + 5000;
vehicle.Driver.Tasks.PerformDrivingManeuver(VehicleManeuver.GoForwardStraightHalfAcceleration).WaitForCompletion(100); // Seems needed for CruiseWithVehicle to take effect
vehicle.Driver.Tasks.CruiseWithVehicle(vehicle.Speed + 3f).WaitForCompletion(5000);
vehicle.Driver.Tasks.Clear();
}
bool isPlayerSirenOn = Game.LocalPlayer.Character.CurrentVehicle.IsSirenOn;
float mergeChance = (60 - vehicle.DistanceTo2D(Game.LocalPlayer.Character.Position)
+ (!isOnHighway ? Settings.WEIGHT_NOT_HIGHWAY : 0)
+ (lastHornWeight * Settings.WEIGHT_HORN)
+ (vehicle.IsBig ? Settings.WEIGHT_BIG_VEHICLES : 0)
+ (Game.LocalPlayer.Character.CurrentVehicle.Model.IsEmergencyVehicle ? Settings.WEIGHT_PLAYER_IN_EMERGENCY_VEHICLE : 0)
+ (isPlayerSirenOn ? 50 : 0)
+ (isKeyButtonDefined ? Settings.WEIGHT_KEY : 0)) / 100;
if ((!isPlayerSirenOn || (Settings.ENABLE_BIG_VEHICLE_SIREN_ON && vehicle.IsBig)) && (isOnLeftSideOfRoad || doesLaneToRightExist) && !isRightLaneOccupied && MathHelper.GetRandomSingle(0, 1) < mergeChance)
{
float taskSpeed = Math.Max(vehicle.Speed, 5);
float laneChangeForwardDistance = 5 + 3 * taskSpeed;
Vector3 targetRoadPosition = GetLaneChangeEndPos(vehicle, isOnHighway) ?? Vector3.Zero;
if (targetRoadPosition == Vector3.Zero)
return;
NativeFunction.Natives.GET_VEHICLE_NODE_PROPERTIES(
targetRoadPosition.X, targetRoadPosition.Y, targetRoadPosition.Z,
out int _, out flags);
isInJunction = (flags & (1 << 7)) != 0;
if (isInJunction)
{
vehicle.Metadata.KR_timeout = Game.GameTime + 5000;
return;
}
Game.LogTrivial($"Starting lane change for {vehicle.Model.Name}. Current heading: {vehicle.Heading} - Speed: {vehicle.Speed} - Target: {targetRoadPosition}");
Blip mergingVehicleBlip = null;
GameFiber drawLine = null;
if (Settings.DEBUG)
{
Game.DisplayNotification($"Starting merge for {vehicle.Model.Name}");
mergingVehicleBlip = new Blip(vehicle)
{
Sprite = BlipSprite.CarWash,
Alpha = 0.5f
};
drawLine = GameFiber.StartNew(delegate
{
uint endTime = Game.GameTime + 5000;
while (Game.GameTime < endTime && vehicle.Exists())
{
NativeFunction.Natives.DRAW_LINE(targetRoadPosition.X, targetRoadPosition.Y, targetRoadPosition.Z + 0.5f, vehicle.Position.X, vehicle.Position.Y, vehicle.Position.Z, 50, 50, 255, 200);
GameFiber.Yield();
}
});
}
vehicle.Driver.Tasks.DriveToPosition(targetRoadPosition, taskSpeed, VehicleDrivingFlags.DriveAroundObjects | VehicleDrivingFlags.DriveAroundPeds | VehicleDrivingFlags.DriveAroundVehicles | VehicleDrivingFlags.IgnorePathFinding | VehicleDrivingFlags.FollowTraffic | VehicleDrivingFlags.RespectIntersections, 3);
uint taskTimeout = Game.GameTime + 10000;
UseTurnSignalForSeconds(vehicle, 10);
while (Vector3.DistanceSquared(vehicle.Position, targetRoadPosition) > (taskSpeed > 5 ? 10 * 10 : 3 * 3) && Game.GameTime < taskTimeout)
{
GameFiber.Sleep(100);
}
if (vehicle.Exists())
{
if (vehicle.HasDriver)
vehicle.Driver.Tasks.Clear();
if (Settings.DEBUG && mergingVehicleBlip.Exists())
mergingVehicleBlip.Delete();
if (Settings.DEBUG && drawLine != null)
drawLine.Abort();
}
UseTurnSignalForSeconds(vehicle, 2 + MathHelper.GetRandomInteger(3));
}
else if ((!isPlayerSirenOn || (Settings.ENABLE_BIG_VEHICLE_SIREN_ON && vehicle.IsBig)) && (isOnLeftSideOfRoad || doesLaneToRightExist) && isRightLaneOccupied)
{
UseTurnSignalForSeconds(vehicle, 2 + MathHelper.GetRandomInteger(2));
}
});
if (vehicle.Exists())
vehicle.Metadata.KR_isGoingRight = false;
GameFiber.Yield();
}
}
private static bool DoesVehicleMeetCriteria(Vehicle vehicle)
{
bool isVehicleValid = vehicle.Exists() && vehicle.HasDriver;
bool isVehicleAlreadyChangingOrTimedOut = vehicle.Metadata.KR_isGoingRight ?? false || (vehicle.Metadata.KR_timeout ?? Game.GameTime - 1000) > Game.GameTime;
bool isVehicleInFrontOfPlayer = Vector3.DistanceSquared(vehicle.Position, Game.LocalPlayer.Character.GetOffsetPositionFront(40)) < 40 * 40;
bool isDriverTaskFree = vehicle.HasDriver && vehicle.Driver.Tasks.CurrentTaskStatus == TaskStatus.NoTask;
bool isVehicleDrivingFastEnough = vehicle.Speed > 3 && vehicle.Speed <= Game.LocalPlayer.Character.Speed + 4;
bool isVehicleHeadingSimilarToPlayer = Math.Abs(vehicle.Heading - Game.LocalPlayer.Character.Heading) < 40;
bool isPlayerJustBehindVehicle = vehicle.GetPositionOffset(Game.LocalPlayer.Character.Position).X < 3 && vehicle.GetPositionOffset(Game.LocalPlayer.Character.Position).X > -5;
return isVehicleValid && !isVehicleAlreadyChangingOrTimedOut && isVehicleInFrontOfPlayer && isDriverTaskFree && isVehicleDrivingFastEnough && isVehicleHeadingSimilarToPlayer && isPlayerJustBehindVehicle && !vehicle.IsSirenOn;
}
private static Vector3? GetLaneChangeEndPos(Vehicle vehicle, bool isOnHighway)
{
if (!vehicle.Exists()) return null;
Vector3 targetPos;
float taskSpeed = Math.Max(vehicle.Speed, 5);
float laneChangeForwardDistance = 5 + 2 * taskSpeed;
// Get first node in front (20m)
Vector3 nearNodeCheckPos = vehicle.GetOffsetPositionFront(20);
NativeFunction.Natives.GET_CLOSEST_VEHICLE_NODE_WITH_HEADING(
nearNodeCheckPos.X, nearNodeCheckPos.Y, nearNodeCheckPos.Z,
out Vector3 nearNodePos, out float nearNodeHeading, 0, 3.0f, 0f);
// Get second node in front of the first one (20m)
Vector3 nextNodeCheckPos = GetOffsetPosition(nearNodePos, nearNodeHeading, new Vector3(0, 20, 0));
NativeFunction.Natives.GET_CLOSEST_VEHICLE_NODE_WITH_HEADING(
nextNodeCheckPos.X, nextNodeCheckPos.Y, nextNodeCheckPos.Z,
out Vector3 _, out float nextNodeHeading, 0, 3.0f, 0f);
float averageHeading = (nearNodeHeading + nextNodeHeading) / 2f;
bool isTargetOnRoad;
int retryNb = 1;
if (Math.Abs(averageHeading - vehicle.Heading) > 15)
{
// Out-of-range node turn data, use basic vehicle offset
do
{
targetPos = vehicle.GetOffsetPosition(new Vector3(isOnHighway ? 5 : 4, laneChangeForwardDistance - retryNb, 0));
isTargetOnRoad = NativeFunction.Natives.IS_POINT_ON_ROAD<bool>(targetPos.X, targetPos.Y, targetPos.Z, vehicle);
retryNb += 3;
}
while (!isTargetOnRoad && retryNb <= 30);
if (!isTargetOnRoad)
return null;
}
else
{
// Node turn acceptable, adjusting distance
bool isStraigth = Math.Abs(nearNodeHeading - nextNodeHeading) < 2;
do
{
targetPos = GetOffsetPosition(vehicle.Position, averageHeading, new Vector3(isOnHighway ? 5 : 4 + (isStraigth ? 0 : (taskSpeed / 15f)), laneChangeForwardDistance - retryNb, 0));
isTargetOnRoad = NativeFunction.Natives.IS_POINT_ON_ROAD<bool>(targetPos.X, targetPos.Y, targetPos.Z, vehicle);
retryNb += 3;
}
while (!isTargetOnRoad && retryNb <= 30);
if (!isTargetOnRoad)
return null;
}
return targetPos;
}
private static void UseTurnSignalForSeconds(Vehicle vehicle, int seconds)
{
GameFiber.StartNew(delegate
{
uint turnSignalTimeout = Game.GameTime + (uint)seconds * 1000;
while (Game.GameTime < turnSignalTimeout && vehicle.Exists())
{
vehicle.IndicatorLightsStatus = VehicleIndicatorLightsStatus.RightOnly;
GameFiber.Yield();
}
});
}
private static Vector3 GetOffsetPosition(Vector3 position, float heading, Vector3 offset)
{
float radians = heading * (float)(Math.PI / 180.0);
float sin = (float)Math.Sin(radians);
float cos = (float)Math.Cos(radians);
return new Vector3(
position.X + offset.X * cos - offset.Y * sin,
position.Y + offset.X * sin + offset.Y * cos,
position.Z + offset.Z
);
}
private static void OnUnload(bool variable)
{
Game.LogTrivial("Unloading...");
Game.LogTrivial("Unloaded");
}
}
}