-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathclient.lua
More file actions
2630 lines (2315 loc) · 103 KB
/
Copy pathclient.lua
File metadata and controls
2630 lines (2315 loc) · 103 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
require("@wizard-lib/client/functions")
--==========================================================================
--
-- VARIABLES
--
--==========================================================================
-- Player / Vehicle state
local playerPed = PlayerPedId() -- Player ped id (updated during runtime)
local serverToken = nil -- Server-issued token for secure communication
local isInVehicle = false -- Is the player currently inside a vehicle?
local currentPlate = nil -- Plate of the vehicle currently being tracked
local vehOwned = false -- Does this vehicle belong to any player?
-- Script state flags
local loaded = false -- Has vehicle data been loaded from the server?
local waitingForData = false -- Waiting for vehicle data response?
local allowSmartGearDetect = true -- Enable smart gear detection for clutch wear
-- UI state flags
local mileageVisible = false -- Is the mileage UI currently visible?
local mileageUIVisible = true -- Should the mileage UI be displayed?
local CWFT = false -- Is the wear check menu opened (target script)
-- Clipboard / inspection entities
local clipboardEntity = nil -- Clipboard prop used for wear inspection
-- Position tracking
local lastVehiclePosition = nil -- Last known vehicle position (vector3)
-- Distance unit conversion
local unitMultiplier = (Cfg.Unit == "imperial") and 1609.34 or 1000
-- Wear distance thresholds
local sparkPlugchangedist = Config.SparkPlugChangeDistance * unitMultiplier
local oilchangedist = Config.OilChangeDistance * unitMultiplier
local oilfilterchangedist = Config.OilFilterDistance * unitMultiplier
local airfilterchangedist = Config.AirFilterDistance * unitMultiplier
local tirechangedist = Config.TireWearDistance * unitMultiplier
-- Mileage tracking
local accumulatedDistance = 0.0 -- Accumulated driven distance (meters)
local lastSavedMileage = 0.0 -- Last saved mileage value
-- Service history (last replacement mileage)
local lastOilChange = 0.0
local lastOilFilterChange = 0.0
local lastAirFilterChange = 0.0
local lastSparkPlugChange = 0.0
local lastClutchChange = 0.0
local lastSuspensionChange = 0.0
-- Component wear values
local sparkPlugWear = 0.0 -- Current spark plug wear
local suspensionWear = 0.0 -- Current suspension wear
local lastClutchWear = 0.0 -- Current clutch wear value
local lastbrakeWear = 0.0 -- Global brake wear cache
-- Per wheel service tracking
local lastTireChange = {0.0,0.0,0.0,0.0,0.0,0.0} -- Mileage of last tire replacement
local lastbrakeChange = {0.0,0.0,0.0,0.0,0.0,0.0} -- Mileage of last brake replacement
-- Per wheel wear values
local tireWear = {0.0,0.0,0.0,0.0,0.0,0.0} -- Tire wear per wheel (0..1)
local brakeWear = {0.0,0.0,0.0,0.0,0.0,0.0} -- Brake wear per wheel (0..1)
-- Dirty sync flags (client -> server)
local clutchWearDirty = false -- Clutch wear changed and needs sync
local brakeWearDirty = false -- Brake wear changed and needs sync
local tireWearDirty = false -- Tire wear changed and needs sync
-- Cached values for server sync optimization
local cachedClutchWear = 0.0
local cachedBrakeWear = 0.0
local cachedPassengerCount = 0
local cachedFrontPassenger = false
local cachedPassengerVehTotal = -1
-- Tire burst / wheel state sync
local tireBurstSynced = {}
-- UI customization
local mileageUIPosX = 0.0
local mileageUIPosY = 0.0
local mileageUISize = 1.0
local checkwearUIPosX = 0.0
local checkwearUIPosY = 0.0
local checkwearUISize = 1.0
-- Engine warning system
local lastEngineCriticalNotify = 0 -- Last time critical engine warning was shown
-- Callback system
local vehicleListCallbacks = {} -- Pending callbacks waiting for vehicle list
-- Thread wait timers (performance tuning)
local waitTimeMain = 3000
local waitTimeClutch = 2000
-- Wear inspection & ownership caching
local ownershipCache = {} -- Cached ownership per vehicle plate
local wearCheckAccess = {} -- Temporary inspection access (plate -> expire time)
-- Wheel count cache
local wheelCountCache = {} -- Cached wheel counts per vehicle model
--==========================================================================
--
-- FUNCTIONS
--
--==========================================================================
--[[
Checks whether a vehicle is owned and caches the result temporarily.
- Normalizes the plate before checking ownership.
- Uses a temporary cache to avoid repeated server callbacks.
- Requests ownership data from the server if no valid cache exists.
- Always returns true when BoughtVehiclesOnly is disabled.
@param plate (string): The vehicle plate to check.
@return boolean: Whether the vehicle is considered owned.
]]--
if Config.BoughtVehiclesOnly then
function IsVehicleOwned(plate)
if not plate then return false end
plate = plate:gsub('%s+', '')
local now = GetGameTimer()
if ownershipCache[plate] and (now - ownershipCache[plate].time) < 5000 then
return ownershipCache[plate].value
end
local owned = lib.callback.await('wizard_vehiclemileage:server:ownerShipCallBack', false, plate)
ownershipCache[plate] = {
value = owned,
time = now
}
return owned
end
else
function IsVehicleOwned()
return true
end
end
--[[
Normalizes a vehicle plate string for consistent comparisons.
- Ensures the provided plate value exists before processing.
- Removes all whitespace characters from the plate string.
- Returns a cleaned plate value that can be safely used for lookups or matching.
@param plate (string): The raw vehicle plate text.
@return string|nil: The normalized plate without spaces, or nil if the input is invalid.
]]--
local function normalizePlate(plate)
if not plate then return nil end
return plate:gsub("%s+", "")
end
--[[
Attempts to detect the number of wheels a vehicle has using bone checks.
- Iterates through common vehicle wheel bone names and checks if they exist on the entity.
- Counts how many valid wheel bones are found.
- Falls back to a default of 4 wheels if no bones are detected.
- Clamps the maximum detected wheel count to 6 to avoid unexpected values.
@param veh (entity): The vehicle entity whose wheel bones will be inspected.
@return number: The detected wheel count (between 4 and 6).
]]--
local function detectWheelCount(veh)
local bones = {"wheel_lf","wheel_rf","wheel_lr","wheel_rr","wheel_lm","wheel_rm"}
local count = 0
for i, b in ipairs(bones) do
local idx = GetEntityBoneIndexByName(veh, b)
if idx ~= -1 then count = count + 1 end
end
if count == 0 then count = 4 end
if count > 6 then count = 6 end
return count
end
local function getCachedWheelCount(veh)
local model = GetEntityModel(veh)
if wheelCountCache[model] == nil then
wheelCountCache[model] = detectWheelCount(veh)
end
return wheelCountCache[model]
end
--[[
Triggers a vehicle list callback to retrieve all vehicles from the server.
This is used for admin/database features that need to display or manage all vehicles.
The callback is stored in a table with a unique ID, so when the server responds,
the correct callback can be executed.
@param cb (function): The function to call with the vehicle list (table).
]]--
local function TriggerVehicleListCallback(cb)
-- Limit callback pool size to prevent memory bloat
local callbackCount = 0
for _ in pairs(vehicleListCallbacks) do
callbackCount = callbackCount + 1
end
if callbackCount >= 50 then
vehicleListCallbacks = {}
end
local cbId = math.random(100000, 999999) -- Generate a unique callback ID
vehicleListCallbacks[cbId] = cb -- Store the callback for later use
TriggerServerEvent('wizard_vehiclemileage:server:getAllVehicles', serverToken, cbId) -- Ask the server for the vehicle list
end
--[[
Checks if the player has permission to use mechanic-related features.
- Retrieves the player's current job and grade using CheckJob().
- Compares the job against the configured mechanic jobs list.
- Ensures the player's grade meets or exceeds the minimum required grade.
- Returns true if the player has mechanic access, otherwise false.
@return boolean: Whether the player has mechanic access.
]]--
local function isMechanic()
if Config.JobRequired then
local Job, Grade = CheckJob()
local allowed = false
for jobName, minGrade in pairs(Config.MechanicJobs) do
if Job == jobName and Grade >= minGrade then
allowed = true
break
end
end
return allowed
else
return true
end
end
--[[
Updates the spark plug wear for the given vehicle.
- Calculates how much the spark plugs have worn based on distance driven since last change.
- Sends the updated wear value to the server for saving.
- If the spark plugs are fully worn, there is a chance for a misfire (engine RPM drops).
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateSparkPlugWear(vehicle)
if not Config.WearTracking.SparkPlugs then return end -- Skip if spark plug wear tracking is disabled
-- Calculate how far the vehicle has driven since last spark plug change
local distanceSinceSparkPlugChange = accumulatedDistance - lastSparkPlugChange
-- Calculate wear ratio (0 = new, 1 = fully worn)
local wearRatio = distanceSinceSparkPlugChange / (Config.SparkPlugChangeDistance * 1000)
if wearRatio > 1 then wearRatio = 1 end
sparkPlugWear = wearRatio
-- If spark plugs are fully worn, chance for a misfire
if sparkPlugWear >= 1.0 then
if DoesEntityExist(veh) then
if math.random() < Config.MissfireChance then
Notify('Wizard Mileage', locale('warning.spark_plug_misfire'), 'warning')
SetVehicleCurrentRpm(veh, 0.0)
Wait(100)
SetVehicleCurrentRpm(veh, 0.0)
end
end
end
end
--[[
Updates the engine damage based on oil and oil filter wear.
- If oil or filter is overdue, applies engine damage and drains oil faster.
- Notifies the player if engine health is critical.
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateEngineDamage(vehicle)
if not Config.WearTracking.Oil then return end
-- Calculate wear ratios for oil and oil filter
local oilDistanceDriven = accumulatedDistance - lastOilChange
local oilWearRatio = oilDistanceDriven / oilchangedist
local filterDistanceDriven = accumulatedDistance - lastOilFilterChange
local filterWearRatio = filterDistanceDriven / oilfilterchangedist
-- If either oil or filter is overdue, apply damage
if oilWearRatio > 1.0 or filterWearRatio > 1.0 then
local engineHealth = GetVehicleEngineHealth(vehicle)
local damage = (math.max(oilWearRatio, filterWearRatio) - 1.0) * Config.EngineDamageRate
-- Simulate oil draining faster as damage increases
local oilDrainRate = damage * 0.1
lastOilChange = lastOilChange - (oilDrainRate * oilchangedist)
-- If engine is very damaged, reset oil change
if engineHealth < 400.0 then
lastOilChange = 0.0
end
-- Apply engine damage
SetVehicleEngineHealth(vehicle, math.max(0.0, engineHealth - damage))
-- Notify player if engine is critical
local invertal = Config.WarningsInterval * 1000
if engineHealth < 200.0 then
local currentTime = GetGameTimer()
if (currentTime - lastEngineCriticalNotify) >= invertal then
Notify('Wizard Mileage', locale('warning.engine_critical'), 'error')
lastEngineCriticalNotify = currentTime
end
end
end
end
--[[
Updates the air filter performance for the given vehicle.
- Reduces acceleration as the air filter wears out.
- Saves and restores original drive force as needed.
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateAirFilterPerformance(vehicle)
if not Config.WearTracking.AirFilter then return end
-- Calculate air filter wear ratio (0 = new, 1 = fully worn)
local airFilterDistanceDriven = accumulatedDistance - lastAirFilterChange
local airFilterWearRatio = math.min(1.0, airFilterDistanceDriven / airfilterchangedist)
-- Get and save original drive force if not already saved
local plate = normalizePlate(GetVehiclePlate(closestVehicle))
TriggerServerEvent('wizard_vehiclemileage:server:getOriginalDriveForce', serverToken, plate)
local currentAcceleration = GetVehicleHandlingFloat(vehicle, "CHandlingData", "fInitialDriveForce")
originalDriveForce = originalDriveForce or currentAcceleration
TriggerServerEvent('wizard_vehiclemileage:server:saveOriginalDriveForce', serverToken, plate, originalDriveForce)
-- Reduce acceleration based on wear
local reducedAcceleration = originalDriveForce * (1.0 - (Config.AccelerationReduction * airFilterWearRatio))
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fInitialDriveForce", reducedAcceleration)
end
--[[
Updates the tire wear for the given vehicle.
- Reduces tire grip as tires wear out.
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateTireWear(vehicle)
if not Config.WearTracking.Tires then return end
-- Determine wheel count (best-effort). Check common wheel bone names.
local function getCachedWheelCount(veh)
local bones = {"wheel_lf","wheel_rf","wheel_lr","wheel_rr","wheel_lm","wheel_rm"}
local count = 0
for i, b in ipairs(bones) do
local idx = GetEntityBoneIndexByName(veh, b)
if idx ~= -1 then count = count + 1 end
end
-- Fallback to 4 if detection failed
if count == 0 then count = 4 end
-- Cap at 6 (we track 0..5)
if count > 6 then count = 6 end
return count
end
local wc = getCachedWheelCount(vehicle)
local mode = Config.TireWearMode or "distance"
for i = 0, wc - 1 do
local idx = i + 1 -- Lua array index
-- distance-based wear (legacy)
local distWear = 0.0
if mode == "distance" or mode == "both" then
local distanceSinceChange = accumulatedDistance - (lastTireChange[idx] or 0.0)
distWear = distanceSinceChange / tirechangedist
if distWear > 1 then distWear = 1 end
end
-- slip-based wear is accumulated into `tireWear[idx]` by the slip thread
local slipWear = tireWear[idx] or 0.0
if mode == "distance" then
tireWear[idx] = distWear
elseif mode == "slip" then
tireWear[idx] = math.min(1.0, slipWear)
else -- both: choose the larger effect to reflect worst-case wear
tireWear[idx] = math.min(1.0, math.max(distWear, slipWear))
end
-- If tyre is burst, consider it fully worn
if IsVehicleTyreBurst(vehicle, i, false) then
tireWear[idx] = 1.0
end
end
-- Apply average grip reduction based on mean tire wear to maintain handling stability
local sum = 0
for i = 1, wc do sum = sum + (tireWear[i] or 0) end
local avgWear = (wc > 0) and (sum / wc) or 0
local newGrip = Config.BaseTireGrip - ((Config.BaseTireGrip - Config.MinTireGrip) * avgWear)
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fTractionCurveMax", newGrip)
end
--[[
Updates the brake wear for the given vehicle.
- Adjusts the brake force based on the current brake wear value.
- The more worn the brakes, the less effective they become.
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateBrakeWear(vehicle)
if not Config.WearTracking.Brakes then return end -- Skip if brake wear tracking is disabled
-- Best-effort: detect wheel count like tires
local function getCachedWheelCount(veh)
local bones = {"wheel_lf","wheel_rf","wheel_lr","wheel_rr","wheel_lm","wheel_rm"}
local count = 0
for i, b in ipairs(bones) do
local idx = GetEntityBoneIndexByName(veh, b)
if idx ~= -1 then count = count + 1 end
end
if count == 0 then count = 4 end
if count > 6 then count = 6 end
return count
end
local wc = getCachedWheelCount(vehicle)
-- Compute an averaged brake efficiency based on per-wheel wear (brakeWear stores 0..MaxBrakeWear)
local sum = 0
for i = 1, wc do
sum = sum + (brakeWear[i] or 0.0)
end
local avgWear = (wc > 0) and (sum / wc) or 0.0 -- avgWear in 0..Config.MaxBrakeWear
-- update legacy scalar for compatibility and warnings
lastbrakeWear = avgWear
-- normalized fraction (0..1)
local norm = math.min(avgWear, Config.MaxBrakeWear) / Config.MaxBrakeWear
local efficiency = 1.0 - (norm * Config.BrakeEfficiencyLoss)
local baseBrakeForce = Config.BaseBrakeForce
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fBrakeForce", baseBrakeForce * efficiency)
end
--[[
Updates the suspension wear for the given vehicle.
- Calculates how much the suspension has worn based on distance driven since last change.
- Saves and restores original suspension force and raise values as needed.
- Applies new suspension values to the vehicle based on wear.
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateSuspensionWear(vehicle)
if not Config.WearTracking.Suspension then return end -- Skip if suspension wear tracking is disabled
-- Calculate how far the vehicle has driven since last suspension change
local distanceSinceSuspensionChange = accumulatedDistance - lastSuspensionChange
-- Calculate wear ratio (0 = new, 1 = fully worn)
local wearRatio = distanceSinceSuspensionChange / (Config.SuspensionChangeDistance * 1000)
if wearRatio > 1 then wearRatio = 1 end
local plate = normalizePlate(GetVehiclePlate(closestVehicle))
-- Request original suspension values from the server (if not already cached)
TriggerServerEvent('wizard_vehiclemileage:server:getOriginalSuspensionValue', serverToken, plate)
suspensionWear = wearRatio
-- Get or save original suspension force and raise values
local originalForce = originalSuspensionForce or GetVehicleHandlingFloat(vehicle, "CHandlingData", "fSuspensionForce")
local originalRaise = originalSuspensionRaise or GetVehicleHandlingFloat(vehicle, "CHandlingData", "fSuspensionRaise")
if not originalSuspensionForce or originalSuspensionForce == 0 then
originalSuspensionForce = originalForce
TriggerServerEvent('wizard_vehiclemileage:server:saveOriginalSuspensionForce', serverToken, plate, originalForce)
end
if not originalSuspensionRaise then
originalSuspensionRaise = originalRaise
TriggerServerEvent('wizard_vehiclemileage:server:saveOriginalSuspensionRaise', serverToken, plate, originalRaise)
end
-- Calculate new suspension values based on wear
local newForce = originalForce * (1.0 - suspensionWear)
local newRaise = originalRaise * (1.0 - suspensionWear)
-- Apply new suspension values to the vehicle
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fSuspensionForce", newForce)
SetVehicleHandlingFloat(vehicle, "CHandlingData", "fSuspensionRaise", newRaise)
end
--[[
Updates the clutch wear for the given vehicle.
- Calculates clutch efficiency based on wear.
- If the clutch is very worn (efficiency <= 20%), simulates clutch failure and possible engine stall.
- Notifies the player if the vehicle stalls due to clutch wear.
@param vehicle (entity): The vehicle entity to update.
]]--
local function updateClutchWear(vehicle)
-- Calculate clutch efficiency (1.0 = new, decreases as wear increases)
local efficiency = 1.0 - (math.min(lastClutchWear, Config.MaxClutchWear) / Config.MaxClutchWear * Config.ClutchEfficiencyLoss)
-- If clutch is very worn, simulate clutch failure and possible stall
if efficiency <= 0.2 then
-- Simulate clutch slipping/failure
InvokeNative(GetHashKey('SET_VEHICLE_CLUTCH') & 0xFFFFFFFF, vehicle, -1.0)
-- Random chance to stall the engine
if math.random() < Config.StallChance then
SetVehicleEngineOn(vehicle, false, true, true)
Notify('Wizard Mileage', locale('warning.stalled'), 'warning')
end
else
-- You can add logic here for normal clutch operation if needed
local baseClutchForce = Config.BaseClutchForce
end
end
--[[
Calculates the remaining life percentage for each tracked vehicle component.
Updates global variables for spark plugs, oil, filter, air filter, tires, brakes, suspension, and clutch based on current mileage and wear.
Also updates the displayed mileage value for the UI.
]]--
local function GetData()
if Config.WearTracking.SparkPlugs then
sparkPlugDistanceDriven = accumulatedDistance - lastSparkPlugChange
sparkPlugLifeRemaining = math.max(0, sparkPlugchangedist - sparkPlugDistanceDriven)
sparkPlugPercentage = math.floor((sparkPlugLifeRemaining / sparkPlugchangedist) * 100)
end
if Config.WearTracking.Oil then
oilDistanceDriven = accumulatedDistance - lastOilChange
oilLifeRemaining = math.max(0, oilchangedist - oilDistanceDriven)
oilPercentage = math.floor((oilLifeRemaining / oilchangedist) * 100)
filterDistanceDriven = accumulatedDistance - lastOilFilterChange
filterLifeRemaining = math.max(0, oilfilterchangedist - filterDistanceDriven)
filterPercentage = math.floor((filterLifeRemaining / oilfilterchangedist) * 100)
end
if Config.WearTracking.AirFilter then
airFilterDistanceDriven = accumulatedDistance - lastAirFilterChange
airFilterLifeRemaining = math.max(0, airfilterchangedist - airFilterDistanceDriven)
airFilterPercentage = math.floor((airFilterLifeRemaining / airfilterchangedist) * 100)
end
if Config.WearTracking.Tires then
-- compute per-tire percentages only for detected wheels
local wc = 4
if DoesEntityExist(veh) then
wc = getCachedWheelCount(veh)
end
tirePercentage = {}
for i = 1, wc do
local w = tireWear[i] or 0
tirePercentage[i] = math.floor((1 - w) * 100)
end
end
if Config.WearTracking.Brakes then
local wc = 4
if DoesEntityExist(veh) then
wc = getCachedWheelCount(veh)
end
brakePercentage = {}
for i = 1, wc do
local w = brakeWear[i] or 0
brakePercentage[i] = math.floor((1 - (w / Config.MaxBrakeWear)) * 100)
end
end
if Config.WearTracking.Suspension then
suspensionDistanceDriven = accumulatedDistance - lastSuspensionChange
suspensionLifeRemaining = math.max(0, Config.SuspensionChangeDistance * 1000 - suspensionDistanceDriven)
suspensionPercentage = math.floor((suspensionLifeRemaining / (Config.SuspensionChangeDistance * 1000)) * 100)
end
if Config.WearTracking.Clutch then
clutchPercentage = math.floor((1 - (lastClutchWear / Config.MaxClutchWear)) * 100)
end
displayedMileage = convertDistance(accumulatedDistance)
end
--[[
Cleans up the clipboard entity and animation for the player.
Deletes the clipboard object if it exists and clears the player's current tasks/animations.
@param ped (entity): The player ped to clear tasks for.
]]--
local function CleanupClipboardEntity(ped)
if clipboardEntity then
DeleteObject(clipboardEntity)
clipboardEntity = nil
end
if ped then
ClearPedTasks(ped)
end
end
local function canOpenServiceMenu()
local closestVehicle, _ = lib.getClosestVehicle(GetEntityCoords(PlayerPedId()), 5.0, true)
local plate = normalizePlate(GetVehiclePlate(closestVehicle))
if not plate then return false end
local expiresAt = wearCheckAccess[plate]
if not expiresAt then
return false
end
if GetGameTimer() > expiresAt then
wearCheckAccess[plate] = nil
return false
end
return true
end
--[[
Opens the service menu for the player, using the configured menu system.
- If Config.Menu is "ox", shows the ox_lib context menu.
- If Config.Menu is "qb", opens the qb-menu with all available service options.
Each menu option triggers a client event to perform the selected maintenance action.
]]--
local function openServiceMenu()
if not canOpenServiceMenu() then
Notify('Wizard Mileage', locale('warning.check_veh'), 'error')
return
end
if Config.Menu == "ox" then
-- Show ox_lib context menu
lib.showContext("vehicle_service_menu")
elseif Config.Menu == "qb" then
-- Open qb-menu with all service options
exports["qb-menu"]:openMenu({
{
header = "Wizard Mileage Service Menu",
isMenuHeader = true,
},
{
header = locale("target.changeoilfilter"),
txt = "Change oil filter",
params = { event = "wizard_vehiclemileage:client:changeoilfilter" }
},
{
header = locale("target.changeairfilter"),
txt = "Change air filter",
params = { event = "wizard_vehiclemileage:client:changeairfilter" }
},
{
header = locale("target.changetires"),
txt = "Change vehicle tires",
params = { event = "wizard_vehiclemileage:client:changetires" }
},
{
header = locale("target.changebrakes"),
txt = "Service vehicle brakes",
params = { event = "wizard_vehiclemileage:client:changebrakes" }
},
{
header = locale("target.changeclutch"),
txt = "Replace vehicle clutch",
params = { event = "wizard_vehiclemileage:client:changeclutch" }
},
{
header = locale("target.changesuspension"),
txt = "Replace vehicle suspension",
params = { event = "wizard_vehiclemileage:client:changesuspension" }
},
{
header = locale("target.changesparkplug"),
txt = "Replace spark plugs",
params = { event = "wizard_vehiclemileage:client:changesparkplug" }
},
})
end
end
--[[
Opens the vehicle wear check menu for a given vehicle.
Plays clipboard animation, checks for valid vehicle and ownership, and retrieves wear data from the server.
Displays error notifications if any checks fail, and cleans up the clipboard entity/animation as needed.
On success, sends wear data to the NUI for display.
@param vehicle (entity): The vehicle entity to check wear for.
]]--
local function openCheckWearMenu(vehicle)
Notify('Wizard Mileage', locale('warning.checking_veh'), 'warning')
local coords = GetEntityCoords(playerPed)
if clipboardEntity then
CleanupClipboardEntity(playerPed)
return
end
local clipboardHash = RequestProp(Config.CheckVehicle.Object)
clipboardEntity = CreateObject(clipboardHash, coords.x, coords.y, coords.z, true, true, true)
AttachEntityToEntity(clipboardEntity, playerPed, GetPedBoneIndex(playerPed, Config.CheckVehicle.Bone), -0.1, 0.0, 0.0, 90.0, 0.0, 0.0, true, true, false, true, 1, true)
TaskPlayAnim(playerPed, Config.CheckVehicle.AnimDict, Config.CheckVehicle.Animation, 8.0, -8.0, -1, 49, 0, false, false, false)
if not DoesEntityExist(vehicle) then
Notify('Wizard Mileage', locale('error.not_found'), 'error')
-- Clear the animation and remove the clipboard
CleanupClipboardEntity(playerPed)
return
end
if isInVehicle then
Notify('Wizard Mileage', locale('error.in_vehicle'), 'error')
-- Clear the animation and remove the clipboard
CleanupClipboardEntity(playerPed)
return
end
local plate = normalizePlate(GetVehiclePlate(vehicle))
if not plate or plate == 'UNKNOWN' then
Notify('Wizard Mileage', locale('error.plate_not_found'), 'error')
-- Clear the animation and remove the clipboard
CleanupClipboardEntity(playerPed)
return
end
if not IsVehicleOwned(plate) then
Notify('Wizard Mileage', locale('error.not_owned'), 'error')
-- Clear the animation and remove the clipboard
CleanupClipboardEntity(playerPed)
return
end
loaded = false
TriggerServerEvent('wizard_vehiclemileage:server:retrieveMileage', serverToken, plate)
while not loaded do
Wait(500)
end
CWFT = true
GetData()
SendNUIMessage({
type = "closeCustomization"
})
SetNuiFocus(true, false)
local wearDataCache = {
type = "updateWear",
showUI = true,
mileage = displayedMileage,
unit = (Cfg.Unit == "imperial" and "miles" or "km"),
sparkPlugPercentage = sparkPlugPercentage,
oilPercentage = oilPercentage,
filterPercentage = filterPercentage,
airFilterPercentage = airFilterPercentage,
tirePercentage = tirePercentage,
brakePercentage = brakePercentage,
suspensionPercentage = suspensionPercentage,
clutchPercentage = clutchPercentage
}
SendNUIMessage(wearDataCache)
wearCheckAccess[plate] = GetGameTimer() + 120000
end
--[[
Performs a maintenance action on the nearest vehicle.
Checks job and inventory requirements, plays animation, shows a progress bar, and removes the required item.
Handles advanced actions (like opening the hood) if specified.
Returns true and the vehicle entity on success, or false and nil on failure.
@param item (string): The required inventory item for maintenance.
@param errorMSG (string): The error message key for missing item.
@param configData (table): Animation and progress bar configuration.
@param progressMSG (string): The progress bar message key.
@param isAdv (boolean): Whether to perform advanced actions (e.g., open hood).
]]--
local function DoMaintenance(item, errorMSG, configData, progressMSG, isAdv, quantity)
if not isMechanic() then
Notify('Wizard Mileage', locale("error.not_mechanic"), "error")
return
end
if Config.InventoryItems and not checkInventoryItem(item) then
Notify('Wizard Mileage', locale("error." .. errorMSG), "error")
return
end
local closestVehicle, _ = lib.getClosestVehicle(GetEntityCoords(PlayerPedId()), 5.0, true)
if not closestVehicle then
Notify('Wizard Mileage', locale("error.no_vehicle_nearby"), "error")
return
end
local vehicleClass = GetVehicleClass(closestVehicle)
if Config.DisabledVehicleClasses[vehicleClass] then
return
end
if isAdv then
if not IsVehicleDoorFullyOpen(closestVehicle, 4) then
SetVehicleDoorOpen(closestVehicle, 4, false, true)
Wait(500)
end
local offset = GetOffsetFromEntityInWorldCoords(closestVehicle, 0.0, 2.0, 0.0)
TaskGoStraightToCoord(playerPed, offset.x, offset.y, offset.z, 1.0, -1, -1, 0.0)
Wait(1000)
end
PlayAnimation(playerPed, configData.AnimationDict, configData.Animation, -1 , 1)
if DisplayProgressBar(configData.Duration, locale("progress." .. progressMSG), configData) then
TriggerServerEvent('wizard_vehiclemileage:server:removeItem', serverToken, item, quantity or 1)
if isAdv then SetVehicleDoorShut(closestVehicle, 4, false) end
ClearPedTasks(playerPed)
return true, closestVehicle
else
if isAdv then SetVehicleDoorShut(closestVehicle, 4, false) end
return false, nil
end
end
--[[
Loads vehicle and mileage data when the player enters a vehicle.
Sets state flags, caches the starting position, resets accumulated distance,
shows the mileage UI if enabled, and requests the latest mileage data from the server.
@side-effect: Updates global state variables and UI.
]]--
local function LoadData()
isInVehicle = true
lastVehiclePosition = GetEntityCoords(veh)
waitingForData = true
accumulatedDistance = 0.0
if mileageUIVisible then
SendNUIMessage({ type = "toggleMileage", visible = true })
mileageVisible = true
end
TriggerServerEvent('wizard_vehiclemileage:server:retrieveMileage', serverToken, currentPlate)
end
--[[
Clears and saves all vehicle and wear data when the player exits a vehicle or disconnects.
Hides the mileage UI, sends any unsaved wear and mileage data to the server,
resets all tracking variables, and clears cached state.
@side-effect: Triggers server events to persist data and resets local state.
]]--
local function ClearData(ClearType)
if mileageVisible then
SendNUIMessage({ type = "toggleMileage", visible = false })
mileageVisible = false
end
if ClearType == "normal" then
isInVehicle = false
inAnyVeh = false
lastVehiclePosition = nil
accumulatedDistance = 0.0
currentPlate = nil
waitingForData = false
lastOilChange = 0.0
lastOilFilterChange = 0.0
lastAirFilterChange = 0.0
lastTireChange = {0.0,0.0,0.0,0.0,0.0,0.0}
lastbrakeChange = {0.0,0.0,0.0,0.0,0.0,0.0}
tireWear = {0.0,0.0,0.0,0.0,0.0,0.0}
brakeWear = {0.0,0.0,0.0,0.0,0.0,0.0}
lastClutchChange = 0.0
lastClutchWear = 0.0
lastSuspensionChange = 0.0
suspensionWear = 0.0
lastSparkPlugChange = 0.0
sparkPlugWear = 0.0
cachedClutchWear = 0.0
cachedBrakeWear = 0.0
clutchWearDirty = false
brakeWearDirty = false
loaded = false
vehOwned = false
end
if currentPlate then
local savedPlate = currentPlate
local savedMil = accumulatedDistance
local savedPlugWear = sparkPlugWear
local savedSusWear = suspensionWear
if clutchWearDirty then
TriggerServerEvent('wizard_vehiclemileage:server:updateClutchWear', serverToken, currentPlate, cachedClutchWear)
clutchWearDirty = false
end
if brakeWearDirty then
TriggerServerEvent('wizard_vehiclemileage:server:updateBrakeWear', serverToken, currentPlate, cachedBrakeWear)
brakeWearDirty = false
end
if tireWearDirty then
TriggerServerEvent("wizard_vehiclemileage:server:updateTireWearAll", serverToken, currentPlate, tireWear)
tireWearDirty = false
end
TriggerServerEvent('wizard_vehiclemileage:server:updateMileage', serverToken, currentPlate, savedMil)
TriggerServerEvent('wizard_vehiclemileage:server:updateSparkPlugWear', serverToken, currentPlate, savedPlugWear)
TriggerServerEvent('wizard_vehiclemileage:server:updateSuspensionWear', serverToken, currentPlate, savedSusWear)
end
end
--==========================================================================
--
-- THREADS
--
--==========================================================================
--[[
Cache listeners for vehicle, seat, and ped state changes.
- Detects when the player enters or exits a vehicle.
- Validates vehicle class and ownership before loading data.
- Loads wear/mileage data only when the player is the driver.
- Clears data when leaving the driver seat or vehicle.
- Keeps the local player ped reference updated.
These cache hooks ensure vehicle data is loaded and cleared safely
based on the player’s current context.
]]--
lib.onCache('vehicle', function(value, oldValue)
if not value then
ClearData("normal")
else
veh = value
inAnyVeh = true
local vehicleClass = GetVehicleClass(veh)
if Config.DisabledVehicleClasses[vehicleClass] then
return
end
currentPlate = normalizePlate(GetVehiclePlate(veh))
if IsVehicleOwned(currentPlate) then
vehOwned = true
if GetPedInVehicleSeat(veh, -1) ~= playerPed then
return
end
LoadData()
else
vehOwned = false
end
end
end)
lib.onCache('seat', function(value, oldValue)
if oldValue == -1 then
ClearData("limited")
end
if value == -1 and vehOwned then
LoadData()
end
end)
lib.onCache('ped', function(value, oldValue)
playerPed = value
end)
CreateThread(function()
while not NetworkIsSessionActive() do
Wait(100)
end
TriggerServerEvent('wizard_vehiclemileage:server:requestToken')
end)
--[[
Main interaction and mileage management thread.
- Handles vehicle interaction validation and ownership checks.
- Registers target interactions for servicing and inspecting vehicles.
- Builds and manages the vehicle service menu system.
- Sends live wear data updates to the NUI interface.
- Tracks traveled distance and updates the displayed mileage in real time.
This thread controls the core interaction flow between the player,
vehicle systems, targeting, UI updates, and mileage calculations.
]]--
CreateThread(function()
local lastMileage = -1
local nuiWearCache = nil
local function canInteractVehicle(entity)
if inAnyVeh then
return false
end
local plate = normalizePlate(GetVehiclePlate(entity))
if not IsVehicleOwned(plate) then
return false
end
return not Config.DisabledVehicleClasses[GetVehicleClass(entity)]
end
local function calculateAverage(table)
if not table then
return 0
end
local total = 0
local count = 0
for _, value in pairs(table) do
total += value or 0
count += 1
end
return count > 0 and floor(total / count) or 0
end
local function sendWearUpdate()
if not currentWear then
return
end