Debian Codegraph @

src/game/car.cpp

raw symbols SCIP
1 // This file is part of Dust Racing 2D.
2 // Copyright (C) 2015 Jussi Lind <[email protected]>
3 //
4 // Dust Racing 2D is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 // Dust Racing 2D is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with Dust Racing 2D. If not, see <http://www.gnu.org/licenses/>.
15
16 #include "car.hpp"
17 #include "carparticleeffectmanager.hpp"
18 #include "carphysicscomponent.hpp"
19 #include "carsoundeffectmanager.hpp"
20 #include "game.hpp"
21 #include "gearbox.hpp"
22 #include "graphicsfactory.hpp"
23 #include "layers.hpp"
24 #include "renderer.hpp"
25 #include "tire.hpp"
26
27 #include <MCAssetManager>
28 #include <MCCollisionEvent>
29 #include <MCDragForceGenerator>
30 #include <MCForceRegistry>
31 #include <MCFrictionGenerator>
32 #include <MCMathUtil>
33 #include <MCPhysicsComponent>
34 #include <MCRectShape>
35 #include <MCShape>
36 #include <MCSurface>
37 #include <MCTrigonom>
38
39 #include <MCVector2d>
40 #include <MCWorld>
41
42 #include <cassert>
43 #include <cmath>
44 #include <memory>
45 #include <string>
46
47 using std::dynamic_pointer_cast;
48 using std::static_pointer_cast;
49
50 Car::Car(Description & desc, MCSurfacePtr surface, size_t index, bool isHuman)
51 : MCObject(surface, "car")
52 , m_desc(desc)
53 , m_onTrackFriction(std::make_shared<MCFrictionGenerator>(desc.rollingFrictionOnTrack, 0.0))
54 , m_leftSideOffTrack(false)
55 , m_rightSideOffTrack(false)
56 , m_skidding(false)
57 , m_steer(Steer::Neutral)
58 , m_index(index)
59 , m_tireAngle(0)
60 , m_initDamageCapacity(100)
61 , m_damageCapacity(m_initDamageCapacity)
62 , m_initTireWearOutCapacity(100)
63 , m_tireWearOutCapacity(m_initTireWearOutCapacity)
64 , m_frontTire(MCAssetManager::surfaceManager().surface("frontTire"))
65 , m_brakeGlow(MCAssetManager::surfaceManager().surface("brakeGlow"))
66 , m_speedInKmh(0)
67 , m_absSpeed(0)
68 , m_dx(0)
69 , m_dy(0)
70 , m_isHuman(isHuman)
71 , m_particleEffectManager(std::make_unique<CarParticleEffectManager>(*this))
72 , m_numberPos(-5, 0, 0)
73 , m_leftFrontTirePos(14, 9, 0)
74 , m_rightFrontTirePos(14, -9, 0)
75 , m_leftRearTirePos(-14, 9, 0)
76 , m_rightRearTirePos(-14, -9, 0)
77 , m_leftBrakeGlowPos(-21, 8, 0)
78 , m_rightBrakeGlowPos(-21, -8, 0)
79 , m_hadHardCrash(false)
80 , m_gearbox(std::make_unique<Gearbox>())
81 {
82 // Override the default physics component to handle damage from impulses
83 setPhysicsComponent(std::make_unique<CarPhysicsComponent>(*this));
84
85 setProperties(desc);
86
87 initForceGenerators(desc);
88
89 createChildObjects(surface->maxZ(), index);
90 }
91
92 void Car::createChildObjects(float maxZ, size_t index)
93 {
94 // Note that the z-coordinate of the actual car body is 0. The small lift is done in the
95 // surface vertex level and configured in surfaces.conf.
96
97 const auto numberPlate = std::make_shared<MCObject>(GraphicsFactory::generateNumberSurface(index), "Number");
98 addChildObject(numberPlate, m_numberPos + MCVector3dF(0, 0, maxZ + 1), 90);
99 numberPlate->setBypassCollisions(true);
100 numberPlate->shape()->view()->setHasShadow(false);
101
102 createTires();
103
104 m_leftBrakeGlowPos += MCVector3dF(0, 0, maxZ + 1.0f);
105 m_rightBrakeGlowPos += MCVector3dF(0, 0, maxZ + 1.0f);
106
107 m_leftBrakeGlow = std::make_shared<MCObject>(m_brakeGlow, "LeftBrakeGlow");
108 m_leftBrakeGlow->setBypassCollisions(true);
109 m_leftBrakeGlow->shape()->view()->setHasShadow(false);
110 m_leftBrakeGlow->setIsRenderable(false);
111 addChildObject(m_leftBrakeGlow, m_leftBrakeGlowPos);
112
113 m_rightBrakeGlow = std::make_shared<MCObject>(m_brakeGlow, "RightBrakeGlow");
114 m_rightBrakeGlow->setBypassCollisions(true);
115 m_rightBrakeGlow->shape()->view()->setHasShadow(false);
116 m_rightBrakeGlow->setIsRenderable(false);
117 addChildObject(m_rightBrakeGlow, m_rightBrakeGlowPos);
118 }
119
120 void Car::createTires()
121 {
122 const float offTrackFrictionFactor = 0.8f;
123 const float frontFriction = 0.85f;
124 const MCVector3dF tireZ = MCVector3dF(0, 0, 1);
125 m_leftFrontTire = std::make_shared<Tire>(*this, frontFriction, frontFriction * offTrackFrictionFactor);
126 addChildObject(m_leftFrontTire, m_leftFrontTirePos + tireZ, 0);
127
128 m_rightFrontTire = std::make_shared<Tire>(*this, frontFriction, frontFriction * offTrackFrictionFactor);
129 addChildObject(m_rightFrontTire, m_rightFrontTirePos + tireZ, 0);
130
131 const float rearFriction = 0.95f;
132 m_leftRearTire = std::make_shared<Tire>(*this, rearFriction, rearFriction * offTrackFrictionFactor);
133 addChildObject(m_leftRearTire, m_leftRearTirePos + tireZ, 0);
134
135 m_rightRearTire = std::make_shared<Tire>(*this, rearFriction, rearFriction * offTrackFrictionFactor);
136 addChildObject(m_rightRearTire, m_rightRearTirePos + tireZ, 0);
137 }
138
139 void Car::setProperties(Description & desc)
140 {
141 physicsComponent().setMass(desc.mass);
142 physicsComponent().setMomentOfInertia(desc.mass * 2.5f);
143 physicsComponent().setRestitution(desc.restitution);
144 setShadowOffset(MCVector3dF(5, -5, 1));
145
146 const float width = dynamic_pointer_cast<MCRectShape>(shape())->width();
147 const float height = dynamic_pointer_cast<MCRectShape>(shape())->height();
148 m_length = std::max(width, height);
149 }
150
151 void Car::initForceGenerators(Description & desc)
152 {
153 // Add rolling friction generator (on-track)
154 MCWorld::instance().forceRegistry().addForceGenerator(m_onTrackFriction, *this);
155 m_onTrackFriction->enable(true);
156
157 MCWorld::instance().forceRegistry().addForceGenerator(std::make_shared<MCDragForceGenerator>(desc.dragLinear, desc.dragQuadratic), *this);
158 }
159
160 size_t Car::index() const
161 {
162 return m_index;
163 }
164
165 void Car::steer(Steer direction, float control)
166 {
167 if (direction == Steer::Neutral)
168 {
169 m_tireAngle = 0;
170 }
171 else
172 {
173 if (const float maxAngle = 15.0f * (direction == Steer::Left ? 1 : -1); !m_isHuman)
174 {
175 m_tireAngle = static_cast<int>(maxAngle * control);
176 }
177 else
178 {
179 m_tireAngle = m_tireAngle + (maxAngle - m_tireAngle) * 0.15f;
180 }
181 }
182
183 m_steer = direction;
184 }
185
186 void Car::accelerate(bool deccelerate)
187 {
188 const float maxForce =
189 physicsComponent().mass() * m_desc.accelerationFriction * std::fabs(MCWorld::instance().gravity().k());
190 float currentForce = maxForce;
191
192 if (const float velocity = physicsComponent().velocity().length(); velocity > 0.001f)
193 {
194 currentForce = m_desc.power / velocity;
195 if (currentForce > maxForce)
196 {
197 currentForce = maxForce;
198 }
199 }
200
201 MCVector2dF direction(m_dx, m_dy);
202 if (deccelerate)
203 {
204 if (std::abs(speedInKmh()) < 25)
205 {
206 direction *= -1;
207 }
208 else
209 {
210 direction *= 0;
211 }
212 }
213
214 physicsComponent().addForce(direction * currentForce * damageFactor());
215 }
216
217 void Car::doTireSpinEffect()
218 {
219 static_pointer_cast<Tire>(m_leftRearTire)->setSpinCoeff(1.0f);
220 static_pointer_cast<Tire>(m_rightRearTire)->setSpinCoeff(1.0f);
221
222 m_skidding = false;
223
224 const float minSpinVelocity = 0.1f;
225 const float maxSpinVelocity = 4.5f;
226 const float velocity = physicsComponent().velocity().length();
227 if (m_acceleratorEnabled && m_gearbox->gear() == Gearbox::Gear::Forward && velocity > minSpinVelocity && velocity < maxSpinVelocity)
228 {
229 if (isHuman()) // Don't enable tire spin for AI yet
230 {
231 const float spinCoeff = 0.025f + 0.975f * std::pow(velocity / maxSpinVelocity, 2.0f);
232 static_pointer_cast<Tire>(m_leftRearTire)->setSpinCoeff(spinCoeff);
233 static_pointer_cast<Tire>(m_rightRearTire)->setSpinCoeff(spinCoeff);
234 }
235
236 m_skidding = true;
237 }
238 }
239
240 bool Car::isAccelerating() const
241 {
242 return m_acceleratorEnabled && (m_gearbox->gear() != Gearbox::Gear::Neutral || !m_isHuman);
243 }
244
245 bool Car::isBraking() const
246 {
247 // This is not entirely correct, but should work in most scenarios
248 return m_brakeEnabled && (m_gearbox->gear() != Gearbox::Gear::Reverse || !m_isHuman);
249 }
250
251 bool Car::isSkidding() const
252 {
253 return m_skidding;
254 }
255
256 bool Car::isSliding()
257 {
258 const float bodyNormalAngle = angle() + 90;
259 const MCVector2dF n(
260 MCTrigonom::cos(bodyNormalAngle), MCTrigonom::sin(bodyNormalAngle));
261 const MCVector2dF & v = physicsComponent().velocity().normalized();
262 const MCVector2dF s = MCVector2dF::projection(v, n);
263 return absSpeed() > 7.5f && s.lengthFast() > 0.25f;
264 }
265
266 int Car::speedInKmh() const
267 {
268 return m_speedInKmh;
269 }
270
271 float Car::absSpeed() const
272 {
273 return m_absSpeed;
274 }
275
276 MCVector3dF Car::leftFrontTireLocation() const
277 {
278 return m_leftFrontTire->location();
279 }
280
281 MCVector3dF Car::rightFrontTireLocation() const
282 {
283 return m_rightFrontTire->location();
284 }
285
286 MCVector3dF Car::leftRearTireLocation() const
287 {
288 return MCMathUtil::rotatedVector(m_leftRearTirePos, angle()) + MCVector2dF(location());
289 }
290
291 MCVector3dF Car::rightRearTireLocation() const
292 {
293 return MCMathUtil::rotatedVector(m_rightRearTirePos, angle()) + MCVector2dF(location());
294 }
295
296 void Car::updateAnimations()
297 {
298 for (auto && collision : m_collisionEffectStack)
299 {
300 m_particleEffectManager->collision(collision.first->typeId(), collision.second);
301 m_soundEffectManager->collision(*collision.first);
302 }
303 m_collisionEffectStack.clear();
304
305 m_particleEffectManager->update();
306
307 if (m_soundEffectManager)
308 {
309 m_soundEffectManager->update();
310 }
311
312 const float offset = 5.0f;
313 m_leftFrontTire->rotateRelative(m_tireAngle - offset);
314 m_rightFrontTire->rotateRelative(m_tireAngle + offset);
315
316 const bool brakingGlowVisible = isBraking() && speedInKmh() > 0;
317 m_leftBrakeGlow->setIsRenderable(brakingGlowVisible);
318 m_rightBrakeGlow->setIsRenderable(brakingGlowVisible);
319 }
320
321 void Car::updateTireWear(int step)
322 {
323 // Cache dx and dy.
324 m_dx = MCTrigonom::cos(angle());
325 m_dy = MCTrigonom::sin(angle());
326
327 // Cache speed in km/h.
328 m_absSpeed = physicsComponent().speed();
329 m_speedInKmh = static_cast<int>(m_absSpeed * 3.6f * 2.75f);
330
331 if (m_isHuman)
332 {
333 if (isBraking() || (isAccelerating() && m_steer != Steer::Neutral))
334 {
335 const float brakingTireWearFactor = 0.05f;
336 wearOutTires(step, brakingTireWearFactor);
337 }
338
339 const float offTrackTireWearFactor = 0.10f;
340
341 if (m_leftSideOffTrack)
342 {
343 static_pointer_cast<Tire>(m_leftFrontTire)->setIsOffTrack(true);
344 static_pointer_cast<Tire>(m_leftRearTire)->setIsOffTrack(true);
345
346 wearOutTires(step, offTrackTireWearFactor);
347 }
348 else
349 {
350 static_pointer_cast<Tire>(m_leftFrontTire)->setIsOffTrack(false);
351 static_pointer_cast<Tire>(m_leftRearTire)->setIsOffTrack(false);
352 }
353
354 if (m_rightSideOffTrack)
355 {
356 static_pointer_cast<Tire>(m_rightFrontTire)->setIsOffTrack(true);
357 static_pointer_cast<Tire>(m_rightRearTire)->setIsOffTrack(true);
358
359 wearOutTires(step, offTrackTireWearFactor);
360 }
361 else
362 {
363 static_pointer_cast<Tire>(m_rightFrontTire)->setIsOffTrack(false);
364 static_pointer_cast<Tire>(m_rightRearTire)->setIsOffTrack(false);
365 }
366 }
367 }
368
369 void Car::collisionEvent(MCCollisionEvent & event)
370 {
371 if (!event.collidingObject().isTriggerObject())
372 {
373 m_collisionEffectStack.push_back({ &event.collidingObject(), event.contactPoint() });
374 }
375
376 event.accept();
377 }
378
379 void Car::addDamage(float damage)
380 {
381 if (m_damageCapacity > damage)
382 {
383 m_damageCapacity -= damage;
384 }
385 else
386 {
387 m_damageCapacity = 0;
388 }
389
390 if (const float hardCrashDamageLimit = 3.5f; damage >= hardCrashDamageLimit)
391 {
392 m_hadHardCrash = true;
393 }
394 }
395
396 void Car::wearOutTires(int step, float factor)
397 {
398 if (Game::instance().difficultyProfile().hasTireWearOut())
399 {
400 if (const float wearOut = physicsComponent().velocity().lengthFast() * step * factor / 1000; m_tireWearOutCapacity >= wearOut)
401 {
402 m_tireWearOutCapacity -= wearOut;
403 }
404 else
405 {
406 m_tireWearOutCapacity = 0;
407 }
408 }
409 }
410
411 void Car::setBrakeEnabled(bool brakeEnabled)
412 {
413 m_brakeEnabled = brakeEnabled;
414
415 m_gearbox->setBrakeEnabled(brakeEnabled);
416 }
417
418 void Car::setAcceleratorEnabled(bool acceleratorEnabled)
419 {
420 m_acceleratorEnabled = acceleratorEnabled;
421
422 m_gearbox->setAcceleratorEnabled(acceleratorEnabled);
423 }
424
425 void Car::resetTireWear()
426 {
427 m_tireWearOutCapacity = m_initTireWearOutCapacity;
428 }
429
430 float Car::tireWearFactor() const
431 {
432 return 0.5f + m_tireWearOutCapacity * 0.5f / m_initTireWearOutCapacity;
433 }
434
435 float Car::tireWearLevel() const
436 {
437 return m_tireWearOutCapacity / m_initTireWearOutCapacity;
438 }
439
440 void Car::resetDamage()
441 {
442 m_damageCapacity = m_initDamageCapacity;
443 }
444
445 float Car::damageFactor() const
446 {
447 return 0.7f + (m_damageCapacity / m_initDamageCapacity) * 0.3f;
448 }
449
450 float Car::damageLevel() const
451 {
452 return m_damageCapacity / m_initDamageCapacity;
453 }
454
455 bool Car::hadHardCrash()
456 {
457 if (m_hadHardCrash)
458 {
459 m_hadHardCrash = false;
460 return true;
461 }
462 return false;
463 }
464
465 void Car::onStepTime(int step)
466 {
467 updateAnimations();
468
469 updateTireWear(step);
470
471 m_gearbox->update(speedInKmh());
472
473 if (m_gearbox->gear() == Gearbox::Gear::Forward && m_acceleratorEnabled)
474 {
475 accelerate();
476 }
477 else if (m_gearbox->gear() == Gearbox::Gear::Reverse && m_brakeEnabled)
478 {
479 accelerate(true);
480 }
481
482 doTireSpinEffect();
483 }
484
485 void Car::setLeftSideOffTrack(bool state)
486 {
487 // Enable off-track friction if left side is off the track.
488 m_leftSideOffTrack = state;
489 }
490
491 bool Car::leftSideOffTrack() const
492 {
493 return m_leftSideOffTrack;
494 }
495
496 void Car::setRightSideOffTrack(bool state)
497 {
498 // Enable off-track friction if right side is off the track.
499 m_rightSideOffTrack = state;
500 }
501
502 bool Car::rightSideOffTrack() const
503 {
504 return m_rightSideOffTrack;
505 }
506
507 bool Car::isOffTrack() const
508 {
509 return leftSideOffTrack() || rightSideOffTrack();
510 }
511
512 bool Car::isHuman() const
513 {
514 return m_isHuman;
515 }
516
517 void Car::setSoundEffectManager(CarSoundEffectManagerPtr soundEffectManager)
518 {
519 m_soundEffectManager = soundEffectManager;
520 }
521
522 CarSoundEffectManagerPtr Car::soundEffectManager() const
523 {
524 return m_soundEffectManager;
525 }
526
527 Car::~Car()
528 {
529 MCWorld::instance().forceRegistry().removeForceGenerators(*this);
530 }