using GTANetworkAPI; using ReallifeGamemode.Server.Entities; using ReallifeGamemode.Server.Managers; using ReallifeGamemode.Server.Models; using System; using System.Collections.Generic; using System.Text; namespace ReallifeGamemode.Server.Events { class Update : Script { private Dictionary lastPositions = new Dictionary(); private DateTime lastSave = DateTime.UtcNow; [ServerEvent(Event.Update)] void UpdateEvent() { NAPI.Pools.GetAllVehicles().ForEach(v => { Vector3 lastPosition = v.Position; if (lastPositions.ContainsKey(v.Handle)) lastPosition = lastPositions[v.Handle]; double distanceDriven = v.HasSharedData("drivenDistance") ? v.GetSharedData("drivenDistance") : 0; distanceDriven += (lastPosition.DistanceTo(v.Position) / 1000.0); v.SetSharedData("drivenDistance", (float)distanceDriven); lastPositions[v.Handle] = v.Position; }); if (DateTime.UtcNow.Subtract(lastSave).Seconds >= 30) { lastSave = DateTime.UtcNow; NAPI.Chat.SendChatMessageToAll("save distances"); // save to db using (var dbContext = new DatabaseContext()) { foreach(var key in lastPositions.Keys) { Vehicle v = key.Entity(); if (!v.HasSharedData("drivenDistance")) continue; ServerVehicle sVeh = VehicleManager.GetServerVehicleFromVehicle(v, dbContext); if (sVeh == null) continue; sVeh.DistanceDriven = (float)v.GetSharedData("drivenDistance"); } dbContext.SaveChanges(); } } } } }