-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombustionEngine.lua
More file actions
3366 lines (2867 loc) · 153 KB
/
combustionEngine.lua
File metadata and controls
3366 lines (2867 loc) · 153 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
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- This Source Code Form is subject to the terms of the bCDDL, v. 1.1.
-- If a copy of the bCDDL was not distributed with this
-- file, You can obtain one at http://beamng.com/bCDDL-1.1.txt
-- Module-level initialization
local function onModuleLoad()
print("\n")
print("========================================")
print("CUSTOM COMBUSTION ENGINE SCRIPT LOADED!")
print("File: lua/vehicle/powertrain/combustionEngine.lua")
print("Time: " .. os.date())
print("========================================")
print("\n")
end
-- Call the initialization
onModuleLoad()
local M = {}
M.outputPorts = {[1] = true} --set dynamically
M.deviceCategories = {engine = true}
local delayLine = rerequire("delayLine")
local max = math.max
local min = math.min
local abs = math.abs
local floor = math.floor
local random = math.random
local smoothmin = smoothmin
local rpmToAV = 0.104719755
local avToRPM = 9.549296596425384
local torqueToPower = 0.0001404345295653085
local psToWatt = 735.499
local hydrolockThreshold = 1.9
local function getTorqueData(device)
local curves = {}
local curveCounter = 1
local maxTorque = 0
local maxTorqueRPM = 0
local maxPower = 0
local maxPowerRPM = 0
local maxRPM = device.maxRPM
local turboCoefs = nil
local superchargerCoefs = nil
local nitrousTorques = nil
local torqueCurve = {}
local powerCurve = {}
for k, v in pairs(device.torqueCurve) do
if type(k) == "number" and k < maxRPM then
torqueCurve[k + 1] = v - device.friction * device.wearFrictionCoef * device.damageFrictionCoef - (device.dynamicFriction * device.wearDynamicFrictionCoef * device.damageDynamicFrictionCoef * k * rpmToAV)
powerCurve[k + 1] = torqueCurve[k + 1] * k * torqueToPower
if torqueCurve[k + 1] > maxTorque then
maxTorque = torqueCurve[k + 1]
maxTorqueRPM = k + 1
end
if powerCurve[k + 1] > maxPower then
maxPower = powerCurve[k + 1]
maxPowerRPM = k + 1
end
end
end
table.insert(curves, curveCounter, {torque = torqueCurve, power = powerCurve, name = "NA", priority = 10})
if device.nitrousOxideInjection.isExisting then
local torqueCurveNitrous = {}
local powerCurveNitrous = {}
nitrousTorques = device.nitrousOxideInjection.getAddedTorque()
for k, v in pairs(device.torqueCurve) do
if type(k) == "number" and k < maxRPM then
torqueCurveNitrous[k + 1] = v + (nitrousTorques[k] or 0) - device.friction * device.wearFrictionCoef * device.damageFrictionCoef - (device.dynamicFriction * device.wearDynamicFrictionCoef * device.damageDynamicFrictionCoef * k * rpmToAV)
powerCurveNitrous[k + 1] = torqueCurveNitrous[k + 1] * k * torqueToPower
if torqueCurveNitrous[k + 1] > maxTorque then
maxTorque = torqueCurveNitrous[k + 1]
maxTorqueRPM = k + 1
end
if powerCurveNitrous[k + 1] > maxPower then
maxPower = powerCurveNitrous[k + 1]
maxPowerRPM = k + 1
end
end
end
curveCounter = curveCounter + 1
table.insert(curves, curveCounter, {torque = torqueCurveNitrous, power = powerCurveNitrous, name = "N2O", priority = 20})
end
if device.turbocharger.isExisting then
local torqueCurveTurbo = {}
local powerCurveTurbo = {}
turboCoefs = device.turbocharger.getTorqueCoefs()
for k, v in pairs(device.torqueCurve) do
if type(k) == "number" and k < maxRPM then
torqueCurveTurbo[k + 1] = (v * (turboCoefs[k] or 0)) - device.friction * device.wearFrictionCoef * device.damageFrictionCoef - (device.dynamicFriction * device.wearDynamicFrictionCoef * device.damageDynamicFrictionCoef * k * rpmToAV)
powerCurveTurbo[k + 1] = torqueCurveTurbo[k + 1] * k * torqueToPower
if torqueCurveTurbo[k + 1] > maxTorque then
maxTorque = torqueCurveTurbo[k + 1]
maxTorqueRPM = k + 1
end
if powerCurveTurbo[k + 1] > maxPower then
maxPower = powerCurveTurbo[k + 1]
maxPowerRPM = k + 1
end
end
end
curveCounter = curveCounter + 1
table.insert(curves, curveCounter, {torque = torqueCurveTurbo, power = powerCurveTurbo, name = "Turbo", priority = 30})
end
if device.supercharger.isExisting then
local torqueCurveSupercharger = {}
local powerCurveSupercharger = {}
superchargerCoefs = device.supercharger.getTorqueCoefs()
for k, v in pairs(device.torqueCurve) do
if type(k) == "number" and k < maxRPM then
torqueCurveSupercharger[k + 1] = (v * (superchargerCoefs[k] or 0)) - device.friction * device.wearFrictionCoef * device.damageFrictionCoef - (device.dynamicFriction * device.wearDynamicFrictionCoef * device.damageDynamicFrictionCoef * k * rpmToAV)
powerCurveSupercharger[k + 1] = torqueCurveSupercharger[k + 1] * k * torqueToPower
if torqueCurveSupercharger[k + 1] > maxTorque then
maxTorque = torqueCurveSupercharger[k + 1]
maxTorqueRPM = k + 1
end
if powerCurveSupercharger[k + 1] > maxPower then
maxPower = powerCurveSupercharger[k + 1]
maxPowerRPM = k + 1
end
end
end
curveCounter = curveCounter + 1
table.insert(curves, curveCounter, {torque = torqueCurveSupercharger, power = powerCurveSupercharger, name = "SC", priority = 40})
end
if device.turbocharger.isExisting and device.supercharger.isExisting then
local torqueCurveFinal = {}
local powerCurveFinal = {}
for k, v in pairs(device.torqueCurve) do
if type(k) == "number" and k < maxRPM then
torqueCurveFinal[k + 1] = (v * (turboCoefs[k] or 0) * (superchargerCoefs[k] or 0)) - device.friction * device.wearFrictionCoef * device.damageFrictionCoef - (device.dynamicFriction * device.wearDynamicFrictionCoef * device.damageDynamicFrictionCoef * k * rpmToAV)
powerCurveFinal[k + 1] = torqueCurveFinal[k + 1] * k * torqueToPower
if torqueCurveFinal[k + 1] > maxTorque then
maxTorque = torqueCurveFinal[k + 1]
maxTorqueRPM = k + 1
end
if powerCurveFinal[k + 1] > maxPower then
maxPower = powerCurveFinal[k + 1]
maxPowerRPM = k + 1
end
end
end
curveCounter = curveCounter + 1
table.insert(curves, curveCounter, {torque = torqueCurveFinal, power = powerCurveFinal, name = "Turbo + SC", priority = 50})
end
if device.turbocharger.isExisting and device.nitrousOxideInjection.isExisting then
local torqueCurveFinal = {}
local powerCurveFinal = {}
for k, v in pairs(device.torqueCurve) do
if type(k) == "number" and k < maxRPM then
torqueCurveFinal[k + 1] = (v * (turboCoefs[k] or 0) + (nitrousTorques[k] or 0)) - device.friction * device.wearFrictionCoef * device.damageFrictionCoef - (device.dynamicFriction * device.wearDynamicFrictionCoef * device.damageDynamicFrictionCoef * k * rpmToAV)
powerCurveFinal[k + 1] = torqueCurveFinal[k + 1] * k * torqueToPower
if torqueCurveFinal[k + 1] > maxTorque then
maxTorque = torqueCurveFinal[k + 1]
maxTorqueRPM = k + 1
end
if powerCurveFinal[k + 1] > maxPower then
maxPower = powerCurveFinal[k + 1]
maxPowerRPM = k + 1
end
end
end
curveCounter = curveCounter + 1
table.insert(curves, curveCounter, {torque = torqueCurveFinal, power = powerCurveFinal, name = "Turbo + N2O", priority = 60})
end
if device.supercharger.isExisting and device.nitrousOxideInjection.isExisting then
local torqueCurveFinal = {}
local powerCurveFinal = {}
for k, v in pairs(device.torqueCurve) do
if type(k) == "number" and k < maxRPM then
torqueCurveFinal[k + 1] = (v * (superchargerCoefs[k] or 0) + (nitrousTorques[k] or 0)) - device.friction * device.wearFrictionCoef * device.damageFrictionCoef - (device.dynamicFriction * device.wearDynamicFrictionCoef * device.damageDynamicFrictionCoef * k * rpmToAV)
powerCurveFinal[k + 1] = torqueCurveFinal[k + 1] * k * torqueToPower
if torqueCurveFinal[k + 1] > maxTorque then
maxTorque = torqueCurveFinal[k + 1]
maxTorqueRPM = k + 1
end
if powerCurveFinal[k + 1] > maxPower then
maxPower = powerCurveFinal[k + 1]
maxPowerRPM = k + 1
end
end
end
curveCounter = curveCounter + 1
table.insert(curves, curveCounter, {torque = torqueCurveFinal, power = powerCurveFinal, name = "SC + N2O", priority = 70})
end
if device.turbocharger.isExisting and device.supercharger.isExisting and device.nitrousOxideInjection.isExisting then
local torqueCurveFinal = {}
local powerCurveFinal = {}
for k, v in pairs(device.torqueCurve) do
if type(k) == "number" and k < maxRPM then
torqueCurveFinal[k + 1] = (v * (turboCoefs[k] or 0) * (superchargerCoefs[k] or 0) + (nitrousTorques[k] or 0)) - device.friction * device.wearFrictionCoef * device.damageFrictionCoef - (device.dynamicFriction * device.wearDynamicFrictionCoef * device.damageDynamicFrictionCoef * k * rpmToAV)
powerCurveFinal[k + 1] = torqueCurveFinal[k + 1] * k * torqueToPower
if torqueCurveFinal[k + 1] > maxTorque then
maxTorque = torqueCurveFinal[k + 1]
maxTorqueRPM = k + 1
end
if powerCurveFinal[k + 1] > maxPower then
maxPower = powerCurveFinal[k + 1]
maxPowerRPM = k + 1
end
end
end
curveCounter = curveCounter + 1
table.insert(curves, curveCounter, {torque = torqueCurveFinal, power = powerCurveFinal, name = "Turbo + SC + N2O", priority = 80})
end
table.sort(
curves,
function(a, b)
local ra, rb = a.priority, b.priority
if ra == rb then
return a.name < b.name
else
return ra > rb
end
end
)
local dashes = {nil, {10, 4}, {8, 3, 4, 3}, {6, 3, 2, 3}, {5, 3}}
for k, v in ipairs(curves) do
v.dash = dashes[k]
v.width = 2
end
return {maxRPM = maxRPM, curves = curves, maxTorque = maxTorque, maxPower = maxPower, maxTorqueRPM = maxTorqueRPM, maxPowerRPM = maxPowerRPM, finalCurveName = 1, deviceName = device.name, vehicleID = obj:getId()}
end
local function sendTorqueData(device, data)
if not data then
data = device:getTorqueData()
end
guihooks.trigger("TorqueCurveChanged", data)
end
local function scaleFrictionInitial(device, friction)
device.friction = device.initialFriction * friction
end
local function scaleFriction(device, friction)
device.friction = device.friction * friction
end
local function scaleOutputTorque(device, state, maxReduction)
--scale torque ouput to some minimum, but do not let that minimum increase the actual scale (otherwise a min of 0.2 could "revive" an engine that sits at 0 scale already)
device.outputTorqueState = max(device.outputTorqueState * state, min(maxReduction or 0, device.outputTorqueState))
damageTracker.setDamage("engine", "engineReducedTorque", device.outputTorqueState < 1)
end
local function disable(device)
device.outputTorqueState = 0
device.isDisabled = true
device.starterDisabled = false
--[[ if device.starterEngagedCoef > 0 then
device.starterEngagedCoef = 0
obj:stopSFX(device.engineMiscSounds.starterSoundEngine)
if device.engineMiscSounds.starterSoundExhaust then
obj:stopSFX(device.engineMiscSounds.starterSoundExhaust)
end
end]]
damageTracker.setDamage("engine", "engineDisabled", true)
end
local function enable(device)
device.outputTorqueState = 1
device.isDisabled = false
device.starterDisabled = false
device.lastMisfireTime = 0
device.misfireActive = false
damageTracker.setDamage("engine", "engineDisabled", false)
end
local function lockUp(device)
device.outputTorqueState = 1
device.outputAVState = 1
device.isDisabled = false
device.isBroken = false
device.starterDisabled = false
if device.starterEngagedCoef > 0 then
device.starterEngagedCoef = 0
obj:stopSFX(device.engineMiscSounds.starterSoundEngine)
if device.engineMiscSounds.starterSoundExhaust then
obj:stopSFX(device.engineMiscSounds.starterSoundExhaust)
end
end
damageTracker.setDamage("powertrain", device.name, true)
damageTracker.setDamage("engine", "engineLockedUp", true)
end
local function updateSounds(device, dt)
local rpm = device.soundRPMSmoother:get(abs(device.outputAV1 * avToRPM), dt)
local maxCurrentTorque = (device.torqueCurve[floor(rpm)] or 1) * device.intakeAirDensityCoef
local engineLoad = device.soundLoadSmoother:get(device.instantEngineLoad, dt)
local baseLoad = 0.3 * min(device.idleTorque / maxCurrentTorque, 1)
engineLoad = max(engineLoad - baseLoad, 0) / (1 - baseLoad)
local volumeCoef = rpm > 0.1 and device.engineVolumeCoef or 0
if device.engineSoundID then
local scaledEngineLoad = engineLoad * (device.soundMaxLoadMix - device.soundMinLoadMix) + device.soundMinLoadMix
local fundamentalFreq = sounds.hzToFMODHz(rpm * device.soundConfiguration.engine.params.fundamentalFrequencyRPMCoef)
obj:setEngineSound(device.engineSoundID, rpm, scaledEngineLoad, fundamentalFreq, volumeCoef)
end
if device.engineSoundIDExhaust then
local minLoad = device.soundMinLoadMixExhaust or device.soundMinLoadMix
local scaledEngineLoadExhaust = engineLoad * ((device.soundMaxLoadMixExhaust or device.soundMaxLoadMix) - minLoad) + minLoad
local fundamentalFreqExhaust = sounds.hzToFMODHz(rpm * device.soundConfiguration.exhaust.params.fundamentalFrequencyRPMCoef)
obj:setEngineSound(device.engineSoundIDExhaust, rpm, scaledEngineLoadExhaust, fundamentalFreqExhaust, volumeCoef)
end
device.turbocharger.updateSounds()
device.supercharger.updateSounds()
end
local function checkHydroLocking(device, dt)
local wetspeed = 0.001
local dryspeed = -5
if device.floodLevel > hydrolockThreshold then
return
end
-- engine starts flooding if ALL of the waterDamage nodes are underwater
local isFlooding = device.canFlood
for _, n in ipairs(device.waterDamageNodes) do
isFlooding = isFlooding and obj:inWater(n)
if not isFlooding then
break
end
end
damageTracker.setDamage("engine", "engineIsHydrolocking", isFlooding)
-- calculate flooding speed (positive) or drying speed (negative, and arbitrarily slower than flooding after some testing)
local floodSpeed = (isFlooding and wetspeed or dryspeed) * (abs(device.outputAV1) / device.maxAV) -- TODO use torque instead of RPM (when torque calculation becomes more realistic)
-- actual check for engine dying. in the future we may want to implement stalling too
device.floodLevel = min(1, max(0, device.floodLevel + dt * floodSpeed))
if device.floodLevel > hydrolockThreshold then
damageTracker.setDamage("engine", "engineHydrolocked", true)
-- avoid piston movement, simulate broken connecting rods
guihooks.message("vehicle.combustionEngine.engineHydrolocked", 4, "vehicle.damage.flood")
return
end
-- we compute the flooding percentage in steps of 1%...
local currPercent = floor(0.01 + device.floodLevel * 100)
-- ...and use that to check when to perform UI updates
if currPercent ~= device.prevFloodPercent then
if currPercent > device.prevFloodPercent then
guihooks.message({txt = "vehicle.combustionEngine.engineFlooding", context = {percent = currPercent}}, 4, "vehicle.damage.flood")
else
if currPercent < 1 then
guihooks.message("vehicle.combustionEngine.engineDried", 4, "vehicle.damage.flood")
else
guihooks.message({txt = "vehicle.combustionEngine.engineDrying", context = {percent = currPercent}}, 4, "vehicle.damage.flood")
end
end
end
device.prevFloodPercent = currPercent
end
local function updateEnergyStorageRatios(device)
for _, s in pairs(device.registeredEnergyStorages) do
local storage = energyStorage.getStorage(s)
if storage and storage.energyType == device.requiredEnergyType then
if storage.storedEnergy > 0 then
device.energyStorageRatios[storage.name] = 1 / device.storageWithEnergyCounter
else
device.energyStorageRatios[storage.name] = 0
end
end
end
end
local function updateFuelUsage(device)
if not device.energyStorage then
return
end
local hasFuel = false
local previousTankCount = device.storageWithEnergyCounter
local remainingFuelRatio = 0
for _, s in pairs(device.registeredEnergyStorages) do
local storage = energyStorage.getStorage(s)
if storage and storage.energyType == device.requiredEnergyType then
local previous = device.previousEnergyLevels[storage.name]
storage.storedEnergy = max(storage.storedEnergy - (device.spentEnergy * device.energyStorageRatios[storage.name]), 0)
if previous > 0 and storage.storedEnergy <= 0 then
device.storageWithEnergyCounter = device.storageWithEnergyCounter - 1
elseif previous <= 0 and storage.storedEnergy > 0 then
device.storageWithEnergyCounter = device.storageWithEnergyCounter + 1
end
device.previousEnergyLevels[storage.name] = storage.storedEnergy
hasFuel = hasFuel or storage.storedEnergy > 0
remainingFuelRatio = remainingFuelRatio + storage.remainingRatio
end
end
if previousTankCount ~= device.storageWithEnergyCounter then
device:updateEnergyStorageRatios()
end
if not hasFuel and device.hasFuel then
device:disable()
elseif hasFuel and not device.hasFuel then
device:enable()
end
device.hasFuel = hasFuel
device.remainingFuelRatio = remainingFuelRatio / device.storageWithEnergyCounter
end
local function updateGFX(device, dt)
if device.stallBuzzerSoundID then -- Check if the source was created successfully at init
-- Condition: Ignition is ON, but engine RPM is below a threshold (e.g., 50% of idle)
local shouldBuzzerBeActive = (device.ignitionCoef > 0) and (device.outputAV1 < device.starterMaxAV * 1.1)
-- Start/Stop the buzzer based on state change
if shouldBuzzerBeActive and not device.stallBuzzerActive then
obj:playSFX(device.stallBuzzerSoundID) -- Play the persistent source
device.stallBuzzerActive = true
-- log('D', 'StallBuzzer', 'Buzzer ON') -- Optional debug
elseif not shouldBuzzerBeActive and device.stallBuzzerActive then
obj:stopSFX(device.stallBuzzerSoundID) -- Stop the persistent source
device.stallBuzzerActive = false
-- log('D', 'StallBuzzer', 'Buzzer OFF') -- Optional debug
end
-- Adjust pitch if the buzzer is active
if device.stallBuzzerActive then
local targetPitch = 1.0
if device.starterEngagedCoef > 0 then
-- Lower pitch slightly when starter is cranking
targetPitch = 1.0 - device.stallBuzzerCrankingPitch
end
obj:setPitch(device.stallBuzzerSoundID, targetPitch) -- Set pitch every frame while active
end
end
device:updateFuelUsage()
device.outputRPM = device.outputAV1 * avToRPM
device.starterThrottleKillTimer = max(device.starterThrottleKillTimer - dt, 0)
device.lastStarterThrottleKillTimerEnd = max((device.lastStarterThrottleKillTimerEnd or 0) - dt*0.1, 0)
if device.starterEngagedCoef > 0 then
-- if device.starterBattery then
-- local starterSpentEnergy = 1 / guardZero(abs(device.outputAV1)) * dt * device.starterTorque / 0.5 --0.5 efficiency
-- device.starterBattery.storedEnergy = device.starterBattery.storedEnergy - starterSpentEnergy
-- --print(starterSpentEnergy)
-- --print(device.starterBattery.remainingRatio)
-- end
-- device.starterThrottleKillCoef = 1-device.starterThrottleKillTimer / device.starterThrottleKillTimerStart + math.max(linearScale(device.starterThrottleKillTimer, device.starterThrottleKillTimerStart, 0, 0, 3), 0.2)-0.2
local killCoefFac = 1
if device.starterThrottleKillTimer > 0 then
killCoefFac = 1 - device.starterThrottleKillTimer/device.starterThrottleKillTimerStart
device.starterIgnitionErrorChance = killCoefFac*6*linearScale(device.thermals.engineBlockTemperature, -270, 15, 1, 0)
killCoefFac = math.pow(killCoefFac, 8)*0.05
end
device.starterThrottleKillCoef = device.starterThrottleKillCoefSmoother:get(killCoefFac, dt)
-- use lower starter max av multiplier in case the engine just doesnt start
-- occasionally this would result in the engine starting and immediately shutting down, so its disabled
local starterMaxAVMultiplier = 1.1 --math.min(1.1, device.outputAV1/device.starterMaxAV+(device.starterThrottleKillTimer == 0 and 0 or math.max(2.0, 1.1)))
-- Initialize smoothed pitch value if not exists
device.smoothedPitch = device.smoothedPitch or 0.5
-- Calculate pitch with a more natural curve at low RPMs
-- Use a logarithmic curve to make low RPMs sound more natural
local rpmRatio = device.outputAV1 / (device.starterMaxAV * starterMaxAVMultiplier)
-- Apply a logarithmic curve that's more natural for engine sounds
-- This will make the pitch increase more slowly at lower RPMs
local curvedRatio = math.log(1 + rpmRatio * 2) / math.log(3)
-- Set pitch range for more natural sound
local minPitch = 0.0 -- Lower minimum pitch for deeper sound at low RPM
local maxPitch = 0.8 -- Slightly reduced max pitch for more realism
-- Calculate final pitch with limits and apply a small offset to prevent extreme lows
local targetPitch = minPitch + (maxPitch - minPitch) * curvedRatio
-- Apply smoothing to prevent sudden pitch changes
local smoothingFactor = 0.5
device.smoothedPitch = device.smoothedPitch or targetPitch
device.smoothedPitch = device.smoothedPitch + (targetPitch - device.smoothedPitch) * smoothingFactor
-- Apply the smoothed pitch to the sounds
obj:setPitch(device.engineMiscSounds.starterSoundEngine, device.smoothedPitch)
if device.engineMiscSounds.starterSoundExhaust then
obj:setPitch(device.engineMiscSounds.starterSoundExhaust, device.smoothedPitch)
end
if device.outputAV1 > device.starterMaxAV * 1.1 then
device.starterThrottleKillTimer = 0
device.starterEngagedCoef = 0
device.starterThrottleKillCoef = 1
device.starterThrottleKillCoefSmoother:set(device.starterThrottleKillCoef)
device.starterDisabled = false
device.starterIgnitionErrorChance = 0
obj:stopSFX(device.engineMiscSounds.starterSoundEngine)
if device.engineMiscSounds.starterSoundExhaust then
obj:stopSFX(device.engineMiscSounds.starterSoundExhaust)
end
end
end
-- Get current RPM
local currentRPM = device.outputAV1 * avToRPM
-- Update battery state
local dt = 1/60 -- Fixed timestep for battery updates
-- Local function to initialize battery parameters
local function initBattery(device, jbeamData)
-- Set battery parameters based on system voltage (12V or 24V)
local is24V = device.batterySystemVoltage == 24
-- Set voltage thresholds based on system voltage
device.batteryNominalVoltage = is24V and 27.6 or 13.8 -- 27.6V for 24V, 13.8V for 12V when fully charged
device.batteryMinVoltage = is24V and 18.0 or 9.0 -- 18V for 24V, 9V for 12V systems
device.batteryCutoffVoltage = is24V and 16.0 or 8.0 -- Absolute minimum voltage before complete cutoff
device.batteryWarningVoltage = is24V and 22.0 or 11.0 -- Voltage when warning indicators activate
device.batteryLowVoltage = is24V and 20.0 or 10.0 -- Voltage when systems start to fail
-- Set charge and drain rates based on system voltage
device.batteryChargeRate = is24V and 1.0 or 0.5 -- Higher charge rate for 24V systems
device.batteryDrainRate = is24V and 30.0 or 15.0 -- Base drain rate when cranking (A)
-- Get battery capacity from vehicle battery if available
if electrics.values.batteryCapacity then
device.batteryCapacity = electrics.values.batteryCapacity
else
-- Fallback to JBeam value or default (100Ah)
device.batteryCapacity = jbeamData.batteryCapacity or 100.0
end
-- Initialize battery charge from vehicle state if available
if electrics.values.batteryCharge then
device.batteryCharge = electrics.values.batteryCharge
else
-- Start with full charge by default
device.batteryCharge = 1.0
end
-- Log battery initialization
log('I', 'combustionEngine.initBattery',
string.format('Battery initialized: %.1fV system, %.1fAh capacity',
device.batterySystemVoltage, device.batteryCapacity))
end
-- Ensure battery parameters are initialized
if not device.batteryNominalVoltage then
-- Initialize battery if not already done
local jbeamData = device.jbeamData or {}
initBattery(device, jbeamData)
end
-- Update battery state based on engine and starter status
local starterActive = device.starterEngagedCoef > 0
local engineRunning = device.outputAV1 > device.starterMaxAV * 1.1
-- Default values in case initialization failed
device.batteryCharge = device.batteryCharge or 1.0
device.batteryDrainScale = device.batteryDrainScale or 1.0
if starterActive and not engineRunning then
-- Drain battery when starting (higher drain for 24V systems)
local drainRate = (device.batteryDrainRate or 15.0) * (device.batteryDrainScale or 1.0)
device.batteryCharge = math.max(0, device.batteryCharge - (drainRate * dt) / ((device.batteryCapacity or 100.0) * 3600))
device.batteryLoad = drainRate -- Track current load in Amps
elseif engineRunning then
-- Recharge battery when engine is running above idle
-- Charge rate is higher for 24V systems and scales with RPM
local chargeRate = (device.batteryChargeRate or 0.5) * (device.outputAV1 / math.max(1, device.idleAV))
device.batteryCharge = math.min(1.0, device.batteryCharge + (chargeRate * dt) / 3600)
device.batteryLoad = -chargeRate -- Negative load indicates charging
else
device.batteryLoad = 0 -- No load when engine is off and starter not engaged
end
-- Calculate battery voltage (scales with charge level using a curve)
-- Use safe defaults if initialization failed
local is24V = (device.batterySystemVoltage or 12) == 24
local minVoltage = device.batteryMinVoltage or (is24V and 18.0 or 9.0)
local maxVoltage = device.batteryNominalVoltage or (is24V and 27.6 or 13.8)
local cutoffVoltage = device.batteryCutoffVoltage or (is24V and 16.0 or 8.0)
-- Ensure we have valid values
minVoltage = tonumber(minVoltage) or (is24V and 18.0 or 9.0)
maxVoltage = tonumber(maxVoltage) or (is24V and 27.6 or 13.8)
cutoffVoltage = tonumber(cutoffVoltage) or (is24V and 16.0 or 8.0)
-- Ensure max > min
if maxVoltage <= minVoltage then
maxVoltage = minVoltage + (is24V and 10.0 or 5.0)
end
-- Calculate voltage with charge curve (more realistic than linear)
local charge = math.max(0, math.min(1, device.batteryCharge or 1.0))
local chargeCurve = math.pow(charge, 0.7) -- More pronounced voltage drop at lower charge
device.batteryVoltage = minVoltage + (maxVoltage - minVoltage) * chargeCurve
-- Ensure voltage stays within bounds
device.batteryVoltage = math.max(cutoffVoltage, math.min(maxVoltage, device.batteryVoltage))
-- Calculate battery voltage factor for lights (0.5 to 1.0 range)
-- Lights will start dimming below warning voltage
local dimStartVoltage = device.batteryWarningVoltage or (is24V and 22.0 or 11.0)
dimStartVoltage = tonumber(dimStartVoltage) or (is24V and 22.0 or 11.0)
-- Ensure dimStartVoltage is between cutoff and max voltage
dimStartVoltage = math.max(cutoffVoltage * 1.1, math.min(maxVoltage * 0.9, dimStartVoltage))
-- Calculate full brightness voltage (slightly below nominal)
local fullBrightnessVoltage = maxVoltage * 0.95 -- 95% of nominal
-- Ensure fullBrightnessVoltage is above dimStartVoltage
fullBrightnessVoltage = math.max(dimStartVoltage * 1.05, fullBrightnessVoltage)
-- Calculate brightness factor with safety checks
local batteryBrightnessFactor = linearScale(
math.max(cutoffVoltage, math.min(maxVoltage, device.batteryVoltage)),
dimStartVoltage,
fullBrightnessVoltage,
0.5, -- Minimum brightness factor
1.0 -- Maximum brightness factor
)
-- Update electrical system with current battery state
if electrics.values then
electrics.values.batteryVoltage = device.batteryVoltage
electrics.values.batteryCharge = device.batteryCharge
end
batteryBrightnessFactor = math.max(0.2, math.min(1.0, batteryBrightnessFactor)) -- Clamp to 20-100%
-- Base brightness based on RPM - starts dim and increases with RPM
-- At 0 RPM: 0.4 (dim)
-- At cranking RPM (200): ~0.5
-- At idle (800): ~0.76
-- At max RPM: 0.8
local baseBrightness = linearScale(currentRPM, 0, device.maxRPM, 0.6, 1.0) * batteryBrightnessFactor
-- Starter effect - when cranking, we want to see the brightness pulse with the engine
-- This creates a flickering effect that gets faster as the engine speeds up
local pulseEffect = 2.0
if device.starterEngagedCoef > 0 then
-- More noticeable pulsing during cranking
local pulseFrequency = math.max(currentRPM * 0.05, 0.3) -- Slower pulsing at low RPM
local pulseAmplitude = 0.8 -- How much the brightness varies (smaller = less variation)
local basePulse = math.sin(currentRPM * 0.1 * math.pi)
pulseEffect = 1 + pulseAmplitude * basePulse
end
-- Combine effects
-- When cranking, we want the brightness to be mostly controlled by RPM
-- but with the pulsing effect on top
local brightness = baseBrightness * pulseEffect
-- Calculate electrical load coefficient based on battery state and brightness
-- Lower battery voltage will reduce the electrical load coefficient more
local loadWarnVoltage = device.batteryWarningVoltage * 0.85 -- Start warning slightly earlier for load reduction
local loadMinVoltage = device.batteryLowVoltage * 0.75 -- Minimum voltage for load reduction
-- Scale based on system voltage
local batteryLoadFactor = linearScale(device.batteryVoltage,
loadMinVoltage,
loadWarnVoltage,
0.5, 1.0)
batteryLoadFactor = math.max(0.5, math.min(1.0, batteryLoadFactor)) -- Clamp to 50-100%
-- Apply battery load factor to brightness and ensure we stay within reasonable bounds
electrics.values.electricalLoadCoef = math.min(math.max(brightness * batteryLoadFactor, 0.3), 1.0)
-- Update battery drain scale based on electrical load (higher load = faster drain)
device.batteryDrainScale = 0.5 + (electrics.values.electricalLoadCoef * 1.5) -- 0.5x to 2.0x drain rate
device.starterIgnitionErrorTimer = device.starterIgnitionErrorTimer - dt
if device.starterIgnitionErrorTimer <= 0 then
device.starterIgnitionErrorTimer = math.random(device.starterIgnitionErrorInterval) * 0.1
device.starterIgnitionErrorActive = math.random() < device.starterIgnitionErrorChance
end
device.starterIgnitionErrorCoef = 1
if device.starterIgnitionErrorActive then
device.starterIgnitionErrorCoef = device.starterIgnitionErrorSmoother:getUncapped(math.random(), dt)
end
device.slowIgnitionErrorTimer = device.slowIgnitionErrorTimer - dt
if device.slowIgnitionErrorTimer <= 0 then
device.slowIgnitionErrorTimer = math.random(device.slowIgnitionErrorInterval) * 0.1
device.slowIgnitionErrorActive = math.random() < device.slowIgnitionErrorChance
end
device.slowIgnitionErrorCoef = 1
if device.slowIgnitionErrorActive then
device.slowIgnitionErrorCoef = device.slowIgnitionErrorSmoother:getUncapped(math.random(), dt)
end
local lowFuelIgnitionErrorChance = linearScale(device.remainingFuelRatio, 0.01, 0, 0, 0.4)
local fastIgnitionErrorCoef = device.fastIgnitionErrorSmoother:getUncapped(math.random(), dt)
device.fastIgnitionErrorCoef = fastIgnitionErrorCoef < (device.fastIgnitionErrorChance + lowFuelIgnitionErrorChance) and 0 or 1
if device.shutOffSoundRequested and device.outputAV1 < device.idleAV * 0.95 and device.outputAV1 > device.idleAV * 0.5 then
device.shutOffSoundRequested = false
if device.engineMiscSounds.shutOffSoundEngine then
obj:cutSFX(device.engineMiscSounds.shutOffSoundEngine)
obj:playSFX(device.engineMiscSounds.shutOffSoundEngine)
end
if device.engineMiscSounds.shutOffSoundExhaust then
obj:cutSFX(device.engineMiscSounds.shutOffSoundExhaust)
obj:playSFX(device.engineMiscSounds.shutOffSoundExhaust)
end
end
if device.outputAV1 < device.starterMaxAV * 0.8 and device.ignitionCoef > 0 then
device.stallTimer = max(device.stallTimer - dt, 0)
if device.stallTimer <= 0 and not device.isStalled then
device.isStalled = true
end
else
device.isStalled = false
device.stallTimer = 1
end
device.revLimiterWasActiveTimer = min(device.revLimiterWasActiveTimer + dt, 1000)
local rpmTooHigh = abs(device.outputAV1) > device.maxPhysicalAV
damageTracker.setDamage("engine", "overRevDanger", rpmTooHigh)
if rpmTooHigh then
device.overRevDamage = min(max(device.overRevDamage + (abs(device.outputAV1) - device.maxPhysicalAV) * dt / device.maxOverRevDamage, 0), 1)
local lockupChance = random(60, 100) * 0.01
local valveHitChance = random(10, 60) * 0.01
if lockupChance <= device.overRevDamage and not damageTracker.getDamage("engine", "catastrophicOverrevDamage") then
device:lockUp()
damageTracker.setDamage("engine", "catastrophicOverrevDamage", true)
guihooks.message({txt = "vehicle.combustionEngine.engineCatastrophicOverrevDamage", context = {}}, 4, "vehicle.damage.catastrophicOverrev")
if #device.engineBlockNodes >= 2 then
sounds.playSoundOnceFollowNode("event:>Vehicle>Failures>engine_explode", device.engineBlockNodes[1], 1)
for i = 1, 50 do
local rnd = random()
obj:addParticleByNodesRelative(device.engineBlockNodes[2], device.engineBlockNodes[1], i * rnd, 43, 0, 1)
obj:addParticleByNodesRelative(device.engineBlockNodes[2], device.engineBlockNodes[1], i * rnd, 39, 0, 1)
obj:addParticleByNodesRelative(device.engineBlockNodes[2], device.engineBlockNodes[1], -i * rnd, 43, 0, 1)
obj:addParticleByNodesRelative(device.engineBlockNodes[2], device.engineBlockNodes[1], -i * rnd, 39, 0, 1)
end
end
end
if valveHitChance <= device.overRevDamage then
device:scaleOutputTorque(0.98, 0.2)
damageTracker.setDamage("engine", "mildOverrevDamage", true)
guihooks.message({txt = "vehicle.combustionEngine.engineMildOverrevDamage", context = {}}, 4, "vehicle.damage.mildOverrev")
end
end
if device.maxTorqueRating > 0 then
damageTracker.setDamage("engine", "overTorqueDanger", device.combustionTorque > device.maxTorqueRating)
if device.combustionTorque > device.maxTorqueRating then
local torqueDifference = device.combustionTorque - device.maxTorqueRating
device.overTorqueDamage = min(device.overTorqueDamage + torqueDifference * dt, device.maxOverTorqueDamage)
if device.overTorqueDamage >= device.maxOverTorqueDamage and not damageTracker.getDamage("engine", "catastrophicOverTorqueDamage") then
device:lockUp()
damageTracker.setDamage("engine", "catastrophicOverTorqueDamage", true)
guihooks.message({txt = "vehicle.combustionEngine.engineCatastrophicOverTorqueDamage", context = {}}, 4, "vehicle.damage.catastrophicOverTorque")
if #device.engineBlockNodes >= 2 then
sounds.playSoundOnceFollowNode("event:>Vehicle>Failures>engine_explode", device.engineBlockNodes[1], 1)
for i = 1, 3 do
local rnd = random()
obj:addParticleByNodesRelative(device.engineBlockNodes[2], device.engineBlockNodes[1], i * rnd * 3, 43, 0, 9)
obj:addParticleByNodesRelative(device.engineBlockNodes[2], device.engineBlockNodes[1], i * rnd * 3, 39, 0, 9)
obj:addParticleByNodesRelative(device.engineBlockNodes[2], device.engineBlockNodes[1], -i * rnd * 3, 43, 0, 9)
obj:addParticleByNodesRelative(device.engineBlockNodes[2], device.engineBlockNodes[1], -i * rnd * 3, 39, 0, 9)
obj:addParticleByNodesRelative(device.engineBlockNodes[2], device.engineBlockNodes[1], i * rnd * 3, 56, 0, 1)
obj:addParticleByNodesRelative(device.engineBlockNodes[2], device.engineBlockNodes[1], i * rnd * 3, 57, 0, 1)
obj:addParticleByNodesRelative(device.engineBlockNodes[2], device.engineBlockNodes[1], i * rnd * 3, 58, 0, 1)
end
end
end
end
end
--calculate the actual current idle torque to check for lockup conditions due to high friction
local idleThrottle = device.maxIdleThrottle
local idleTorque = (device.torqueCurve[floor(abs(device.idleAV) * avToRPM)] or 0) * device.intakeAirDensityCoef
local idleThrottleMap = min(max(idleThrottle + idleThrottle * device.maxPowerThrottleMap / (idleTorque * device.forcedInductionCoef * abs(device.outputAV1) + 1e-30) * (1 - idleThrottle), 0), 1)
idleTorque = ((idleTorque * device.forcedInductionCoef * idleThrottleMap) + device.nitrousOxideTorque)
local finalFriction = device.friction * device.wearFrictionCoef * device.damageFrictionCoef
local finalDynamicFriction = device.dynamicFriction * device.wearDynamicFrictionCoef * device.damageDynamicFrictionCoef
local frictionTorque = finalFriction - (finalDynamicFriction * device.idleAV)
if not device.isDisabled and (frictionTorque > device.maxTorque or (device.outputAV1 < device.idleAV * 0.5 and frictionTorque > idleTorque * 0.95)) then
--if our friction is higher than the biggest torque we can output, the engine WILL lock up automatically
--however, we need to communicate that with other subsystems to prevent issues, so in this case we ADDITIONALLY lock it up manually
--device:lockUp()
end
local compressionBrakeCoefAdjusted = device.throttle > 0 and 0 or device.compressionBrakeCoefDesired
if compressionBrakeCoefAdjusted ~= device.compressionBrakeCoefActual then
device.compressionBrakeCoefActual = compressionBrakeCoefAdjusted
device:setEngineSoundParameter(device.engineSoundIDExhaust, "compression_brake_coef", device.compressionBrakeCoefActual, "exhaust")
end
local antiLagCoefAdjusted = device.antiLagCoefDesired
if antiLagCoefAdjusted ~= device.antiLagCoefActual then
device.antiLagCoefActual = antiLagCoefAdjusted
device:setEngineSoundParameter(device.engineSoundIDExhaust, "triggerAntilag", device.antiLagCoefActual, "exhaust")
device.turbocharger.setAntilagCoef(device.antiLagCoefActual)
end
device.exhaustFlowDelay:push(device.engineLoad)
--push our summed fuels into the delay lines (shift fuel does not have any delay and therefore does not need a line)
if device.shiftAfterFireFuel <= 0 then
if device.instantAfterFireFuel > 0 then
device.instantAfterFireFuelDelay:push(device.instantAfterFireFuel / dt)
end
if device.sustainedAfterFireFuel > 0 then
device.sustainedAfterFireFuelDelay:push(device.sustainedAfterFireFuel / dt)
end
end
if device.sustainedAfterFireTimer > 0 then
device.sustainedAfterFireTimer = device.sustainedAfterFireTimer - dt
elseif device.instantEngineLoad > 0 then
device.sustainedAfterFireTimer = device.sustainedAfterFireTime
end
device.nitrousOxideTorque = 0 -- reset N2O torque
device.engineVolumeCoef = 1 -- reset volume coef
device.invBurnEfficiencyCoef = 1 -- reset burn efficiency coef
device.turbocharger.updateGFX(dt)
device.supercharger.updateGFX(dt)
device.nitrousOxideInjection.updateGFX(dt)
device.thermals.updateGFX(dt)
device.intakeAirDensityCoef = obj:getRelativeAirDensity()
device:checkHydroLocking(dt)
device.idleAVReadError = device.idleAVReadErrorSmoother:getUncapped(device.idleAVReadErrorRangeHalf - random(device.idleAVReadErrorRange), dt) * device.wearIdleAVReadErrorRangeCoef * device.damageIdleAVReadErrorRangeCoef
device.idleAVStartOffset = device.idleAVStartOffsetSmoother:get(device.idleAV * device.idleStartCoef * device.starterEngagedCoef, dt)
device.maxIdleAV = device.idleAV + device.idleAVReadErrorRangeHalf * device.wearIdleAVReadErrorRangeCoef * device.damageIdleAVReadErrorRangeCoef
device.minIdleAV = device.idleAV - device.idleAVReadErrorRangeHalf * device.wearIdleAVReadErrorRangeCoef * device.damageIdleAVReadErrorRangeCoef
device.spentEnergy = 0
device.spentEnergyNitrousOxide = 0
device.engineWorkPerUpdate = 0
device.frictionLossPerUpdate = 0
device.pumpingLossPerUpdate = 0
device.instantAfterFireFuel = 0
device.sustainedAfterFireFuel = 0
device.shiftAfterFireFuel = 0
device.continuousAfterFireFuel = 0
end
local function setTempRevLimiter(device, revLimiterAV, maxOvershootAV)
device.tempRevLimiterAV = revLimiterAV
device.tempRevLimiterMaxAVOvershoot = maxOvershootAV or device.tempRevLimiterAV * 0.01
device.invTempRevLimiterRange = 1 / device.tempRevLimiterMaxAVOvershoot
device.isTempRevLimiterActive = true
end
local function resetTempRevLimiter(device)
device.tempRevLimiterAV = device.maxAV * 10
device.tempRevLimiterMaxAVOvershoot = device.tempRevLimiterAV * 0.01
device.invTempRevLimiterRange = 1 / device.tempRevLimiterMaxAVOvershoot
device.isTempRevLimiterActive = false
device:setExhaustGainMufflingOffsetRevLimiter(0, 0)
end
local function revLimiterDisabledMethod(device, engineAV, throttle, dt)
return throttle
end
local function revLimiterSoftMethod(device, engineAV, throttle, dt)
local limiterAV = min(device.revLimiterAV, device.tempRevLimiterAV)
local correctedThrottle = -throttle * min(max(engineAV - limiterAV, 0), device.revLimiterMaxAVOvershoot) * device.invRevLimiterRange + throttle
if device.isTempRevLimiterActive and correctedThrottle < throttle then
device:setExhaustGainMufflingOffsetRevLimiter(-0.1, 2)
end
return correctedThrottle
end
local function revLimiterTimeMethod(device, engineAV, throttle, dt)
local limiterAV = min(device.revLimiterAV, device.tempRevLimiterAV)
if device.revLimiterActive then
device.revLimiterActiveTimer = device.revLimiterActiveTimer - dt
local revLimiterAVThreshold = min(limiterAV - device.revLimiterMaxAVDrop, limiterAV)
--Deactivate the limiter once below the deactivation threshold
device.revLimiterActive = device.revLimiterActiveTimer > 0 and engineAV > revLimiterAVThreshold
device.revLimiterWasActiveTimer = 0
return 0
end
if engineAV > limiterAV and not device.revLimiterActive then
device.revLimiterActiveTimer = device.revLimiterCutTime
device.revLimiterActive = true
device.revLimiterWasActiveTimer = 0
return 0
end
return throttle
end
local function revLimiterRPMDropMethod(device, engineAV, throttle, dt)
local limiterAV = min(device.revLimiterAV, device.tempRevLimiterAV)
if device.revLimiterActive or engineAV > limiterAV then
--Deactivate the limiter once below the deactivation threshold
local revLimiterAVThreshold = min(limiterAV - device.revLimiterAVDrop, limiterAV)
device.revLimiterActive = engineAV > revLimiterAVThreshold
device.revLimiterWasActiveTimer = 0
return 0
end
return throttle
end
local function updateFixedStep(device, dt)
--update idle throttle
device.idleTimer = device.idleTimer - dt
if device.idleTimer <= 0 then
local idleTimeRandomCoef = linearScale(device.idleTimeRandomness, 0, 1, 1, randomGauss3() * 0.6666667)
device.idleTimer = device.idleTimer + device.idleTime * idleTimeRandomCoef
-- device.idleTime
local engineAV = device.outputAV1
local highIdle = device.idleAV + math.max(math.min(60+linearScale(device.thermals.engineBlockTemperature, 60, -60, -60, 60), 250), 0)*0.6 -- ((max(-device.thermals.engineBlockTemperature, 10)-10) * 0.7)
local idleAV = max(highIdle, device.idleAVOverwrite)
local maxIdleThrottle = min(max(device.maxIdleThrottle, device.maxIdleThrottleOverwrite), 1)
local idleAVError = max(idleAV - engineAV + device.idleAVReadError + device.idleAVStartOffset, 0)
device.idleThrottleTarget = min(idleAVError * device.idleControllerP, maxIdleThrottle)
--print(device.idleThrottle)
end
device.idleThrottle = device.idleThrottleSmoother:get(device.idleThrottleTarget, dt)
device.forcedInductionCoef = 1
device.turbocharger.updateFixedStep(dt)
device.supercharger.updateFixedStep(dt)
end
--velocity update is always nopped for engines
local function updateTorque(device, dt)
local isFlooded = device.floodLevel > 0.5 -- Adjust threshold as needed
local isCranking = device.starterEngagedCoef > 0 and math.abs(device.outputAV1) < 300 * (math.pi/30) -- Below 100 RPM
local engineAV = device.outputAV1