forked from pioneerspacesim/pioneer
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Ship-AI.cpp
359 lines (293 loc) · 11.9 KB
/
Ship-AI.cpp
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// Copyright © 2008-2013 Pioneer Developers. See AUTHORS.txt for details
// Licensed under the terms of the GPL v3. See licenses/GPL-3.txt
#include "libs.h"
#include "Ship.h"
#include "ShipAICmd.h"
#include "Pi.h"
#include "Player.h"
#include "perlin.h"
#include "Frame.h"
#include "Planet.h"
#include "SpaceStation.h"
#include "Space.h"
#include "LuaConstants.h"
#include "LuaEvent.h"
#include "KeyBindings.h"
#include "EnumStrings.h"
void Ship::AIModelCoordsMatchAngVel(vector3d desiredAngVel, double softness)
{
double angAccel = m_type->angThrust / GetAngularInertia();
const double softTimeStep = Pi::game->GetTimeStep() * softness;
vector3d angVel = desiredAngVel - GetAngVelocity() * GetOrient();
vector3d thrust;
for (int axis=0; axis<3; axis++) {
if (angAccel * softTimeStep >= fabs(angVel[axis])) {
thrust[axis] = angVel[axis] / (softTimeStep * angAccel);
} else {
thrust[axis] = (angVel[axis] > 0.0 ? 1.0 : -1.0);
}
}
SetAngThrusterState(thrust);
}
void Ship::AIModelCoordsMatchSpeedRelTo(const vector3d v, const Ship *other)
{
vector3d relToVel = other->GetVelocity() * GetOrient() + v;
AIAccelToModelRelativeVelocity(relToVel);
}
// Try to reach this model-relative velocity.
// (0,0,-100) would mean going 100m/s forward.
void Ship::AIAccelToModelRelativeVelocity(const vector3d v)
{
vector3d difVel = v - GetVelocity() * GetOrient(); // required change in velocity
vector3d maxThrust = GetMaxThrust(difVel);
vector3d maxFrameAccel = maxThrust * (Pi::game->GetTimeStep() / GetMass());
SetThrusterState(0, difVel.x / maxFrameAccel.x);
SetThrusterState(1, difVel.y / maxFrameAccel.y);
SetThrusterState(2, difVel.z / maxFrameAccel.z); // use clamping
}
// returns true if command is complete
bool Ship::AITimeStep(float timeStep)
{
// allow the launch thruster thing to happen
if (m_launchLockTimeout > 0.0) return false;
m_decelerating = false;
if (!m_curAICmd) {
if (this == Pi::player) return true;
// just in case the AI left it on
ClearThrusterState();
for (int i=0; i<ShipType::GUNMOUNT_MAX; i++)
SetGunState(i,0);
return true;
}
if (m_curAICmd->TimeStepUpdate()) {
AIClearInstructions();
// ClearThrusterState(); // otherwise it does one timestep at 10k and gravity is fatal
LuaEvent::Queue("onAICompleted", this, EnumStrings::GetString("ShipAIError", AIMessage()));
return true;
}
else return false;
}
void Ship::AIClearInstructions()
{
if (!m_curAICmd) return;
delete m_curAICmd; // rely on destructor to kill children
m_curAICmd = 0;
m_decelerating = false; // don't adjust unless AI is running
}
void Ship::AIGetStatusText(char *str)
{
if (!m_curAICmd) strcpy(str, "AI inactive");
else m_curAICmd->GetStatusText(str);
}
void Ship::AIKamikaze(Body *target)
{
AIClearInstructions();
m_curAICmd = new AICmdKamikaze(this, target);
}
void Ship::AIKill(Ship *target)
{
AIClearInstructions();
SetFuelReserve((GetFuel() < 0.5) ? GetFuel() / 2 : 0.25);
m_curAICmd = new AICmdKill(this, target);
}
/*
void Ship::AIJourney(SystemBodyPath &dest)
{
AIClearInstructions();
// m_curAICmd = new AICmdJourney(this, dest);
}
*/
void Ship::AIFlyTo(Body *target)
{
AIClearInstructions();
SetFuelReserve((GetFuel() < 0.5) ? GetFuel() / 2 : 0.25);
if (target->IsType(Object::SHIP)) { // test code
vector3d posoff(-1000.0, 0.0, 1000.0);
m_curAICmd = new AICmdFormation(this, static_cast<Ship*>(target), posoff);
}
else m_curAICmd = new AICmdFlyTo(this, target);
}
void Ship::AIDock(SpaceStation *target)
{
AIClearInstructions();
SetFuelReserve((GetFuel() < 0.5) ? GetFuel() / 2 : 0.25);
m_curAICmd = new AICmdDock(this, target);
}
void Ship::AIOrbit(Body *target, double alt)
{
AIClearInstructions();
SetFuelReserve((GetFuel() < 0.5) ? GetFuel() / 2 : 0.25);
m_curAICmd = new AICmdFlyAround(this, target, alt);
}
void Ship::AIHoldPosition()
{
AIClearInstructions();
m_curAICmd = new AICmdHoldPosition(this);
}
// Because of issues when reducing timestep, must do parts of this as if 1x accel
// final frame has too high velocity to correct if timestep is reduced
// fix is too slow in the terminal stages:
// if (endvel <= vel) { endvel = vel; ivel = dist / Pi::game->GetTimeStep(); } // last frame discrete correction
// ivel = std::min(ivel, endvel + 0.5*acc/PHYSICS_HZ); // unknown next timestep discrete overshoot correction
// yeah ok, this doesn't work
// sometimes endvel is too low to catch moving objects
// worked around with half-accel hack in dynamicbody & pi.cpp
double calc_ivel(double dist, double vel, double acc)
{
bool inv = false;
if (dist < 0) { dist = -dist; vel = -vel; inv = true; }
double ivel = 0.9 * sqrt(vel*vel + 2.0 * acc * dist); // fudge hardly necessary
double endvel = ivel - (acc * Pi::game->GetTimeStep());
if (endvel <= 0.0) ivel = dist / Pi::game->GetTimeStep(); // last frame discrete correction
else ivel = (ivel + endvel) * 0.5; // discrete overshoot correction
// else ivel = endvel + 0.5*acc/PHYSICS_HZ; // unknown next timestep discrete overshoot correction
return (inv) ? -ivel : ivel;
}
// version for all-positive values
double calc_ivel_pos(double dist, double vel, double acc)
{
double ivel = 0.9 * sqrt(vel*vel + 2.0 * acc * dist); // fudge hardly necessary
double endvel = ivel - (acc * Pi::game->GetTimeStep());
if (endvel <= 0.0) ivel = dist / Pi::game->GetTimeStep(); // last frame discrete correction
else ivel = (ivel + endvel) * 0.5; // discrete overshoot correction
return ivel;
}
// vel is desired velocity in ship's frame
// returns true if this can be attained in a single timestep
bool Ship::AIMatchVel(const vector3d &vel)
{
vector3d diffvel = (vel - GetVelocity()) * GetOrient();
return AIChangeVelBy(diffvel);
}
// diffvel is required change in velocity in object space
// returns true if this can be done in a single timestep
bool Ship::AIChangeVelBy(const vector3d &diffvel)
{
// counter external forces
vector3d extf = GetExternalForce() * (Pi::game->GetTimeStep() / GetMass());
vector3d diffvel2 = diffvel - extf * GetOrient();
vector3d maxThrust = GetMaxThrust(diffvel2);
vector3d maxFrameAccel = maxThrust * (Pi::game->GetTimeStep() / GetMass());
vector3d thrust(diffvel2.x / maxFrameAccel.x,
diffvel2.y / maxFrameAccel.y,
diffvel2.z / maxFrameAccel.z);
SetThrusterState(thrust); // use clamping
if (thrust.x*thrust.x > 1.0 || thrust.y*thrust.y > 1.0 || thrust.z*thrust.z > 1.0) return false;
return true;
}
// Change object-space velocity in direction of param
vector3d Ship::AIChangeVelDir(const vector3d &reqdiffvel)
{
// get max thrust in desired direction after external force compensation
vector3d maxthrust = GetMaxThrust(reqdiffvel);
maxthrust += GetExternalForce() * GetOrient();
vector3d maxFA = maxthrust * (Pi::game->GetTimeStep() / GetMass());
maxFA.x = fabs(maxFA.x); maxFA.y = fabs(maxFA.y); maxFA.z = fabs(maxFA.z);
// crunch diffvel by relative thruster power to get acceleration in right direction
vector3d diffvel = reqdiffvel;
if (fabs(diffvel.x) > maxFA.x) diffvel *= maxFA.x / fabs(diffvel.x);
if (fabs(diffvel.y) > maxFA.y) diffvel *= maxFA.y / fabs(diffvel.y);
if (fabs(diffvel.z) > maxFA.z) diffvel *= maxFA.z / fabs(diffvel.z);
AIChangeVelBy(diffvel); // should always return true because it's already capped?
return GetOrient() * (reqdiffvel - diffvel); // should be remaining diffvel to correct
}
// Input in object space
void Ship::AIMatchAngVelObjSpace(const vector3d &angvel)
{
double maxAccel = m_type->angThrust / GetAngularInertia();
double invFrameAccel = 1.0 / (maxAccel * Pi::game->GetTimeStep());
vector3d diff = angvel - GetAngVelocity() * GetOrient(); // find diff between current & desired angvel
SetAngThrusterState(diff * invFrameAccel);
}
// get updir as close as possible just using roll thrusters
double Ship::AIFaceUpdir(const vector3d &updir, double av)
{
double maxAccel = m_type->angThrust / GetAngularInertia(); // should probably be in stats anyway
double frameAccel = maxAccel * Pi::game->GetTimeStep();
vector3d uphead = updir * GetOrient(); // create desired object-space updir
if (uphead.z > 0.99999) return 0; // bail out if facing updir
uphead.z = 0; uphead = uphead.Normalized(); // only care about roll axis
double ang = 0.0, dav = 0.0;
if (uphead.y < 0.99999999)
{
ang = acos(Clamp(uphead.y, -1.0, 1.0)); // scalar angle from head to curhead
double iangvel = av + calc_ivel_pos(ang, 0.0, maxAccel); // ideal angvel at current time
dav = uphead.x > 0 ? -iangvel : iangvel;
}
double cav = (GetAngVelocity() * GetOrient()).z; // current obj-rel angvel
double diff = (dav - cav) / frameAccel; // find diff between current & desired angvel
SetAngThrusterState(2, diff);
return ang;
}
// Input: direction in ship's frame, doesn't need to be normalized
// Approximate positive angular velocity at match point
// Applies thrust directly
// old: returns whether it can reach that direction in this frame
// returns angle to target
double Ship::AIFaceDirection(const vector3d &dir, double av)
{
double maxAccel = m_type->angThrust / GetAngularInertia(); // should probably be in stats anyway
vector3d head = (dir * GetOrient()).Normalized(); // create desired object-space heading
vector3d dav(0.0, 0.0, 0.0); // desired angular velocity
double ang = 0.0;
if (head.z > -0.99999999)
{
ang = acos (Clamp(-head.z, -1.0, 1.0)); // scalar angle from head to curhead
double iangvel = av + calc_ivel_pos(ang, 0.0, maxAccel); // ideal angvel at current time
// Normalize (head.x, head.y) to give desired angvel direction
if (head.z > 0.999999) head.x = 1.0;
double head2dnorm = 1.0 / sqrt(head.x*head.x + head.y*head.y); // NAN fix shouldn't be necessary if inputs are normalized
dav.x = head.y * head2dnorm * iangvel;
dav.y = -head.x * head2dnorm * iangvel;
}
vector3d cav = GetAngVelocity() * GetOrient(); // current obj-rel angvel
double frameAccel = maxAccel * Pi::game->GetTimeStep();
vector3d diff = (dav - cav) / frameAccel; // find diff between current & desired angvel
// If the player is pressing a roll key, don't override roll.
// XXX this really shouldn't be here. a better way would be to have a
// field in Ship describing the wanted angvel adjustment from input. the
// baseclass version in Ship would always be 0. the version in Player
// would be constructed from user input. that adjustment could then be
// considered by this method when computing the required change
if (IsType(Object::PLAYER) && (KeyBindings::rollLeft.IsActive() || KeyBindings::rollRight.IsActive()))
diff.z = m_angThrusters.z;
SetAngThrusterState(diff);
return ang;
}
// returns direction in ship's frame from this ship to target lead position
vector3d Ship::AIGetLeadDir(const Body *target, const vector3d& targaccel, int gunindex)
{
vector3d targpos = target->GetPositionRelTo(this);
vector3d targvel = target->GetVelocityRelTo(this);
// todo: should adjust targpos for gunmount offset
int laser = Equip::types[m_equipment.Get(Equip::SLOT_LASER, gunindex)].tableIndex;
double projspeed = Equip::lasers[laser].speed;
// first attempt
double projtime = targpos.Length() / projspeed;
vector3d leadpos = targpos + targvel*projtime + 0.5*targaccel*projtime*projtime;
// second pass
projtime = leadpos.Length() / projspeed;
leadpos = targpos + targvel*projtime + 0.5*targaccel*projtime*projtime;
return leadpos.Normalized();
}
// underestimates if endspeed isn't reachable
/*
double Ship::AITravelTime(double targdist, double relspeed, double endspeed, double maxdecel)
{
// double speed = relvel.Dot(reldir); // speed >0 is towards
double dist = targdist;
double faccel = GetAccelFwd();
double time1, time2, time3;
// time to reduce speed to zero:
time1 = -relspeed / faccel;
dist += 0.5 * time1 * -relspeed;
// time to reduce speed to zero after target reached:
time3 = -endspeed / maxdecel;
dist += 0.5 * time3 * -endspeed;
// now time to cover distance between zero-vel points
// midpoint = intercept of two gradients
double m = dist*maxdecel / (faccel+maxdecel);
time2 = sqrt(2*m/faccel) + sqrt(2*(dist-m)/maxdecel);
return time1+time2+time3;
}
*/