public ImminentReminderModel(Vehicle vehicle, Reminder reminder, bool isOverdue) { IsOverdue = isOverdue; _vehicle = vehicle; _reminder = reminder; _summary = new ReminderSummaryModel(reminder,isOverdue); }
public override void GetBufferStatus(ushort vehicleID, ref Vehicle data, out string localeKey, out int current, out int max) { localeKey = "Default"; current = (int)data.m_transferSize; max = this.m_passengerCapacity; if (data.m_leadingVehicle == 0) { VehicleManager instance = Singleton<VehicleManager>.instance; ushort trailingVehicle = data.m_trailingVehicle; int num = 0; while (trailingVehicle != 0) { VehicleInfo info = instance.m_vehicles.m_buffer [(int)trailingVehicle].Info; if (instance.m_vehicles.m_buffer [(int)trailingVehicle].m_leadingVehicle != 0) { int num2; int num3; info.m_vehicleAI.GetBufferStatus (trailingVehicle, ref instance.m_vehicles.m_buffer [(int)trailingVehicle], out localeKey, out num2, out num3); current += num2; max += num3; } trailingVehicle = instance.m_vehicles.m_buffer [(int)trailingVehicle].m_trailingVehicle; if (++num > 65536) { CODebugBase<LogChannel>.Error (LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace); break; } } } if ((data.m_flags & Vehicle.Flags.DummyTraffic) != Vehicle.Flags.None) { Randomizer randomizer = new Randomizer ((int)vehicleID); current = randomizer.Int32 (max >> 1, max); } }
public void CalculateSegmentPosition2(ushort vehicleId, ref Vehicle vehicleData, PathUnit.Position position, uint laneId, byte offset, out Vector3 pos, out Vector3 dir, out float maxSpeed) { var instance = Singleton<NetManager>.instance; instance.m_lanes.m_buffer[(int)((UIntPtr)laneId)].CalculatePositionAndDirection(offset * 0.003921569f, out pos, out dir); var info = instance.m_segments.m_buffer[position.m_segment].Info; if (info.m_lanes != null && info.m_lanes.Length > position.m_lane) { var laneSpeedLimit = info.m_lanes[position.m_lane].m_speedLimit; if (TrafficRoadRestrictions.IsSegment(position.m_segment)) { var restrictionSegment = TrafficRoadRestrictions.GetSegment(position.m_segment); if (restrictionSegment.SpeedLimits[position.m_lane] > 0.1f) { laneSpeedLimit = restrictionSegment.SpeedLimits[position.m_lane]; } } maxSpeed = CalculateTargetSpeed(vehicleId, ref vehicleData, laneSpeedLimit, instance.m_lanes.m_buffer[(int)((UIntPtr)laneId)].m_curve); } else { maxSpeed = CalculateTargetSpeed(vehicleId, ref vehicleData, 1f, 0f); } }
public void WhenAddingReminder_ThenUpdatesServiceReminder() { const int newReminderId = 456; var vehicle = new Vehicle { VehicleId = DefaultVehicleId, Name = "vehicle" }; _vehicleRepository .Setup(r => r.GetVehicle(DefaultUserId, DefaultVehicleId)) .Returns(vehicle); _reminderRepository .Setup(r => r.Create(DefaultVehicleId, It.IsAny<Reminder>())) .Callback(new Action<int, Reminder>((vehicleId, reminder) => { // represents the entity created internally reminder.ReminderId = newReminderId; reminder.VehicleId = DefaultVehicleId; })); var formModel = new ReminderFormModel(); var handler = new AddReminderToVehicle(_vehicleRepository.Object, _reminderRepository.Object); handler.Execute(DefaultUserId, DefaultVehicleId, formModel); Assert.Equal(newReminderId, formModel.ReminderId); Assert.Equal(DefaultVehicleId, formModel.VehicleId); }
public CockpitView(Vehicle vehicle, string cockpitFile) { _vehicle = vehicle; if (GameVars.Emulation == EmulationMode.Demo) cockpitFile = Path.GetDirectoryName(cockpitFile) + "\\blkeagle.txt"; else if (GameVars.Emulation == EmulationMode.SplatPackDemo) cockpitFile = Path.GetDirectoryName(cockpitFile) + "\\neweagle.txt"; else if (!File.Exists(cockpitFile)) cockpitFile = Path.GetDirectoryName(cockpitFile) + "\\blkeagle.txt"; if (File.Exists(cockpitFile)) { _cockpitFile = new CockpitFile(cockpitFile); ActFile actFile = new ActFile(vehicle.Config.BonnetActorFile); if (!actFile.Exists) actFile = new ActFile("EBONNET.ACT"); _actors = actFile.Hierarchy; DatFile modelsFile = new DatFile(_actors.Root.ModelName); _actors.AttachModels(modelsFile.Models); _actors.ResolveTransforms(false, null); //move head back _vehicle.Config.DriverHeadPosition.Z += 0.11f; } _camera = new SimpleCamera(); _camera.FieldOfView = MathHelper.ToRadians(55.55f); }
public bool CustomStartPathFind(ushort vehicleID, ref Vehicle vehicleData, Vector3 startPos, Vector3 endPos, bool startBothWays, bool endBothWays, bool undergroundTarget) { VehicleInfo info = this.m_info; bool allowUnderground = (vehicleData.m_flags & (Vehicle.Flags.Underground | Vehicle.Flags.Transition)) != 0; PathUnit.Position startPosA; PathUnit.Position startPosB; float num; float num2; PathUnit.Position endPosA; PathUnit.Position endPosB; float num3; float num4; if (CustomPathManager.FindPathPosition(startPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle, info.m_vehicleType, allowUnderground, false, 32f, out startPosA, out startPosB, out num, out num2) && CustomPathManager.FindPathPosition(endPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle, info.m_vehicleType, undergroundTarget, false, 32f, out endPosA, out endPosB, out num3, out num4)) { if (!startBothWays || num < 10f) { startPosB = default(PathUnit.Position); } if (!endBothWays || num3 < 10f) { endPosB = default(PathUnit.Position); } uint path; if (Singleton<CustomPathManager>.instance.CreatePath((vehicleData.m_flags & Vehicle.Flags.Emergency2) != 0 ? ExtVehicleType.Emergency : ExtVehicleType.Service, out path, ref Singleton<SimulationManager>.instance.m_randomizer, Singleton<SimulationManager>.instance.m_currentBuildIndex, startPosA, startPosB, endPosA, endPosB, NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle, info.m_vehicleType, 20000f, this.IsHeavyVehicle(), this.IgnoreBlocked(vehicleID, ref vehicleData), false, false)) { if (vehicleData.m_path != 0u) { Singleton<PathManager>.instance.ReleasePath(vehicleData.m_path); } vehicleData.m_path = path; vehicleData.m_flags |= Vehicle.Flags.WaitingPath; return true; } } return false; }
public override void SimulationStep(ushort vehicleID, ref Vehicle vehicleData, ref Vehicle.Frame frameData, ushort leaderID, ref Vehicle leaderData, int lodPhysics) { if ((CSLTraffic.Options & OptionsManager.ModOptions.UseRealisticSpeeds) == OptionsManager.ModOptions.UseRealisticSpeeds) { if (CustomCarAI.sm_speedData[vehicleID].speedMultiplier == 0 || CustomCarAI.sm_speedData[vehicleID].currentPath != vehicleData.m_path) { CustomCarAI.sm_speedData[vehicleID].currentPath = vehicleData.m_path; CustomCarAI.sm_speedData[vehicleID].SetRandomSpeedMultiplier(0.65f, 1.05f); } CustomCarAI.sm_speedData[vehicleID].ApplySpeedMultiplier(this.m_info); } if ((vehicleData.m_flags & Vehicle.Flags.Stopped) != Vehicle.Flags.None) { vehicleData.m_waitCounter += 1; if (this.CanLeave(vehicleID, ref vehicleData)) { vehicleData.m_flags &= ~Vehicle.Flags.Stopped; vehicleData.m_flags |= Vehicle.Flags.Leaving; vehicleData.m_waitCounter = 0; } } CustomCarAI.SimulationStep(this, vehicleID, ref vehicleData, ref frameData, leaderID, ref leaderData, lodPhysics); if ((vehicleData.m_flags & Vehicle.Flags.GoingBack) == Vehicle.Flags.None && this.ShouldReturnToSource(vehicleID, ref vehicleData)) { this.SetTransportLine(vehicleID, ref vehicleData, 0); } if ((CSLTraffic.Options & OptionsManager.ModOptions.UseRealisticSpeeds) == OptionsManager.ModOptions.UseRealisticSpeeds) { CustomCarAI.sm_speedData[vehicleID].RestoreVehicleSpeed(this.m_info); } }
public bool CustomStartPathFind(ushort vehicleID, ref Vehicle vehicleData, Vector3 startPos, Vector3 endPos, bool startBothWays, bool endBothWays, bool undergroundTarget) { VehicleInfo info = this.m_info; ushort driverInstance = CustomPassengerCarAI.GetDriverInstance(vehicleID, ref vehicleData); if (driverInstance == 0) { return false; } CitizenManager instance = Singleton<CitizenManager>.instance; CitizenInfo info2 = instance.m_instances.m_buffer[(int)driverInstance].Info; NetInfo.LaneType laneTypes = NetInfo.LaneType.Vehicle | NetInfo.LaneType.Pedestrian; VehicleInfo.VehicleType vehicleType = this.m_info.m_vehicleType; bool allowUnderground = (vehicleData.m_flags & Vehicle.Flags.Underground) != 0; PathUnit.Position startPosA; PathUnit.Position startPosB; float num; float num2; PathUnit.Position endPosA; if (CustomPathManager.FindPathPosition(startPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle, info.m_vehicleType, allowUnderground, false, 32f, out startPosA, out startPosB, out num, out num2) && info2.m_citizenAI.FindPathPosition(driverInstance, ref instance.m_instances.m_buffer[(int)driverInstance], endPos, laneTypes, vehicleType, undergroundTarget, out endPosA)) { if (!startBothWays || num < 10f) { startPosB = default(PathUnit.Position); } PathUnit.Position endPosB = default(PathUnit.Position); SimulationManager instance2 = Singleton<SimulationManager>.instance; uint path; if (Singleton<CustomPathManager>.instance.CreatePath(ExtVehicleType.PassengerCar, out path, ref instance2.m_randomizer, instance2.m_currentBuildIndex, startPosA, startPosB, endPosA, endPosB, laneTypes, vehicleType, 20000f)) { if (vehicleData.m_path != 0u) { Singleton<PathManager>.instance.ReleasePath(vehicleData.m_path); } vehicleData.m_path = path; vehicleData.m_flags |= Vehicle.Flags.WaitingPath; return true; } } return false; }
private LHandle pursuit; // an API pursuit handle /// <summary> /// OnBeforeCalloutDisplayed is where we create a blip for the user to see where the pursuit is happening, we initiliaize any variables above and set /// the callout message and position for the API to display /// </summary> /// <returns></returns> public override bool OnBeforeCalloutDisplayed() { //Set our spawn point to be on a street around 300f (distance) away from the player. SpawnPoint = World.GetNextPositionOnStreet(Game.LocalPlayer.Character.Position.Around(300f)); //Create our ped in the world myPed = new Ped("a_m_y_mexthug_01", SpawnPoint, 0f); //Create the vehicle for our ped myVehicle = new Vehicle("DUKES2", SpawnPoint); //Now we have spawned them, check they actually exist and if not return false (preventing the callout from being accepted and aborting it) if (!myPed.Exists()) return false; if (!myVehicle.Exists()) return false; //If we made it this far both exist so let's warp the ped into the driver seat myPed.WarpIntoVehicle(myVehicle, -1); // Show the user where the pursuit is about to happen and block very close peds. this.ShowCalloutAreaBlipBeforeAccepting(SpawnPoint, 15f); this.AddMinimumDistanceCheck(5f, myPed.Position); // Set up our callout message and location this.CalloutMessage = "Example Callout Message"; this.CalloutPosition = SpawnPoint; //Play the police scanner audio for this callout (available as of the 0.2a API) Functions.PlayScannerAudioUsingPosition("CITIZENS_REPORT CRIME_RESIST_ARREST IN_OR_ON_POSITION", SpawnPoint); return base.OnBeforeCalloutDisplayed(); }
public void useToll(Vehicle vehicle) { Console.WriteLine("Vehicle {0} enters tollbooth",vehicle.getVehicleId()+1); vehicle.travel(50); // vehicle spends 50 time units in the toll booth Console.WriteLine("Vehicle {0} exits tollbooth",vehicle.getVehicleId()+1); }
public override void SimulationStep(ushort vehicleID, ref Vehicle data, Vector3 physicsLodRefPos) { var bc = blockCounter[vehicleID]; if (data.m_blockCounter == 0) { bc = 0; } else if (data.m_blockCounter > 1) { bc = (byte)Mathf.Min(bc + 1, 0xff); } if ((data.m_flags & Vehicle.Flags.Congestion) != Vehicle.Flags.None) { bc = (byte)Mathf.Min(bc + 5, 0xff); data.m_flags &= ~Vehicle.Flags.Congestion; } data.m_blockCounter = 1; blockCounter[vehicleID] = bc; if (bc == 0xff) { blockCounter[vehicleID] = 0; Singleton<VehicleManager>.instance.ReleaseVehicle(vehicleID); } else { base.SimulationStep(vehicleID, ref data, physicsLodRefPos); } }
public static Vehicle[] GetData() { Int32 unixTimestamp = (Int32)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; double latMin = 55.2; double lonMin = 8.1; double latMax = 56.7; double lonMax = 12.6; double latStep = (latMax - latMin) / stationsCount; double lonStep = (lonMax - lonMin) / stationsCount; Vehicle[] vehicles = new Vehicle[stationsCount]; for (int i = 0; i < stationsCount; i++) { string trainType = trainTypes[rnd.Next(0, 10)]; int delay = rnd.Next(0, 15); double lat = latMin + latStep * i; double lon = lonMin + lonStep * i; double alt = rnd.NextDouble() * (40 - 20) + 20; int speed = rnd.Next(0, 140); speed = speed < 9 ? 0 : speed; double direction = rnd.NextDouble() * 360; int weight = rnd.Next(1, 90); vehicles[i] = new Vehicle("ab100" + i.ToString(), trainType, stations[i], "e", delay, Math.Round(lat, 6), Math.Round(lon, 6), Math.Round(alt, 1), speed, Math.Round(direction, 1), weight, unixTimestamp); } return vehicles; }
public override void SimulationStep(ushort vehicleID, ref Vehicle data, Vector3 physicsLodRefPos) { // Logger.dbgLog("called ."); byte bc = blockCounter[vehicleID]; if (data.m_blockCounter == 0) { bc = 0; blockCounter[vehicleID] = 0; } else if (data.m_blockCounter > 1) { bc = (byte)Mathf.Min(bc + 1, 255); WBResidentAI6.AddCommuteWait(data, 1); } if ((data.m_flags & Vehicle.Flags.Congestion) != Vehicle.Flags.None) { bc = (byte)Mathf.Min(bc + 5, 255); data.m_flags &= ~Vehicle.Flags.Congestion; } data.m_blockCounter = 1; blockCounter[vehicleID] = bc; if (bc == 255) { blockCounter[vehicleID] = 0; Singleton<VehicleManager>.instance.ReleaseVehicle(vehicleID); } else { base.SimulationStep(vehicleID, ref data, physicsLodRefPos); } }
public void RemoveVehicle(ushort vehicleID, ref Vehicle data) { VehicleManager instance = Singleton<VehicleManager>.instance; ushort num = 0; ushort num2 = this.m_vehicles; int num3 = 0; while (num2 != 0) { if (num2 == vehicleID) { if (num != 0) { instance.m_vehicles.m_buffer [(int)num].m_nextLineVehicle = data.m_nextLineVehicle; } else { this.m_vehicles = data.m_nextLineVehicle; } data.m_nextLineVehicle = 0; data.m_targetBuilding = 0; return; } num = num2; num2 = instance.m_vehicles.m_buffer [(int)num2].m_nextLineVehicle; if (++num3 > 65536) { CODebugBase<LogChannel>.Error (LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace); break; } } }
/// <summary> /// Calculcates the metrics. /// </summary> /// <param name="vehicle"></param> /// <param name="p"></param> /// <returns></returns> public override Dictionary<string, double> Calculate(Vehicle vehicle, AggregatedPoint p) { Dictionary<string, double> result = new Dictionary<string, double>(); result.Add(DISTANCE_KEY, 0); result.Add(TIME_KEY, 0); Aggregated next = p; while (next != null) { if (next is AggregatedPoint) { AggregatedPoint point = (next as AggregatedPoint); this.CalculatePointMetrics(vehicle, result, point); } if (next is AggregatedArc) { AggregatedArc arc = (next as AggregatedArc); this.CalculateArcMetrics(vehicle, result, arc); } next = next.GetNext(); } return result; }
private String parseVehicle(Vehicle veh) { return (String.Format("\"{0}_{1}\": {{\"name\": null, \"short\": null}}", veh.nation.ToLower(), veh.name.Replace("-", "_") )); }
/// <summary> /// Lightweight simulation step method. /// This method is occasionally being called for different cars. /// </summary> /// <param name="vehicleId"></param> /// <param name="vehicleData"></param> /// <param name="physicsLodRefPos"></param> public void TrafficManagerSimulationStep(ushort vehicleId, ref Vehicle vehicleData, Vector3 physicsLodRefPos) { if ((vehicleData.m_flags & Vehicle.Flags.WaitingPath) != 0) { PathManager instance = Singleton<PathManager>.instance; byte pathFindFlags = instance.m_pathUnits.m_buffer[(int)((UIntPtr)vehicleData.m_path)].m_pathFindFlags; if ((pathFindFlags & 4) != 0) { vehicleData.m_pathPositionIndex = 255; vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath; vehicleData.m_flags &= ~Vehicle.Flags.Arriving; this.PathfindSuccess(vehicleId, ref vehicleData); this.TrySpawn(vehicleId, ref vehicleData); } else if ((pathFindFlags & 8) != 0) { vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath; Singleton<PathManager>.instance.ReleasePath(vehicleData.m_path); vehicleData.m_path = 0u; this.PathfindFailure(vehicleId, ref vehicleData); return; } } else if ((vehicleData.m_flags & Vehicle.Flags.WaitingSpace) != 0) { this.TrySpawn(vehicleId, ref vehicleData); } try { CustomVehicleAI.HandleVehicle(vehicleId, ref Singleton<VehicleManager>.instance.m_vehicles.m_buffer[vehicleId], true, true); } catch (Exception e) { Log.Error("CarAI TrafficManagerSimulationStep Error: " + e.ToString()); } Vector3 lastFramePosition = vehicleData.GetLastFramePosition(); int lodPhysics; if (Vector3.SqrMagnitude(physicsLodRefPos - lastFramePosition) >= 1210000f) { lodPhysics = 2; } else if (Vector3.SqrMagnitude(Singleton<SimulationManager>.instance.m_simulationView.m_position - lastFramePosition) >= 250000f) { lodPhysics = 1; } else { lodPhysics = 0; } this.SimulationStep(vehicleId, ref vehicleData, vehicleId, ref vehicleData, lodPhysics); if (vehicleData.m_leadingVehicle == 0 && vehicleData.m_trailingVehicle != 0) { VehicleManager instance2 = Singleton<VehicleManager>.instance; ushort num = vehicleData.m_trailingVehicle; int num2 = 0; while (num != 0) { ushort trailingVehicle = instance2.m_vehicles.m_buffer[(int)num].m_trailingVehicle; VehicleInfo info = instance2.m_vehicles.m_buffer[(int)num].Info; info.m_vehicleAI.SimulationStep(num, ref instance2.m_vehicles.m_buffer[(int)num], vehicleId, ref vehicleData, lodPhysics); num = trailingVehicle; if (++num2 > 16384) { CODebugBase<LogChannel>.Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace); break; } } } int privateServiceIndex = ItemClass.GetPrivateServiceIndex(this.m_info.m_class.m_service); int num3 = (privateServiceIndex == -1) ? 150 : 100; if ((vehicleData.m_flags & (Vehicle.Flags.Spawned | Vehicle.Flags.WaitingPath | Vehicle.Flags.WaitingSpace)) == 0 && vehicleData.m_cargoParent == 0) { Singleton<VehicleManager>.instance.ReleaseVehicle(vehicleId); } else if ((int)vehicleData.m_blockCounter == num3 && Options.enableDespawning) { Singleton<VehicleManager>.instance.ReleaseVehicle(vehicleId); } }
public static Vehicle GetVehicleData(int vehicleId) { //Get vehicle make / model var context = new seleniumScrapeEntities(); IQueryable<string> makeQuery = from v in context.tblVehicles where v.Vehicle_ID_Pk == vehicleId select v.Vehicle_Make; var makeList = makeQuery.ToList(); IQueryable<string> modelQuery = from db in context.tblVehicles where db.Vehicle_ID_Pk == vehicleId select db.Vehicle_Model; var modelList = modelQuery.ToList(); var vehicleData = new Vehicle() { vehicleMake = makeList[0], vehicleModel = modelList[0] }; return vehicleData; }
public int Edit(Vehicle editVehicle) { int editResult = 0; try { using (SqlCommand sqlCommand = new SqlCommand("Update_Vehicle", ManageDatabaseConnection("Open"))) { sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.AddWithValue("@VehicleId", editVehicle.Id); sqlCommand.Parameters.AddWithValue("@Brand", editVehicle.Brand); sqlCommand.Parameters.AddWithValue("@Vehicletype", editVehicle.VehicleType); editResult = Convert.ToInt32(sqlCommand.ExecuteScalar()); sqlCommand.ExecuteNonQuery(); } ManageDatabaseConnection("Close"); } catch (SqlException sqlException) { throw sqlException; } return editResult; }
public static ushort GetDriverInstance2(ushort vehicleID, ref Vehicle data) { CitizenManager instance = Singleton<CitizenManager>.instance; uint num = data.m_citizenUnits; int num2 = 0; while (num != 0u) { uint nextUnit = instance.m_units.m_buffer[(int)((UIntPtr)num)].m_nextUnit; for (int i = 0; i < 5; i++) { uint citizen = instance.m_units.m_buffer[(int)((UIntPtr)num)].GetCitizen(i); if (citizen != 0u) { ushort instance2 = instance.m_citizens.m_buffer[(int)((UIntPtr)citizen)].m_instance; if (instance2 != 0) { return instance2; } } } num = nextUnit; if (++num2 > 524288) { CODebugBase<LogChannel>.Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace); break; } } return 0; }
/// <summary> /// Loads the UIConfiguration from its default path. /// </summary> /// <returns></returns> public static UIConfiguration Load() { string configFile = Path.Combine(Utilities.GetLocalAppDataFolderPath(), "IlsAnsbachOperationViewerConfig.xml"); if (!File.Exists(configFile)) { return new UIConfiguration(); } UIConfiguration configuration = new UIConfiguration(); XDocument doc = XDocument.Load(configFile); XElement vehicleE = doc.Root.Element("Vehicles"); configuration.VehicleMustContainAbbreviations = vehicleE.Attribute("MustContainAbbreviations").Value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); foreach (XElement resE in vehicleE.Elements("Vehicle")) { Vehicle vehicle = new Vehicle(); vehicle.Identifier = resE.Attribute("Identifier").Value; vehicle.Name = resE.Attribute("Name").Value; FileInfo imageFile = new FileInfo(Path.Combine(Utilities.GetWorkingDirectory(Assembly.GetExecutingAssembly()), resE.Attribute("Image").Value)); vehicle.Image = imageFile.FullName; configuration.Vehicles.Add(vehicle); } return configuration; }
protected override bool StartPathFind(ushort vehicleID, ref Vehicle vehicleData) { if ((vehicleData.m_flags & Vehicle.Flags.WaitingTarget) != 0) { return true; } if ((vehicleData.m_flags & Vehicle.Flags.GoingBack) != 0) { if (vehicleData.m_sourceBuilding != 0) { BuildingManager instance = Singleton<BuildingManager>.instance; BuildingInfo info = instance.m_buildings.m_buffer[(int)vehicleData.m_sourceBuilding].Info; Randomizer randomizer = new Randomizer((int)vehicleID); Vector3 vector; Vector3 endPos; info.m_buildingAI.CalculateUnspawnPosition(vehicleData.m_sourceBuilding, ref instance.m_buildings.m_buffer[(int)vehicleData.m_sourceBuilding], ref randomizer, this.m_info, out vector, out endPos); return this.StartPathFind(ExtendedVehicleType.Hearse, vehicleID, ref vehicleData, vehicleData.m_targetPos3, endPos, IsHeavyVehicle(), IgnoreBlocked(vehicleID, ref vehicleData)); } } else if (vehicleData.m_targetBuilding != 0) { BuildingManager instance2 = Singleton<BuildingManager>.instance; BuildingInfo info2 = instance2.m_buildings.m_buffer[(int)vehicleData.m_targetBuilding].Info; Randomizer randomizer2 = new Randomizer((int)vehicleID); Vector3 vector2; Vector3 endPos2; info2.m_buildingAI.CalculateUnspawnPosition(vehicleData.m_targetBuilding, ref instance2.m_buildings.m_buffer[(int)vehicleData.m_targetBuilding], ref randomizer2, this.m_info, out vector2, out endPos2); return this.StartPathFind(ExtendedVehicleType.Hearse, vehicleID, ref vehicleData, vehicleData.m_targetPos3, endPos2, IsHeavyVehicle(), IgnoreBlocked(vehicleID, ref vehicleData)); } return false; }
private void DrawContainerFront(Canvas canvas, Container container, Vehicle currentVehicle) { var length = container.Width/Scale; var height = container.Length/Scale; var x = container.FirstPoint.X/Scale; var z = (container.FirstPoint.Y - currentVehicle.FirstPoint.Y)/Scale; var r = new Rectangle(); r.Width = length; r.Height = height; Brush brush = new SolidColorBrush(); brush = Brushes.White; r.Stroke = new SolidColorBrush(Colors.Black); r.Fill = brush; Canvas.SetLeft(r, x); Canvas.SetTop(r, z); canvas.Children.Add(r); var t = new TextBlock(); t.Text = Math.Round(container.Mass) + " кг"; t.FontSize = 12; Canvas.SetLeft(t, x + 2); var delta = 2; Canvas.SetTop(t, z + 2); canvas.Children.Add(t); t = new TextBlock {Text = container.ShortName, FontSize = 12}; Canvas.SetLeft(t, x + 2); delta = delta + 15; Canvas.SetTop(t, z + delta); canvas.Children.Add(t); }
protected override float CalculateTargetSpeed(ushort vehicleID, ref Vehicle data, float speedLimit, float curve) { if ((data.m_flags & Vehicle.Flags.Emergency2) == Vehicle.Flags.None) return base.CalculateTargetSpeed(vehicleID, ref data, speedLimit, curve); return Mathf.Min(base.CalculateTargetSpeed(vehicleID, ref data, speedLimit * 2, curve * 0.5f), m_info.m_maxSpeed * 2); }
private void DrawContainerUp(Canvas canvas, Container container, Vehicle currentVehicle) { var length = container.Width/Scale; var height = container.Height/Scale; var x = (container.FirstPoint.X - currentVehicle.FirstPoint.X)/Scale; var z = container.FirstPoint.Z/Scale; var rectangle = new Rectangle(); rectangle.Width = length; rectangle.Height = height; Brush brush = new SolidColorBrush(); brush = Brushes.White; rectangle.Stroke = new SolidColorBrush(Colors.Black); rectangle.Fill = brush; Canvas.SetLeft(rectangle, x); Canvas.SetTop(rectangle, canvas.Height - height - z); canvas.Children.Add(rectangle); var textBlock = new TextBlock {Text = Math.Round(container.Mass) + " кг", FontSize = 12}; Canvas.SetLeft(textBlock, x + 2); var delta = 2; Canvas.SetTop(textBlock, canvas.Height - height - z + 2); canvas.Children.Add(textBlock); textBlock = new TextBlock {Text = container.ShortName, FontSize = 12}; Canvas.SetLeft(textBlock, x + 2); delta = delta + 15; Canvas.SetTop(textBlock, canvas.Height - height - z + delta); canvas.Children.Add(textBlock); }
Operator IOperatorProfile.GetOperator(string operatorName, string trafficFileNumber) { Operator operatorFormWeb = new Operator(); try { handHeldService.HandHeldService service = new VSDApp.handHeldService.HandHeldService(); handHeldService.AuthHeader authorize = new VSDApp.handHeldService.AuthHeader(); authorize.password = AppProperties.empPassword; authorize.userName = AppProperties.empUserName; service.authHeader = authorize; handHeldService.InquireCompanyProfileResponseItem responseItem = new VSDApp.handHeldService.InquireCompanyProfileResponseItem(); operatorFormWeb = new Operator(); responseItem = service.inquireCompanyProfile("H-PS-ICP-1", trafficFileNumber, null); if (responseItem.response.code.Equals("1000", StringComparison.CurrentCultureIgnoreCase)) { operatorFormWeb.OperatorOVRRScore = responseItem.company.riskRating.riskRatingName; operatorFormWeb.OperatorName = responseItem.company.ownerName; operatorFormWeb.OperatorNameAr = responseItem.company.ownerNameArabic; operatorFormWeb.TrafficFileNumber = responseItem.company.trafficFileNumber; Vehicle[] copyResponseVehicles = new Vehicle[responseItem.company.vehicles.Length]; int count = 0; foreach (handHeldService.Vehicle responseVehicles in responseItem.company.vehicles) { copyResponseVehicles[count] = new Vehicle(); copyResponseVehicles[count].RiskRating = responseVehicles.riskRating.riskRatingName; copyResponseVehicles[count].PlateNumber = responseVehicles.plateDetails.number; copyResponseVehicles[count].PlateCode = responseVehicles.plateDetails.code; copyResponseVehicles[count].PlateCategory = responseVehicles.plateDetails.category; copyResponseVehicles[count].Emirate = ((IDBDataLoad)DBDataLoadManager.GetInstance()).GetPlateEmirate(responseVehicles.plateDetails.source); copyResponseVehicles[count].PlateSource = responseVehicles.plateDetails.source; count++; } operatorFormWeb.TopViolatingVehicles = copyResponseVehicles; } else if (responseItem.response.code.Equals("2000")) { AppProperties.businessError = true; AppProperties.errorMessageFromBusiness = responseItem.response.message; } else { AppProperties.NotFoundError = true; AppProperties.errorMessageFromBusiness = responseItem.response.message; // System.Windows.Forms.MessageBox.Show(responseItem.response.message); return null; } } catch (Exception ex) { AppProperties.IsException = true; AppProperties.errorMessageFromBusiness = ex.InnerException.Message; CommonUtils.WriteLog(ex.StackTrace); return null; } return operatorFormWeb; }
private bool ArriveAtTarget(ushort vehicleID, ref Vehicle data) { VehicleManager instance = Singleton<VehicleManager>.instance; ushort num = data.m_firstCargo; data.m_firstCargo = 0; int num2 = 0; while (num != 0) { ushort nextCargo = instance.m_vehicles.m_buffer [(int)num].m_nextCargo; instance.m_vehicles.m_buffer [(int)num].m_nextCargo = 0; instance.m_vehicles.m_buffer [(int)num].m_cargoParent = 0; VehicleInfo info = instance.m_vehicles.m_buffer [(int)num].Info; if (data.m_targetBuilding != 0) { info.m_vehicleAI.SetSource (num, ref instance.m_vehicles.m_buffer [(int)num], data.m_targetBuilding); info.m_vehicleAI.SetTarget (num, ref instance.m_vehicles.m_buffer [(int)num], instance.m_vehicles.m_buffer [(int)num].m_targetBuilding); } num = nextCargo; if (++num2 > 65536) { CODebugBase<LogChannel>.Error (LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace); break; } } data.m_waitCounter = 0; data.m_flags |= Vehicle.Flags.WaitingLoading; return false; }
public override void SimulationStep(ushort vehicleID, ref Vehicle vehicleData, ref Vehicle.Frame frameData, ushort leaderID, ref Vehicle leaderData, int lodPhysics) { if ((TrafficMod.Options & OptionsManager.ModOptions.UseRealisticSpeeds) == OptionsManager.ModOptions.UseRealisticSpeeds) { var speedData = CarSpeedData.Of(vehicleID); if (speedData.SpeedMultiplier == 0 || speedData.CurrentPath != vehicleData.m_path) { speedData.CurrentPath = vehicleData.m_path; speedData.SetRandomSpeedMultiplier(0.7f, 1.15f); } m_info.ApplySpeedMultiplier(CarSpeedData.Of(vehicleID)); } base.SimulationStep(vehicleID, ref vehicleData, ref frameData, leaderID, ref leaderData, lodPhysics); if ((vehicleData.m_flags & Vehicle.Flags.Stopped) != 0 && this.CanLeave(vehicleID, ref vehicleData)) { vehicleData.m_flags &= ~Vehicle.Flags.Stopped; vehicleData.m_flags |= Vehicle.Flags.Leaving; } if ((vehicleData.m_flags & (Vehicle.Flags.TransferToSource | Vehicle.Flags.GoingBack)) == Vehicle.Flags.TransferToSource && this.ShouldReturnToSource(vehicleID, ref vehicleData)) { this.SetTarget(vehicleID, ref vehicleData, 0); } if ((TrafficMod.Options & OptionsManager.ModOptions.UseRealisticSpeeds) == OptionsManager.ModOptions.UseRealisticSpeeds) { m_info.RestoreVehicleSpeed(CarSpeedData.Of(vehicleID)); } }
public void Start(Vehicle vechicle) { // Send details to Administrator // Print Console.WriteLine("Race Vehicle started, Name : {0} | Model : {1} | Driver : {2}", vechicle.Name, vechicle.Model, vechicle.DriverName); }
/// <summary> /// Creates a new target. /// </summary> /// <param name="stream"></param> /// <param name="dynamicGraph"></param> /// <param name="interpreter"></param> /// <param name="tagsIndex"></param> /// <param name="vehicle"></param> public CHEdgeGraphFileStreamTarget(Stream stream, DynamicGraphRouterDataSource<CHEdgeData> dynamicGraph, IOsmRoutingInterpreter interpreter, ITagsCollectionIndex tagsIndex, Vehicle vehicle) : base(dynamicGraph, interpreter, tagsIndex, vehicle) { _graph = dynamicGraph; _graphStream = stream; }
public override bool OnBeforeCalloutDisplayed() { spawnPoint = World.GetNextPositionOnStreet(Game.LocalPlayer.Character.Position.Around(300f)); if (Vector3.Distance(Game.LocalPlayer.Character.Position, spawnPoint) < 30.0f) { return(false); } recklessDriver = new Ped(Vector3.Zero); if (!recklessDriver.Exists()) { return(false); } string vModel = vehicleModel.GetRandomElement(true); for (int i = 0; i < 5; i++) { if (new Model(vModel).IsValid) { break; } else { Logger.LogTrivial(this.GetType().Name, "Vehicle Model < " + vModel + " > is invalid. Choosing new model..."); vModel = vehicleModel.GetRandomElement(false); } } if (!new Model(vModel).IsValid) { Logger.LogTrivial(this.GetType().Name, "Aborting: Final Vehicle Model < " + vModel + " > is invalid"); return(false); } vehicle = new Vehicle(vModel, spawnPoint, spawnPoint.GetClosestVehicleNodeHeading()); if (!vehicle.Exists()) { return(false); } if (vehicle.Model == new Model("phantom") || vehicle.Model == new Model("docktug") || vehicle.Model == new Model("packer") || vehicle.Model == new Model("hauler") || vehicle.Model == new Model("barracks2")) { vehicle.TopSpeed = MathHelper.GetRandomSingle(vehicle.TopSpeed + 25, vehicle.TopSpeed + 250f); vehicle.DriveForce = MathHelper.GetRandomSingle(vehicle.DriveForce, vehicle.DriveForce + 25f); if (Globals.Random.Next(5) <= 3) { possibleTrailer = new Vehicle(trailerModel.GetRandomElement(true), vehicle.GetOffsetPosition(new Vector3(0f, -6.0f, 0f)), vehicle.Heading); vehicle.Trailer = possibleTrailer; } } //vehicle.Heading = vehicle.Position.GetClosestVehicleNodeHeading(); recklessDriver.WarpIntoVehicle(vehicle, -1); recklessDriver.BlockPermanentEvents = true; if (Globals.Random.Next(5) <= 3) { vehicle.InstallRandomMods(); } // Show the user where the pursuit is about to happen and block very close peds. this.ShowCalloutAreaBlipBeforeAccepting(spawnPoint, 45f); this.AddMinimumDistanceCheck(10f, vehicle.Position); // Set up our callout message and location this.CalloutMessage = "Reckless driver"; this.CalloutPosition = spawnPoint; Functions.PlayScannerAudioUsingPosition("ATTENTION_ALL_UNITS CRIME_RECKLESS_DRIVER IN_OR_ON_POSITION UNITS_RESPOND_CODE_03", spawnPoint); return(base.OnBeforeCalloutDisplayed()); }
public void UpdateVehiclePosition(VehicleMovementData vehicleModel, Optional <RemotePlayer> player) { Vector3 remotePosition = vehicleModel.Position; Vector3 remoteVelocity = vehicleModel.Velocity; Quaternion remoteRotation = vehicleModel.Rotation; Vector3 angularVelocity = vehicleModel.AngularVelocity; Vehicle vehicle = null; SubRoot subRoot = null; Optional <GameObject> opGameObject = GuidHelper.GetObjectFrom(vehicleModel.Guid); if (opGameObject.IsPresent()) { GameObject gameObject = opGameObject.Get(); vehicle = gameObject.GetComponent <Vehicle>(); subRoot = gameObject.GetComponent <SubRoot>(); MultiplayerVehicleControl mvc = null; if (subRoot != null) { mvc = subRoot.gameObject.EnsureComponent <MultiplayerCyclops>(); } else if (vehicle != null) { SeaMoth seamoth = vehicle as SeaMoth; Exosuit exosuit = vehicle as Exosuit; if (seamoth) { mvc = seamoth.gameObject.EnsureComponent <MultiplayerSeaMoth>(); } else if (exosuit) { mvc = exosuit.gameObject.EnsureComponent <MultiplayerExosuit>(); if (vehicleModel.GetType() == typeof(ExosuitMovementData)) { ExosuitMovementData exoSuitMovement = (ExosuitMovementData)vehicleModel; mvc.SetArmPositions(exoSuitMovement.LeftAimTarget, exoSuitMovement.RightAimTarget); } else { Log.Error("Got exosuit vehicle but no ExosuitMovementData"); } } } if (mvc != null) { mvc.SetPositionVelocityRotation(remotePosition, remoteVelocity, remoteRotation, angularVelocity); mvc.SetThrottle(vehicleModel.AppliedThrottle); mvc.SetSteeringWheel(vehicleModel.SteeringWheelYaw, vehicleModel.SteeringWheelPitch); } } if (player.IsPresent()) { RemotePlayer playerInstance = player.Get(); playerInstance.SetVehicle(vehicle); playerInstance.SetSubRoot(subRoot); playerInstance.SetPilotingChair(subRoot?.GetComponentInChildren <PilotingChair>()); playerInstance.AnimationController.UpdatePlayerAnimations = false; } }
private void OnVehiclePrefabLoaded(TechType techType, GameObject prefab, string guid, Vector3 spawnPosition, Quaternion spawnRotation, Optional <List <InteractiveChildObjectIdentifier> > interactiveChildIdentifiers, Optional <string> dockingBayGuid, string name, Vector3[] hsb, Vector3[] colours) { // Partially copied from SubConsoleCommand.OnSubPrefabLoaded GameObject gameObject = Utils.SpawnPrefabAt(prefab, null, spawnPosition); gameObject.transform.rotation = spawnRotation; gameObject.SetActive(true); gameObject.SendMessage("StartConstruction", SendMessageOptions.DontRequireReceiver); CrafterLogic.NotifyCraftEnd(gameObject, CraftData.GetTechType(gameObject)); Rigidbody rigidBody = gameObject.GetComponent <Rigidbody>(); rigidBody.isKinematic = false; GuidHelper.SetNewGuid(gameObject, guid); // Updates names and colours with persisted data if (techType == TechType.Seamoth || techType == TechType.Exosuit) { Vehicle vehicle = gameObject.GetComponent <Vehicle>(); if (dockingBayGuid.IsPresent()) { GameObject dockingBayBase = GuidHelper.RequireObjectFrom(dockingBayGuid.Get()); VehicleDockingBay dockingBay = dockingBayBase.GetComponentInChildren <VehicleDockingBay>(); dockingBay.DockVehicle(vehicle); } else if (techType == TechType.Exosuit) { // exosuits tend to fall through the ground after spawning. This should prevent that vehicle.ReflectionSet("onGround", true); } if (!string.IsNullOrEmpty(name)) { vehicle.vehicleName = name; vehicle.subName.DeserializeName(vehicle.vehicleName); } if (colours != null) { Vector3[] colour = new Vector3[5]; for (int i = 0; i < hsb.Length; i++) { colour[i] = hsb[i]; } vehicle.vehicleColors = colour; vehicle.subName.DeserializeColors(vehicle.vehicleColors); } } else if (techType == TechType.Cyclops) { GameObject target = GuidHelper.RequireObjectFrom(guid); SubNameInput subNameInput = target.RequireComponentInChildren <SubNameInput>(); SubName subNameTarget = (SubName)subNameInput.ReflectionGet("target"); subNameInput.OnNameChange(name); for (int i = 0; i < hsb.Length; i++) { subNameInput.SetSelected(i); Color tmpColour = new Vector4(colours[i].x, colours[i].y, colours[i].z); subNameTarget.SetColor(i, hsb[i], tmpColour); subNameTarget.DeserializeColors(hsb); } } if (interactiveChildIdentifiers.IsPresent()) { VehicleChildObjectIdentifierHelper.SetInteractiveChildrenGuids(gameObject, interactiveChildIdentifiers.Get()); //Copy From ConstructorBeginCraftingProcessor } // Send event after everthing is created if (VehicleCreated != null) { VehicleCreated(gameObject); } }
private ushort GetClosestTarget(ushort vehicleID, ref HashSet <ushort> targets, bool immediateOnly, SearchDirection immediateDirection) { Vehicle vehicle = Singleton <VehicleManager> .instance.m_vehicles.m_buffer[vehicleID]; Building[] buildings = Singleton <BuildingManager> .instance.m_buildings.m_buffer; List <ushort> removals = new List <ushort>(); ushort target = vehicle.m_targetBuilding; if (_master.ContainsKey(target) && _master[target].IsValid && _master[target].Vehicle != vehicleID) { target = 0; } int targetProblematicLevel = 0; float targetdistance = float.PositiveInfinity; float distance = float.PositiveInfinity; Vector3 velocity = vehicle.GetLastFrameVelocity(); Vector3 position = vehicle.GetLastFramePosition(); double bearing = double.PositiveInfinity; double facing = Math.Atan2(velocity.z, velocity.x); if (targets.Contains(target)) { if (!Helper.IsBuildingWithDead(target)) { removals.Add(target); target = 0; } else { if ((buildings[target].m_problems & Notification.Problem.Death) != Notification.Problem.None) { if (Identity.ModConf.PrioritizeTargetWithRedSigns && (buildings[target].m_problems & Notification.Problem.MajorProblem) != Notification.Problem.None) { targetProblematicLevel = 2; } else { targetProblematicLevel = 1; } } Vector3 a = buildings[target].m_position; targetdistance = distance = (a - position).sqrMagnitude; bearing = Math.Atan2(a.z - position.z, a.x - position.x); } } else if (!immediateOnly) { target = 0; } foreach (ushort id in targets) { if (target == id) { continue; } if (!Helper.IsBuildingWithDead(id)) { removals.Add(id); continue; } if (_master.ContainsKey(id) && _master[id].IsValid && !_master[id].IsChallengable) { continue; } if (_master.ContainsKey(id) && _master[id].IsValid && _master[id].Vehicle != vehicleID) { Vehicle vehicle2 = Singleton <VehicleManager> .instance.m_vehicles.m_buffer[_master[id].Vehicle]; if (vehicle2.m_flags.IsFlagSet(Vehicle.Flags.Spawned) && vehicle2.m_path != 0 && Singleton <PathManager> .instance.m_pathUnits.m_buffer[vehicle2.m_path].m_nextPathUnit == 0) { byte b = vehicle2.m_pathPositionIndex; if (b == 255) { b = 0; } if ((b & 1) == 0) { b += 1; } if ((b >> 1) + 1 >= Singleton <PathManager> .instance.m_pathUnits.m_buffer[vehicle2.m_path].m_positionCount) { continue; } } } Vector3 p = buildings[id].m_position; float d = (p - position).sqrMagnitude; int candidateProblematicLevel = 0; if ((buildings[id].m_problems & Notification.Problem.Death) != Notification.Problem.None) { if (Identity.ModConf.PrioritizeTargetWithRedSigns && (buildings[id].m_problems & Notification.Problem.MajorProblem) != Notification.Problem.None) { candidateProblematicLevel = 2; } else { candidateProblematicLevel = 1; } } if (_oldtargets.ContainsKey(vehicleID) && _oldtargets[vehicleID].Count > 5 && targetProblematicLevel >= candidateProblematicLevel) { continue; } if (_master.ContainsKey(id) && _master[id].IsValid && _master[id].IsChallengable) { if (targetProblematicLevel > candidateProblematicLevel) { continue; } if (d > targetdistance * 0.9) { continue; } if (d > distance) { continue; } if (d > _master[id].Distance * 0.9) { continue; } double angle = Helper.GetAngleDifference(facing, Math.Atan2(p.z - position.z, p.x - position.x)); int immediateLevel = GetImmediateLevel(d, angle, immediateDirection); if (immediateLevel == 0) { continue; } if (_oldtargets.ContainsKey(vehicleID) && _oldtargets[vehicleID].Contains(id)) { continue; } } else { double angle = Helper.GetAngleDifference(facing, Math.Atan2(p.z - position.z, p.x - position.x)); int immediateLevel = GetImmediateLevel(d, angle, immediateDirection); if (immediateOnly && immediateLevel == 0) { continue; } if (_oldtargets.ContainsKey(vehicleID) && _oldtargets[vehicleID].Contains(id)) { continue; } if (targetProblematicLevel > candidateProblematicLevel) { continue; } if (targetProblematicLevel < candidateProblematicLevel) { // No additonal conditions at the moment. Problematic buildings always have priority over nonproblematic buildings } else { if (d > targetdistance * 0.9) { continue; } if (d > distance) { continue; } if (immediateLevel > 0) { // If it's that close, no need to further qualify its priority } else if (IsAlongTheWay(d, angle)) { // If it's in the general direction the vehicle is facing, it's good enough } else if (!double.IsPositiveInfinity(bearing)) { if (IsAlongTheWay(d, Helper.GetAngleDifference(bearing, Math.Atan2(p.z - position.z, p.x - position.x)))) { // If it's in the general direction along the vehicle's target path, we will have to settle for it at this point } else { continue; } } else { // If it's not closeby and not in the direction the vehicle is facing, but our vehicle also has no bearing, we will take whatever is out there } } } target = id; targetProblematicLevel = candidateProblematicLevel; distance = d; } foreach (ushort id in removals) { _master.Remove(id); targets.Remove(id); } return(target); }
private SearchDirection GetImmediateSearchDirection(ushort vehicleID) { Vehicle vehicle = Singleton <VehicleManager> .instance.m_vehicles.m_buffer[vehicleID]; PathManager pm = Singleton <PathManager> .instance; PathUnit pu = pm.m_pathUnits.m_buffer[vehicle.m_path]; byte pi = vehicle.m_pathPositionIndex; if (pi == 255) { pi = 0; } PathUnit.Position position = pu.GetPosition(pi >> 1); NetManager nm = Singleton <NetManager> .instance; NetSegment segment = nm.m_segments.m_buffer[position.m_segment]; int laneCount = 0; int leftLane = -1; float leftPosition = float.PositiveInfinity; int rightLane = -1; float rightPosition = float.NegativeInfinity; for (int i = 0; i < segment.Info.m_lanes.Length; i++) { NetInfo.Lane l = segment.Info.m_lanes[i]; if (l.m_laneType != NetInfo.LaneType.Vehicle || l.m_vehicleType != VehicleInfo.VehicleType.Car) { continue; } laneCount++; if (l.m_position < leftPosition) { leftLane = i; leftPosition = l.m_position; } if (l.m_position > rightPosition) { rightLane = i; rightPosition = l.m_position; } } SearchDirection dir = SearchDirection.None; if (laneCount == 0) { } else if (position.m_lane != leftLane && position.m_lane != rightLane) { dir = SearchDirection.Ahead; } else if (leftLane == rightLane) { dir = SearchDirection.Left | SearchDirection.Right | SearchDirection.Ahead; } else if (laneCount == 2 && segment.Info.m_lanes[leftLane].m_direction != segment.Info.m_lanes[rightLane].m_direction) { dir = SearchDirection.Left | SearchDirection.Right | SearchDirection.Ahead; } else { if (position.m_lane == leftLane) { dir = SearchDirection.Left | SearchDirection.Ahead; } else { dir = SearchDirection.Right | SearchDirection.Ahead; } } return(dir); }
public ushort AssignTarget(ushort vehicleID) { Vehicle vehicle = Singleton <VehicleManager> .instance.m_vehicles.m_buffer[vehicleID]; ushort target = 0; if (vehicle.m_sourceBuilding != _buildingID) { return(target); } if (Singleton <PathManager> .instance.m_pathUnits.m_buffer[vehicle.m_path].m_nextPathUnit == 0) { byte b = vehicle.m_pathPositionIndex; if (b == 255) { b = 0; } if ((b & 1) == 0) { b += 1; } if ((b >> 1) + 1 >= Singleton <PathManager> .instance.m_pathUnits.m_buffer[vehicle.m_path].m_positionCount) { return(target); } } ushort current = vehicle.m_targetBuilding; if (!Helper.IsBuildingWithDead(current)) { _oldtargets.Remove(vehicleID); _master.Remove(current); _primary.Remove(current); _secondary.Remove(current); current = 0; } else if (_master.ContainsKey(current)) { if (_master[current].IsValid && _master[current].Vehicle != vehicleID) { current = 0; } } int vehicleStatus = Dispatcher.GetHearseStatus(ref vehicle); if (current != 0 && vehicleStatus == Dispatcher.VEHICLE_STATUS_HEARSE_COLLECT && _lastchangetimes.ContainsKey(vehicleID) && (SimulationManager.instance.m_currentGameTime - _lastchangetimes[vehicleID]).TotalDays < 0.5) { return(target); } bool immediateOnly = (_primary.Contains(current) || _secondary.Contains(current)); SearchDirection immediateDirection = GetImmediateSearchDirection(vehicleID); if (immediateOnly && immediateDirection == SearchDirection.None) { target = current; } else { target = GetClosestTarget(vehicleID, ref _primary, immediateOnly, immediateDirection); if (target == 0) { target = GetClosestTarget(vehicleID, ref _secondary, immediateOnly, immediateDirection); } } if (target == 0) { _oldtargets.Remove(vehicleID); if ((vehicle.m_targetBuilding != 0 && WithinPrimaryRange(vehicle.m_targetBuilding)) || _checkups.Count == 0) { target = vehicle.m_targetBuilding; } else { target = _checkups[0]; _checkups.RemoveAt(0); } } return(target); }
public async void Main() { FixedANPR lastTriggeredANPRCamera = null; DateTime timeLastTriggeredANPRCamera = DateTime.Now; string lastTriggeredDir = ""; FixedANPR LastBlockedFixedANPR = null; DateTime timeLastBlockedANPR = DateTime.Now; while (true) { await Delay(5); if (Game.Player != null && Game.Player.Character != null && Game.Player.Character.Exists() && Game.Player.Character.IsInVehicle() && Game.Player.Character.CurrentVehicle.Exists()) { Vehicle playerVeh = Game.Player.Character.CurrentVehicle; if (BlipsCreated && !ANPRModels.Contains(playerVeh.Model)) { RemoveANPRBlips(); } else if (FixedANPRAlertsToggle && !BlipsCreated && ANPRModels.Contains(playerVeh.Model)) { CreateFixedANPRBlips(); } if (RouteBlip != null && RouteBlip.Exists() && Vector3.Distance(playerVeh.Position, RouteBlip.Position) < 140) { RouteBlip.ShowRoute = false; RouteBlip = null; } //Fixed ANPR Detection if (playerVeh.Driver == Game.Player.Character && playerVeh.Speed > 0.2f) { string plate = API.GetVehicleNumberPlateText(playerVeh.Handle).Replace(" ", string.Empty); if (PlateInfo.ContainsKey(plate)) { FixedANPR anpr = FixedANPRCameras.OrderBy(x => Vector3.Distance(x.Location, playerVeh.Position)).FirstOrDefault(); if (anpr != null) { float ZDiff = Math.Abs(anpr.Z - playerVeh.Position.Z); string dir = DegreesToCardinal(playerVeh.Heading); if (Vector3.Distance(anpr.Location, playerVeh.Position) <= FixedANPRRadius && ZDiff < 3.5f && (lastTriggeredANPRCamera != anpr || (DateTime.Now - timeLastTriggeredANPRCamera).Seconds > 20 || lastTriggeredDir != dir)) { if ((anpr != LastBlockedFixedANPR || (DateTime.Now - timeLastTriggeredANPRCamera).Seconds > 120) && API.GetRandomIntInRange(0, 100) < ANPRHitChance) { //alert hit await Delay(1800); dir = DegreesToCardinal(playerVeh.Heading); string modelName = API.GetDisplayNameFromVehicleModel((uint)API.GetEntityModel(playerVeh.Handle)); string colour = VehicleColour.GetVehicleColour(playerVeh.Handle).PrimarySimpleColourName; TriggerServerEvent("CameraTech:FixedANPRAlert", colour, modelName, anpr.Name, dir, plate); lastTriggeredANPRCamera = anpr; timeLastTriggeredANPRCamera = DateTime.Now; lastTriggeredDir = dir; LastBlockedFixedANPR = null; } else { if (LastBlockedFixedANPR != anpr) { timeLastBlockedANPR = DateTime.Now; } LastBlockedFixedANPR = anpr; } } } } } } else if (BlipsCreated) { RemoveANPRBlips(); } } }
public ActionResult SaveOrUpdate(VehicleViewModel model) { string newData = string.Empty, oldData = string.Empty; try { int id = model.Id; Vehicle vehicle = null; Vehicle oldVehicle = null; if (model.Id == 0) { vehicle = new Vehicle { VehicleNo = model.VehicleNo, Capacity = model.Capacity, IsActive = true, GPSDeviceId = model.GPSDeviceId }; oldVehicle = new Vehicle(); oldData = new JavaScriptSerializer().Serialize(oldVehicle); newData = new JavaScriptSerializer().Serialize(vehicle); } else { vehicle = genericService.GetList <Vehicle>().Where(o => o.Id == model.Id).FirstOrDefault(); oldVehicle = genericService.GetList <Vehicle>().Where(o => o.Id == model.Id).FirstOrDefault(); oldData = new JavaScriptSerializer().Serialize(new Vehicle() { Id = oldVehicle.Id, Capacity = oldVehicle.Capacity, IsActive = oldVehicle.IsActive, GPSDeviceId = model.GPSDeviceId }); vehicle.VehicleNo = model.VehicleNo; vehicle.Capacity = model.Capacity; vehicle.GPSDeviceId = model.GPSDeviceId; vehicle.IsActive = model.IsActive; newData = new JavaScriptSerializer().Serialize(new Vehicle() { Id = vehicle.Id, VehicleNo = vehicle.VehicleNo, IsActive = vehicle.IsActive }); } genericService.SaveOrUpdate <Vehicle>(vehicle, vehicle.Id); //CommonService.SaveDataAudit(new DataAudit() //{ // Entity = "Vehicles", // NewData = newData, // OldData = oldData, // UpdatedOn = DateTime.Now, // UserId = User.Identity.GetUserId() //}); TempData["Message"] = ResourceData.SaveSuccessMessage; } catch (Exception ex) { TempData["Message"] = string.Format(ResourceData.SaveErrorMessage, ex.InnerException); } return(RedirectToAction("Index", "Vehicle")); }
private void ReleaseVehicleImplementation(ushort vehicleId, ref Vehicle vehicleData) { Log.Error("CustomVehicleManager.ReleaseVehicleImplementation called."); }
private void CalculateSpeed(Vehicle vehicle, float deltaTime) { TramIntersection tramIntersection; if (vehicle.Id.Contains("07:52 - 50")) { var a = 4; } //Check if is on stop if (vehicle.Speed < CalculationConsts.EPSILON && !vehicle.IsOnStop && vehicle.IsBusStopReached()) { vehicle.IsOnStop = true; int timeToStop = vehicle.Departure.NextStopIntervals.Count > vehicle.LastVisitedStops.Count ? (int)vehicle.Departure.NextStopIntervals[vehicle.LastVisitedStops.Count] : 0; float idealStopTimeInterval = vehicle.Departure.NextStopIntervals.Take(vehicle.LastVisitedStops.Count + 1).Sum(); vehicle.DelaysHistory.Add((mainController.ActualRealTime - vehicle.StartTime.AddMinutes(idealStopTimeInterval)).TotalSeconds); //int timeToStop = vehicle.Departure.NextStopIntervals.Count > vehicle.LastVisitedStops.Count ? (int)vehicle.Departure.NextStopIntervals[vehicle.LastVisitedStops.Count] : 0; //vehicle.DelaysHistory.Add(((mainController.ActualRealTime - vehicle.LastDepartureTime).TotalMinutes - timeToStop) * 60); double timeToBoard = capacityController.SetTramCapacity(vehicle); vehicle.Speed = (float)timeToBoard * VehicleConsts.ACCELERATION * 3600 / 1000; // when speed comes to 0, then tram will run } else if (vehicle.Speed < CalculationConsts.EPSILON && !vehicle.IsOnStop && vehicle.IsIntersectionReached(out tramIntersection)) { if (vehicle.CurrentIntersection != null && !tramIntersection.Equals(vehicle.CurrentIntersection)) { DequeueIntersection(vehicle.CurrentIntersection); vehicle.LastIntersection = vehicle.CurrentIntersection; vehicle.CurrentIntersection = null; } if ((tramIntersection.CurrentVehicle == null && tramIntersection.Vehicles.Count == 0) || tramIntersection.CurrentVehicle.Equals(vehicle)) { tramIntersection.CurrentVehicle = vehicle; vehicle.CurrentIntersection = tramIntersection; vehicle.Speed = PhysicsHelper.GetNewSpeed(vehicle.Speed, deltaTime, true); } else if (!tramIntersection.Vehicles.Any(v => v.Equals(vehicle))) { tramIntersection.Vehicles.Enqueue(vehicle); } } else if (vehicle.Speed < CalculationConsts.EPSILON && !vehicle.IsOnStop && vehicle.IsOnLights() && !vehicle.IsOnLightsAndHasRedLight(deltaTime)) { vehicle.Speed = PhysicsHelper.GetNewSpeed(vehicle.Speed, deltaTime, true); } //When is on stop, check if can run else if (vehicle.IsOnStop) { if (vehicle.Speed < CalculationConsts.EPSILON && vehicle.CanArleadyStart(mainController.ActualRealTime)) { vehicle.IsOnStop = false; vehicle.LastVisitedStop = vehicle.Position.Node1 != null && vehicle.Position.Node1.Type == NodeType.TramStop && vehicle.LastVisitedStop != vehicle.Position.Node1 ? vehicle.Position.Node1 : vehicle.Position.Node2; vehicle.LastVisitedStops.Add(vehicle.LastVisitedStop); vehicle.Speed = PhysicsHelper.GetNewSpeed(vehicle.Speed, deltaTime, true); float distanceToNextStop = vehicle.Line.MainNodes.Last().Equals(vehicle.LastVisitedStop) ? 0 : vehicle.Line.GetNextStopDistance(vehicle.LastVisitedStop); int timeToNextStop = vehicle.Departure.NextStopIntervals.Count > vehicle.LastVisitedStops.Count ? (int)vehicle.Departure.NextStopIntervals[vehicle.LastVisitedStops.Count] : 0; timeToNextStop *= 60; if (vehicle.DelaysHistory.Any()) { timeToNextStop -= 10 + (int)vehicle.DelaysHistory.Last(); } vehicle.MaxSpeed = Math.Min(VehicleConsts.MAX_SPEED, timeToNextStop <= 0 ? int.MaxValue : PhysicsHelper.GetMaxSpeed(distanceToNextStop, timeToNextStop)); vehicle.LastDepartureTime = mainController.ActualRealTime; } else { vehicle.Speed = PhysicsHelper.GetNewSpeed(vehicle.Speed, deltaTime, false); } } else if (vehicle.IsAnyVehicleClose(deltaTime)) { vehicle.Speed = PhysicsHelper.GetNewSpeed(vehicle.Speed, deltaTime, false); } else if (vehicle.IsOnLights() && vehicle.IsOnLightsAndHasRedLight(deltaTime)) { vehicle.Speed = PhysicsHelper.GetNewSpeed(vehicle.Speed, deltaTime, false); } //Check if there is any obstacle on road (intersection, stop) else if (!vehicle.IsStraightRoad(deltaTime)) { vehicle.Speed = PhysicsHelper.GetNewSpeed(vehicle.Speed, deltaTime, false); } else if (vehicle.CurrentIntersection != null) { if (vehicle.Speed < VehicleConsts.MAX_CROSS_SPEED) { vehicle.Speed = PhysicsHelper.GetNewSpeed(vehicle.Speed, deltaTime, true); } else { vehicle.Speed = PhysicsHelper.GetNewSpeed(vehicle.Speed, deltaTime, false); } } else if (vehicle.Speed < (vehicle.MaxSpeed ?? VehicleConsts.MAX_SPEED)) { vehicle.Speed = PhysicsHelper.GetNewSpeed(vehicle.Speed, deltaTime, true); } else { vehicle.Speed = PhysicsHelper.GetNewSpeed(vehicle.Speed, deltaTime, false); } vehicle.NormalizeSpeed(); }
/// Create a Vehicle Modification from an XmlNode and return the TreeNodes for it. /// <param name="objXmlMod">XmlNode to create the object from.</param> /// <param name="objNode">TreeNode to populate a TreeView.</param> /// <param name="objParent">Vehicle that the mod will be attached to.</param> /// <param name="intMarkup">Discount or markup that applies to the base cost of the mod.</param> public void Create(XmlNode objXmlMod, TreeNode objNode, Vehicle objParent, int intMarkup = 0) { if (objParent == null) { throw new ArgumentNullException(nameof(objParent)); } Parent = objParent; if (objXmlMod == null) { Utils.BreakIfDebug(); } objXmlMod.TryGetStringFieldQuickly("name", ref _strName); objXmlMod.TryGetStringFieldQuickly("category", ref _strCategory); objXmlMod.TryGetStringFieldQuickly("limit", ref _strLimit); objXmlMod.TryGetStringFieldQuickly("slots", ref _strSlots); objXmlMod.TryGetStringFieldQuickly("weaponmountcategories", ref _strWeaponMountCategories); objXmlMod.TryGetStringFieldQuickly("avail", ref _strAvail); // Check for a Variable Cost. if (objXmlMod["cost"] != null) { if (objXmlMod["cost"].InnerText.StartsWith("Variable")) { int intMin; var intMax = 0; char[] chrParentheses = { '(', ')' }; string strCost = objXmlMod["cost"].InnerText.Replace("Variable", string.Empty).Trim(chrParentheses); if (strCost.Contains("-")) { string[] strValues = strCost.Split('-'); intMin = Convert.ToInt32(strValues[0]); intMax = Convert.ToInt32(strValues[1]); } else { intMin = Convert.ToInt32(strCost.Replace("+", string.Empty)); } if (intMin != 0 || intMax != 0) { var frmPickNumber = new frmSelectNumber(); if (intMax == 0) { intMax = 1000000; } frmPickNumber.Minimum = intMin; frmPickNumber.Maximum = intMax; frmPickNumber.Description = LanguageManager.Instance.GetString("String_SelectVariableCost").Replace("{0}", DisplayNameShort); frmPickNumber.AllowCancel = false; frmPickNumber.ShowDialog(); _strCost = frmPickNumber.SelectedValue.ToString(); } } else { _strCost = objXmlMod["cost"].InnerText; } } _intMarkup = intMarkup; objXmlMod.TryGetStringFieldQuickly("source", ref _strSource); objXmlMod.TryGetStringFieldQuickly("page", ref _strPage); if (GlobalOptions.Instance.Language != "en-us") { XmlNode objModNode = MyXmlNode; if (objModNode != null) { objModNode.TryGetStringFieldQuickly("translate", ref _strAltName); objModNode.TryGetStringFieldQuickly("altpage", ref _strAltPage); } XmlDocument objXmlDocument = XmlManager.Instance.Load("vehicles.xml"); objModNode = objXmlDocument.SelectSingleNode("/chummer/categories/category[. = \"" + _strCategory + "\"]"); _strAltCategory = objModNode?.Attributes?["translate"]?.InnerText; } objNode.Text = DisplayName; objNode.Tag = _guiID.ToString(); }
public static float GetVehKMHSpeed(Vehicle veh) { return(veh.Speed * 3.6f); }
public Vehicle VehiclesById(int Vehicle_Id) { Vehicle _Vehicle = _vehicleBAL.GetVehicle(Vehicle_Id); return(_Vehicle); }
private void OnTick(object o, EventArgs e) { if (ArduinoInterface.IsAvailable()) { if (WantedLevel != Game.Player.WantedLevel) { WantedLevel = Game.Player.WantedLevel; ArduinoInterface.SetLEDCount(WantedLevel); } Ped player = Game.Player.Character; if (player.Exists()) { if (player.IsAlive) { if (Function.Call <bool>(Hash.IS_PLAYER_BEING_ARRESTED, player, true)) { SetHUDState(HUDState.Busted); } else if (player.IsInVehicle()) { Vehicle vehicle = player.CurrentVehicle; Boolean stateChanged = false; if (Timer >= MaxRotatingStateLength) { if (state == HUDState.VehicleHealth) { SetHUDState(HUDState.VehicleSpeed); } else { SetHUDState(HUDState.VehicleHealth); } stateChanged = true; } else if (state != HUDState.VehicleHealth && state != HUDState.VehicleSpeed) { stateChanged = SetHUDState(HUDState.VehicleSpeed); } switch (state) { case HUDState.VehicleSpeed: if (stateChanged) { ArduinoInterface.SetCursor(0, 0); ArduinoInterface.Print(vehicle.FriendlyName); } ArduinoInterface.SetCursor(0, 1); float speed = vehicle.Speed; if (Preferences.SpeedFormat == "mph") { speed *= 2.236936292054f; } else { speed *= 3.6f; } ArduinoInterface.Print("Speed: " + (Math.Round(speed).ToString() + Preferences.SpeedFormat).MinLength(6)); break; case HUDState.VehicleHealth: if (vehicle.BodyHealth != VehicleBodyHealth) { VehicleBodyHealth = vehicle.BodyHealth; ArduinoInterface.SetCursor(8, 0); ArduinoInterface.Print((Math.Round(VehicleBodyHealth / 10).ToString() + "%").MinLength(4)); } if (vehicle.EngineHealth != VehicleEngineHealth) { VehicleEngineHealth = vehicle.EngineHealth; ArduinoInterface.SetCursor(8, 1); ArduinoInterface.Print((Math.Round(VehicleEngineHealth / 10).ToString() + "%").MinLength(4)); } break; } } else { if (Timer >= MaxRotatingStateLength) { if (state == HUDState.WorldInfo) { SetHUDState(HUDState.PlayerHealth); } else { SetHUDState(HUDState.WorldInfo); } } else if (state != HUDState.WorldInfo && state != HUDState.PlayerHealth) { SetHUDState(HUDState.WorldInfo); } switch (state) { case HUDState.WorldInfo: DateTime currentTime = new DateTime(World.CurrentDayTime.Ticks); ArduinoInterface.SetCursor(0, 0); ArduinoInterface.Print((currentTime.ToString(Preferences.HourFormat == "12h" ? "h:mmtt" : "HH:mm").ToLower() + " - " + WorldExtension.Weather).MinLength(12)); ArduinoInterface.SetCursor(0, 1); ArduinoInterface.Print(World.GetZoneName(player.Position).MinLength(12)); break; case HUDState.PlayerHealth: if (player.Health != PlayerHealth) { PlayerHealth = player.Health; ArduinoInterface.SetCursor(8, 0); ArduinoInterface.Print((PlayerHealth.ToString() + "%").MinLength(4)); } if (player.Armor != PlayerArmor) { PlayerArmor = player.Armor; ArduinoInterface.SetCursor(8, 1); ArduinoInterface.Print((PlayerArmor.ToString() + "%").MinLength(4)); } break; } } } else { SetHUDState(HUDState.Wasted); } } } Timer += Interval; }
private static List <CorrectOrbit> GenerateCorrectOrbit(List <KeyValuePair <Orbit, double> > currentOrbit, Vehicle car) { return (currentOrbit.Select(c => new CorrectOrbit() { TypeofVehicle = car, Destination = c.Key.Destination, Orbit = c.Key.OrbitName, TimeTaken = c.Value }).ToList()); }
private void exportToXML(XmlDocument xmlDoc, Transform currentObject, XmlNode parent) { XmlNode node = null; if (currentObject.GetComponent <CommentElement>() != null) { CommentElement commentElement = (CommentElement)currentObject.GetComponent <CommentElement>(); node = xmlDoc.CreateComment(commentElement.comment); } else if (currentObject.GetComponent <Scene>() != null) { Scene tag = (Scene)currentObject.GetComponent <Scene>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "scene", ""); enrichXmlWithGeneralAttributes(xmlDoc, tag, node); XmlAttribute version = xmlDoc.CreateAttribute("version"); version.Value = tag.version.ToString().Replace(",", ".");; node.Attributes.Append(version); XmlAttribute shadowvolume = xmlDoc.CreateAttribute("shadowVolume"); shadowvolume.Value = $"{tag.shadowVolume.x} {tag.shadowVolume.y} {tag.shadowVolume.z}".Replace(",", ".");; node.Attributes.Append(shadowvolume); } else if (currentObject.GetComponent <TeardownEnvironment>() != null) { TeardownEnvironment tag = (TeardownEnvironment)currentObject.GetComponent <TeardownEnvironment>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "environment", ""); enrichXmlWithGeneralAttributes(xmlDoc, tag, node); XmlAttribute attribute = xmlDoc.CreateAttribute("template"); attribute.Value = tag.template.ToString().ToLower(); node.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("skyboxrot"); attribute.Value = tag.skyboxrot.ToString().Replace(",", ".");; node.Attributes.Append(attribute); if (tag.sunDir != null && !$"{tag.sunDir.x} {tag.sunDir.y} {tag.sunDir.z}".Equals("0 0 0")) { attribute = xmlDoc.CreateAttribute("sunDir"); attribute.Value = $"{tag.sunDir.x} {tag.sunDir.y} {tag.sunDir.z}".Replace(",", "."); node.Attributes.Append(attribute); } if (tag.sunBrightness >= 0) { attribute = xmlDoc.CreateAttribute("sunBrightness"); attribute.Value = tag.sunBrightness.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.sunFogScale >= 0) { attribute = xmlDoc.CreateAttribute("sunFogScale"); attribute.Value = tag.sunFogScale.ToString().Replace(",", "."); node.Attributes.Append(attribute); } attribute = xmlDoc.CreateAttribute("sunColorTint"); attribute.Value = $"{tag.sunColorTint.r} {tag.sunColorTint.g} {tag.sunColorTint.b}".Replace(",", "."); node.Attributes.Append(attribute); } else if (currentObject.GetComponent <Body>() != null) { Body tag = (Body)currentObject.GetComponent <Body>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "body", ""); enrichXmlWithGameObjectAttributes(xmlDoc, tag, node); XmlAttribute attribute = xmlDoc.CreateAttribute("dynamic"); attribute.Value = tag.dynamic ? "true" : "false"; node.Attributes.Append(attribute); } else if (currentObject.GetComponent <Boundary>() != null) { Boundary tag = (Boundary)currentObject.GetComponent <Boundary>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "boundary", ""); enrichXmlWithGeneralAttributes(xmlDoc, tag, node); } else if (currentObject.GetComponent <Vertex>() != null) { Vertex tag = (Vertex)currentObject.GetComponent <Vertex>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "vertex", ""); enrichXmlWithGeneralAttributes(xmlDoc, tag, node); XmlAttribute attribute = xmlDoc.CreateAttribute("pos"); attribute.Value = $"{tag.pos.x} {tag.pos.y}".Replace(",", ".");; node.Attributes.Append(attribute); } else if (currentObject.GetComponent <Script>() != null) { Script tag = (Script)currentObject.GetComponent <Script>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "script", ""); enrichXmlWithGeneralAttributes(xmlDoc, tag, node); XmlAttribute attribute = xmlDoc.CreateAttribute("file"); attribute.Value = tag.file.Replace(XmlImporter.getLevelFolder(tag.file), "LEVEL"); node.Attributes.Append(attribute); } else if (currentObject.GetComponent <Instance>() != null) { Instance tag = (Instance)currentObject.GetComponent <Instance>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "instance", ""); enrichXmlWithGeneralAttributes(xmlDoc, tag, node); XmlAttribute attribute = xmlDoc.CreateAttribute("file"); attribute.Value = tag.file.Replace(XmlImporter.getLevelFolder(tag.file), "LEVEL"); node.Attributes.Append(attribute); } else if (currentObject.GetComponent <SpawnPoint>() != null) { SpawnPoint tag = (SpawnPoint)currentObject.GetComponent <SpawnPoint>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "spawnpoint", ""); enrichXmlWithTransformAttributes(xmlDoc, tag, node); } else if (currentObject.GetComponent <Location>() != null) { Location tag = (Location)currentObject.GetComponent <Location>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "location", ""); enrichXmlWithTransformAttributes(xmlDoc, tag, node); } else if (currentObject.GetComponent <Group>() != null) { Group tag = (Group)currentObject.GetComponent <Group>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "group", ""); enrichXmlWithTransformAttributes(xmlDoc, tag, node); } else if (currentObject.GetComponent <Water>() != null) { Water tag = (Water)currentObject.GetComponent <Water>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "water", ""); enrichXmlWithTransformAttributes(xmlDoc, tag, node); XmlAttribute attribute = xmlDoc.CreateAttribute("size"); attribute.Value = $"{tag.size.x} {tag.size.y}".Replace(",", "."); node.Attributes.Append(attribute); if (tag.wave > -1) { attribute = xmlDoc.CreateAttribute("wave"); attribute.Value = tag.wave.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.ripple > -1) { attribute = xmlDoc.CreateAttribute("ripple"); attribute.Value = tag.ripple.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.foam > -1) { attribute = xmlDoc.CreateAttribute("foam"); attribute.Value = tag.foam.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.motion > -1) { attribute = xmlDoc.CreateAttribute("motion"); attribute.Value = tag.motion.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (!String.IsNullOrEmpty(tag.type)) { attribute = xmlDoc.CreateAttribute("type"); attribute.Value = tag.type.ToString().ToLower(); node.Attributes.Append(attribute); } } else if (currentObject.GetComponent <Screen>() != null) { Screen tag = (Screen)currentObject.GetComponent <Screen>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "water", ""); enrichXmlWithTransformAttributes(xmlDoc, tag, node); XmlAttribute attribute = xmlDoc.CreateAttribute("size"); attribute.Value = $"{tag.size.x} {tag.size.y}".Replace(",", "."); node.Attributes.Append(attribute); if (!tag.resolution.Equals(Vector2.zero)) { attribute = xmlDoc.CreateAttribute("resolution"); attribute.Value = $"{tag.resolution.x} {tag.resolution.y}".Replace(",", "."); node.Attributes.Append(attribute); } if (!tag.bulge.Equals(Vector2.zero)) { attribute = xmlDoc.CreateAttribute("bulge"); attribute.Value = $"{tag.bulge.x} {tag.bulge.y}".Replace(",", "."); node.Attributes.Append(attribute); } if (!String.IsNullOrEmpty(tag.script)) { attribute = xmlDoc.CreateAttribute("script"); attribute.Value = tag.script; node.Attributes.Append(attribute); } attribute = xmlDoc.CreateAttribute("color"); attribute.Value = $"{tag.color.r} {tag.color.g} {tag.color.b}".Replace(",", "."); node.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("enabled"); attribute.Value = tag.enabled ? "true" : "false"; node.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("interactive"); attribute.Value = tag.interactive ? "true" : "false"; node.Attributes.Append(attribute); if (tag.emissive > -1) { attribute = xmlDoc.CreateAttribute("resolution"); attribute.Value = tag.emissive.ToString().Replace(",", "."); node.Attributes.Append(attribute); } } else if (currentObject.GetComponent <Light>() != null) { Light tag = (Light)currentObject.GetComponent <Light>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "light", ""); enrichXmlWithTransformAttributes(xmlDoc, tag, node); XmlAttribute attribute = xmlDoc.CreateAttribute("type"); attribute.Value = tag.type.ToString().ToLower(); node.Attributes.Append(attribute); if (tag.glare > -1) { attribute = xmlDoc.CreateAttribute("glare"); attribute.Value = tag.glare.ToString().Replace(",", "."); node.Attributes.Append(attribute); } attribute = xmlDoc.CreateAttribute("angle"); attribute.Value = tag.angle.ToString().Replace(",", "."); node.Attributes.Append(attribute); if (tag.penumbra > -1) { attribute = xmlDoc.CreateAttribute("penumbra"); attribute.Value = tag.penumbra.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.unshadowed > -1) { attribute = xmlDoc.CreateAttribute("unshadowed"); attribute.Value = tag.unshadowed.ToString().Replace(",", "."); node.Attributes.Append(attribute); } attribute = xmlDoc.CreateAttribute("color"); attribute.Value = $"{tag.color.r} {tag.color.g} {tag.color.b}".Replace(",", "."); node.Attributes.Append(attribute); } else if (currentObject.GetComponent <Rope>() != null) { Rope tag = (Rope)currentObject.GetComponent <Rope>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "rope", ""); enrichXmlWithTransformAttributes(xmlDoc, tag, node); if (tag.slack > -1) { XmlAttribute attribute = xmlDoc.CreateAttribute("friction"); attribute.Value = tag.slack.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.strength > -1) { XmlAttribute attribute = xmlDoc.CreateAttribute("steerassist"); attribute.Value = tag.strength.ToString().Replace(",", "."); node.Attributes.Append(attribute); } } else if (currentObject.GetComponent <Wheel>() != null) { Wheel tag = (Wheel)currentObject.GetComponent <Wheel>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "wheel", ""); enrichXmlWithTransformAttributes(xmlDoc, tag, node); XmlAttribute attribute = xmlDoc.CreateAttribute("drive"); attribute.Value = tag.drive.ToString().Replace(",", "."); node.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("steer"); attribute.Value = tag.steer.ToString().Replace(",", "."); node.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("travel"); attribute.Value = $"{tag.travel.x} {tag.travel.y}".Replace(",", "."); node.Attributes.Append(attribute); } else if (currentObject.GetComponent <Vehicle>() != null) { Vehicle tag = (Vehicle)currentObject.GetComponent <Vehicle>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "vehicle", ""); enrichXmlWithGameObjectAttributes(xmlDoc, tag, node); XmlAttribute attribute = xmlDoc.CreateAttribute("driven"); attribute.Value = tag.driven ? "true" : "false"; node.Attributes.Append(attribute); if (tag.friction > -1) { attribute = xmlDoc.CreateAttribute("friction"); attribute.Value = tag.friction.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.steerassist > -1) { attribute = xmlDoc.CreateAttribute("steerassist"); attribute.Value = tag.steerassist.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.difflock > -1) { attribute = xmlDoc.CreateAttribute("difflock"); attribute.Value = tag.difflock.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.antiroll > -1) { attribute = xmlDoc.CreateAttribute("antiroll"); attribute.Value = tag.antiroll.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.antispin > -1) { attribute = xmlDoc.CreateAttribute("antispin"); attribute.Value = tag.antispin.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.acceleration > -1) { attribute = xmlDoc.CreateAttribute("acceleration"); attribute.Value = tag.acceleration.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.spring > -1) { attribute = xmlDoc.CreateAttribute("spring"); attribute.Value = tag.spring.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.damping > -1) { attribute = xmlDoc.CreateAttribute("damping"); attribute.Value = tag.damping.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.topspeed > -1) { attribute = xmlDoc.CreateAttribute("topspeed"); attribute.Value = tag.topspeed.ToString().Replace(",", "."); node.Attributes.Append(attribute); } attribute = xmlDoc.CreateAttribute("sound"); attribute.Value = tag.sound; node.Attributes.Append(attribute); } else if (currentObject.GetComponent <Vox>() != null) { Vox tag = (Vox)currentObject.GetComponent <Vox>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "vox", ""); enrichXmlWithGameObjectAttributes(xmlDoc, tag, node); XmlAttribute attribute = xmlDoc.CreateAttribute("file"); attribute.Value = tag.file.Replace(XmlImporter.getLevelFolder(tag.file), "LEVEL"); node.Attributes.Append(attribute); if (!String.IsNullOrEmpty(tag.voxObject)) { attribute = xmlDoc.CreateAttribute("object"); attribute.Value = tag.voxObject; node.Attributes.Append(attribute); } attribute = xmlDoc.CreateAttribute("prop"); attribute.Value = tag.dynamic ? "true" : "false"; node.Attributes.Append(attribute); } else if (currentObject.GetComponent <VoxBox>() != null) { VoxBox tag = (VoxBox)currentObject.GetComponent <VoxBox>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "voxbox", ""); enrichXmlWithGameObjectAttributes(xmlDoc, tag, node); Debug.Log(tag.position); XmlAttribute attribute = xmlDoc.CreateAttribute("color"); attribute.Value = $"{tag.color.r} {tag.color.g} {tag.color.b}".Replace(",", "."); node.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("prop"); attribute.Value = tag.dynamic ? "true" : "false"; node.Attributes.Append(attribute); } else if (currentObject.GetComponent <TeardownJoint>() != null) { TeardownJoint tag = (TeardownJoint)currentObject.GetComponent <TeardownJoint>(); node = xmlDoc.CreateNode(XmlNodeType.Element, "joint", ""); enrichXmlWithTransformAttributes(xmlDoc, tag, node); XmlAttribute attribute = xmlDoc.CreateAttribute("type"); attribute.Value = tag.type.ToString().ToLower(); node.Attributes.Append(attribute); if (tag.limits != null && !$"{tag.limits.x} {tag.limits.y}".Replace(",", ".").Equals("0 0")) { attribute = xmlDoc.CreateAttribute("limits"); attribute.Value = $"{tag.limits.x} {tag.limits.y}".Replace(",", "."); node.Attributes.Append(attribute); } attribute = xmlDoc.CreateAttribute("size"); attribute.Value = tag.size.ToString().Replace(",", "."); node.Attributes.Append(attribute); if (tag.rotstrength >= 0) { attribute = xmlDoc.CreateAttribute("rotstrength"); attribute.Value = tag.rotstrength.ToString().Replace(",", "."); node.Attributes.Append(attribute); } if (tag.rotspring >= 0) { attribute = xmlDoc.CreateAttribute("rotspring"); attribute.Value = tag.rotspring.ToString().Replace(",", "."); node.Attributes.Append(attribute); } } if (node != null) { foreach (Transform child in currentObject) { exportToXML(xmlDoc, child, node); } if (parent == null) { xmlDoc.AppendChild(node); } else { parent.AppendChild(node); } } }
public static bool WeCanEnter(Vehicle v) => ThereIs(v) && v.IsDriveable && !v.IsOnFire && (v.Model.IsBicycle || v.Model.IsBike || v.Model.IsQuadbike || !v.IsUpsideDown || !v.IsStopped);
internal static void Initialize(IServiceProvider services) { var options = services.GetRequiredService <DbContextOptions <Garage_2_0Context> >(); using (var context = new Garage_2_0Context(options)) { if (context.Members.Any() && context.Vehicles.Any() && context.VehicleTypeClass.Any()) { return; } var rnd = new Random(); // Populate Member var members = new List <Member>(); for (int i = 0; i < 100; i++) { var member = new Member() { Name = Faker.Name.FullName() }; members.Add(member); } context.AddRange(members); // Populate VehicleTypeClass var types = new Dictionary <string, int>() { { "Bil", 2 }, { "Motorcykel", 1 }, { "Båt", 10 }, { "Flygplan", 100 }, { "Buss", 20 } }; var vehicleTypeClasses = new List <VehicleTypeClass>(); foreach (var type in types) { var vehicleTypeClass = new VehicleTypeClass() { Type = type.Key, Price = type.Value }; vehicleTypeClasses.Add(vehicleTypeClass); } context.AddRange(vehicleTypeClasses); var aToZ = new List <string>() { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; var brands = new List <string>() { "Volvo", "Ferrari", "BMW", "Mercedes", "Audi", "Ford", "Mini", "Boeing", "Nimbus" }; var models = new List <string>() { "XC90", "Testarossa", "M3", "Sport", "A5", "Mustang", "Clubman", "747", "Flybridge" }; var colors = new List <string>() { "Röd", "Blå", "Grön", "Blå", "Gul", "Silver", "Svart", "Vit" }; // Populate Vehicle var vehicles = new List <Vehicle>(); foreach (var member in members) { if (Faker.RandomNumber.Next(2) == 0) { foreach (var vehicleTypeClass in vehicleTypeClasses) { var randomCarBrandsAndModel = rnd.Next(0, brands.Count); var vehicle = new Vehicle() { RegNr = "" + aToZ[rnd.Next(26)] + aToZ[rnd.Next(26)] + aToZ[rnd.Next(26)] + rnd.Next(0, 9) + rnd.Next(0, 9) + rnd.Next(0, 9), Color = colors[rnd.Next(0, colors.Count)], Brand = brands[randomCarBrandsAndModel], Model = models[randomCarBrandsAndModel], Member = member, VehicleTypeClass = vehicleTypeClass, NoWheels = vehicleTypeClass.Type == "Bil" ? 4 : vehicleTypeClass.Type == "Motorcykel" ? 2 : vehicleTypeClass.Type == "Buss" ? 18 : vehicleTypeClass.Type == "Flygplan" ? 10 : 0, ParkedIn = DateTime.Now }; vehicles.Add(vehicle); } } } context.AddRange(vehicles); context.SaveChanges(); } }
private void onTick(object sender, EventArgs e) { if (firstTime) { UI.Notify(ModName + " " + Version + " by " + Developer + " Loaded"); firstTime = false; } if (ped.IsInVehicle()) { displayScore(); Vehicle[] closeVehicles = GTA.World.GetNearbyVehicles(ped.Position, 10); Vehicle xVehicle = getClosestVehicle(closeVehicles); if (xVehicle != null) { float distance; if (GTA.World.GetDistance(ped.Position, xVehicle.Position) < GTA.World.GetDistance(ped.CurrentVehicle.Position, xVehicle.Position)) { distance = GTA.World.GetDistance(ped.Position, xVehicle.Position); } else { distance = GTA.World.GetDistance(ped.CurrentVehicle.Position, xVehicle.Position); } bool collision = ped.CurrentVehicle.IsTouching(xVehicle); if (collision) { if (streak > 0) { UI.Notify("Collision, streak ended."); } streak = 0; prevDistance = float.MaxValue; prevVehicle = xVehicle; } if (xVehicle != prevVehicle) { if (distance <= prevDistance) { prevDistance = distance; } else if (prevDistance <= 3) { UI.Notify("CLOSE CALL!: " + prevDistance.ToString("F")); prevVehicle = xVehicle; if (prevDistance < minDistance) { minDistance = prevDistance; } prevDistance = float.MaxValue; streak++; } } } } else { streak = 0; } }
private void Awake() { _vehicle = GetComponent<Vehicle>(); }
public async Task AddAsync(Vehicle vehicle) { await _repository.AddAsync(vehicle) .AnyContext(); }
internal void AddVehicle(Vehicle vehicle) { Context.Vehicle.Add(vehicle); Context.SaveChanges(); }
public static void CargoTruckAI_PostChangeVehicleType(bool __result, ref CargoParcel __state, ushort vehicleID, ref Vehicle vehicleData, PathUnit.Position pathPos, uint laneID) { if (__result) { CargoData.Instance.Count(__state); } }
public async Task UpdateAsync(Vehicle vehicle) { await _repository.UpdateAsync(vehicle) .AnyContext(); }
/// <summary> /// Main OnTick task runs every game tick and handles all the menu stuff. /// </summary> /// <returns></returns> private async Task OnTick() { #region FirstTick // Only run this the first tick. if (firstTick) { firstTick = false; // Clear all previous pause menu info/brief messages on resource start. ClearBrief(); // Request the permissions data from the server. TriggerServerEvent("vMenu:RequestPermissions", Game.Player.Handle); // Wait until the data is received and the player's name is loaded correctly. while (!PreSetupComplete || Game.Player.Name == "**Invalid**" || Game.Player.Name == "** Invalid **") { await Delay(0); } if ((IsAllowed(Permission.Staff) && GetSettingsBool(Setting.vmenu_menu_staff_only)) || GetSettingsBool(Setting.vmenu_menu_staff_only) == false) { if (GetSettingsInt(Setting.vmenu_menu_toggle_key) != -1) { MenuController.MenuToggleKey = (Control)GetSettingsInt(Setting.vmenu_menu_toggle_key); //MenuToggleKey = GetSettingsInt(Setting.vmenu_menu_toggle_key); } if (GetSettingsInt(Setting.vmenu_noclip_toggle_key) != -1) { NoClipKey = GetSettingsInt(Setting.vmenu_noclip_toggle_key); } // Create the main menu. Menu = new Menu(Game.Player.Name, "Main Menu"); // Add the main menu to the menu pool. MenuController.AddMenu(Menu); MenuController.MainMenu = Menu; Menu.RefreshIndex(); //Menu.UpdateScaleform(); // Create all (sub)menus. CreateSubmenus(); } // Manage Stamina if (PlayerOptionsMenu != null && PlayerOptionsMenu.PlayerStamina && IsAllowed(Permission.POUnlimitedStamina)) { StatSetInt((uint)GetHashKey("MP0_STAMINA"), 100, true); } else { StatSetInt((uint)GetHashKey("MP0_STAMINA"), 0, true); } // Manage other stats. StatSetInt((uint)GetHashKey("MP0_STRENGTH"), 100, true); StatSetInt((uint)GetHashKey("MP0_LUNG_CAPACITY"), 80, true); // reduced because it was over powered StatSetInt((uint)GetHashKey("MP0_WHEELIE_ABILITY"), 100, true); StatSetInt((uint)GetHashKey("MP0_FLYING_ABILITY"), 100, true); StatSetInt((uint)GetHashKey("MP0_SHOOTING_ABILITY"), 50, true); // reduced because it was over powered StatSetInt((uint)GetHashKey("MP0_STEALTH_ABILITY"), 100, true); } #endregion // If the setup (permissions) is done, and it's not the first tick, then do this: if (PreSetupComplete && !firstTick) { #region Handle Opening/Closing of the menu. var tmpMenu = GetOpenMenu(); if (MpPedCustomizationMenu != null) { if (tmpMenu == MpPedCustomizationMenu.createCharacterMenu) { MpPedCustomization.DisableBackButton = true; MpPedCustomization.DontCloseMenus = true; } else { MpPedCustomization.DisableBackButton = false; MpPedCustomization.DontCloseMenus = false; } } if (Game.IsDisabledControlJustReleased(0, Control.PhoneCancel) && MpPedCustomization.DisableBackButton) { await Delay(0); Notify.Alert("You must save your ped first before exiting, or click the ~r~Exit Without Saving~s~ button."); } if (Game.CurrentInputMode == InputMode.MouseAndKeyboard) { if (!MenuController.IsAnyMenuOpen() || NoClipEnabled) { if (Game.IsControlJustPressed(0, (Control)NoClipKey) && IsAllowed(Permission.NoClip)) { if (MenuController.IsAnyMenuOpen()) { if (MenuController.GetCurrentMenu() != null && MenuController.GetCurrentMenu() != NoClipMenu) { MenuController.CloseAllMenus(); } } if (Game.PlayerPed.IsInVehicle()) { Vehicle veh = GetVehicle(); if (veh != null && veh.Exists() && !veh.IsDead && veh.Driver == Game.PlayerPed) { NoClipEnabled = !NoClipEnabled; MenuController.DontOpenAnyMenu = NoClipEnabled; } else { NoClipEnabled = false; MenuController.DontOpenAnyMenu = NoClipEnabled; Notify.Error("You need to be the driver of this vehicle to enable noclip!"); } } else { NoClipEnabled = !NoClipEnabled; MenuController.DontOpenAnyMenu = NoClipEnabled; } } } } if (NoClipEnabled) { MenuController.DontOpenAnyMenu = true; } #endregion // Menu toggle button. Game.DisableControlThisFrame(0, (Control)MenuToggleKey); } }
public static void CargoTruckAI_SetSource(ushort vehicleID, ref Vehicle data, ushort sourceBuilding) { var parcel = new CargoParcel(sourceBuilding, false, data.m_transferType, data.m_transferSize, data.m_flags); CargoData.Instance.Count(parcel); }
public string Add(FormCollection formCollection) { string photoUrl = "", type = "", area = ""; decimal price = decimal.MaxValue; foreach (var key in formCollection.AllKeys) { type = formCollection["type"]; area = formCollection["area"]; price = Convert.ToDecimal(formCollection["price"]); } if (Request.Files.Count > 0) { try { // Get all files from Request object HttpFileCollectionBase files = Request.Files; for (int i = 0; i < files.Count; i++) { //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/"; //string filename = Path.GetFileName(Request.Files[i].FileName); HttpPostedFileBase file = files[i]; // Checking for Internet Explorer if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER") { string[] testfiles = file.FileName.Split(new char[] { '\\' }); photoUrl = testfiles[testfiles.Length - 1]; } else { photoUrl = file.FileName; } if (!System.IO.Directory.Exists(Server.MapPath("~/Uploads/"))) { System.IO.Directory.CreateDirectory(Server.MapPath("~/Uploads/")); } // Get the complete folder path and store the file inside it. string fullPathUrl = Path.Combine(Server.MapPath("~/Uploads/"), photoUrl); Vehicle vehicle = new Vehicle() { Id = Guid.NewGuid().ToString(), Type = type, Area = area, Price = Convert.ToDecimal(price), Photo = "/Uploads/" + photoUrl }; db.Vehicles.Add(vehicle); if (db.SaveChanges() > 0) { file.SaveAs(fullPathUrl); return("添加成功"); } } // Returns message that successfully uploaded //return "File Uploaded Successfully!"; } catch (DbEntityValidationException dbEx) { StringBuilder sb = new StringBuilder(); foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { sb.Append("Property:" + validationError.PropertyName + " Error: " + validationError.ErrorMessage); } } return(sb.ToString()); } } else { return("No files selected."); } return("添加失败"); }
public static void CargoTruckAI_PreChangeVehicleType(out CargoParcel __state, ushort vehicleID, ref Vehicle vehicleData, PathUnit.Position pathPos, uint laneID) { Vector3 vector = NetManager.instance.m_lanes.m_buffer[laneID].CalculatePosition(0.5f); NetInfo info = NetManager.instance.m_segments.m_buffer[pathPos.m_segment].Info; ushort buildingID = BuildingManager.instance.FindBuilding(vector, 100f, info.m_class.m_service, ItemClass.SubService.None, Building.Flags.None, Building.Flags.None); __state = new CargoParcel(buildingID, true, vehicleData.m_transferType, vehicleData.m_transferSize, vehicleData.m_flags); }
/// <summary> /// Point where modificated vehicle object is received /// </summary> /// <param name="vehicle">modificated vehicle object</param> /// <param name="callback">callback for modificated vehcile object</param> public void _messageReceived(Vehicle vehicle, System.Action <Vehicle> callback) { callback(vehicle); }
}//Start void Update() { if (vehicle.Count > 0) { timer_create += Time.deltaTime; if (timer_create > 1f && game_sc.vehicle.Count < vehicle_max) { vehicle[0].GetComponent <ColliderCreator>().Create(); timer_create = 0; } //timer_create } //Count if (man.Count > 0) { timer_create_man += Time.deltaTime; if (timer_create_man > 0.5f && man_count < man_max) { man[0].GetComponent <ManCreator>().Create(); timer_create_man = 0; } //timer_create } //Count if (script_player.wanted_score >= 300 && script_player.danger) { timer_cpc += Time.deltaTime; if (timer_cpc > 5) { CreatePoliceCar(); timer_cpc = 0; } //timer_cpc } //wanted_score if (CarsDeath.Count > LimitDeathCars) { game_sc.vehicle.Remove(CarsDeath[0]); Transform temp = CarsDeath[0]; CarsDeath.Remove(CarsDeath[0]); Vehicle tempVehSc = temp.GetComponent <Vehicle>(); if (tempVehSc) { if (tempVehSc.place[0].man) { Debug.Log("1234"); game_sc.man.Remove(tempVehSc.place[0].man); MansDeath.Remove(tempVehSc.place[0].man); Destroy(tempVehSc.place[0].man.gameObject); } if (tempVehSc.place[1].man) { game_sc.man.Remove(tempVehSc.place[1].man); MansDeath.Remove(tempVehSc.place[1].man); Destroy(tempVehSc.place[1].man.gameObject); } } Destroy(temp.gameObject); } if (MansDeath.Count > LimitDeathMans) { game_sc.man.Remove(MansDeath[0]); Transform tempM = MansDeath[0]; MansDeath.Remove(MansDeath[0]); Destroy(tempM.gameObject); } } //Update