public void Init(PathManager argPath) { path = argPath; ActivePoint = path.CheckPoints [1]; transform.LookAt (ActivePoint.transform, Vector3.back); _isInit = true; }
IEnumerator SpwanWave(PathManager path, float timebetweenspwan, int SpwanNumber) { int number = 0; Debug.Log (path.CheckPoints [0]); while (number < SpwanNumber) { GameObject DwarfClone = Instantiate (Dwarf, path.CheckPoints [0].transform.position, Quaternion.identity) as GameObject; DwarfClone.GetComponent<FollowPath> ().Init (path); number++; yield return new WaitForSeconds (timebetweenspwan); } }
public void UpdateWithPathManagerValues(PathManager stockPathManager) { // Needed fields come from joaofarias' csl-traffic // https://github.com/joaofarias/csl-traffic m_simulationProfiler = stockPathManager.m_simulationProfiler; m_drawCallData = stockPathManager.m_drawCallData; m_properties = stockPathManager.m_properties; m_pathUnitCount = stockPathManager.m_pathUnitCount; m_renderPathGizmo = stockPathManager.m_renderPathGizmo; m_pathUnits = stockPathManager.m_pathUnits; m_bufferLock = stockPathManager.m_bufferLock; }
// copy values from original to new path manager public void SetOriginalValues(PathManager originalPathManager) { // members of SimulationManagerBase this.m_simulationProfiler = originalPathManager.m_simulationProfiler; this.m_drawCallData = originalPathManager.m_drawCallData; this.m_properties = originalPathManager.m_properties; // members of PathManager this.m_pathUnitCount = originalPathManager.m_pathUnitCount; this.m_renderPathGizmo = originalPathManager.m_renderPathGizmo; this.m_pathUnits = originalPathManager.m_pathUnits; this.m_bufferLock = originalPathManager.m_bufferLock; }
public Path( PathManager pathManager, GameObject movingObject, Vector2 source, Vector2 destination, List<int> pathNodeIndices, SparseGraph graph) { PathEdgeList = new List<PathEdge>(); Source = source; Destination = destination; PathManager = pathManager; MovingObject = movingObject; int fromNodeIndex = -1; int toNodeIndex = -1; Node fromNode = null; Node toNode = null; Edge currentEdge = null; Vector2 from = source; foreach (int nodeIndex in pathNodeIndices) { fromNodeIndex = toNodeIndex; toNodeIndex = nodeIndex; fromNode = toNode; toNode = graph.GetNode(nodeIndex); Vector2 to = toNode.Position; if (from == to) { // this could happen when source is exactly on a node // position. In this case, skip this redundant edge continue; } if (fromNodeIndex != -1 && toNodeIndex != -1) { currentEdge = graph.GetEdge(fromNodeIndex, toNodeIndex); } PathEdgeList.Add(new PathEdge(from, to, fromNode, toNode, currentEdge, PathManager, MovingObject)); from = to; // copy } if (from != destination) { PathEdgeList.Add(new PathEdge(from, destination, toNode, null, null, PathManager, MovingObject)); } }
//Check for collisions with the wall, if you do collide, try and walk away from it. void OnCollisionStay2D(Collision2D collision) { parentPM = GetComponentInParent<PathManager> (); GetComponentInParent<PathManager> ().SendMessage ("DirectionSet", "clear"); if (collision.gameObject.tag == "Player") { //Stuff } else if (collision.gameObject.tag == "Wall" || collision.gameObject.tag == "Lava") { parentPM.DirectionSet(direction); parentPM.obstacle = true; if(parentPM.delP == Vector3.zero || parentPM.delP == null){ //parentPM.delP = parentPM.transform.localPosition; } } }
// Use this for initialization void init() { isActive = false; outofplay = false; waveNum = -1; //gets available paths GameObject go = (GameObject)GameObject.FindGameObjectWithTag("WaveGen"); WE = (WaveEmitter)go.GetComponent ("WaveEmitter"); //pths = (RPathGen)go.GetComponent("RPathGen"); PM = (PathManager)go.GetComponent ("PathManager"); PM.init (); go = (GameObject)GameObject.FindGameObjectWithTag ("MainCamera"); cam1 = (Camera)go.GetComponent ("Camera"); //add iTween component and get ref gameObject.AddComponent("iTweenPath"); path = (iTweenPath)gameObject.GetComponent("iTweenPath"); }
public static PathSurfaceWalker AttachPathSurfaceWalker(GameObject obj, PathManager path, int nodeIdx, float tngOffset, float binrmOffset, float nrmOffset, float speed) { if (obj.GetComponent<PathSurfaceWalker>() != null) throw new UnityException("object already attached"); var walker = obj.AddComponent<PathSurfaceWalker>(); walker._path = path; walker._currNodeIdx = nodeIdx; walker._currTngOffset = tngOffset; walker._currNrmOffset = nrmOffset; walker.transform.position = Bezier.GetPoint3d(path.Nodes[nodeIdx]._ctrlPts, tngOffset) + Bezier.GetBinormal3d(path.Nodes[nodeIdx]._ctrlPts, tngOffset, path.transform.up) * binrmOffset + Bezier.GetNormal3d(path.Nodes[nodeIdx]._ctrlPts, tngOffset, path.transform.up) * nrmOffset; walker.transform.rotation = Bezier.GetOrientation3d(path.Nodes[nodeIdx]._ctrlPts, tngOffset, path.transform.up); walker._speed = speed; return walker; }
public PathEdge( Vector2 source, Vector2 destination, Node fromNode, Node toNode, Edge edge, PathManager pathManager, GameObject movingObject) { Source = source; Destination = destination; FromNode = fromNode; ToNode = toNode; Edge = edge; PathManager = pathManager; MovingObject = movingObject; MovingEntity = movingObject.GetComponent<MovingEntity>(); }
/// <summary> /// Return the 'selected' texture of the node. /// </summary> /// <returns></returns> protected override Texture2D GetSelectedTexture() { return((Texture2D)AssetDatabase.LoadAssetAtPath( PathManager.EliotImages() + "rombSelected.png", typeof(Texture2D))); }
public abstract Task <bool> IsActive(GameManager gameManager, PathManager pathManager, AutoControllerState state);
private void BaseSimulationStep(ushort vehicleId, ref Vehicle data, Vector3 physicsLodRefPos) { if ((data.m_flags & Vehicle.Flags.WaitingPath) != Vehicle.Flags.None) { PathManager instance = Singleton <PathManager> .instance; byte pathFindFlags = instance.m_pathUnits.m_buffer[(int)((UIntPtr)data.m_path)].m_pathFindFlags; if ((pathFindFlags & 4) != 0) { data.m_pathPositionIndex = 255; data.m_flags &= ~Vehicle.Flags.WaitingPath; data.m_flags &= ~Vehicle.Flags.Arriving; PathfindSuccess(vehicleId, ref data); TrySpawn(vehicleId, ref data); } else if ((pathFindFlags & 8) != 0) { data.m_flags &= ~Vehicle.Flags.WaitingPath; Singleton <PathManager> .instance.ReleasePath(data.m_path); data.m_path = 0u; PathfindFailure(vehicleId, ref data); return; } } else if ((data.m_flags & Vehicle.Flags.WaitingSpace) != Vehicle.Flags.None) { TrySpawn(vehicleId, ref data); } Vector3 lastFramePosition = data.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; } SimulationStep(vehicleId, ref data, vehicleId, ref data, lodPhysics); if (data.m_leadingVehicle == 0 && data.m_trailingVehicle != 0) { VehicleManager instance2 = Singleton <VehicleManager> .instance; ushort num = data.m_trailingVehicle; int num2 = 0; while (num != 0) { ushort trailingVehicle = instance2.m_vehicles.m_buffer[num].m_trailingVehicle; VehicleInfo info = instance2.m_vehicles.m_buffer[num].Info; info.m_vehicleAI.SimulationStep(num, ref instance2.m_vehicles.m_buffer[num], vehicleId, ref data, lodPhysics); num = trailingVehicle; if (++num2 > 16384) { CODebugBase <LogChannel> .Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace); break; } } } int maxBlockCounter = (m_info.m_class.m_service > ItemClass.Service.Office) ? 150 : 100; if ((data.m_flags & (Vehicle.Flags.Spawned | Vehicle.Flags.WaitingPath | Vehicle.Flags.WaitingSpace)) == Vehicle.Flags.None && data.m_cargoParent == 0) { Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId); } else if (data.m_blockCounter >= maxBlockCounter && Options.enableDespawning) { Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId); } else if (data.m_leadingVehicle == 0 && CustomVehicleAI.ShouldRecalculatePath(vehicleId, ref data, maxBlockCounter)) { CustomVehicleAI.MarkPathRecalculation(vehicleId); InvalidPath(vehicleId, ref data, vehicleId, ref data); } }
private void OnValidate() { myPathManager = FindObjectOfType <PathManager>(); }
public void Awake() { pathManager = GetComponent<PathManager>(); }
public bool CustomStartPathFind(ushort vehicleId, ref Vehicle vehicleData, Vector3 startPos, Vector3 endPos, bool startBothWays, bool endBothWays, bool undergroundTarget) { if (vehicleData.m_transferType == (byte)TransferManager.TransferReason.Mail) { return(base.StartPathFind( vehicleId, ref vehicleData, startPos, endPos, startBothWays, endBothWays, undergroundTarget)); } if ((vehicleData.m_flags & (Vehicle.Flags.TransferToSource | Vehicle.Flags.GoingBack)) != 0) { return(base.StartPathFind( vehicleId, ref vehicleData, startPos, endPos, startBothWays, endBothWays, undergroundTarget)); } bool allowUnderground = (vehicleData.m_flags & (Vehicle.Flags.Underground | Vehicle.Flags.Transition)) != 0; // try to find road start position bool startPosFound = PathManager.FindPathPosition( startPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle, VehicleInfo.VehicleType.Car, allowUnderground, false, 32f, out PathUnit.Position startPosA, out PathUnit.Position startPosB, out float startDistSqrA, out _); // try to find other start position (plane, train, ship) const VehicleInfo.VehicleType VEH_TYPE_MASK = VehicleInfo.VehicleType.Train | VehicleInfo.VehicleType.Ship | VehicleInfo.VehicleType.Plane; if (PathManager.FindPathPosition( startPos, ItemClass.Service.PublicTransport, NetInfo.LaneType.Vehicle, VEH_TYPE_MASK, allowUnderground, false, 32f, out PathUnit.Position altStartPosA, out PathUnit.Position altStartPosB, out float altStartDistSqrA, out _)) { if (!startPosFound || (altStartDistSqrA < startDistSqrA && (Mathf.Abs(startPos.x) > 4800f || Mathf.Abs(startPos.z) > 4800f))) { startPosA = altStartPosA; startPosB = altStartPosB; startDistSqrA = altStartDistSqrA; } startPosFound = true; } // try to find road end position bool endPosFound = PathManager.FindPathPosition( endPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle, VehicleInfo.VehicleType.Car, undergroundTarget, false, 32f, out PathUnit.Position endPosA, out PathUnit.Position endPosB, out float endDistSqrA, out _); // try to find other end position (plane, train, ship) if (PathManager.FindPathPosition( endPos, ItemClass.Service.PublicTransport, NetInfo.LaneType.Vehicle, VEH_TYPE_MASK, undergroundTarget, false, 32f, out PathUnit.Position altEndPosA, out PathUnit.Position altEndPosB, out float altEndDistSqrA, out _)) { if (!endPosFound || (altEndDistSqrA < endDistSqrA && (Mathf.Abs(endPos.x) > 4800f || Mathf.Abs(endPos.z) > 4800f))) { endPosA = altEndPosA; endPosB = altEndPosB; endDistSqrA = altEndDistSqrA; } endPosFound = true; } if (!startPosFound || !endPosFound) { return(false); } CustomPathManager pathManager = CustomPathManager._instance; if (!startBothWays || startDistSqrA < 10f) { startPosB = default; } if (!endBothWays || endDistSqrA < 10f) { endPosB = default; } PathCreationArgs args; args.extPathType = ExtPathType.None; args.extVehicleType = ExtVehicleType.Service; args.vehicleId = vehicleId; args.spawned = (vehicleData.m_flags & Vehicle.Flags.Spawned) != 0; args.buildIndex = Singleton <SimulationManager> .instance.m_currentBuildIndex; args.startPosA = startPosA; args.startPosB = startPosB; args.endPosA = endPosA; args.endPosB = endPosB; args.vehiclePosition = default; args.laneTypes = NetInfo.LaneType.Vehicle | NetInfo.LaneType.CargoVehicle; args.vehicleTypes = VehicleInfo.VehicleType.Car | VehicleInfo.VehicleType.Train | VehicleInfo.VehicleType.Ship | VehicleInfo.VehicleType.Plane; args.maxLength = 20000f; args.isHeavyVehicle = IsHeavyVehicle(); args.hasCombustionEngine = CombustionEngine(); args.ignoreBlocked = IgnoreBlocked(vehicleId, ref vehicleData); args.ignoreFlooded = false; args.ignoreCosts = false; args.randomParking = false; args.stablePath = false; args.skipQueue = (vehicleData.m_flags & Vehicle.Flags.Spawned) != 0; if (pathManager.CustomCreatePath( out uint path, ref Singleton <SimulationManager> .instance.m_randomizer, args)) { if (vehicleData.m_path != 0) { pathManager.ReleasePath(vehicleData.m_path); } vehicleData.m_path = path; vehicleData.m_flags |= Vehicle.Flags.WaitingPath; return(true); } return(false); }
public void LoadLuaFile(string path) { var processedPath = PathManager.TryMakeRelative(path); string pathToLoad = Path.IsPathRooted(processedPath) ? processedPath : PathManager.MakeProgramRelativePath(processedPath); //JUNIPIER SQUATCHBOX COMPLEX if (LuaAlreadyInSession(processedPath) == false) { var luaFile = new LuaFile(string.Empty, processedPath); _luaList.Add(luaFile); LuaListView.ItemCount = _luaList.Count; Global.Config.RecentLua.Add(processedPath); if (!Global.Config.DisableLuaScriptsOnLoad) { try { LuaSandbox.Sandbox(null, () => { luaFile.Thread = LuaImp.SpawnCoroutine(pathToLoad); LuaSandbox.CreateSandbox(luaFile.Thread, Path.GetDirectoryName(pathToLoad)); luaFile.State = LuaFile.RunState.Running; }, () => { luaFile.State = LuaFile.RunState.Disabled; }); } catch (Exception e) { MessageBox.Show(e.ToString()); } } else { luaFile.State = LuaFile.RunState.Disabled; } if (Global.Config.LuaReloadOnScriptFileChange) { CreateFileWatcher(processedPath); } //luaFile.Paused = false; } else { foreach (var file in _luaList.Where(file => processedPath == file.Path && file.Enabled == false && !Global.Config.DisableLuaScriptsOnLoad)) { file.Toggle(); break; } RunLuaScripts(); } UpdateDialog(); }
// After all objects are initialized, Awake is called when the script // is being loaded. This occurs before any Start calls. // Use Awake instead of the constructor for initialization. public void Awake() { motor = GetComponent<Motor>(); if (motor == null) { Debug.Log("No Motor"); } pathManager = GetComponent<PathManager>(); GameObject mainCamera = GameObject.Find("Main Camera"); if (mainCamera != null) { targetedCameras = mainCamera.GetComponents<TargetedCamera>(); } targetRowsPerColumn = Mathf.Max(3, targetRowsPerColumn); }
private void RunImportJob(IEnumerable <string> files) { bool didSomething = false; var basepath = PathManager.MakeAbsolutePath(Global.Config.PathEntries.FirmwaresPathFragment, null); string errors = ""; foreach (var f in files) { using (var hf = new HawkFile(f)) { if (hf.IsArchive) { // blech. the worst extraction code in the universe. string extractpath = $"{Path.GetTempFileName()}.dir"; DirectoryInfo di = Directory.CreateDirectory(extractpath); try { foreach (var ai in hf.ArchiveItems) { hf.BindArchiveMember(ai); var stream = hf.GetStream(); var ms = new MemoryStream(); Util.CopyStream(hf.GetStream(), ms, stream.Length); string outfile = ai.Name; string myname = Path.GetFileName(outfile); outfile = Path.Combine(extractpath, myname); File.WriteAllBytes(outfile, ms.ToArray()); hf.Unbind(); if (cbAllowImport.Checked || Manager.CanFileBeImported(outfile)) { didSomething |= RunImportJobSingle(basepath, outfile, ref errors); } } } finally { di.Delete(true); } } else { if (cbAllowImport.Checked || Manager.CanFileBeImported(hf.CanonicalFullPath)) { didSomething |= RunImportJobSingle(basepath, f, ref errors); } } } } if (!string.IsNullOrEmpty(errors)) { MessageBox.Show(errors, "Error importing these files"); } if (didSomething) { DoScan(); } }
protected void LoadTemplate(int templateId) { Template templateItem = new PathManager().GetTemplate(templateId); txtName.Text = templateItem.Title; ftbShortDesc.Content = templateItem.Body; txtScript.Text = templateItem.Script; //ftbShortDesc.EnableHtmlMode = true; txtTag.Text = templateItem.Tag; txtURILabel.Text = templateItem.UriLabel; if (templateItem.ExpireDate.Value.Year != 2079) { dateControlStart.ValueLocal = templateItem.ExpireDate; } List <TemplateSku> selectedItems = templateItem.Items.FindAll(x => x.TypeId == TemplateItemTypeEnum.ListItems); foreach (TemplateSku item in selectedItems) { ListItem listItem = lstSku.Items.FindByValue(item.SkuId.ToString()); listItem.Selected = true; } List <TemplateSku> triggerItems = templateItem.Items.FindAll(x => x.TypeId == TemplateItemTypeEnum.Triggers); foreach (TemplateSku item in triggerItems) { ListItem listItem = lstTriggerItem.Items.FindByValue(item.SkuId.ToString()); listItem.Selected = true; } List <TemplateSku> supressItems = templateItem.Items.FindAll(x => x.TypeId == TemplateItemTypeEnum.Supress); foreach (TemplateSku item in supressItems) { ListItem listItem = lstSuppressItem.Items.FindByValue(item.SkuId.ToString()); listItem.Selected = true; } List <TemplateSku> addItems = templateItem.Items.FindAll(x => x.TypeId == TemplateItemTypeEnum.Add); foreach (TemplateSku item in addItems) { ListItem listItem = lstAddItems.Items.FindByValue(item.SkuId.ToString()); listItem.Selected = true; } //remove items bind List <TemplateSku> removeItems = templateItem.Items.FindAll(x => x.TypeId == TemplateItemTypeEnum.Remove); foreach (TemplateSku item in removeItems) { ListItem listItem = lstRemoveItems.Items.FindByValue(item.SkuId.ToString()); listItem.Selected = true; } foreach (CSBusiness.PostSale.TemplateControl item in templateItem.ControlItems) { if (item.StateId.HasValue && item.DisableTemplate.HasValue && item.DisableTemplate.Value) { lstDisableStates.Items.FindByValue(item.StateId.Value.ToString()).Selected = true; } } }
private void tsmiSetCustomization_Click(object sender, EventArgs e) { using (var ofd = new OpenFileDialog()) { ofd.InitialDirectory = currSelectorDir; ofd.RestoreDirectory = true; string frmwarePath = PathManager.MakeAbsolutePath(Global.Config.PathEntries.FirmwaresPathFragment, null); if (ofd.ShowDialog() == DialogResult.OK) { // remember the location we selected this firmware from, maybe there are others currSelectorDir = Path.GetDirectoryName(ofd.FileName); try { using (var hf = new HawkFile(ofd.FileName)) { // for each selected item, set the user choice (even though multiple selection for this operation is no longer allowed) foreach (ListViewItem lvi in lvFirmwares.SelectedItems) { var fr = lvi.Tag as FirmwareDatabase.FirmwareRecord; string filePath = ofd.FileName; // if the selected file is an archive, allow the user to pick the inside file // to always be copied to the global firmwares directory if (hf.IsArchive) { var ac = new ArchiveChooser(new HawkFile(filePath)); int memIdx = -1; if (ac.ShowDialog(this) == DialogResult.OK) { memIdx = ac.SelectedMemberIndex; } else { return; } var insideFile = hf.BindArchiveMember(memIdx); var fileData = insideFile.ReadAllBytes(); // write to file in the firmwares folder File.WriteAllBytes(Path.Combine(frmwarePath, insideFile.Name), fileData); filePath = Path.Combine(frmwarePath, insideFile.Name); } else { // selected file is not an archive // check whether this file is currently outside of the global firmware directory if (currSelectorDir != frmwarePath) { var askMoveResult = MessageBox.Show(this, "The selected custom firmware does not reside in the root of the global firmware directory.\nDo you want to copy it there?", "Import Custom Firmware", MessageBoxButtons.YesNo); if (askMoveResult == DialogResult.Yes) { try { FileInfo fi = new FileInfo(filePath); filePath = Path.Combine(frmwarePath, fi.Name); File.Copy(ofd.FileName, filePath); } catch (Exception ex) { MessageBox.Show(this, $"There was an issue copying the file. The customization has NOT been set.\n\n{ex.StackTrace}"); continue; } } } } Global.Config.FirmwareUserSpecifications[fr.ConfigKey] = filePath; } } } catch (Exception ex) { MessageBox.Show(this, $"There was an issue during the process. The customization has NOT been set.\n\n{ex.StackTrace}"); return; } DoScan(); } } }
private void DoScan() { lvFirmwares.BeginUpdate(); Manager.DoScanAndResolve(); // for each type of firmware, try resolving and record the result foreach (ListViewItem lvi in lvFirmwares.Items) { var fr = lvi.Tag as FirmwareDatabase.FirmwareRecord; var ri = Manager.Resolve(fr, true); for (int i = 4; i <= 7; i++) { lvi.SubItems[i].Text = ""; } if (ri == null) { lvi.ImageIndex = idMissing; lvi.ToolTipText = "No file bound for this firmware!"; } else { // lazy substring extraction. really should do a better job var basePath = PathManager.MakeAbsolutePath(Global.Config.PathEntries.FirmwaresPathFragment, null) + Path.DirectorySeparatorChar; var path = ri.FilePath.Replace(basePath, ""); // bolden the item if the user has specified a path for it bool bolden = ri.UserSpecified; // set columns based on whether it was a known file if (ri.KnownFirmwareFile == null) { lvi.ImageIndex = idUnsure; lvi.ToolTipText = "You've bound a custom choice here. Hope you know what you're doing."; lvi.SubItems[4].Text = "-custom-"; } else { lvi.ImageIndex = idOk; lvi.ToolTipText = "Good! This file has been bound to some kind of a decent choice"; lvi.SubItems[4].Text = ri.KnownFirmwareFile.Description; } // bolden the item if necessary if (bolden) { foreach (ListViewItem.ListViewSubItem lvsi in lvi.SubItems) { lvsi.Font = boldFont; } lvi.SubItems[6].Font = boldFixedFont; } else { foreach (ListViewItem.ListViewSubItem lvsi in lvi.SubItems) { lvsi.Font = lvFirmwares.Font; } lvi.SubItems[6].Font = fixedFont; } // if the user specified a file but its missing, mark it as such if (ri.Missing) { lvi.ImageIndex = idMissing; lvi.ToolTipText = "The file that's specified is missing!"; } // if the user specified a known firmware file but its for some other firmware, it was probably a mistake. mark it as suspicious if (ri.KnownMismatching) { lvi.ImageIndex = idUnsure; lvi.ToolTipText = "You've manually specified a firmware file, and we're sure it's wrong. Hope you know what you're doing."; } lvi.SubItems[5].Text = path; lvi.SubItems[6].Text = ri.Size.ToString(); if (ri.Hash != null) { lvi.SubItems[7].Text = $"sha1:{ri.Hash}"; } else { lvi.SubItems[7].Text = ""; } } } lvFirmwares.EndUpdate(); }
/// <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 CustomSimulationStep(ushort vehicleId, ref Vehicle vehicleData, Vector3 physicsLodRefPos) { PathManager pathMan = Singleton <PathManager> .instance; #if DEBUG /*if (!Options.disableSomething1) { * Log._Debug($"CustomCarAI.CustomSimulationStep({vehicleId}) called. flags: {vehicleData.m_flags} pfFlags: {pathMan.m_pathUnits.m_buffer[vehicleData.m_path].m_pathFindFlags}"); * }*/ #endif if ((vehicleData.m_flags & Vehicle.Flags.WaitingPath) != 0) { PathManager pathManager = Singleton <PathManager> .instance; byte pathFindFlags = pathManager.m_pathUnits.m_buffer[vehicleData.m_path].m_pathFindFlags; #if USEPATHWAITCOUNTER if ((pathFindFlags & (PathUnit.FLAG_READY | PathUnit.FLAG_FAILED)) != 0) { VehicleState state = VehicleStateManager.Instance()._GetVehicleState(vehicleId); state.PathWaitCounter = 0; // NON-STOCK CODE } #endif if ((pathFindFlags & PathUnit.FLAG_READY) != 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 & PathUnit.FLAG_FAILED) != 0 || vehicleData.m_path == 0) // path == 0: non-stock code! { vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath; Singleton <PathManager> .instance.ReleasePath(vehicleData.m_path); vehicleData.m_path = 0u; this.PathfindFailure(vehicleId, ref vehicleData); return; } #if USEPATHWAITCOUNTER else { VehicleState state = VehicleStateManager.Instance()._GetVehicleState(vehicleId); state.PathWaitCounter = (ushort)Math.Min(ushort.MaxValue, (int)state.PathWaitCounter + 1); // NON-STOCK CODE } #endif } else { if ((vehicleData.m_flags & Vehicle.Flags.WaitingSpace) != 0) { this.TrySpawn(vehicleId, ref vehicleData); } } /// NON-STOCK CODE START /// VehicleStateManager vehStateManager = VehicleStateManager.Instance(); if (Options.prioritySignsEnabled || Options.timedLightsEnabled) { try { vehStateManager.UpdateVehiclePos(vehicleId, ref vehicleData); } catch (Exception e) { Log.Error("CarAI CustomSimulationStep Error: " + e.ToString()); } } if (!Options.isStockLaneChangerUsed()) { try { vehStateManager.LogTraffic(vehicleId, ref vehicleData, true); } catch (Exception e) { Log.Error("CarAI CustomSimulationStep Error: " + e.ToString()); } } /// NON-STOCK CODE END /// 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; } } } #if PATHRECALC ushort recalcSegmentId = 0; #endif int privateServiceIndex = ItemClass.GetPrivateServiceIndex(this.m_info.m_class.m_service); int maxBlockCounter = (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 >= maxBlockCounter && Options.enableDespawning) { Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId); } #if PATHRECALC else if (vehicleData.m_leadingVehicle == 0 && CustomVehicleAI.ShouldRecalculatePath(vehicleId, ref vehicleData, maxBlockCounter, out recalcSegmentId)) { CustomVehicleAI.MarkPathRecalculation(vehicleId, recalcSegmentId); InvalidPath(vehicleId, ref vehicleData, vehicleId, ref vehicleData); } #endif }
public static PathManager GetInstance() { if (instance == null) { instance = (PathManager) FindObjectOfType(typeof(PathManager)); } return instance; }
public void RunLuaScripts() { foreach (var file in _luaList) { if (!file.Enabled && file.Thread == null) { try { LuaSandbox.Sandbox(null, () => { string pathToLoad = Path.IsPathRooted(file.Path) ? file.Path : PathManager.MakeProgramRelativePath(file.Path); //JUNIPIER SQUATCHBOX COMPLEX file.Thread = LuaImp.SpawnCoroutine(file.Path); LuaSandbox.CreateSandbox(file.Thread, Path.GetDirectoryName(pathToLoad)); }, () => { file.State = LuaFile.RunState.Disabled; }); } catch (Exception e) { MessageBox.Show(e.ToString()); } } else { file.Stop(); } } }
///<summary> ///constructor with map file parameter ///</summary> ///<param name="filename"></param> public GameManager(string filename) { Assert.Fatal(null == _instance, "Singleton already created."); _instance = this; _selectedBot = null; MyGame.Instance.GamePaused = false; RemoveABot = false; _map = null; _pathManager = null; _botList = new List<BotEntity>(); _projectiles = new List<Projectile>(); _graveMarkerList = new List<GraveMarker>(); _minimapComponentList = new List<MinimapComponent>(); ////4 upper right minimaps //_minimapComponentList.Add(CreateMinimapComponent( // new Vector2(0, 0), // new Vector2(64.0f, 64.0f), // new Vector2(512.0f, 0.0f), // new Vector2(256.0f, 256.0f), // true)); //_minimapComponentList.Add(CreateMinimapComponent( // new Vector2(0, 0), // new Vector2(64.0f, 64.0f), // new Vector2(768.0f, 0.0f), // new Vector2(256.0f, 256.0f), // true // )); //_minimapComponentList.Add(CreateMinimapComponent( // new Vector2(0, 0), // new Vector2(64.0f, 64.0f), // new Vector2(512.0f, 256.0f), // new Vector2(256.0f, 256.0f), // true // )); //_minimapComponentList.Add(CreateMinimapComponent( // new Vector2(0, 0), // new Vector2(64.0f, 64.0f), // new Vector2(768.0f, 256.0f), // new Vector2(256.0f, 256.0f), // true // )); ////4 lower left minimaps //_minimapComponentList.Add(CreateMinimapComponent( // new Vector2(0, 0), // new Vector2(64.0f, 64.0f), // new Vector2(0.0f, 512.0f), // new Vector2(256.0f, 256.0f), // true)); //_minimapComponentList.Add(CreateMinimapComponent( // new Vector2(0, 0), // new Vector2(64.0f, 64.0f), // new Vector2(256.0f, 512.0f), // new Vector2(256.0f, 256.0f), // true // )); //_minimapComponentList.Add(CreateMinimapComponent( // new Vector2(0, 0), // new Vector2(64.0f, 64.0f), // new Vector2(0.0f, 768.0f), // new Vector2(256.0f, 256.0f), // true // )); //_minimapComponentList.Add(CreateMinimapComponent( // new Vector2(0, 0), // new Vector2(64.0f, 64.0f), // new Vector2(256.0f, 768.0f), // new Vector2(256.0f, 256.0f), // true // )); try { Options = MyGame.Instance.Content.Load<OptionsData>(@"data\maps\Options"); } catch (Exception e) { Assert.Fatal(false, "GameManager.GameManager: Bad options filename -> " + e.Message); MyGame.Instance.Exit(); } try { Parameters = MyGame.Instance.Content.Load<ParameterData>(@"data\maps\Parameters"); } catch (Exception e) { Assert.Fatal(false, "GameManager.GameManager: Bad parameters filename -> " + e.Message); MyGame.Instance.Exit(); } //load in the map LoadMap(filename); //temp code until mouse select implemented //TODO: If we have time we should implement the above comment. If he added the comment I'm sure he'd be pleased to see it implemented ;). TempSetBotSelected(BotList[0]); }
private void ToggleScriptMenuItem_Click(object sender, EventArgs e) { var files = !SelectedFiles.Any() && Global.Config.ToggleAllIfNoneSelected ? _luaList : SelectedFiles; foreach (var item in files) { item.Toggle(); if (item.Enabled && item.Thread == null) { try { LuaSandbox.Sandbox(null, () => { string pathToLoad = Path.IsPathRooted(item.Path) ? item.Path : PathManager.MakeProgramRelativePath(item.Path); //JUNIPIER SQUATCHBOX COMPLEX item.Thread = LuaImp.SpawnCoroutine(pathToLoad); LuaSandbox.CreateSandbox(item.Thread, Path.GetDirectoryName(pathToLoad)); }, () => { item.State = LuaFile.RunState.Disabled; }); } catch (IOException) { ConsoleLog("Unable to access file " + item.Path); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } else if (!item.Enabled && item.Thread != null) { LuaImp.CallExitEvent(item.Thread); var items = SelectedItems.ToList(); foreach (var sitem in items) { var temp = sitem; var functions = LuaImp.RegisteredFunctions.Where(x => x.Lua == temp.Thread).ToList(); foreach (var function in functions) { LuaImp.RegisteredFunctions.Remove(function); } UpdateRegisteredFunctionsDialog(); } LuaImp.CallExitEvent(item.Thread); item.Stop(); if (Global.Config.RemoveRegisteredFunctionsOnToggle) { GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions.ClearAll(); } } } UpdateDialog(); UpdateNumberOfScripts(); LuaListView.Refresh(); }
void Awake() { // add event listeners Events.instance.AddListener<IssueOrdersEvent> (IssueOrders); Events.instance.AddListener<TileClickedEvent> (TileClicked); Events.instance.AddListener<UnitClickedEvent> (UnitClicked); // get input manager and set UI to false inputManager = InputManager.Instance; pathManager = PathManager.Instance; orderUI.SetActive(false); CommandsInteractable(false); OrdersInteractable(true); // UI button delegate assignment orderOneButton.onClick.AddListener(() => {ChangeActiveOrder(1);}); orderTwoAButton.onClick.AddListener(() => {ChangeActiveOrder(2);}); orderTwoBButton.onClick.AddListener(() => {ChangeActiveOrder(3);}); holdCommand.onClick.AddListener(() => {SetOrderCommand(OrderType.Hold);}); moveCommand.onClick.AddListener(() => {SetOrderCommand(OrderType.Move);}); attackCommand.onClick.AddListener(() => {SetOrderCommand(OrderType.Attack);}); // get the size of the sprite spriteExtents = transform.GetComponent<SpriteRenderer>().bounds.extents.x; // set current unit state curState = UnitState.Waiting; }
public DisplayManager(PresentationPanel presentationPanel) { GL = GlobalWin.GL; this.presentationPanel = presentationPanel; GraphicsControl = this.presentationPanel.GraphicsControl; CR_GraphicsControl = GlobalWin.GLManager.GetContextForGraphicsControl(GraphicsControl); //it's sort of important for these to be initialized to something nonzero currEmuWidth = currEmuHeight = 1; if (GL is BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK) { Renderer = new GuiRenderer(GL); } else if (GL is BizHawk.Bizware.BizwareGL.Drivers.SlimDX.IGL_SlimDX9) { Renderer = new GuiRenderer(GL); } else { Renderer = new GDIPlusGuiRenderer((BizHawk.Bizware.BizwareGL.Drivers.GdiPlus.IGL_GdiPlus)GL); } VideoTextureFrugalizer = new TextureFrugalizer(GL); ShaderChainFrugalizers = new RenderTargetFrugalizer[16]; //hacky hardcoded limit.. need some other way to manage these for (int i = 0; i < 16; i++) { ShaderChainFrugalizers[i] = new RenderTargetFrugalizer(GL); } using (var xml = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.courier16px.fnt")) using (var tex = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.courier16px_0.png")) TheOneFont = new StringRenderer(GL, xml, tex); using (var gens = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.gens.ttf")) LoadCustomFont(gens); using (var fceux = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.fceux.ttf")) LoadCustomFont(fceux); if (GL is BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK || GL is BizHawk.Bizware.BizwareGL.Drivers.SlimDX.IGL_SlimDX9) { var fiHq2x = new FileInfo(Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk/hq2x.cgp")); if (fiHq2x.Exists) { using (var stream = fiHq2x.OpenRead()) ShaderChain_hq2x = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk")); } var fiScanlines = new FileInfo(Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk/BizScanlines.cgp")); if (fiScanlines.Exists) { using (var stream = fiScanlines.OpenRead()) ShaderChain_scanlines = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk")); } string bicubic_path = "Shaders/BizHawk/bicubic-fast.cgp"; if (GL is BizHawk.Bizware.BizwareGL.Drivers.SlimDX.IGL_SlimDX9) { bicubic_path = "Shaders/BizHawk/bicubic-normal.cgp"; } var fiBicubic = new FileInfo(Path.Combine(PathManager.GetExeDirectoryAbsolute(), bicubic_path)); if (fiBicubic.Exists) { using (var stream = fiBicubic.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) ShaderChain_bicubic = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk")); } } LuaSurfaceSets["emu"] = new SwappableDisplaySurfaceSet(); LuaSurfaceSets["native"] = new SwappableDisplaySurfaceSet(); LuaSurfaceFrugalizers["emu"] = new TextureFrugalizer(GL); LuaSurfaceFrugalizers["native"] = new TextureFrugalizer(GL); RefreshUserShader(); }
public ReflectionBasedTypeSystem() { SurrogateProvider = null; PathManager = new PathManager(); }
public static void UpdatePathTargetPositions(VehicleAI vehicleAI, ushort vehicleID, ref Vehicle vehicleData, Vector3 refPos, ref int index, int max, float minSqrDistanceA, float minSqrDistanceB) { PathManager instance = Singleton <PathManager> .instance; NetManager instance2 = Singleton <NetManager> .instance; Vector4 vector = vehicleData.m_targetPos0; vector.w = 1000f; float num = minSqrDistanceA; uint num2 = vehicleData.m_path; byte b = vehicleData.m_pathPositionIndex; byte b2 = vehicleData.m_lastPathOffset; if (b == 255) { b = 0; if (index <= 0) { vehicleData.m_pathPositionIndex = 0; } if (!Singleton <PathManager> .instance.m_pathUnits.m_buffer[(int)((UIntPtr)num2)].CalculatePathPositionOffset(b >> 1, vector, out b2)) { (vehicleAI as IVehicle).InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData); return; } } PathUnit.Position position; if (!instance.m_pathUnits.m_buffer[(int)((UIntPtr)num2)].GetPosition(b >> 1, out position)) { (vehicleAI as IVehicle).InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData); return; } NetInfo info = instance2.m_segments.m_buffer[(int)position.m_segment].Info; if (info.m_lanes.Length <= (int)position.m_lane) { (vehicleAI as IVehicle).InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData); return; } uint num3 = PathManager.GetLaneID(position); NetInfo.Lane lane = info.m_lanes[(int)position.m_lane]; Bezier3 bezier; while (true) { if ((b & 1) == 0) { if (lane.m_laneType != NetInfo.LaneType.Cargo) { bool flag = true; while (b2 != position.m_offset) { if (flag) { flag = false; } else { float num4 = Mathf.Sqrt(num) - Vector3.Distance(vector, refPos); int num5; if (num4 < 0f) { num5 = 4; } else { num5 = 4 + Mathf.CeilToInt(num4 * 256f / (instance2.m_lanes.m_buffer[(int)((UIntPtr)num3)].m_length + 1f)); } if (b2 > position.m_offset) { b2 = (byte)Mathf.Max((int)b2 - num5, (int)position.m_offset); } else { if (b2 < position.m_offset) { b2 = (byte)Mathf.Min((int)b2 + num5, (int)position.m_offset); } } } Vector3 a; Vector3 vector2; float b3; (vehicleAI as IVehicle).CalculateSegmentPosition(vehicleID, ref vehicleData, position, num3, b2, out a, out vector2, out b3); vector.Set(a.x, a.y, a.z, Mathf.Min(vector.w, b3)); float sqrMagnitude = (a - refPos).sqrMagnitude; if (sqrMagnitude >= num) { if (index <= 0) { vehicleData.m_lastPathOffset = b2; } vehicleData.SetTargetPos(index++, vector); num = minSqrDistanceB; refPos = vector; vector.w = 1000f; if (index == max) { return; } } } } b += 1; b2 = 0; if (index <= 0) { vehicleData.m_pathPositionIndex = b; vehicleData.m_lastPathOffset = b2; } } int num6 = (b >> 1) + 1; uint num7 = num2; if (num6 >= (int)instance.m_pathUnits.m_buffer[(int)((UIntPtr)num2)].m_positionCount) { num6 = 0; num7 = instance.m_pathUnits.m_buffer[(int)((UIntPtr)num2)].m_nextPathUnit; if (num7 == 0u) { if (index <= 0) { Singleton <PathManager> .instance.ReleasePath(vehicleData.m_path); vehicleData.m_path = 0u; } vector.w = 1f; vehicleData.SetTargetPos(index++, vector); return; } } PathUnit.Position position2; if (!instance.m_pathUnits.m_buffer[(int)((UIntPtr)num7)].GetPosition(num6, out position2)) { (vehicleAI as IVehicle).InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData); return; } NetInfo info2 = instance2.m_segments.m_buffer[(int)position2.m_segment].Info; if (info2.m_lanes.Length <= (int)position2.m_lane) { (vehicleAI as IVehicle).InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData); return; } uint laneID = PathManager.GetLaneID(position2); NetInfo.Lane lane2 = info2.m_lanes[(int)position2.m_lane]; ushort startNode = instance2.m_segments.m_buffer[(int)position.m_segment].m_startNode; ushort endNode = instance2.m_segments.m_buffer[(int)position.m_segment].m_endNode; ushort startNode2 = instance2.m_segments.m_buffer[(int)position2.m_segment].m_startNode; ushort endNode2 = instance2.m_segments.m_buffer[(int)position2.m_segment].m_endNode; if (startNode2 != startNode && startNode2 != endNode && endNode2 != startNode && endNode2 != endNode && ((instance2.m_nodes.m_buffer[(int)startNode].m_flags | instance2.m_nodes.m_buffer[(int)endNode].m_flags) & NetNode.Flags.Disabled) == NetNode.Flags.None && ((instance2.m_nodes.m_buffer[(int)startNode2].m_flags | instance2.m_nodes.m_buffer[(int)endNode2].m_flags) & NetNode.Flags.Disabled) != NetNode.Flags.None) { (vehicleAI as IVehicle).InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData); return; } if (lane2.m_laneType == NetInfo.LaneType.Pedestrian) { if (vehicleID != 0 && (vehicleData.m_flags & Vehicle.Flags.Parking) == Vehicle.Flags.None) { byte offset = position.m_offset; byte offset2 = position.m_offset; if ((vehicleAI as IVehicle).ParkVehicle(vehicleID, ref vehicleData, position, num7, num6 << 1, out offset2)) { if (offset2 != offset) { if (index <= 0) { vehicleData.m_pathPositionIndex = (byte)((int)vehicleData.m_pathPositionIndex & -2); vehicleData.m_lastPathOffset = offset; } position.m_offset = offset2; instance.m_pathUnits.m_buffer[(int)((UIntPtr)num2)].SetPosition(b >> 1, position); } vehicleData.m_flags |= Vehicle.Flags.Parking; } else { (vehicleAI as IVehicle).InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData); } } return; } if ((byte)(lane2.m_laneType & (NetInfo.LaneType.Vehicle | NetInfo.LaneType.Cargo | ((NetInfo.LaneType)((byte)32)) | ((NetInfo.LaneType)((byte)64)))) == 0) { (vehicleAI as IVehicle).InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData); return; } if (lane2.m_vehicleType != vehicleAI.m_info.m_vehicleType && (vehicleAI as IVehicle).NeedChangeVehicleType(vehicleID, ref vehicleData, position2, laneID, lane2.m_vehicleType, ref vector)) { float sqrMagnitude3 = (vector - (Vector4)refPos).sqrMagnitude; if (sqrMagnitude3 >= num) { vehicleData.SetTargetPos(index++, vector); } if (index <= 0) { if (num6 == 0) { Singleton <PathManager> .instance.ReleaseFirstUnit(ref vehicleData.m_path); } vehicleData.m_pathPositionIndex = (byte)(num6 << 1); PathUnit.CalculatePathPositionOffset(laneID, vector, out vehicleData.m_lastPathOffset); if (vehicleID != 0 && !(vehicleAI as IVehicle).ChangeVehicleType(vehicleID, ref vehicleData, position2, laneID)) { (vehicleAI as IVehicle).InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData); } } return; } if (position2.m_segment != position.m_segment && vehicleID != 0) { vehicleData.m_flags &= ~Vehicle.Flags.Leaving; } byte b4 = 0; if ((vehicleData.m_flags & Vehicle.Flags.Flying) != Vehicle.Flags.None) { b4 = (byte)((position2.m_offset < 128) ? 255 : 0); } else { if (num3 != laneID && lane.m_laneType != NetInfo.LaneType.Cargo) { PathUnit.CalculatePathPositionOffset(laneID, vector, out b4); bezier = default(Bezier3); Vector3 vector3; float num8; (vehicleAI as IVehicle).CalculateSegmentPosition(vehicleID, ref vehicleData, position, num3, position.m_offset, out bezier.a, out vector3, out num8); bool flag2 = b2 == 0; if (flag2) { if ((vehicleData.m_flags & Vehicle.Flags.Reversed) != Vehicle.Flags.None) { flag2 = (vehicleData.m_trailingVehicle == 0); } else { flag2 = (vehicleData.m_leadingVehicle == 0); } } Vector3 vector4; float num9; if (flag2) { PathUnit.Position nextPosition; if (!instance.m_pathUnits.m_buffer[(int)((UIntPtr)num7)].GetNextPosition(num6, out nextPosition)) { nextPosition = default(PathUnit.Position); } (vehicleAI as IVehicle).CalculateSegmentPosition(vehicleID, ref vehicleData, nextPosition, position2, laneID, b4, position, num3, position.m_offset, out bezier.d, out vector4, out num9); } else { (vehicleAI as IVehicle).CalculateSegmentPosition(vehicleID, ref vehicleData, position2, laneID, b4, out bezier.d, out vector4, out num9); } if (num9 < 0.01f || (instance2.m_segments.m_buffer[(int)position2.m_segment].m_flags & NetSegment.Flags.Flooded) != NetSegment.Flags.None) { if (index <= 0) { vehicleData.m_lastPathOffset = b2; } vector = bezier.a; vector.w = 0f; while (index < max) { vehicleData.SetTargetPos(index++, vector); } } if (position.m_offset == 0) { vector3 = -vector3; } if (b4 < position2.m_offset) { vector4 = -vector4; } vector3.Normalize(); vector4.Normalize(); float num10; NetSegment.CalculateMiddlePoints(bezier.a, vector3, bezier.d, vector4, true, true, out bezier.b, out bezier.c, out num10); if (num10 > 1f) { ushort num11; if (b4 == 0) { num11 = instance2.m_segments.m_buffer[(int)position2.m_segment].m_startNode; } else { if (b4 == 255) { num11 = instance2.m_segments.m_buffer[(int)position2.m_segment].m_endNode; } else { num11 = 0; } } float num12 = 1.57079637f * (1f + Vector3.Dot(vector3, vector4)); if (num10 > 1f) { num12 /= num10; } num9 = Mathf.Min(num9, (vehicleAI as IVehicle).CalculateTargetSpeed(vehicleID, ref vehicleData, 1000f, num12)); while (b2 < 255) { float num13 = Mathf.Sqrt(num) - Vector3.Distance(vector, refPos); int num14; if (num13 < 0f) { num14 = 8; } else { num14 = 8 + Mathf.CeilToInt(num13 * 256f / (num10 + 1f)); } b2 = (byte)Mathf.Min((int)b2 + num14, 255); Vector3 a2 = bezier.Position((float)b2 * 0.003921569f); vector.Set(a2.x, a2.y, a2.z, Mathf.Min(vector.w, num9)); float sqrMagnitude2 = (a2 - refPos).sqrMagnitude; if (sqrMagnitude2 >= num) { if (index <= 0) { vehicleData.m_lastPathOffset = b2; } if (num11 != 0) { (vehicleAI as IVehicle).UpdateNodeTargetPos(vehicleID, ref vehicleData, num11, ref instance2.m_nodes.m_buffer[(int)num11], ref vector, index); } vehicleData.SetTargetPos(index++, vector); num = minSqrDistanceB; refPos = vector; vector.w = 1000f; if (index == max) { return; } } } } } else { PathUnit.CalculatePathPositionOffset(laneID, vector, out b4); } } if (index <= 0) { if (num6 == 0) { Singleton <PathManager> .instance.ReleaseFirstUnit(ref vehicleData.m_path); } if (num6 >= (int)(instance.m_pathUnits.m_buffer[(int)((UIntPtr)num7)].m_positionCount - 1) && instance.m_pathUnits.m_buffer[(int)((UIntPtr)num7)].m_nextPathUnit == 0u && vehicleID != 0) { (vehicleAI as IVehicle).ArrivingToDestination(vehicleID, ref vehicleData); } } num2 = num7; b = (byte)(num6 << 1); b2 = b4; if (index <= 0) { vehicleData.m_pathPositionIndex = b; vehicleData.m_lastPathOffset = b2; vehicleData.m_flags = ((vehicleData.m_flags & ~Vehicle.Flags.OnGravel) | info2.m_setVehicleFlags); } position = position2; num3 = laneID; lane = lane2; } }
/// <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 CustomSimulationStep(ushort vehicleId, ref Vehicle vehicleData, Vector3 physicsLodRefPos) { if ((vehicleData.m_flags & Vehicle.Flags.WaitingPath) != 0) { PathManager pathManager = Singleton <PathManager> .instance; byte pathFindFlags = pathManager.m_pathUnits.m_buffer[vehicleData.m_path].m_pathFindFlags; // NON-STOCK CODE START ExtPathState mainPathState = ExtPathState.Calculating; if ((pathFindFlags & PathUnit.FLAG_FAILED) != 0 || vehicleData.m_path == 0) { mainPathState = ExtPathState.Failed; } else if ((pathFindFlags & PathUnit.FLAG_READY) != 0) { mainPathState = ExtPathState.Ready; } #if BENCHMARK using (var bm = new Benchmark(null, "UpdateCarPathState")) { #endif if (Options.prohibitPocketCars && VehicleStateManager.Instance.VehicleStates[vehicleId].vehicleType == ExtVehicleType.PassengerCar) { mainPathState = AdvancedParkingManager.Instance.UpdateCarPathState(vehicleId, ref vehicleData, ref ExtCitizenInstanceManager.Instance.ExtInstances[CustomPassengerCarAI.GetDriverInstanceId(vehicleId, ref vehicleData)], mainPathState); } #if BENCHMARK } #endif // NON-STOCK CODE END if (mainPathState == ExtPathState.Ready) { 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 (mainPathState == ExtPathState.Failed) { 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); } } // NON-STOCK CODE START #if BENCHMARK using (var bm = new Benchmark(null, "UpdateVehiclePosition")) { #endif VehicleStateManager.Instance.UpdateVehiclePosition(vehicleId, ref vehicleData); #if BENCHMARK } #endif if (!Options.isStockLaneChangerUsed()) { #if BENCHMARK using (var bm = new Benchmark(null, "LogTraffic")) { #endif // Advanced AI traffic measurement VehicleStateManager.Instance.LogTraffic(vehicleId); #if BENCHMARK } #endif } // NON-STOCK CODE END 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 vehManager = Singleton <VehicleManager> .instance; ushort trailerId = vehicleData.m_trailingVehicle; int numIters = 0; while (trailerId != 0) { ushort trailingVehicle = vehManager.m_vehicles.m_buffer[(int)trailerId].m_trailingVehicle; VehicleInfo info = vehManager.m_vehicles.m_buffer[(int)trailerId].Info; info.m_vehicleAI.SimulationStep(trailerId, ref vehManager.m_vehicles.m_buffer[(int)trailerId], vehicleId, ref vehicleData, lodPhysics); trailerId = trailingVehicle; if (++numIters > 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 maxBlockCounter = (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 >= maxBlockCounter) { // NON-STOCK CODE START bool mayDespawn = true; #if BENCHMARK using (var bm = new Benchmark(null, "MayDespawn")) { #endif mayDespawn = VehicleBehaviorManager.Instance.MayDespawn(ref vehicleData); #if BENCHMARK } #endif if (mayDespawn) { // NON-STOCK CODE END Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId); } // NON-STOCK CODE } }
/// <summary> /// Configures the splash screen and initializes the main application form /// This runs once the splash screen is visible. /// </summary> protected override void OnCreateMainForm() { CommandLineArgs clargs = new CommandLineArgs(this.CommandLineArgs); if (clargs.Hide) { this.SplashScreen.SafeInvoke( () => ((TVRenameSplash)this.SplashScreen).Visible = false, true); } // Update splash screen this.SplashScreen.SafeInvoke( () => ((TVRenameSplash)this.SplashScreen).UpdateStatus("Initializing"), true); // Update RegVersion to bring the WebBrowser up to speed RegistryHelper.UpdateBrowserEmulationVersion(); bool recover = false; string recoverText = string.Empty; // Check arguments for forced recover if (clargs.ForceRecover) { recover = true; recoverText = "Recover manually requested."; } // Check arguments for custom settings path if (!string.IsNullOrEmpty(clargs.UserFilePath)) { try { PathManager.SetUserDefinedBasePath(clargs.UserFilePath); } catch (Exception ex) { if (!clargs.Unattended && !clargs.Hide) { MessageBox.Show($"Error while setting the User-Defined File Path:{Environment.NewLine}{ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } logger.Error(ex, $"Error while setting the User-Defined File Path - EXITING: {clargs.UserFilePath}"); Environment.Exit(1); } } FileInfo tvdbFile = PathManager.TVDBFile; FileInfo settingsFile = PathManager.TVDocSettingsFile; TVDoc doc; do // Loop until files correctly load { if (recover) // Recovery required, prompt user { RecoverXML recoveryForm = new RecoverXML(recoverText); if (recoveryForm.ShowDialog() == DialogResult.OK) { tvdbFile = recoveryForm.DBFile; settingsFile = recoveryForm.SettingsFile; } else { // TODO: Throw an error return; } } // Try loading TheTVDB cache file TheTVDB.Instance.Setup(tvdbFile, PathManager.TVDBFile, clargs); // Try loading settings file doc = new TVDoc(settingsFile, clargs); if (recover) { doc.SetDirty(); } recover = !doc.LoadOK; // Continue if correctly loaded if (!recover) { continue; } // Set recover message recoverText = string.Empty; if (!doc.LoadOK && !string.IsNullOrEmpty(doc.LoadErr)) { recoverText = doc.LoadErr; } if (!TheTVDB.Instance.LoadOK && !string.IsNullOrEmpty(TheTVDB.Instance.LoadErr)) { recoverText += $"{Environment.NewLine}{TheTVDB.Instance.LoadErr}"; } } while (recover); ConvertSeriesTimeZones(doc, TheTVDB.Instance); // Show user interface UI ui = new UI(doc, (TVRenameSplash)this.SplashScreen, !clargs.Unattended && !clargs.Hide); // Bind IPC actions to the form, this allows another instance to trigger form actions RemoteClient.Bind(ui, doc); this.MainForm = ui; }
protected static bool StartPathFind(ushort segmentID, ref NetSegment data, ItemClass.Service netService, VehicleInfo.VehicleType vehicleType, bool skipQueue) { if (data.m_path != 0u) { Singleton <PathManager> .instance.ReleasePath(data.m_path); data.m_path = 0u; } NetManager instance = Singleton <NetManager> .instance; if ((instance.m_nodes.m_buffer[(int)data.m_startNode].m_flags & NetNode.Flags.Ambiguous) != NetNode.Flags.None) { for (int i = 0; i < 8; i++) { ushort segment = instance.m_nodes.m_buffer[(int)data.m_startNode].GetSegment(i); if (segment != 0 && segment != segmentID && instance.m_segments.m_buffer[(int)segment].m_path != 0u) { return(true); } } } if ((instance.m_nodes.m_buffer[(int)data.m_endNode].m_flags & NetNode.Flags.Ambiguous) != NetNode.Flags.None) { for (int j = 0; j < 8; j++) { ushort segment2 = instance.m_nodes.m_buffer[(int)data.m_endNode].GetSegment(j); if (segment2 != 0 && segment2 != segmentID && instance.m_segments.m_buffer[(int)segment2].m_path != 0u) { return(true); } } } Vector3 position = instance.m_nodes.m_buffer[(int)data.m_startNode].m_position; Vector3 position2 = instance.m_nodes.m_buffer[(int)data.m_endNode].m_position; PathUnit.Position startPosA; PathUnit.Position startPosB; float num; float num2; if (!PathManager.FindPathPosition(position, netService, NetInfo.LaneType.Pedestrian, VehicleInfo.VehicleType.None, 32f, out startPosA, out startPosB, out num, out num2)) { return(true); } PathUnit.Position endPosA; PathUnit.Position endPosB; float num3; float num4; if (!PathManager.FindPathPosition(position2, netService, NetInfo.LaneType.Pedestrian, VehicleInfo.VehicleType.None, 32f, out endPosA, out endPosB, out num3, out num4)) { return(true); } if ((instance.m_nodes.m_buffer[(int)data.m_startNode].m_flags & NetNode.Flags.Fixed) != NetNode.Flags.None) { startPosB = default(PathUnit.Position); } if ((instance.m_nodes.m_buffer[(int)data.m_endNode].m_flags & NetNode.Flags.Fixed) != NetNode.Flags.None) { endPosB = default(PathUnit.Position); } startPosA.m_offset = 128; startPosB.m_offset = 128; endPosA.m_offset = 128; endPosB.m_offset = 128; bool stopLane = CustomTransportLineAI.GetStopLane(ref startPosA, vehicleType); bool stopLane2 = CustomTransportLineAI.GetStopLane(ref startPosB, vehicleType); bool stopLane3 = CustomTransportLineAI.GetStopLane(ref endPosA, vehicleType); bool stopLane4 = CustomTransportLineAI.GetStopLane(ref endPosB, vehicleType); if ((!stopLane && !stopLane2) || (!stopLane3 && !stopLane4)) { return(true); } uint path; if (Singleton <CustomPathManager> .instance.CreatePath(out path, ref Singleton <SimulationManager> .instance.m_randomizer, Singleton <SimulationManager> .instance.m_currentBuildIndex, startPosA, startPosB, endPosA, endPosB, NetInfo.LaneType.Vehicle, vehicleType, 20000f, false, true, true, skipQueue, ItemClass.Service.PublicTransport)) { if (startPosA.m_segment != 0 && startPosB.m_segment != 0) { NetNode[] expr_2D9_cp_0 = instance.m_nodes.m_buffer; ushort expr_2D9_cp_1 = data.m_startNode; expr_2D9_cp_0[(int)expr_2D9_cp_1].m_flags = (expr_2D9_cp_0[(int)expr_2D9_cp_1].m_flags | NetNode.Flags.Ambiguous); } else { NetNode[] expr_305_cp_0 = instance.m_nodes.m_buffer; ushort expr_305_cp_1 = data.m_startNode; expr_305_cp_0[(int)expr_305_cp_1].m_flags = (expr_305_cp_0[(int)expr_305_cp_1].m_flags & ~NetNode.Flags.Ambiguous); } if (endPosA.m_segment != 0 && endPosB.m_segment != 0) { NetNode[] expr_344_cp_0 = instance.m_nodes.m_buffer; ushort expr_344_cp_1 = data.m_endNode; expr_344_cp_0[(int)expr_344_cp_1].m_flags = (expr_344_cp_0[(int)expr_344_cp_1].m_flags | NetNode.Flags.Ambiguous); } else { NetNode[] expr_370_cp_0 = instance.m_nodes.m_buffer; ushort expr_370_cp_1 = data.m_endNode; expr_370_cp_0[(int)expr_370_cp_1].m_flags = (expr_370_cp_0[(int)expr_370_cp_1].m_flags & ~NetNode.Flags.Ambiguous); } data.m_path = path; data.m_flags |= NetSegment.Flags.WaitingPath; return(false); } return(true); }
/// <summary> /// Save a state with specified name /// </summary> /// <param name="name">Savestate friendly name</param> public static void SaveState(string name) { InvokeMainFormMethod("SaveState", new object[] { Path.Combine(PathManager.GetSaveStatePath(Global.Game), $"{name}.State"), name, false }); }
/// <summary> /// Return the GUI skin of the node. /// </summary> /// <returns></returns> public override GUISkin GetSkin() { return((GUISkin)AssetDatabase.LoadAssetAtPath( PathManager.EliotStyles() + "ObserverWindowStyle.guiskin", typeof(GUISkin))); }
public void CustomSimulationStep(ushort instanceId, ref CitizenInstance instanceData, Vector3 physicsLodRefPos) { #if DEBUG bool citizenDebug = (DebugSettings.CitizenInstanceId == 0 || DebugSettings.CitizenInstanceId == instanceId) && (DebugSettings.CitizenId == 0 || DebugSettings.CitizenId == instanceData.m_citizen) && (DebugSettings.SourceBuildingId == 0 || DebugSettings.SourceBuildingId == instanceData.m_sourceBuilding) && (DebugSettings.TargetBuildingId == 0 || DebugSettings.TargetBuildingId == instanceData.m_targetBuilding); bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug; #else var logParkingAi = false; #endif CitizenManager citizenManager = Singleton <CitizenManager> .instance; uint citizenId = instanceData.m_citizen; if ((instanceData.m_flags & (CitizenInstance.Flags.Blown | CitizenInstance.Flags.Floating)) != CitizenInstance.Flags.None && (instanceData.m_flags & CitizenInstance.Flags.Character) == CitizenInstance.Flags.None) { citizenManager.ReleaseCitizenInstance(instanceId); if (citizenId != 0u) { citizenManager.ReleaseCitizen(citizenId); } return; } Citizen[] citizensBuffer = citizenManager.m_citizens.m_buffer; if ((instanceData.m_flags & CitizenInstance.Flags.WaitingPath) != CitizenInstance.Flags.None) { PathManager pathManager = Singleton <PathManager> .instance; byte pathFindFlags = pathManager.m_pathUnits.m_buffer[instanceData.m_path].m_pathFindFlags; // NON-STOCK CODE START ExtPathState mainPathState = ExtPathState.Calculating; if ((pathFindFlags & PathUnit.FLAG_FAILED) != 0 || instanceData.m_path == 0) { mainPathState = ExtPathState.Failed; } else if ((pathFindFlags & PathUnit.FLAG_READY) != 0) { mainPathState = ExtPathState.Ready; } if (logParkingAi) { Log._Debug( $"CustomHumanAI.CustomSimulationStep({instanceId}): " + $"Path: {instanceData.m_path}, mainPathState={mainPathState}"); } #if BENCHMARK using (var bm = new Benchmark(null, "ConvertPathStateToSoftPathState+UpdateCitizenPathState")) { #endif ExtSoftPathState finalPathState = ExtCitizenInstance.ConvertPathStateToSoftPathState(mainPathState); if (Options.parkingAI) { finalPathState = AdvancedParkingManager.Instance.UpdateCitizenPathState( instanceId, ref instanceData, ref ExtCitizenInstanceManager.Instance.ExtInstances[instanceId], ref ExtCitizenManager.Instance.ExtCitizens[citizenId], ref citizensBuffer[instanceData.m_citizen], mainPathState); if (logParkingAi) { Log._Debug( $"CustomHumanAI.CustomSimulationStep({instanceId}): " + $"Applied Parking AI logic. Path: {instanceData.m_path}, " + $"mainPathState={mainPathState}, finalPathState={finalPathState}, " + $"extCitizenInstance={ExtCitizenInstanceManager.Instance.ExtInstances[instanceId]}"); } } // if Options.parkingAi #if BENCHMARK } #endif switch (finalPathState) { case ExtSoftPathState.Ready: { if (logParkingAi) { Log._Debug( $"CustomHumanAI.CustomSimulationStep({instanceId}): Path-finding " + $"succeeded for citizen instance {instanceId} " + $"(finalPathState={finalPathState}). Path: {instanceData.m_path} " + "-- calling HumanAI.PathfindSuccess"); } if (citizenId == 0 || citizensBuffer[instanceData.m_citizen].m_vehicle == 0) { Spawn(instanceId, ref instanceData); } instanceData.m_pathPositionIndex = 255; instanceData.m_flags &= ~CitizenInstance.Flags.WaitingPath; instanceData.m_flags &= ~(CitizenInstance.Flags.HangAround | CitizenInstance.Flags.Panicking | CitizenInstance.Flags.SittingDown | CitizenInstance.Flags.Cheering); // NON-STOCK CODE START (transferred from ResidentAI.PathfindSuccess) const Citizen.Flags CTZ_MASK = Citizen.Flags.Tourist | Citizen.Flags.MovingIn | Citizen.Flags.DummyTraffic; if (citizenId != 0 && (citizensBuffer[citizenId].m_flags & CTZ_MASK) == Citizen.Flags.MovingIn) { StatisticBase statisticBase = Singleton <StatisticsManager> .instance.Acquire <StatisticInt32>(StatisticType.MoveRate); statisticBase.Add(1); } // NON-STOCK CODE END PathfindSuccess(instanceId, ref instanceData); break; } case ExtSoftPathState.Ignore: { if (logParkingAi) { Log._Debug( $"CustomHumanAI.CustomSimulationStep({instanceId}): " + "Path-finding result shall be ignored for citizen instance " + $"{instanceId} (finalPathState={finalPathState}). " + $"Path: {instanceData.m_path} -- ignoring"); } return; } case ExtSoftPathState.Calculating: default: { if (logParkingAi) { Log._Debug( $"CustomHumanAI.CustomSimulationStep({instanceId}): " + $"Path-finding result undetermined for citizen instance {instanceId} " + $"(finalPathState={finalPathState}). " + $"Path: {instanceData.m_path} -- continue"); } break; } case ExtSoftPathState.FailedHard: { if (logParkingAi) { Log._Debug( $"CustomHumanAI.CustomSimulationStep({instanceId}): " + $"HARD path-finding failure for citizen instance {instanceId} " + $"(finalPathState={finalPathState}). Path: {instanceData.m_path} " + "-- calling HumanAI.PathfindFailure"); } instanceData.m_flags &= ~CitizenInstance.Flags.WaitingPath; instanceData.m_flags &= ~(CitizenInstance.Flags.HangAround | CitizenInstance.Flags.Panicking | CitizenInstance.Flags.SittingDown | CitizenInstance.Flags.Cheering); Singleton <PathManager> .instance.ReleasePath(instanceData.m_path); instanceData.m_path = 0u; PathfindFailure(instanceId, ref instanceData); return; } case ExtSoftPathState.FailedSoft: { if (logParkingAi) { Log._Debug( $"CustomHumanAI.CustomSimulationStep({instanceId}): " + $"SOFT path-finding failure for citizen instance {instanceId} " + $"(finalPathState={finalPathState}). Path: {instanceData.m_path} " + "-- calling HumanAI.InvalidPath"); } // path mode has been updated, repeat path-finding instanceData.m_flags &= ~CitizenInstance.Flags.WaitingPath; instanceData.m_flags &= ~(CitizenInstance.Flags.HangAround | CitizenInstance.Flags.Panicking | CitizenInstance.Flags.SittingDown | CitizenInstance.Flags.Cheering); InvalidPath(instanceId, ref instanceData); break; } } // NON-STOCK CODE END } // NON-STOCK CODE START #if BENCHMARK using (var bm = new Benchmark(null, "ExtSimulationStep")) { #endif if (Options.parkingAI) { if (ExtSimulationStep( instanceId, ref instanceData, ref ExtCitizenInstanceManager.Instance.ExtInstances[instanceId], physicsLodRefPos)) { return; } } #if BENCHMARK } #endif // NON-STOCK CODE END base.SimulationStep(instanceId, ref instanceData, physicsLodRefPos); VehicleManager vehicleManager = Singleton <VehicleManager> .instance; ushort vehicleId = 0; if (instanceData.m_citizen != 0u) { vehicleId = citizensBuffer[instanceData.m_citizen].m_vehicle; } if (vehicleId != 0) { Vehicle[] vehiclesBuffer = vehicleManager.m_vehicles.m_buffer; VehicleInfo vehicleInfo = vehiclesBuffer[vehicleId].Info; if (vehicleInfo.m_vehicleType == VehicleInfo.VehicleType.Bicycle) { vehicleInfo.m_vehicleAI.SimulationStep( vehicleId, ref vehiclesBuffer[vehicleId], vehicleId, ref vehiclesBuffer[vehicleId], 0); vehicleId = 0; } } if (vehicleId != 0 || (instanceData.m_flags & (CitizenInstance.Flags.Character | CitizenInstance.Flags.WaitingPath | CitizenInstance.Flags.Blown | CitizenInstance.Flags.Floating)) != CitizenInstance.Flags.None) { return; } instanceData.m_flags &= ~(CitizenInstance.Flags.HangAround | CitizenInstance.Flags.Panicking | CitizenInstance.Flags.SittingDown); ArriveAtDestination(instanceId, ref instanceData, false); citizenManager.ReleaseCitizenInstance(instanceId); }
public static FileInfo GetWatchSaveFileFromUser(string currentFile) { return(SaveFileDialog(currentFile, PathManager.MakeAbsolutePath(Global.Config.PathEntries.WatchPathFragment, null), "Watch Files", "wch")); }
public override void OnLevelLoaded(LoadMode mode) { SimulationManager.UpdateMode updateMode = SimulationManager.instance.m_metaData.m_updateMode; Log.Info($"OnLevelLoaded({mode}) called. updateMode={updateMode}"); base.OnLevelLoaded(mode); Log._Debug("OnLevelLoaded Returned from base, calling custom code."); IsGameLoaded = false; switch (updateMode) { case SimulationManager.UpdateMode.NewGameFromMap: case SimulationManager.UpdateMode.NewGameFromScenario: case SimulationManager.UpdateMode.LoadGame: { if (BuildConfig.applicationVersion != BuildConfig.VersionToString( TrafficManagerMod.GAME_VERSION, false)) { string[] majorVersionElms = BuildConfig.applicationVersion.Split('-'); string[] versionElms = majorVersionElms[0].Split('.'); uint versionA = Convert.ToUInt32(versionElms[0]); uint versionB = Convert.ToUInt32(versionElms[1]); uint versionC = Convert.ToUInt32(versionElms[2]); Log.Info($"Detected game version v{BuildConfig.applicationVersion}"); bool isModTooOld = TrafficManagerMod.GAME_VERSION_A < versionA || (TrafficManagerMod.GAME_VERSION_A == versionA && TrafficManagerMod.GAME_VERSION_B < versionB); // || (TrafficManagerMod.GameVersionA == versionA // && TrafficManagerMod.GameVersionB == versionB // && TrafficManagerMod.GameVersionC < versionC); bool isModNewer = TrafficManagerMod.GAME_VERSION_A < versionA || (TrafficManagerMod.GAME_VERSION_A == versionA && TrafficManagerMod.GAME_VERSION_B > versionB); // || (TrafficManagerMod.GameVersionA == versionA // && TrafficManagerMod.GameVersionB == versionB // && TrafficManagerMod.GameVersionC > versionC); if (isModTooOld) { string msg = string.Format( "Traffic Manager: President Edition detected that you are running " + "a newer game version ({0}) than TM:PE has been built for ({1}). " + "Please be aware that TM:PE has not been updated for the newest game " + "version yet and thus it is very likely it will not work as expected.", BuildConfig.applicationVersion, BuildConfig.VersionToString(TrafficManagerMod.GAME_VERSION, false)); Log.Error(msg); Singleton <SimulationManager> .instance.m_ThreadingWrapper.QueueMainThread( () => { UIView.library .ShowModal <ExceptionPanel>("ExceptionPanel") .SetMessage( "TM:PE has not been updated yet", msg, false); }); } else if (isModNewer) { string msg = string.Format( "Traffic Manager: President Edition has been built for game version {0}. " + "You are running game version {1}. Some features of TM:PE will not " + "work with older game versions. Please let Steam update your game.", BuildConfig.VersionToString(TrafficManagerMod.GAME_VERSION, false), BuildConfig.applicationVersion); Log.Error(msg); Singleton <SimulationManager> .instance.m_ThreadingWrapper.QueueMainThread( () => { UIView.library .ShowModal <ExceptionPanel>("ExceptionPanel") .SetMessage( "Your game should be updated", msg, false); }); } } IsGameLoaded = true; break; } default: { Log.Info($"OnLevelLoaded: Unsupported game mode {mode}"); return; } } //it will replace stock PathManager or already Replaced before HotReload if (!IsPathManagerReplaced || TrafficManagerMod.Instance.InGameHotReload) { try { Log.Info("Pathfinder Compatible. Setting up CustomPathManager and SimManager."); FieldInfo pathManagerInstance = typeof(Singleton <PathManager>).GetField( "sInstance", BindingFlags.Static | BindingFlags.NonPublic); if (pathManagerInstance == null) { throw new Exception("pathManagerInstance is null"); } PathManager stockPathManager = PathManager.instance; if (stockPathManager == null) { throw new Exception("stockPathManager is null"); } Log._Debug($"Got stock PathManager instance {stockPathManager?.GetName()}"); CustomPathManager = stockPathManager.gameObject.AddComponent <CustomPathManager>(); Log._Debug("Added CustomPathManager to gameObject List"); if (CustomPathManager == null) { Log.Error("CustomPathManager null. Error creating it."); return; } CustomPathManager.UpdateWithPathManagerValues(stockPathManager); Log._Debug("UpdateWithPathManagerValues success"); pathManagerInstance.SetValue(null, CustomPathManager); Log._Debug("Getting Current SimulationManager"); var simManager = this.simManager; if (simManager == null) { throw new Exception("simManager is null"); } Log._Debug("Removing Stock PathManager"); simManager.Remove(stockPathManager); Log._Debug("Adding Custom PathManager"); simManager.Add(CustomPathManager); Object.Destroy(stockPathManager, 10f); Log._Debug("Should be custom: " + Singleton <PathManager> .instance.GetType()); IsPathManagerReplaced = true; } catch (Exception ex) { string error = "Traffic Manager: President Edition failed to load. You can continue " + "playing but it's NOT recommended. Traffic Manager will not work as expected."; Log.Error(error); Log.Error($"Path manager replacement error: {ex}"); Singleton <SimulationManager> .instance.m_ThreadingWrapper.QueueMainThread( () => { UIView.library .ShowModal <ExceptionPanel>( "ExceptionPanel") .SetMessage( "TM:PE failed to load", error, true); }); } } ModUI.OnLevelLoaded(); // Init transport demand UI if (TransportDemandUI == null) { UIView uiView = UIView.GetAView(); TransportDemandUI = (UITransportDemand)uiView.AddUIComponent(typeof(UITransportDemand)); } // add "remove vehicle" button UIView.GetAView().gameObject.AddComponent <RemoveVehicleButtonExtender>(); // add "remove citizen instance" button UIView.GetAView().gameObject.AddComponent <RemoveCitizenInstanceButtonExtender>(); UIView.GetAView().gameObject.AddComponent <RoadSelectionPanels>(); Patcher.Create().Install(); // Log.Info("Fixing non-created nodes with problems..."); // FixNonCreatedNodeProblems(); Log.Info("Notifying managers..."); foreach (ICustomManager manager in RegisteredManagers) { Log.Info($"OnLevelLoading: {manager.GetType().Name}"); manager.OnLevelLoading(); } // InitTool(); // Log._Debug($"Current tool: {ToolManager.instance.m_properties.CurrentTool}"); Log.Info("OnLevelLoaded complete."); }
void Awake() { if (instance != null) { Destroy (instance.gameObject); } instance = null; cache = new PriorityQueue<PathInstance> (); cache.comparator = PathInstance.Comparison; }
private void BrowseButton_Click(object sender, EventArgs e) { using (var ofd = new OpenFileDialog { InitialDirectory = PathManager.MakeAbsolutePath(Global.Config.PathEntries["Global_NULL", "ROM"].Path, "Global_NULL"), Filter = MainForm.RomFilter, RestoreDirectory = true }) { string _path = ""; var result = ofd.ShowHawkDialog(); if (result == DialogResult.OK) { _path = ofd.FileName; } else { return; } try { var file = new FileInfo(ofd.FileName); var path = BizHawk.Common.HawkFile.Util_ResolveLink(file.FullName); using (var hf = new BizHawk.Common.HawkFile(path)) { if (hf.IsArchive) { // archive - run the archive chooser if (SystemString == "PSX" || SystemString == "PCFX" || SystemString == "SAT") { MessageBox.Show("Using archives with PSX, PCFX or SATURN is not currently recommended/supported."); return; } var ac = new ArchiveChooser(new BizHawk.Common.HawkFile(_path)); int memIdx = -1; if (ac.ShowDialog(this) == DialogResult.OK) { memIdx = ac.SelectedMemberIndex; } var intName = hf.ArchiveItems[memIdx]; PathBox.Text = $"{_path}|{intName.Name}"; } else { // file is not an archive PathBox.Text = _path; } } } catch { return; } } }
void OnEnable() { _target = (PathManager)target; }
private void Start() { pathMngr = GameObject.Find("pathManager").GetComponent<PathManager>() as PathManager; enemyMngr = GameObject.Find("gameManager").GetComponent<EnemyManager>() as EnemyManager; getTarget(); transform.rotation = movement.RotateToPoint(transform,target); sprite = gameObject.GetComponent<SpriteRenderer>(); }
///<summary> ///sets up the game environment from map file ///</summary> ///<param name="filename"></param> ///<returns></returns> public bool LoadMap(string filename) { //clear any current bots and projectiles Clear(); _map = new Map(); //make sure the entity manager is reset EntityManager.Instance.Reset(); //load the new map data if (_map.LoadMap(filename, out _mapData)) { _pathManager = new PathManager( Parameters.MaxSearchCyclesPerUpdateStep); AddBots(Parameters.NumBots); return true; } return false; }
//method to change the current path of this walker object public void SetPath(PathManager newPath) { //disable any running movement methods Stop(); //set new path container pathContainer = newPath; //get new waypoint positions of our new path waypoints = pathContainer.waypoints; //reset current waypoint index to zero currentPoint = 0; //restart/continue movement on new path StartMove(); }
// This creates the GUI inside the window. // It requires the id of the window it's currently making GUI for. private void WindowFunction(int windowID) { // Draw any Controls inside the window here. if (motor == null) { Debug.Log("Getting Motor"); motor = GetComponent<Motor>(); } if (motor == null) { Debug.Log("No Motor"); return; } if (pathManager == null) { Debug.Log("Getting Path Manager"); pathManager = GetComponent<PathManager>(); } if (pathManager == null) { Debug.Log("No Path Manager"); return; } if (centeredLabelStyle == null) { centeredLabelStyle = new GUIStyle(GUI.skin.GetStyle("Label")); centeredLabelStyle.alignment = TextAnchor.MiddleCenter; } GUILayout.BeginHorizontal(); GUILayout.Label(name, centeredLabelStyle); if (GUILayout.Button(motor.isAiControlled ? "is an AI" : "is a Player")) { motor.isAiControlled = !motor.isAiControlled; } if (targetedCameras != null && GUILayout.Button("Watch")) { foreach (TargetedCamera targetedCamera in targetedCameras) { targetedCamera.target = transform; } } GUILayout.EndHorizontal(); int targetRow; int targetIndex = 0; GUILayout.BeginHorizontal(); GUILayout.BeginVertical(); if (GUILayout.Button("None")) { currentDestination = null; } if (GUILayout.Button("Origin")) { currentDestination = Vector2.zero; if (currentDestination.HasValue) { EventManager.Instance.Enqueue<PathRequestEventPayload>( Events.PathRequest, new PathRequestEventPayload(pathManager.searchSpace.gameObject, currentDestination.Value)); } } if (GUILayout.Button("Random")) { currentDestination = pathManager.searchSpace.GetRandomEntityPosition(); if (currentDestination.HasValue) { EventManager.Instance.Enqueue<PathRequestEventPayload>( Events.PathRequest, new PathRequestEventPayload(pathManager.searchSpace.gameObject, currentDestination.Value)); } } targetRow = 3; while (targetRow < targetRowsPerColumn && targetIndex < targets.Length) { if (GUILayout.Button(targets[targetIndex].name)) { currentDestination = targets[targetIndex].transform.position.To2D(); if (currentDestination.HasValue) { EventManager.Instance.Enqueue<PathRequestEventPayload>( Events.PathRequest, new PathRequestEventPayload(pathManager.searchSpace.gameObject, currentDestination.Value)); } } targetRow++; targetIndex++; } GUILayout.EndVertical(); while (targetIndex < targets.Length) { GUILayout.BeginVertical(); targetRow = 0; while (targetRow < targetRowsPerColumn && targetIndex < targets.Length) { if (GUILayout.Button(targets[targetIndex].name)) { currentDestination = targets[targetIndex].transform.position.To2D(); if (currentDestination.HasValue) { EventManager.Instance.Enqueue<PathRequestEventPayload>( Events.PathRequest, new PathRequestEventPayload(pathManager.searchSpace.gameObject, currentDestination.Value)); } } targetRow++; targetIndex++; } GUILayout.EndVertical(); } GUILayout.EndHorizontal(); // Make the windows be draggable. GUI.DragWindow(); }
void Awake() { grid = GetComponent<AStarGrid>(); pathManager = GetComponent<PathManager>(); }
void Awake() { instance = this; pathFinding = GetComponent<Pathfinding>(); }
/// <summary> /// Used for things like SaveFile dialogs to suggest a name to the user /// </summary> private static string SuggestedTasProjName() { return(Path.Combine( PathManager.MakeAbsolutePath(Global.Config.PathEntries.MoviesPathFragment, null), $"{PathManager.FilesystemSafeName(Global.Game)}.{TasMovie.Extension}")); }
// Use this for initialization void Start() { // set instance if(instance == null){ instance = gameObject.GetComponent<PathManager>(); }else{ Destroy(gameObject); } }
void Awake() { instance = this; }
public override void OnDead(AttackableUnit source) { PathManager.Reset(); DashManager.CancelDash(); base.OnDead(source); }
protected override bool StartPathFind(ushort vehicleID, ref Vehicle vehicleData, Vector3 startPos, Vector3 endPos, bool startBothWays, bool endBothWays, bool undergroundTarget) { if ((vehicleData.m_flags & (Vehicle.Flags.TransferToSource | Vehicle.Flags.GoingBack)) != 0) { return(this.StartPathFind(ExtendedVehicleType.CargoTruck, vehicleID, ref vehicleData, startPos, endPos, startBothWays, endBothWays, undergroundTarget, this.IsHeavyVehicle(), this.IgnoreBlocked(vehicleID, ref vehicleData))); } bool allowUnderground = (vehicleData.m_flags & (Vehicle.Flags.Underground | Vehicle.Flags.Transition)) != 0; PathUnit.Position startPosA; PathUnit.Position startPosB; float num; float num2; bool flag = PathManager.FindPathPosition(startPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle, VehicleInfo.VehicleType.Car, allowUnderground, false, 32f, out startPosA, out startPosB, out num, out num2); PathUnit.Position position; PathUnit.Position position2; float num3; float num4; if (PathManager.FindPathPosition(startPos, ItemClass.Service.PublicTransport, NetInfo.LaneType.Vehicle, VehicleInfo.VehicleType.Train | VehicleInfo.VehicleType.Ship, allowUnderground, false, 32f, out position, out position2, out num3, out num4)) { if (!flag || num3 < num) { startPosA = position; startPosB = position2; num = num3; num2 = num4; } flag = true; } PathUnit.Position endPosA; PathUnit.Position endPosB; float num5; float num6; bool flag2 = PathManager.FindPathPosition(endPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle, VehicleInfo.VehicleType.Car, undergroundTarget, false, 32f, out endPosA, out endPosB, out num5, out num6); PathUnit.Position position3; PathUnit.Position position4; float num7; float num8; if (PathManager.FindPathPosition(endPos, ItemClass.Service.PublicTransport, NetInfo.LaneType.Vehicle, VehicleInfo.VehicleType.Train | VehicleInfo.VehicleType.Ship, undergroundTarget, false, 32f, out position3, out position4, out num7, out num8)) { if (!flag2 || num7 < num5) { endPosA = position3; endPosB = position4; num5 = num7; num6 = num8; } flag2 = true; } if (flag && flag2) { PathManager instance = Singleton <PathManager> .instance; if (!startBothWays || num < 10f) { startPosB = default(PathUnit.Position); } if (!endBothWays || num5 < 10f) { endPosB = default(PathUnit.Position); } NetInfo.LaneType laneTypes = NetInfo.LaneType.Vehicle | NetInfo.LaneType.CargoVehicle; VehicleInfo.VehicleType vehicleTypes = VehicleInfo.VehicleType.Car | VehicleInfo.VehicleType.Train | VehicleInfo.VehicleType.Ship; uint path; if (instance.CreatePath(ExtendedVehicleType.CargoTruck, out path, ref Singleton <SimulationManager> .instance.m_randomizer, Singleton <SimulationManager> .instance.m_currentBuildIndex, startPosA, startPosB, endPosA, endPosB, laneTypes, vehicleTypes, 20000f, this.IsHeavyVehicle(), this.IgnoreBlocked(vehicleID, ref vehicleData), false, false)) { if (vehicleData.m_path != 0u) { instance.ReleasePath(vehicleData.m_path); } vehicleData.m_path = path; vehicleData.m_flags |= Vehicle.Flags.WaitingPath; return(true); } } return(false); }
public void Awake() { pathManager = GetComponent <PathManager>(); }
/// <summary> /// Used when starting a new project /// </summary> private static string DefaultTasProjName() { return(Path.Combine( PathManager.MakeAbsolutePath(Global.Config.PathEntries.MoviesPathFragment, null), $"{TasMovie.DefaultProjectName}.{TasMovie.Extension}")); }
private List<GameObject> wpList = new List<GameObject>(); //temporary list for editor created waypoints in a path #endregion Fields #region Methods //inspector input public override void OnInspectorGUI() { //show default variables of script "WaypointManager" DrawDefaultInspector(); //get WaypointManager.cs reference script = (WaypointManager)target; //make the default styles used by EditorGUI look like controls EditorGUIUtility.LookLikeControls(); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); //draw path text label GUILayout.Label("Enter Path Name: ", EditorStyles.boldLabel, GUILayout.Height(15)); //display text field for creating a path with that name pathName = EditorGUILayout.TextField(pathName, GUILayout.Height(15)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); //create new waypoint path button if (!placing && GUILayout.Button("Start Waypoint Path", GUILayout.Height(40))) { //no path name defined, abort with short editor warning if (pathName == "") { Debug.LogWarning("no path name defined"); return; } //path name already given, abort with short editor warning if (script.transform.FindChild(pathName) != null) { Debug.LogWarning("path name already given"); return; } //create a new container transform which will hold all new waypoints path = new GameObject(pathName); //attach PathManager component to this new waypoint container pathMan = path.AddComponent<PathManager>(); //create waypoint array instance of PathManager pathMan.waypoints = new Transform[0]; //reset position and parent container gameobject to this manager gameobject path.transform.position = script.gameObject.transform.position; path.transform.parent = script.gameObject.transform; //we passed all prior checks, toggle waypoint placing on placing = true; //fokus sceneview for placing new waypoints SceneView sceneView = (SceneView)SceneView.sceneViews[0]; sceneView.Focus(); } //finish path button //create new bezier path button if (!placing && GUILayout.Button("Start Bezier Path", GUILayout.Height(40))) { //same as above if (pathName == "") { Debug.LogWarning("no path name defined"); return; } if (script.transform.FindChild(pathName) != null) { Debug.LogWarning("path name already given"); return; } path = new GameObject(pathName); //attach BezierPathManager component to this new waypoint container bezierPathMan = path.AddComponent<BezierPathManager>(); bezierPathMan.showGizmos = true; //create waypoint list instance of BezierPathManager bezierPathMan.points = new List<BezierPoint>(); //reset position and parent container gameobject to this manager gameobject path.transform.position = script.gameObject.transform.position; path.transform.parent = script.gameObject.transform; //we passed all prior checks, toggle waypoint placing on placing = true; //fokus sceneview for placing new waypoints SceneView sceneView = (SceneView)SceneView.sceneViews[0]; sceneView.Focus(); } //finish path button if (placing && GUILayout.Button("Finish Editing", GUILayout.Height(40))) { //return if no path was started or not enough waypoints, so wpList/bwpList is empty if (pathMan && wpList.Count < 2 || bezierPathMan && bwpList.Count < 2) { Debug.LogWarning("not enough waypoints placed"); //if we have created a path already, destroy it again if (path) DestroyImmediate(path); } else if (pathMan) { //switch name of last created waypoint to waypointEnd, //so we will recognize this path ended (this gets an other editor gizmo) wpList[wpList.Count - 1].name = "WaypointEnd"; //do the same with first waypoint wpList[0].name = "WaypointStart"; } else if (bezierPathMan) { //do the same with the bezier path points in case they were used bwpList[bwpList.Count - 1].wp.name = "WaypointEnd"; bwpList[0].wp.name = "WaypointStart"; } //toggle placing off placing = false; //clear list with temporary waypoint references, //we only needed this list for getting first and last waypoint easily wpList.Clear(); bwpList.Clear(); //reset path name input field pathName = ""; //make the new path the active selection Selection.activeGameObject = path; } EditorGUILayout.Space(); GUILayout.Label("Hint:\nPress 'Start Path' to begin a new path," + "\npress 'p' on your keyboard to place\nwaypoints onto objects with colliders." + "\nPress 'Finish Editing' to end your path."); }
public UnitAI(PathFinder pathRef) { pathFinderRef = pathRef; pathManager = new PathManager(pathFinderRef); }