public void Reset() { Waypoints.Clear(); Zone = Zone.Unknown; _position = 0; _positions.Clear(); }
public PutItemWithTagTask(TagList tags, Zone zone) { Name = "Put Item with tag: " + tags + " in zone " + zone.ID; Tags = tags; Zone = zone; Priority = PriorityType.Low; }
public override void activate(ContentHandler content, Zone currentZone, string activationCode) { switch (activationCode) { case "STATIONARY": stationary = true; setNewAnimation(content.getObjectContentHandler().getObjectAnimations()[type][activationCode], content.getObjectContentHandler().getObjectAnimationOffsets()[type][activationCode]); break; case "PUSH_UP": stationary = false; moveUp(currentZone); setNewAnimation(content.getObjectContentHandler().getObjectAnimations()[type][activationCode], content.getObjectContentHandler().getObjectAnimationOffsets()[type][activationCode]); break; case "PUSH_DOWN": stationary = false; moveDown(currentZone); setNewAnimation(content.getObjectContentHandler().getObjectAnimations()[type][activationCode], content.getObjectContentHandler().getObjectAnimationOffsets()[type][activationCode]); break; case "PUSH_RIGHT": stationary = false; moveRight(currentZone); setNewAnimation(content.getObjectContentHandler().getObjectAnimations()[type][activationCode], content.getObjectContentHandler().getObjectAnimationOffsets()[type][activationCode]); break; case "PUSH_LEFT": stationary = false; moveLeft(currentZone); setNewAnimation(content.getObjectContentHandler().getObjectAnimations()[type][activationCode], content.getObjectContentHandler().getObjectAnimationOffsets()[type][activationCode]); break; default: break; } }
public static Dictionary<string, object> BuildingSurfacesByGeometryGroups(List<List<Surface>> geometrySurfaces) { //var elements = new Elements(); var zones = new List<Zone>(); var buildingSurfaces = new List<BuildingSurface>(); var counter = 1; foreach (var geometry in geometrySurfaces) { var bb = BoundingBox.ByGeometry(geometry); var orientation = bb.ContextCoordinateSystem.XAxis.AngleBetween(Vector.ByCoordinates(1, 0, 0)); var zone = new Zone("Zone" + counter, orientation, bb.MinPoint); counter++; zones.Add(zone); var p = bb.MinPoint.Add(bb.MaxPoint.AsVector()); var centerpoint = Point.ByCoordinates(p.X/2, p.Y/2, p.Z/2); buildingSurfaces.AddRange(BuildingSurfacesByOrientation(geometry, zone, centerpoint)); } //elements.AddZones(zones); //elements.AddBuildingSurfaces(buildingSurfaces); //return elements; // elements seems to be better, but for further editing zones and buildingsurfaces are retruned seperately... return new Dictionary<string, object> { { "Zones", zones }, { "BuildingSurfaces", buildingSurfaces } }; }
static void EjectPlayer(Zone zone, BasePlayer player) { cachedDirection = player.transform.position - zone.transform.position; player.transform.position = zone.transform.position + (cachedDirection / cachedDirection.magnitude * (zone.GetComponent<UnityEngine.SphereCollider>().radius + 1f)); player.ClientRPCPlayer(null, player, "ForcePositionTo", new object[] { player.transform.position }); player.TransformChanged(); }
public string Stylize(Zone zone) { var fileStr = string.IsNullOrEmpty(zone.FileName) ? "" : string.Format(" in file '{0}'", zone.FileName); var callStr = ""; if(zone.CallExtract != null) { callStr = string.Format(@" from line {0}: {0,5:[#]}: {1}", zone.CallLine, zone.CallExtract.Line); } return string.Format(@" {1} on line {4}{0}: {2,5:[#]}: {3} {4,5:[#]}: {5} {6}^ {7,5:[#]}: {8}{9}", fileStr, zone.Message, zone.LineNumber - 1, zone.Extract.Before, zone.LineNumber, zone.Extract.Line, new string('-', zone.Position), zone.LineNumber + 1, zone.Extract.After, callStr); }
public void CustomerDroppedInZone(Zone zone) { GameObject feedbackIcon = Instantiate(God.instance.feedbackIconPrefab, transform.position, Quaternion.identity) as GameObject; Customer.ZoneMatchingResults result = customerModel.DroppedInZone(zone); if (result == Customer.ZoneMatchingResults.Fail) { feedbackIcon.GetComponent<FeedbackIcon>().icon = FeedbackIcon.Icons.Fail; AudioManager.instance.PlayAudioForIcon(FeedbackIcon.Icons.Fail); GetComponent<UIDragDropItem>().enabled = false; customerModel.Die(); return; } else if (result == Customer.ZoneMatchingResults.SecondBest) { //Should create little icon customer here? feedbackIcon.GetComponent<FeedbackIcon>().icon = FeedbackIcon.Icons.SecondBestOption; } else { //Should create little icon customer here? feedbackIcon.GetComponent<FeedbackIcon>().icon = FeedbackIcon.Icons.BestOption; } GetComponent<UIDragDropItem>().enabled = false; zone.AddCustomer(customerModel); AudioManager.instance.PlayAudioForIcon(feedbackIcon.GetComponent<FeedbackIcon>().icon); // transform.parent = null; DestroyCustomerView(); }
private void navigatePath() { _pathIterator++; nextZone = _path[_path.Count - 1]; _path.RemoveAt(_path.Count - 1); Vector3 diff = gameObject.transform.position - nextZone.transform.position; if(diff != Vector3.zero) { if(Mathf.Abs(diff.x) > Mathf.Abs(diff.y)) { if(diff.x < 0) _animator.SetInteger("Direction", (int) DIRECTIONS.RIGHT); else _animator.SetInteger("Direction", (int) DIRECTIONS.LEFT); } else { if(diff.y < 0) _animator.SetInteger("Direction", (int) DIRECTIONS.UP); else _animator.SetInteger("Direction", (int) DIRECTIONS.DOWN); } iTween.MoveTo(gameObject, iTween.Hash("x", nextZone.position.x, "y", nextZone.position.y, "easeType", "easeOutExpo", "oncomplete", "navigateToZoneComplete")); } else navigatePath(); }
void Worker_DoWork(object sender, DoWorkEventArgs e) { // If the program is not running or the zone is the same // bail out. if (!IsWorking || _zone == _fface.Player.Zone) { _zone = _fface.Player.Zone; return; } App.InformUser("Program Paused"); // Stop the state machine. StateMachine.Stop(); // Set up waiting of 5 seconds to be our current time + 10 seconds. var waitDelay = DateTime.Now.Add(TimeSpan.FromSeconds(10)); // Wait for five seconds after zoning. while (DateTime.Now < waitDelay) { } // Start up the state machine again. StateMachine.Start(); // Set our zone to our new zone. _zone = _fface.Player.Zone; App.InformUser("Program Resumed"); }
public string Stylize(Zone zone) { var template = @" <div id=""less-error-message""> <h3>There is an error in your .less file</h3> <p>on line {1}, column {3}</p> <div class=""extract""> <pre class=""before""><span>{0}</span>{4}</pre> <pre class=""line""><span>{1}</span>{5}<span class=""error"">{6}</span>{7}</pre> <pre class=""after""><span>{2}</span>{8}</pre> </div> </div> "; return string.Format(template, zone.LineNumber - 1, zone.LineNumber, zone.LineNumber + 1, zone.Position, zone.Extract.Before, // zone.Extract.Line.Substring(0, zone.Position), // zone.Extract.Line[zone.Position], // Html Encode zone.Extract.Line.Substring(zone.Position + 1), // zone.Extract.After); // }
/// <summary> /// Creates a Map object from file. /// </summary> /// <param name="File">The map file to create the object from.</param> public Map(string filename) { using(FileStream stream = new FileStream(filename,FileMode.Open)) using(BinaryReader reader = new BinaryReader(stream)) { short type; _grid = new Zone[8, 8]; _version = reader.ReadInt32(); for(int zy = 0; zy < 8; zy++) for(int zx = 0; zx < 8; zx++) for(int y = 0; y < 32; y++) for(int x = 0; x < 32; x++) { type = 0; if(reader.ReadInt16() > 0) { type &= 0x20; } type &= reader.ReadInt16(); _grid[zx, zy] = new Zone(); _grid[zx, zy][x, y] = (byte)type; } } }
public static DateTime Convert(Zone fromZone, Zone toZone, int year, int month, int day, int hour, int minute, int second, int millisecond) { TimeZoneInfo fromZoneInfo; switch (fromZone) { case Zone.Utc: fromZoneInfo = TimeZoneInfo.Utc; break; case Zone.System: fromZoneInfo = TimeZoneInfo.Local; break; case Zone.Shoot: fromZoneInfo = TimeZoneHandler.ShootTimeZone; break; default: throw new ArgumentOutOfRangeException("fromZone"); } TimeZoneInfo toZoneInfo; switch (toZone) { case Zone.Utc: toZoneInfo = TimeZoneInfo.Utc; break; case Zone.System: toZoneInfo = TimeZoneInfo.Local; break; case Zone.Shoot: toZoneInfo = TimeZoneHandler.ShootTimeZone; break; default: throw new ArgumentOutOfRangeException("toZone"); } return TimeZoneHandler.Convert(fromZoneInfo, toZoneInfo, year, month, day, hour, minute, second, millisecond); }
/// <summary> /// The constructor of ZoneNode class /// </summary> /// <param name="zone"></param> public ZoneNode(Zone zone) : base(zone.Name) { m_zone = zone; base.Text = m_zone.Name; base.ToolTipText = "Phase: " + m_zone.Phase.Name; }
public ZoneOrder(Zone zone, bool isAllowed, Dictionary<PlayerIndex, Player> players) { this.isAllowed = isAllowed; this.zone = zone; this.players = players; duration = 9; }
public TileEngine(Map m) { this.m = m; ee = new EntityEngine(new EntityEngineInterface(this)); camera = new TileEngineCamera(m.width,m.height); foreach(Map.Entdef entdef in m.entdefs) { //todo //Entity e = ee.SpawnMapEntity(entdef); //mapEnts.add(e, entdef.descr, entdef.index); } foreach (Map.Zonedef zd in m.zonedefs) { Zone z = new Zone(); z.bAdjacent = (zd.method == 1); z.chance = zd.percent / 255.0f; z.name = zd.name; z.script = zd.script; zones.Add(z); } ee.EntityActivated += new EntityEngine.EntityActivationHandler(ee_EntityActivated); ee.ZoneActivated += new EntityEngine.ZoneActivationHandler(ee_ZoneActivated); }
static void EjectPlayer(Zone zone, PlayerClient player) { cachedDirection = player.lastKnownPosition - zone.transform.position; player.lastKnownPosition = zone.transform.position + (cachedDirection / cachedDirection.magnitude * (zone.GetComponent<UnityEngine.SphereCollider>().radius + 2f)); management.TeleportPlayerToWorld(player.netPlayer, player.lastKnownPosition); Interface.CallHook("IsCollidingEject",zone, player); }
public string Stylize(Zone zone) { var fileStr = string.IsNullOrEmpty(zone.FileName) ? "" : string.Format(" in '{0}'", zone.FileName); return string.Format(@" <div id=""less-error-message""> <h3>There is an error{0}</h3> <p>{1} on line {3}, column {5}</p> <div class=""extract""> <pre class=""before""><span>{2}</span>{6}</pre> <pre class=""line""><span>{3}</span>{7}<span class=""error"">{8}</span>{9}</pre> <pre class=""after""><span>{4}</span>{10}</pre> </div> </div> ", fileStr, zone.Message, zone.LineNumber - 1, zone.LineNumber, zone.LineNumber + 1, zone.Position, zone.Extract.Before, zone.Extract.Line.Substring(0, zone.Position), zone.Extract.Line[zone.Position], zone.Extract.Line.Substring(zone.Position + 1), zone.Extract.After); }
/// <summary> /// Switch a specific zone of lights off /// </summary> /// <param name="zone">Zone to be switched off</param> /// <returns>Byte command</returns> public static byte[] Off(Zone zone) { byte value; switch (zone) { case Zone.All: value = 0x41; break; case Zone.One: value = 0x46; break; case Zone.Two: value = 0x48; break; case Zone.Three: value = 0x4A; break; case Zone.Four: value = 0x4C; break; default: throw new ArgumentOutOfRangeException("zone"); } return new byte[] { value, 0x00, 0x55 }; }
public void SetControlValueTable(FUnit[] cvt, float scale, float ppem, byte[] cvProgram) { if (this.scale == scale || cvt == null) return; if (controlValueTable == null) controlValueTable = new float[cvt.Length]; for (int i = 0; i < cvt.Length; i++) controlValueTable[i] = cvt[i] * scale; this.scale = scale; this.ppem = (int)Math.Round(ppem); zp0 = zp1 = zp2 = points; state.Reset(); stack.Clear(); if (cvProgram != null) { Execute(new InstructionStream(cvProgram), false, false); // save off the CVT graphics state so that we can restore it for each glyph we hint if ((state.InstructionControl & InstructionControlFlags.UseDefaultGraphicsState) != 0) cvtState.Reset(); else { // always reset a few fields; copy the reset cvtState = state; cvtState.Freedom = Vector2.UnitX; cvtState.Projection = Vector2.UnitX; cvtState.DualProjection = Vector2.UnitX; cvtState.RoundState = RoundMode.ToGrid; cvtState.Loop = 1; } } }
public PutItemInZoneTask(Item item, Zone zone) { Name = "Put Item: " + item.ID + " in zone " + zone.ID; Item = item; Zone = zone; Priority = PriorityType.Low; }
public string Save(Zone zone) { int totalzonetype = zoneGateway.GetCountZoneType(); if (zone.TypeName == string.Empty) { return "Zone Name is missing"; } else if (zoneGateway.IsThisZoneExists(zone.TypeName)) { return "This Zone already Exists"; } else { int value = zoneGateway.Save(zone); if (value > 0) { return "Save Successfully"; } else { return "Save Failed"; } } }
public GoToZoneAct(CreatureAI agent, Zone zone) : base(agent) { Tree = null; Name = "Goto zone : " + zone.ID; Destination = zone; }
private void CheckZoneUsage(Journey journey) { if (_zoneUsed < journey.Zone) { DailyCostCap = Prices.DailyCapZoneB; _zoneUsed = Zone.B; } }
// Action de jeu : essai public override bool OnTry(Zone z) { GameActionState newSon = new GameActionState(sm, cam, game); sm.state_change_son(this, newSon); newSon.OnTry(z); return true; }
internal void Destroy() { Debug.Requires(Created); OnDestruction(); ParentZone = null; }
internal void Create() { Debug.Requires(!Created); ParentZone = Game.Zone; OnCreation(); }
// Use this for initialization void Start() { if (zoneModel == null) { zoneModel = GetComponent<Zone>(); } queue = GameObject.Find("Queue"); }
public string Stylize(Zone zone) { return string.Format("{0}\n{1}\n{2}^\n{3}", zone.Extract.Before, zone.Extract.Line, new string('-', zone.Position), zone.Extract.After); }
public void PurgeAllFiles(Zone zone) { if (zone == null) return; var nvc = new NameValueCollection {{"v", "1"}}; GetFromCloudFlare("fpurge_ts", CheckForSuccess, zone.ZoneName, nvc); }
public GetNearestFreeVoxelInZone(CreatureAI agent, Zone targetZone, string outputVoxel, bool reserve) : base(agent) { Name = "Get Free Voxel"; OutputVoxel = outputVoxel; TargetZone = targetZone; ReserveVoxel = reserve; }
// Use this for initialization void Start() { //Set Zone to the zone object in the scene Zone = GameObject.Find("Zone").GetComponent <ZoneHandler>().CurrentZone; }
public static bool processCommand(Command command, ref string response) { if (command.Name == "GetZoneConfig") { Zone zone = getZoneByName(command.get("ZoneName")); response = "{"; response += "\"ZoneName\":\"" + zone.Name + "\","; response += "\"TimeOut\":\"" + toString(zone.Config.TimeOut) + "\","; response += "\"OffHour\":\"" + toString(zone.Config.OffHour) + "\","; response += "\"OffMin\":\"" + toString(zone.Config.OffMin) + "\","; response += "\"OffByTime\":" + toString(zone.Config.OffByTime); response += "}"; return(true); } else if (command.Name == "SaveZoneConfig") { Zone zone = getZoneByName(command.get("ZoneName")); zone.Config.OffByTime = command.getBool("OffByTime"); zone.Config.OffHour = command.getInt("OffHour"); zone.Config.OffMin = command.getInt("OffMin"); zone.Config.TimeOut = command.getLong("TimeOut"); return(true); } else if (command.Name == "GetZonesState") { response = "["; for (int i = 0; i < _zonesCount; i++) { response += "{"; response += "\"ZoneName\":\"" + _zones[i].Name + "\","; response += "\"IsLightOn\":" + toString(_zones[i].IsLightOn) + ","; response += "\"IsManualMode\":" + toString(_zones[i].Config.IsManualMode); response += "}"; if (i != _zonesCount - 1) { response += ","; } } response += "]"; return(true); } else if (command.Name == "SwitchManualMode") { Zone zone = getZoneByName(command.get("ZoneName")); zone.Config.IsManualMode = !zone.Config.IsManualMode; response = "{"; response += "\"ZoneName\":\"" + zone.Name + "\","; response += "\"IsManualMode\":" + toString(zone.Config.IsManualMode); response += "}"; return(true); } else if (command.Name == "SwitchLight") { Zone zone = getZoneByName(command.get("ZoneName")); if (zone.Config.IsManualMode) { zone.IsLightOn = !zone.IsLightOn; } response = "{"; response += "\"ZoneName\":\"" + zone.Name + "\","; response += "\"IsLightOn\":" + toString(zone.IsLightOn); response += "}"; return(true); } return(false); }
public UpdateVolume(Zone z) : base(z) { }
/// <summary> /// Handles the zone login request packet /// </summary> static public void Handle_CS_Auth(CS_Auth <Zone> pkt, Client <Zone> client) { //Note the login request Log.write(TLog.Normal, "Login request from ({0}): {1} / {2}", client._ipe, pkt.zoneID, pkt.password); //Attempt to find the associated zone DBServer server = client._handler as DBServer; Data.DB.zone dbZone; using (InfantryDataContext db = server.getContext()) dbZone = db.zones.SingleOrDefault(z => z.id == pkt.zoneID); //Does the zone exist? if (dbZone == null) { //Reply with failure SC_Auth <Zone> reply = new SC_Auth <Zone>(); reply.result = SC_Auth <Zone> .LoginResult.Failure; reply.message = "Invalid zone."; client.sendReliable(reply); return; } //Are the passwords a match? if (dbZone.password != pkt.password) { //Oh dear. SC_Auth <Zone> reply = new SC_Auth <Zone>(); reply.result = SC_Auth <Zone> .LoginResult.BadCredentials; client.sendReliable(reply); return; } //Great! Escalate our client object to a zone Zone zone = new Zone(client, server, dbZone); client._obj = zone; server._zones.Add(zone); //Called on connection close / timeout zone._client.Destruct += delegate(NetworkClient nc) { zone.destroy(); }; //Success! SC_Auth <Zone> success = new SC_Auth <Zone>(); success.result = SC_Auth <Zone> .LoginResult.Success; success.message = dbZone.notice; client.sendReliable(success); using (InfantryDataContext db = server.getContext()) { //Update and activate the zone for our directory server Data.DB.zone zoneentry = db.zones.SingleOrDefault(z => z.id == pkt.zoneID); zoneentry.name = pkt.zoneName; zoneentry.description = pkt.zoneDescription; zoneentry.ip = pkt.zoneIP; zoneentry.port = pkt.zonePort; zoneentry.advanced = Convert.ToInt16(pkt.zoneIsAdvanced); zoneentry.active = 1; db.SubmitChanges(); } Log.write("Successful login from {0} ({1})", dbZone.name, client._ipe); }
public Portal(short id, Fighter source, SpellLevelRecord spellLevel, EffectInstance effect, MapPoint centerPoint, Zone zone, Color color) : base(id, source, spellLevel, effect, centerPoint, zone, color, MarkTriggerTypeEnum.AFTER_MOVE) { }
public static bool MouseoverReadoutOnGUI(MouseoverReadout __instance) { IntVec3 c = UI.MouseCell(); if (!c.InBounds(Find.CurrentMap) || Event.current.type != EventType.Repaint || Find.MainTabsRoot.OpenTab != null) { return(false); } if (Find.CurrentMap.GetComponent <MapComponent_FertilityMods>().Get is MapComponent_FertilityMods fert && fert.ActiveCells.Contains(c)) { //Original Variables Vector2 BotLeft = new Vector2(15f, 65f); GenUI.DrawTextWinterShadow(new Rect(256f, (float)(UI.screenHeight - 256), -256f, 256f)); Text.Font = GameFont.Small; GUI.color = new Color(1f, 1f, 1f, 0.8f); float num = 0f; Rect rect; if (c.Fogged(Find.CurrentMap)) { rect = new Rect(BotLeft.x, (float)UI.screenHeight - BotLeft.y - num, 999f, 999f); Widgets.Label(rect, "Undiscovered".Translate()); GUI.color = Color.white; return(false); } rect = new Rect(BotLeft.x, (float)UI.screenHeight - BotLeft.y - num, 999f, 999f); int num2 = Mathf.RoundToInt(Find.CurrentMap.glowGrid.GameGlowAt(c) * 100f); string[] glowStrings = Traverse.Create(__instance).Field("glowStrings").GetValue <string[]>(); Widgets.Label(rect, glowStrings[num2]); num += 19f; rect = new Rect(BotLeft.x, (float)UI.screenHeight - BotLeft.y - num, 999f, 999f); TerrainDef terrain = c.GetTerrain(Find.CurrentMap); //string SpeedPercentString = Traverse.Create(__instance).Method("SpeedPercentString", (float)terrain.pathCost).GetValue<string>(); //TerrainDef cachedTerrain = Traverse.Create(__instance).Field("cachedTerrain").GetValue<TerrainDef>(); string cachedTerrainString = Traverse.Create(__instance).Field("cachedTerrainString").GetValue <string>(); //if (terrain != cachedTerrain) //{ float fertNum = Find.CurrentMap.fertilityGrid.FertilityAt(c); string str = ((double)fertNum <= 0.0001) ? string.Empty : (" " + "FertShort".Translate() + " " + fertNum.ToStringPercent()); cachedTerrainString = terrain.LabelCap + ((terrain.passability == Traversability.Impassable) ? null : (" (" + "WalkSpeed".Translate(new object[] { SpeedPercentString((float)terrain.pathCost) }) + str + ")")); //cachedTerrain = terrain; //} Widgets.Label(rect, cachedTerrainString); num += 19f; Zone zone = c.GetZone(Find.CurrentMap); if (zone != null) { rect = new Rect(BotLeft.x, (float)UI.screenHeight - BotLeft.y - num, 999f, 999f); string label = zone.label; Widgets.Label(rect, label); num += 19f; } float depth = Find.CurrentMap.snowGrid.GetDepth(c); if (depth > 0.03f) { rect = new Rect(BotLeft.x, (float)UI.screenHeight - BotLeft.y - num, 999f, 999f); SnowCategory snowCategory = SnowUtility.GetSnowCategory(depth); string label2 = SnowUtility.GetDescription(snowCategory) + " (" + "WalkSpeed".Translate(new object[] { SpeedPercentString((float)SnowUtility.MovementTicksAddOn(snowCategory)) }) + ")"; Widgets.Label(rect, label2); num += 19f; } List <Thing> thingList = c.GetThingList(Find.CurrentMap); for (int i = 0; i < thingList.Count; i++) { Thing thing = thingList[i]; if (thing.def.category != ThingCategory.Mote) { rect = new Rect(BotLeft.x, (float)UI.screenHeight - BotLeft.y - num, 999f, 999f); string labelMouseover = thing.LabelMouseover; Widgets.Label(rect, labelMouseover); num += 19f; } } RoofDef roof = c.GetRoof(Find.CurrentMap); if (roof != null) { rect = new Rect(BotLeft.x, (float)UI.screenHeight - BotLeft.y - num, 999f, 999f); Widgets.Label(rect, roof.LabelCap); num += 19f; } GUI.color = Color.white; return(false); } return(true); }
private void OnSceneGUI() { if (!enemy) { return; } Event e = Event.current; if (Tools.current == Tool.Custom && EditorTools.activeToolType == typeof(EnemyTool)) { Zone guardZone = enemy.GuardZone; if (guardZone.Width * guardZone.Height != 0) { EditorGUI.BeginChangeCheck(); Vector3 V = Handles.PositionHandle(guardZone.center, Quaternion.identity); Handles.Label(V, "Guard Zone"); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(enemy, "Move Guard Zone"); guardZone.center = V; } else { switch (guardZone.Type) { case ZoneType.Rectangle: { Vector2 size = new Vector2(guardZone.Width, guardZone.Height); Handles.DrawSolidRectangleWithOutline(new Rect(guardZone.center - size / 2f, size), new Color(1f, 0f, 0f, 0.2f), new Color(1f, 0f, 0f, 0.2f)); Handles.CapFunction cap = Handles.CubeHandleCap; Vector3 c = guardZone.center; Vector2 w = new Vector2(guardZone.Width / 2, 0); Vector2 h = new Vector2(0, guardZone.Height / 2); EditorGUI.BeginChangeCheck(); Vector3 rightHandlePosition = guardZone.center + w; Vector3 leftHandlePosition = guardZone.center - w; Vector3 topHandlePosition = guardZone.center + h; Vector3 bottomHandlePosition = guardZone.center - h; Handles.color = Color.red; rightHandlePosition = Handles.Slider(rightHandlePosition, rightHandlePosition - c, 0.2f, cap, 0); leftHandlePosition = Handles.Slider(leftHandlePosition, leftHandlePosition - c, 0.2f, cap, 0); Handles.color = Color.green; topHandlePosition = Handles.Slider(topHandlePosition, topHandlePosition - c, 0.2f, cap, 0); bottomHandlePosition = Handles.Slider(bottomHandlePosition, bottomHandlePosition - c, 0.2f, cap, 0); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(enemy, "Modify Guard Zone"); guardZone.center.x = (rightHandlePosition.x + leftHandlePosition.x) / 2f; guardZone.center.y = (topHandlePosition.y + bottomHandlePosition.y) / 2f; guardZone.Width = rightHandlePosition.x - leftHandlePosition.x; guardZone.Height = topHandlePosition.y - bottomHandlePosition.y; } } break; case ZoneType.Circle: { Handles.color = new Color(1f, 0f, 0f, 0.2f); Handles.DrawSolidDisc(guardZone.center, Vector3.forward, guardZone.Radius); Handles.CapFunction cap = Handles.CubeHandleCap; Vector3 c = guardZone.center; Vector2 w = new Vector2(guardZone.Radius, 0); Vector2 h = new Vector2(0, guardZone.Radius); Vector3 rightHandlePosition = guardZone.center + w; Vector3 leftHandlePosition = guardZone.center - w; Vector3 topHandlePosition = guardZone.center + h; Vector3 bottomHandlePosition = guardZone.center - h; Handles.color = Color.red; EditorGUI.BeginChangeCheck(); rightHandlePosition = Handles.Slider(rightHandlePosition, rightHandlePosition - c, 0.2f, cap, 0); leftHandlePosition = Handles.Slider(leftHandlePosition, leftHandlePosition - c, 0.2f, cap, 0); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(enemy, "Modify Guard Zone"); guardZone.center.x = (rightHandlePosition.x + leftHandlePosition.x) / 2f; guardZone.Radius = (rightHandlePosition.x - leftHandlePosition.x) / 2f; break; } Handles.color = Color.green; EditorGUI.BeginChangeCheck(); topHandlePosition = Handles.Slider(topHandlePosition, topHandlePosition - c, 0.2f, cap, 0); bottomHandlePosition = Handles.Slider(bottomHandlePosition, bottomHandlePosition - c, 0.2f, cap, 0); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(enemy, "Modify Guard Zone"); guardZone.center.y = (topHandlePosition.y + bottomHandlePosition.y) / 2f; guardZone.Radius = (topHandlePosition.y - bottomHandlePosition.y) / 2f; break; } } break; } } } foreach (FieldInfo fieldInfo in enemy.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { try { PathAttribute pathAttribute = fieldInfo.GetCustomAttribute <PathAttribute>(false); if (pathAttribute != null) { Type fieldType = fieldInfo.FieldType; if (fieldType == typeof(Route)) { Route route = fieldInfo.GetValue(enemy) as Route; FieldInfo wayPointsField = route.GetType().GetField("wayPoints", BindingFlags.NonPublic | BindingFlags.Instance); Vector3[] wayPoints = wayPointsField.GetValue(route) as Vector3[]; if (wayPoints.Length > 1) { for (int i = 0; i < wayPoints.Length; ++i) { EditorGUI.BeginChangeCheck(); Handles.color = new Color(0f, 0f, 1f, 0.8f); Handles.DrawSolidDisc(wayPoints[i], Vector3.forward, 0.1f); Vector3 V = Handles.PositionHandle(wayPoints[i], Quaternion.identity); Handles.Label(V, i.ToString()); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(enemy, "Set New Patrol Point " + i); wayPoints[i] = V; break; } } Handles.color = new Color(0f, 1f, 0f, 0.8f); for (int i = 0; i < wayPoints.Length - 1; ++i) { EditorUtility.DrawHandlesArrow(wayPoints[i], wayPoints[i + 1]); } if (pathAttribute.isLooping) { EditorUtility.DrawHandlesArrow(wayPoints[wayPoints.Length - 1], wayPoints[0]); } } } } } catch (Exception) { } } } }
public override void Use(Player p, string message) { if (message == "") { message = "list"; } string[] parameters = message.Split(' '); if (parameters[0].ToLower() == "list") { if (parameters.Length > 1) { int pageNum, currentNum; try { pageNum = int.Parse(parameters[1]) * 10; currentNum = pageNum - 10; } catch { Help(p); return; } if (currentNum < 0) { Player.SendMessage(p, "Must be greater than 0"); return; } if (pageNum > p.level.ZoneList.Count) { pageNum = p.level.ZoneList.Count; } if (currentNum > p.level.ZoneList.Count) { Player.SendMessage(p, "No Zones beyond number " + (p.level.ZoneList.Count - 1)); return; } Player.SendMessage(p, "Zones (" + currentNum + " to " + (pageNum - 1) + "):"); for (int i = currentNum; i < pageNum; i++) { Zone zone = p.level.ZoneList[i]; Player.SendMessage(p, "&c" + i + " &b(" + zone.smallX + "-" + zone.bigX + ", " + zone.smallY + "-" + zone.bigY + ", " + zone.smallZ + "-" + zone.bigZ + ") &f" + zone.owner); } } else { for (int i = 0; i < p.level.ZoneList.Count; i++) { Zone zone = p.level.ZoneList[i]; Player.SendMessage(p, "&c" + i + " &b(" + zone.smallX + "-" + zone.bigX + ", " + zone.smallY + "-" + zone.bigY + ", " + zone.smallZ + "-" + zone.bigZ + ") &f" + zone.owner); } Player.SendMessage(p, "For a more structured list, use /tpzone list <1/2/3/..>"); } } else { int zoneID; try { zoneID = int.Parse(message); } catch { Help(p); return; } if (zoneID < 0 || zoneID > p.level.ZoneList.Count) { Player.SendMessage(p, "This zone doesn't exist"); return; } Zone zone = p.level.ZoneList[zoneID]; unchecked { p.SendPos((byte)-1, (ushort)(zone.bigX * 32 + 16), (ushort)(zone.bigY * 32 + 32), (ushort)(zone.bigZ * 32 + 16), p.rot[0], p.rot[1]); } Player.SendMessage(p, "Teleported to zone &c" + zoneID + " &b(" + zone.bigX + ", " + zone.bigY + ", " + zone.bigZ + ") &f" + zone.owner); } }
public void RemoveZone(Zone Zone, Zone FlushPlayersTo) { // v v v unfinished zones.Remove(Zone); }
private async Task DeleteRecord(string recordName, string token, IAuthorizedSyntax context, Zone zone) { var dns = context.Zone(zone).Dns; var records = await dns .List() .OfType(DnsRecordType.TXT) .WithName(recordName) .WithContent(token) .Match(MatchType.All) .CallAsync(_hc) .ConfigureAwait(false); var record = records.FirstOrDefault(); if (record == null) { _log.Warning($"The record {recordName} that should be deleted does not exist at Cloudflare."); return; } try { _ = await dns.Delete(record.Id) .CallAsync(_hc) .ConfigureAwait(false); } catch (Exception ex) { _log.Warning($"Unable to delete record from Cloudflare: {ex.Message}"); } }
public override NodeState Evaluate() { //Debug.Log("ChooseDestinationNode"); // Se elige una nueva zona int randomZoneNumber; Zone newZone = GameManager.instance.zones[0];; // Comparamos que no sea la misma if (thief.actualZone != null) { do { randomZoneNumber = Random.Range(0, GameManager.instance.zones.Count); newZone = GameManager.instance.zones[randomZoneNumber]; } while (newZone.zoneName == thief.actualZone.zoneName); thief.actualZone.villagerCount--; thief.actualZone = null; } // Comparamos que no sea la previa if (thief.previousZone != null) { do { randomZoneNumber = Random.Range(0, GameManager.instance.zones.Count); newZone = GameManager.instance.zones[randomZoneNumber]; } while (newZone.zoneName == thief.previousZone.zoneName); thief.previousZone = null; } // Se establece la máscara para todas las áreas thief.thisAgent.areaMask = NavMesh.AllAreas; // Se establece el destino thief.destinationZone = newZone; thief.thisAgent.SetDestination(newZone.enterPoint.position); // Se elige si va andando o corriendo int randomSpeedProbability = Random.Range(0, 100); if (randomSpeedProbability < thief.SPEED_RUN_PROBABILITY) { thief.thisAgent.speed = thief.RUNNING_SPEED; thief.isRunning = true; thief.thisAnimator.SetTrigger("run"); } else { thief.thisAgent.speed = thief.WALKING_SPEED; thief.isRunning = false; thief.thisAnimator.SetTrigger("walk"); } // Si tenía víctima, ya no jeje if (thief.victim != null) { thief.victim = null; } // Devolvemos SUCCESS _nodeState = NodeState.SUCCESS; return(_nodeState); }
protected override Facility Mapping(IIfcBuilding ifcBuilding, Facility facility) { //Reset to prevent freezing in cases of various facilities Exchanger.ReportProgress.Reset(); //Helper should do 10% of progress Exchanger.ReportProgress.NextStage(4, 42, string.Format("Creating Facility {0}", ifcBuilding.Name != null ? ifcBuilding.Name.ToString() : string.Empty));//finish progress at 42% var helper = ((IfcToCOBieLiteUkExchanger)Exchanger).Helper; var model = ifcBuilding.Model; facility.ExternalEntity = helper.ExternalEntityName(ifcBuilding); facility.ExternalId = helper.ExternalEntityIdentity(ifcBuilding); facility.AltExternalId = ifcBuilding.GlobalId; facility.ExternalSystem = helper.ExternalSystemName(ifcBuilding); facility.Name = helper.GetFacilityName(ifcBuilding); facility.Description = ifcBuilding.Description; facility.CreatedBy = helper.GetCreatedBy(ifcBuilding); facility.CreatedOn = helper.GetCreatedOn(ifcBuilding); facility.Categories = helper.GetCategories(ifcBuilding); var ifcProject = model.Instances.OfType <IIfcProject>().FirstOrDefault(); if (ifcProject != null) { if (facility.Categories == null) //use the project Categories instead { facility.Categories = helper.GetCategories(ifcProject); } facility.Project = new Project(); var projectMapping = Exchanger.GetOrCreateMappings <MappingIfcProjectToProject>(); projectMapping.AddMapping(ifcProject, facility.Project); Exchanger.ReportProgress.IncrementAndUpdate(); var ifcSite = ifcProject.Sites.FirstOrDefault(); var siteMapping = Exchanger.GetOrCreateMappings <MappingIfcSiteToSite>(); //Facility Attributes facility.Attributes = helper.GetAttributes(ifcBuilding); if (ifcSite != null && facility.Attributes != null) { facility.Site = new Site(); siteMapping.AddMapping(ifcSite, facility.Site); if (ifcSite.RefLatitude.HasValue && ifcSite.RefLongitude.HasValue) { facility.Attributes.Add(helper.MakeAttribute(ifcSite, "RefLatitude", ifcSite.RefLatitude.Value.AsDouble)); facility.Attributes.Add(helper.MakeAttribute(ifcSite, "RefLongtitude", ifcSite.RefLongitude.Value.AsDouble)); } } else //create a default "External area" { facility.Site = new Site { Description = "Default area if no site has been defined in the model", Name = "Default" }; } Exchanger.ReportProgress.IncrementAndUpdate(); facility.AreaUnits = helper.ModelAreaUnit ?? AreaUnit.notdefined; facility.LinearUnits = helper.ModelLinearUnit ?? LinearUnit.notdefined; facility.VolumeUnits = helper.ModelVolumeUnit ?? VolumeUnit.notdefined; facility.CurrencyUnit = helper.ModelCurrencyUnit ?? CurrencyUnit.notdefined; var storeys = ifcBuilding.BuildingStoreys; var cobieFloors = storeys.Cast <IIfcSpatialStructureElement>().ToList(); if (ifcSite != null) { cobieFloors.Add(ifcSite); } Exchanger.ReportProgress.IncrementAndUpdate(); if (ifcBuilding != null) { cobieFloors.Add(ifcBuilding); } Exchanger.ReportProgress.IncrementAndUpdate(); facility.Floors = new List <Floor>(cobieFloors.Count); Exchanger.ReportProgress.NextStage(cobieFloors.Count, 50); //finish progress at 50% var floorMappings = Exchanger.GetOrCreateMappings <MappingIfcSpatialStructureElementToFloor>(); for (int i = 0; i < cobieFloors.Count; i++) { var floor = new Floor(); floor = floorMappings.AddMapping(cobieFloors[i], floor); facility.Floors.Add(floor); Exchanger.ReportProgress.IncrementAndUpdate(); } } //Documents var docsMappings = Exchanger.GetOrCreateMappings <MappingIfcDocumentSelectToDocument>(); helper.AddDocuments(docsMappings, facility, ifcBuilding); if (helper.OrphanDocs.Any()) { foreach (var docSel in helper.OrphanDocs) { List <Document> docs = docsMappings.MappingMulti(docSel); facility.Documents.AddRange(docs); } } //Zones var allSpaces = GetAllSpaces(ifcBuilding); var allZones = GetAllZones(allSpaces, helper); var ifcZones = allZones.ToArray(); if (ifcZones.Any()) { Exchanger.ReportProgress.NextStage(ifcZones.Count(), 65); //finish progress at 65% facility.Zones = new List <Zone>(ifcZones.Length); var zoneMappings = Exchanger.GetOrCreateMappings <MappingIfcZoneToZone>(); for (int i = 0; i < ifcZones.Length; i++) { var zone = new Zone(); zone = zoneMappings.AddMapping(ifcZones[i], zone); facility.Zones.Add(zone); Exchanger.ReportProgress.IncrementAndUpdate(); } } //Assets // var allIfcElementsinThisFacility = new HashSet<IfcElement>(helper.GetAllAssets(ifcBuilding)); //AssetTypes //Get all assets that are in this facility/building //Asset Types are groups of assets that share a common typology //Some types are defined explicitly in the ifc file some have to be inferred var allIfcTypes = helper.DefiningTypeObjectMap.OrderBy(t => t.Key.Name); if (allIfcTypes.Any()) { Exchanger.ReportProgress.NextStage(allIfcTypes.Count(), 90); //finish progress at 90% facility.AssetTypes = new List <AssetType>(); var assetTypeMappings = Exchanger.GetOrCreateMappings <MappingXbimIfcProxyTypeObjectToAssetType>(); foreach (var elementsByType in allIfcTypes) { if (elementsByType.Value.Any()) { var assetType = new AssetType(); assetType = assetTypeMappings.AddMapping(elementsByType.Key, assetType); facility.AssetTypes.Add(assetType); Exchanger.ReportProgress.IncrementAndUpdate(); } } } //Systems facility.Systems = new List <Xbim.CobieLiteUk.System>(); if (helper.SystemMode.HasFlag(SystemExtractionMode.System) && helper.SystemAssignment.Any()) { var systemMappings = Exchanger.GetOrCreateMappings <MappingIfcSystemToSystem>(); Exchanger.ReportProgress.NextStage(helper.SystemAssignment.Keys.Count(), 95); //finish progress at 95% foreach (var ifcSystem in helper.SystemAssignment.Keys) { var system = new Xbim.CobieLiteUk.System(); system = systemMappings.AddMapping(ifcSystem, system); facility.Systems.Add(system); Exchanger.ReportProgress.IncrementAndUpdate(); } } //Get systems via propertySets if (helper.SystemMode.HasFlag(SystemExtractionMode.PropertyMaps) && helper.SystemViaPropAssignment.Any()) { var systemMappings = Exchanger.GetOrCreateMappings <MappingSystemViaIfcPropertyToSystem>(); Exchanger.ReportProgress.NextStage(helper.SystemAssignment.Keys.Count(), 96); //finish progress at 95% foreach (var ifcPropSet in helper.SystemViaPropAssignment.Keys) { var system = new Xbim.CobieLiteUk.System(); system = systemMappings.AddMapping(ifcPropSet, system); var init = facility.Systems.Where(sys => sys.Name.Equals(system.Name, netSystem.StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); if (init != null) { var idx = facility.Systems.IndexOf(init); facility.Systems[idx].Components = facility.Systems[idx].Components.Concat(system.Components).Distinct(new AssetKeyCompare()).ToList(); } else { facility.Systems.Add(system); } Exchanger.ReportProgress.IncrementAndUpdate(); } } //Contacts var ifcActorSelects = helper.Contacts; if (ifcActorSelects != null && ifcActorSelects.Any()) { Exchanger.ReportProgress.NextStage(ifcActorSelects.Count(), 97); //finish progress at 97% var cobieContacts = new List <Contact>(ifcActorSelects.Count()); var contactMappings = Exchanger.GetOrCreateMappings <MappingIfcActorToContact>(); foreach (var actor in ifcActorSelects) { var contact = new Contact(); contact = contactMappings.AddMapping(actor, contact); cobieContacts.Add(contact); Exchanger.ReportProgress.IncrementAndUpdate(); } facility.Contacts = cobieContacts.Distinct(new ContactComparer()).ToList(); } //assign all unallocated spaces to a zone var spaces = facility.Get <Space>().ToList(); var zones = facility.Zones ?? new List <Zone>(); var unAllocatedSpaces = spaces.Where(space => !zones.Any(z => z.Spaces != null && z.Spaces.Select(s => s.Name).Contains(space.Name))); Exchanger.ReportProgress.NextStage(unAllocatedSpaces.Count(), 98); //finish progress at 98% var defaultZone = helper.CreateXbimDefaultZone(); foreach (var space in unAllocatedSpaces) { if (facility.Zones == null) { facility.Zones = new List <Zone>(); } defaultZone.Spaces.Add(new SpaceKey { Name = space.Name }); Exchanger.ReportProgress.IncrementAndUpdate(); } if (facility.Zones != null) { facility.Zones.Add(defaultZone); } //assign all assets that are not in a system to the default if (helper.SystemMode.HasFlag(SystemExtractionMode.Types)) { var assetTypes = facility.Get <AssetType>().ToList(); var systemsWritten = facility.Get <Xbim.CobieLiteUk.System>(); var assetsAssignedToSystem = new HashSet <string>(systemsWritten.SelectMany(s => s.Components).Select(a => a.Name)); var systems = facility.Systems ?? new List <Xbim.CobieLiteUk.System>(); var defaultSystem = helper.CreateUndefinedSystem(); Exchanger.ReportProgress.NextStage(assetTypes.Count(), 100); //finish progress at 100% //go over all unasigned assets foreach (var assetType in assetTypes) { Xbim.CobieLiteUk.System assetTypeSystem = null; foreach (var asset in assetType.Assets.Where(a => !assetsAssignedToSystem.Contains(a.Name))) { if (assetTypeSystem == null) { assetTypeSystem = helper.CreateUndefinedSystem(); assetTypeSystem.Name = string.Format("Type System {0} ", assetType.Name); } assetTypeSystem.Components.Add(new AssetKey { Name = asset.Name }); } //add to tle list only if it is not null if (assetTypeSystem == null) { continue; } if (facility.Systems == null) { facility.Systems = new List <Xbim.CobieLiteUk.System>(); } facility.Systems.Add(assetTypeSystem); Exchanger.ReportProgress.IncrementAndUpdate(); } } //write out contacts created in the process if (helper.SundryContacts.Any()) { if (facility.Contacts == null) { facility.Contacts = new List <Contact>(); } facility.Contacts.AddRange(helper.SundryContacts.Values); } helper.SundryContacts.Clear(); //clear ready for processing next facility Exchanger.ReportProgress.Finalise(500); //finish with 500 millisecond delay return(facility); }
public float GetActionChance(PlayerAction _action, ActionChancePerZoneTable.Actions _zoneChance, MarkingType _marking, Zone _zone) { float chance = 0f; float bonus = 0f; Team_Strategy teamStrategy = Team.GetStrategy(); switch (_action) { case PlayerAction.Pass: chance = _zoneChance.Pass * Prob_Pass; bonus = GetAttributeBonus(Passing); if (_marking == MarkingType.Close) { chance *= 2f; } if (Dice.Roll(20, 1, (int)Dice.RollType.None, Mathf.FloorToInt((chance * 5) + (bonus / 10)), 100) >= 20) { chance *= 2f; } if (Team.IsStrategyApplicable(_zone)) { chance *= teamStrategy.PassingChance; } break; case PlayerAction.LongPass: float longPass = _zoneChance.LongPass * Prob_LongPass; bonus = GetAttributeBonus(Mathf.FloorToInt((float)(Passing + Strength) / 2)); if (_marking == MarkingType.Close) { longPass *= 1.75f; } if (Dice.Roll(20, 1, (int)Dice.RollType.None, Mathf.FloorToInt((longPass * 5) + (bonus / 10)), 100) >= 20) { longPass *= 2f; } if (Team.IsStrategyApplicable(_zone)) { chance *= teamStrategy.LongPassChance; } break; case PlayerAction.Dribble: chance = _zoneChance.Dribble * Prob_Dribble; bonus = GetAttributeBonus(Dribbling); if (_marking == MarkingType.Close) { chance *= 0.5f; } else if (_marking == MarkingType.Distance) { chance *= 1.5f; } if (Dice.Roll(20, 1, (int)Dice.RollType.None, Mathf.FloorToInt((chance * 5) + (bonus / 10))) >= 20) { chance *= 2f; } if (Team.IsStrategyApplicable(_zone)) { chance *= teamStrategy.DribblingChance; } break; case PlayerAction.Cross: chance = _zoneChance.Cross * Prob_Crossing; bonus = GetAttributeBonus(Crossing); if (_marking == MarkingType.Close) { chance *= 0.5f; } if (Dice.Roll(20, 1, (int)Dice.RollType.None, Mathf.FloorToInt((chance * 5) + (bonus / 10))) >= 20) { chance *= 2f; } if (Team.IsStrategyApplicable(_zone)) { chance *= teamStrategy.CrossingChance; } break; case PlayerAction.Shot: chance = _zoneChance.Shot * Prob_Shoot; bonus = GetAttributeBonus(Shooting); if (_marking == MarkingType.Close) { chance *= 0.5f; } else if (_marking == MarkingType.None) { chance *= 3f; } if (Dice.Roll(20, 1, (int)Dice.RollType.None, Mathf.FloorToInt((chance * 5) + (bonus / 10))) >= 20) { chance *= 2f; } if (Team.IsStrategyApplicable(_zone)) { chance *= teamStrategy.ShootingChance; } break; case PlayerAction.Header: chance = (_zoneChance.Shot + Prob_Shoot) * 1.5f; bonus = GetAttributeBonus(Heading); if (_marking == MarkingType.Distance) { chance *= 2f; } else if (_marking == MarkingType.None) { chance *= 3f; } if (Dice.Roll(20, 1, (int)Dice.RollType.None, Mathf.FloorToInt((chance * 5) + (bonus / 10))) >= 20) { chance *= 2f; } if (Team.IsStrategyApplicable(_zone)) { chance *= teamStrategy.ShootingChance; } break; } return(chance); }
///------------------------------------------------------------------- /// /// <summary> /// Создание сцены /// </summary> /// ///-------------------------------------------------------------------- private void createScene() { var cache = ResourceCache; mScene = new Scene(); // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must // exist before creating drawable components, the PhysicsWorld must exist before creating physics components. // Finally, create a DebugRenderer component so that we can draw physics debug geometry mScene.CreateComponent <Octree>(); var physics = mScene.CreateComponent <PhysicsWorld>(); //physics.SetGravity(Vector3.Zero); // mScene.CreateComponent<DebugRenderer>(); // Create a Zone component for ambient lighting & fog control Node zoneNode = mScene.CreateChild("Zone"); Zone zone = zoneNode.CreateComponent <Zone>(); zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f)); zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f); zone.FogColor = new Color(1.0f, 1.0f, 1.0f); zone.FogStart = 300.0f; zone.FogEnd = 500.0f; // Create a directional light to the world. Enable cascaded shadows on it Node lightNode = mScene.CreateChild("DirectionalLight"); lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f)); Light light = lightNode.CreateComponent <Light>(); light.LightType = LightType.Directional; light.CastShadows = true; light.ShadowBias = new BiasParameters(0.00025f, 0.5f); // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f); // Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the // illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will // generate the necessary 3D texture coordinates for cube mapping /* * Node skyNode = mScene.CreateChild("Sky"); * skyNode.SetScale(500.0f); // The scale actually does not matter * Skybox skybox = skyNode.CreateComponent<Skybox>(); * skybox.Model = cache.GetModel("Models/Box.mdl"); * skybox.SetMaterial(cache.GetMaterial("Materials/Skybox.xml"));*/ { // Create a floor object, 1000 x 1000 world units. Adjust position so that the ground is at zero Y Node floorNode = mScene.CreateChild("Floor"); floorNode.Position = new Vector3(0.0f, -0.5f, 0.0f); floorNode.Scale = new Vector3(1000.0f, 1.0f, 1000.0f); var floorObject = floorNode.CreateComponent <Box>(); floorObject.Color = Color.Gray; //floorObject.Model = cache.GetModel("Models/Box.mdl"); //floorObject.SetMaterial(cache.GetMaterial("Materials/StoneTiled.xml")); // Make the floor physical by adding RigidBody and CollisionShape components. The RigidBody's default // parameters make the object static (zero mass.) Note that a CollisionShape by itself will not participate // in the physics simulation floorNode.CreateComponent <RigidBody>(); CollisionShape shape = floorNode.CreateComponent <CollisionShape>(); // Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the // rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.) shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity); } { // Create a pyramid of movable physics objects for (int y = 0; y < 8; ++y) { for (int x = -y; x <= y; ++x) { Node boxNode = mScene.CreateChild("Box"); boxNode.Position = new Vector3((float)x, -(float)y + 8.0f, 0.0f); var boxObject = boxNode.CreateComponent <Box>(); boxObject.Color = Color.Blue; //boxObject.Model = cache.GetModel("Models/Box.mdl"); //boxObject.SetMaterial(cache.GetMaterial("Materials/StoneEnvMapSmall.xml")); boxObject.CastShadows = true; // Create RigidBody and CollisionShape components like above. Give the RigidBody mass to make it movable // and also adjust friction. The actual mass is not important; only the mass ratios between colliding // objects are significant RigidBody body = boxNode.CreateComponent <RigidBody>(); body.Mass = 0.06f; body.Friction = 0.75f; CollisionShape shape = boxNode.CreateComponent <CollisionShape>(); shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity); } } } // Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside // the scene, because we want it to be unaffected by scene load / save mCameraNode = mScene.CreateChild(); Camera camera = mCameraNode.CreateComponent <Camera>(); camera.FarClip = 500.0f; // Set an initial position for the camera scene node above the floor mCameraNode.Position = (new Vector3(0.0f, 2.0f, -12.0f)); mCameraNode.Position = (new Vector3(0.0f, 8.0f, -15.0f)); mCameraNode.Rotation = new Quaternion(30, 0, 0); Renderer.SetViewport(0, new Viewport(Context, mScene, camera, null)); mScene.GetOrCreateComponent <AMainHUD>(); }
public float GetChancePerZone(Zone _zone) { Zones _chancePerZone = GameData.Instance.GetPosChanceData(Team.Strategy, _zone); float pct = 0f; switch (Zone) { case Zone.OwnGoal: pct = _chancePerZone.OwnGoal; break; case Zone.BLD: pct = _chancePerZone.BLD; break; case Zone.BRD: pct = _chancePerZone.BRD; break; case Zone.LD: pct = _chancePerZone.LD; break; case Zone.LCD: pct = _chancePerZone.LCD; break; case Zone.CD: pct = _chancePerZone.CD; break; case Zone.RCD: pct = _chancePerZone.RCD; break; case Zone.RD: pct = _chancePerZone.RD; break; case Zone.LDM: pct = _chancePerZone.LDM; break; case Zone.LCDM: pct = _chancePerZone.LCDM; break; case Zone.CDM: pct = _chancePerZone.CDM; break; case Zone.RCDM: pct = _chancePerZone.RCDM; break; case Zone.RDM: pct = _chancePerZone.RDM; break; case Zone.LM: pct = _chancePerZone.LM; break; case Zone.LCM: pct = _chancePerZone.LCM; break; case Zone.CM: pct = _chancePerZone.CM; break; case Zone.RCM: pct = _chancePerZone.RCM; break; case Zone.RM: pct = _chancePerZone.RM; break; case Zone.LAM: pct = _chancePerZone.LAM; break; case Zone.LCAM: pct = _chancePerZone.LCAM; break; case Zone.CAM: pct = _chancePerZone.CAM; break; case Zone.RCAM: pct = _chancePerZone.RCAM; break; case Zone.RAM: pct = _chancePerZone.RAM; break; case Zone.LF: pct = _chancePerZone.LF; break; case Zone.LCF: pct = _chancePerZone.LCF; break; case Zone.CF: pct = _chancePerZone.CF; break; case Zone.RCF: pct = _chancePerZone.RCF; break; case Zone.RF: pct = _chancePerZone.RF; break; case Zone.ALF: pct = _chancePerZone.ALF; break; case Zone.ARF: pct = _chancePerZone.ARF; break; case Zone.Box: pct = _chancePerZone.Box; break; } if (Zone == Zone.OwnGoal && _zone != Zone.OwnGoal && pct > 0) { Debug.LogFormat("{0} CHANCE: {1} TEAM STRATEGY: {2} ZONE: {3}", FullName, pct, Team.Strategy.ToString(), _zone.ToString()); } return(pct); }
/// <summary> /// Handles the zone login request packet /// </summary> static public void Handle_CS_PlayerLogin(CS_PlayerLogin <Zone> pkt, Zone zone) { //Make a note Log.write(TLog.Inane, "Player login request for '{0}' on '{1}'", pkt.alias, zone); SC_PlayerLogin <Zone> plog = new SC_PlayerLogin <Zone>(); plog.player = pkt.player; if (String.IsNullOrWhiteSpace(pkt.alias)) { plog.bSuccess = false; plog.loginMessage = "Please enter an alias."; zone._client.send(plog); return; } //Are they using the launcher? if (String.IsNullOrWhiteSpace(pkt.ticketid)) { //They're trying to trick us, jim! plog.bSuccess = false; plog.loginMessage = "Please use the Infantry launcher to run the game."; zone._client.send(plog); return; } if (pkt.ticketid.Contains(':')) { //They're using the old, outdated launcher plog.bSuccess = false; plog.loginMessage = "Please use the updated launcher from the website."; zone._client.send(plog); return; } using (InfantryDataContext db = zone._server.getContext()) { Data.DB.player player = null; Data.DB.account account = db.accounts.SingleOrDefault(acct => acct.ticket.Equals(pkt.ticketid)); if (account == null) { //They're trying to trick us, jim! plog.bSuccess = false; plog.loginMessage = "Your session id has expired. Please re-login."; zone._client.send(plog); return; } //Is there already a player online under this account? if (!DBServer.bAllowMulticlienting && zone._server._zones.Any(z => z.hasAccountPlayer(account.id))) { plog.bSuccess = false; plog.loginMessage = "Account is currently in use."; zone._client.send(plog); return; } //Check for IP and UID bans Logic_Bans.Ban banned = Logic_Bans.checkBan(pkt, db, account, zone._zone.id); if (banned.type == Logic_Bans.Ban.BanType.GlobalBan) { //We don't respond to globally banned player requests plog.bSuccess = false; plog.loginMessage = "Banned."; Log.write(TLog.Warning, "Failed login: "******" Alias: " + pkt.alias + " Reason: " + banned.type.ToString()); zone._client.send(plog); return; } if (banned.type == Logic_Bans.Ban.BanType.IPBan) { //Their IP has been banned, make something up! plog.bSuccess = false; plog.loginMessage = "You have been temporarily suspended until " + banned.expiration.ToString("f", CultureInfo.CreateSpecificCulture("en-US")); Log.write(TLog.Warning, "Failed login: "******" Alias: " + pkt.alias + " Reason: " + banned.type.ToString()); zone._client.send(plog); return; } if (banned.type == Logic.Logic_Bans.Ban.BanType.ZoneBan) { //They've been blocked from entering the zone, tell them how long they've got left on their ban plog.bSuccess = false; plog.loginMessage = "You have been temporarily suspended from this zone until " + banned.expiration.ToString("f", CultureInfo.CreateSpecificCulture("en-US")); Log.write(TLog.Warning, "Failed login: "******" Alias: " + pkt.alias + " Reason: " + banned.type.ToString()); zone._client.send(plog); return; } if (banned.type == Logic.Logic_Bans.Ban.BanType.AccountBan) { //They've been blocked from entering any zone, tell them when to come back plog.bSuccess = false; plog.loginMessage = "Your account has been temporarily suspended until " + banned.expiration.ToString("f", CultureInfo.CreateSpecificCulture("en-US")); Log.write(TLog.Warning, "Failed login: "******" Alias: " + pkt.alias + " Reason: " + banned.type.ToString()); zone._client.send(plog); return; } //They made it! //We have the account associated! plog.permission = (PlayerPermission)account.permission; if (account.permission > (int)PlayerPermission.Sysop) { plog.permission = PlayerPermission.Sysop; } //Attempt to find the related alias Data.DB.alias alias = db.alias.SingleOrDefault(a => a.name.Equals(pkt.alias)); Data.DB.stats stats = null; //Is there already a player online under this alias? if (alias != null && zone._server._zones.Any(z => z.hasAliasPlayer(alias.id))) { plog.bSuccess = false; plog.loginMessage = "Alias is currently in use."; zone._client.send(plog); return; } if (alias == null && !pkt.bCreateAlias) { //Prompt him to create a new alias if he has room if (account.alias.Count < 30) { //He has space! Prompt him to make a new alias plog.bSuccess = false; plog.bNewAlias = true; zone._client.send(plog); return; } else { plog.bSuccess = false; plog.loginMessage = "Your account has reached the maximum number of aliases allowed."; zone._client.send(plog); return; } } else if (alias == null && pkt.bCreateAlias) { //We want to create a new alias! alias = new InfServer.Data.DB.alias(); alias.name = pkt.alias; alias.creation = DateTime.Now; alias.account1 = account; alias.IPAddress = pkt.ipaddress; alias.lastAccess = DateTime.Now; alias.timeplayed = 0; db.alias.InsertOnSubmit(alias); Log.write(TLog.Normal, "Creating new alias '{0}' on account '{1}'", pkt.alias, account.name); } else if (alias != null) { //We can't recreate an existing alias or login to one that isn't ours.. if (pkt.bCreateAlias || alias.account1 != account) { plog.bSuccess = false; plog.loginMessage = "The specified alias already exists."; zone._client.send(plog); return; } } //Do we have a player row for this zone? player = db.players.SingleOrDefault( plyr => plyr.alias1 == alias && plyr.zone1 == zone._zone); if (player == null) { //We need to create another! player = new InfServer.Data.DB.player(); player.squad1 = null; player.zone = zone._zone.id; player.alias1 = alias; player.lastAccess = DateTime.Now; player.permission = 0; //Create a blank stats row stats = new InfServer.Data.DB.stats(); stats.zone = zone._zone.id; player.stats1 = stats; db.stats.InsertOnSubmit(stats); db.players.InsertOnSubmit(player); //It's a first-time login, so no need to load stats plog.bFirstTimeSetup = true; } else { //Load the player details and stats! plog.banner = player.banner; if (account.id == 17 && alias.name.ToLower().Contains("hoto")) { plog.permission = 0; } else { plog.permission = (PlayerPermission)Math.Max(player.permission, (int)plog.permission); } if (player.permission > account.permission) { //He's a dev here, set the bool plog.developer = true; } //Check for admin if (Logic_Admins.checkAdmin(alias.name)) { plog.admin = true; } plog.squad = (player.squad1 == null) ? "" : player.squad1.name; if (player.squad1 != null) { plog.squadID = player.squad1.id; } stats = player.stats1; plog.stats.zonestat1 = stats.zonestat1; plog.stats.zonestat2 = stats.zonestat2; plog.stats.zonestat3 = stats.zonestat3; plog.stats.zonestat4 = stats.zonestat4; plog.stats.zonestat5 = stats.zonestat5; plog.stats.zonestat6 = stats.zonestat6; plog.stats.zonestat7 = stats.zonestat7; plog.stats.zonestat8 = stats.zonestat8; plog.stats.zonestat9 = stats.zonestat9; plog.stats.zonestat10 = stats.zonestat10; plog.stats.zonestat11 = stats.zonestat11; plog.stats.zonestat12 = stats.zonestat12; plog.stats.kills = stats.kills; plog.stats.deaths = stats.deaths; plog.stats.killPoints = stats.killPoints; plog.stats.deathPoints = stats.deathPoints; plog.stats.assistPoints = stats.assistPoints; plog.stats.bonusPoints = stats.bonusPoints; plog.stats.vehicleKills = stats.vehicleKills; plog.stats.vehicleDeaths = stats.vehicleDeaths; plog.stats.playSeconds = stats.playSeconds; plog.stats.cash = stats.cash; plog.stats.inventory = new List <PlayerStats.InventoryStat>(); plog.stats.experience = stats.experience; plog.stats.experienceTotal = stats.experienceTotal; plog.stats.skills = new List <PlayerStats.SkillStat>(); //Convert the binary inventory/skill data if (player.inventory != null) { DBHelpers.binToInventory(plog.stats.inventory, player.inventory); } if (player.skills != null) { DBHelpers.binToSkills(plog.stats.skills, player.skills); } } //Rename him plog.alias = alias.name; //Try and submit any new rows before we try and use them try { db.SubmitChanges(); } catch (Exception e) { plog.bSuccess = false; plog.loginMessage = "Unable to create new player / alias, please try again."; Log.write(TLog.Exception, "Exception adding player or alias to DB: {0}", e); zone._client.send(plog); return; } //Add them if (zone.newPlayer(pkt.player.id, alias.name, player)) { plog.bSuccess = true; Log.write("Player '{0}' logged into zone '{1}'", alias.name, zone._zone.name); //Modify his alias IP address and access times alias.IPAddress = pkt.ipaddress.Trim(); alias.lastAccess = DateTime.Now; //Change it db.SubmitChanges(); } else { plog.bSuccess = false; plog.loginMessage = "Unknown login failure."; Log.write("Failed adding player '{0}' from '{1}'", alias.name, zone._zone.name); } //Give them an answer zone._client.sendReliable(plog); } }
public void AddZone(Zone Zone) { zones.Add(Zone); Zone.Server = this; }
public Volume(Zone zone = Zone.Main) : base(zone == Zone.Zone2 ? "ZVL" : "MVL") { }
/// <summary> /// Tries to get a cloned zone /// </summary> /// <param name="zoneid">id to find</param> /// <param name="zone">Zone to find</param> /// <returns></returns> public bool TryFindClonedZone(byte zoneid, out Zone zone) { this.TryGetZone(zoneid, out zone); zone = (Zone)((ICloneable)zone).Clone(); return(zone != null); }
/// <summary> /// Construct an application domain for running a test package /// </summary> /// <param name="package">The TestPackage to be run</param> public AppDomain CreateDomain(TestPackage package) { AppDomainSetup setup = new AppDomainSetup(); //For paralell tests, we need to use distinct application name setup.ApplicationName = "Tests" + "_" + Environment.TickCount; FileInfo testFile = package.FullName != null && package.FullName != string.Empty ? new FileInfo(package.FullName) : null; string appBase = package.BasePath; string configFile = package.ConfigurationFile; string binPath = package.PrivateBinPath; if (testFile != null) { if (appBase == null || appBase == string.Empty) { appBase = testFile.DirectoryName; } if (configFile == null || configFile == string.Empty) { configFile = Services.ProjectService.CanLoadProject(testFile.Name) ? Path.GetFileNameWithoutExtension(testFile.Name) + ".config" : testFile.Name + ".config"; } } else if (appBase == null || appBase == string.Empty) { appBase = GetCommonAppBase(package.Assemblies); } setup.ApplicationBase = appBase; // TODO: Check whether Mono still needs full path to config file... setup.ConfigurationFile = appBase != null && configFile != null ? Path.Combine(appBase, configFile) : configFile; if (package.AutoBinPath) { binPath = GetPrivateBinPath(appBase, package.Assemblies); } setup.PrivateBinPath = binPath; if (package.GetSetting("ShadowCopyFiles", true)) { setup.ShadowCopyFiles = "true"; setup.ShadowCopyDirectories = appBase; setup.CachePath = GetCachePath(); } else { setup.ShadowCopyFiles = "false"; } string domainName = "test-domain-" + package.Name; // Setup the Evidence Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence); if (evidence.Count == 0) { Zone zone = new Zone(SecurityZone.MyComputer); evidence.AddHost(zone); Assembly assembly = Assembly.GetExecutingAssembly(); Url url = new Url(assembly.CodeBase); evidence.AddHost(url); Hash hash = new Hash(assembly); evidence.AddHost(hash); } log.Info("Creating AppDomain " + domainName); AppDomain runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup); // HACK: Only pass down our AddinRegistry one level so that tests of NUnit // itself start without any addins defined. if (!IsTestDomain(AppDomain.CurrentDomain)) { runnerDomain.SetData("AddinRegistry", Services.AddinRegistry); } // Inject DomainInitializer into the remote domain - there are other // approaches, but this works for all CLR versions. DomainInitializer initializer = DomainInitializer.CreateInstance(runnerDomain); initializer.InitializeDomain(IsTestDomain(AppDomain.CurrentDomain) ? TraceLevel.Off : InternalTrace.Level); return(runnerDomain); }
/// <summary> /// Try to get the specified zone. /// </summary> /// <param name="id"></param> /// <param name="map"></param> /// <returns></returns> public bool TryGetZone(uint id, out Zone map) { return(maps.TryGetValue(id, out map)); }
public KoalaCreator(Zone zone) { this.zone = zone; }
void Start() { // Calculate what type of resources are generables depending on the profile's progress. LevelResources.instance.CalculateLimits(XenatekManager.xenatek.GetCurrentProfileProgress()); // Create an instante for the level. level = Instantiate(levelPrefab) as Level; // Initialize the variables. level.name = "Level"; level.SetMinimapTransform(minimapTransform); // For DEBUG... // level.width = XenatekManager.xenatek.levelWidth; // level.height = XenatekManager.xenatek.levelHeight; // level.generateMode = XenatekManager.xenatek.generateMode; GenerateLevelAndZoneSize(); // Generate the level. level.Generate(); // Asign the initial position of the player. Zone startZone = level.GetStartZone(); Vector3 initialPosition = new Vector3(0.0f, 1.0f, 0.0f); initialPosition.x = startZone.x * startZone.width * Globals.ROOM_SIZE + startZone.centralRoom.x * Globals.ROOM_SIZE; initialPosition.z = startZone.y * startZone.height * Globals.ROOM_SIZE + startZone.centralRoom.y * Globals.ROOM_SIZE; player = Instantiate(playerPrefab, initialPosition, Quaternion.identity) as Player; player.name = "Player"; // Initialize the current zone and current room variables. lastZone.x = Mathf.FloorToInt((transform.position.x + Globals.HALF_ROOM_SIZE) / Globals.ROOM_SIZE / XenatekManager.xenatek.zoneWidth); lastZone.y = Mathf.FloorToInt((transform.position.z + Globals.HALF_ROOM_SIZE) / Globals.ROOM_SIZE / XenatekManager.xenatek.zoneHeight); lastRoom.x = Mathf.FloorToInt((transform.position.x + Globals.HALF_ROOM_SIZE) / Globals.ROOM_SIZE) % XenatekManager.xenatek.zoneWidth; lastRoom.y = Mathf.FloorToInt((transform.position.z + Globals.HALF_ROOM_SIZE) / Globals.ROOM_SIZE) % XenatekManager.xenatek.zoneHeight; // Register the delegates for the player's health and update it for first time. player.OnHealthChanged = UpdateHealth; player.OnShieldChanged = UpdateShield; UpdateHealth(); UpdateShield(); // Register the weapon's delegates. player.OnWeaponSwitched = UpdateWeaponSlots; player.OnWeaponAmmoChanged = UpdateWeaponAmmo; // Register the item picking delegate. player.OnItemPicked = ShowItemPickedFeedback; // Register the power ups delegates (picking and updating). player.OnPowerUpChanged = UpdatePowerUpIcons; // Register the player's death delegate. player.OnPlayerDead = FinishGame; // Always start in the first region. hud.ChangeCurrentRegion(1); hud.ChangeCurrentMission(MissionController.instance.GetMissionByRegion(1).GetName()); hud.ChangeCurrentProgress(MissionController.instance.GetMissionByRegion(1).GetProgress()); // Register the progress mission update delegate. MissionController.instance.OnMissionInfoChanged = UpdateMissionProgress; // Register the level completed delegate. MissionController.instance.OnSimulationCompleted = FinishGame; }
public ZoneItem(Zone zone) : base(className: Resources.CloudExplorerGceZoneCategory, componentName: zone.Name) { _zone = zone; }
private void CreatePosts(Site site1, Zone zone1) { var userRole = GetOrCreateUserRole(); var postCreator = TestDataBuilder.NewUser("postOwner", "*****@*****.**", userRole, UserStatus.Active); Session.Save(postCreator); var post = TestDataBuilder.NewPost(site1, zone1, postCreator, commentsCount: 5, pingbackCounts: 3, ratingsCount: 10); post.Creator = postCreator; post.LatestRevision.Reviser = postCreator; Session.Save(post); Session.Flush(); var revision = post.Revise(); revision.Reviser = postCreator; revision.Body = "modified " + revision.Body; Session.SaveOrUpdate(post); var comment = post.Comment(); comment.AuthorName = "commenter"; comment.Body = "this is a test comment"; Session.SaveOrUpdate(post); Session.Flush(); var rate = post.Rate(); rate.Rate = (decimal)4.5; rate.UserIdentity = "user.identity123"; Session.SaveOrUpdate(post); Session.Flush(); var link = TestDataBuilder.Build <PostLink>().Without(c => c.Post).Create(); link.Post = post; post.Links.Add(link); var pingback = TestDataBuilder.Build <Pingback>().Without(c => c.Post).Without(x => x.Snippet).Create(); pingback.Post = post; post.Pingbacks.Add(pingback); Session.SaveOrUpdate(post); Session.Flush(); var tag = TestDataBuilder.Build <Tag>() .With(t => t.Site, site1) .Create(); Session.Save(tag); var category = TestDataBuilder.Build <Category>() .Without(t => t.Parent) .With(t => t.Site, site1) .Create(); Session.Save(category); post.Tags.Add(tag); post.Tags.Add(category); Session.SaveOrUpdate(post); Session.Flush(); var serie = TestDataBuilder.Build <PostSerie>() .With(s => s.Site, site1) .Create(); serie.Posts.Add(post); Session.Save(serie); Session.Flush(); var postPermission = TestDataBuilder.Build <PostPermission>() .With(x => x.User, postCreator) .With(x => x.Post, post) .Create(); Session.Save(postPermission); Session.Flush(); }
/// <summary> /// Passthrough for child nodes that need information from the tree. /// Saves having to query the simulation for the node location all the time. /// </summary> /// <param name="z">The zone.</param> /// <returns></returns> public double GetDistanceFromTrees(Zone z) { return(tree.GetDistanceFromTrees(z)); }
public async Task <HttpResponseMessage> PostTaking([FromBody] TakingDTO value) { string token = GetHeader("token"); if (token == null || (token != null && !TokenManager.ValidateToken(token))) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } User loggedUser = usersService.GetLoggedUser(token); if (value.TicketType != TicketType.REGULAR) { bool nearByFavoritePlace = paidParkingPlacesService.CheckWheterIsParkingPlaceNearByFavoritePlace( loggedUser.FavoritePlaces, value.CurrentLocationLatitude, value.CurrentLocationLongitude); if (!nearByFavoritePlace) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } } bool reservationFoundedAndRemoved = reservationsService.RemoveReservation(loggedUser); Zone zone = null; try { zone = zonesService.GetZone(value.ZoneId); } catch (Exception e) { return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message)); } ParkingPlace parkingPlace = null; try { parkingPlace = zone.ParkingPlaces .Where(pp => pp.Id == value.ParkingPlaceId) .Single(); } catch (Exception e) { return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message)); } PaidParkingPlace paidParkingPlace; lock (parkingPlace) { if (parkingPlace.Status == ParkingPlaceStatus.TAKEN) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "parkingPlace.Status == ParkingPlaceStatus.TAKEN")); } else if (parkingPlace.Status == ParkingPlaceStatus.RESERVED && !reservationFoundedAndRemoved) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "parkingPlace.Status == ParkingPlaceStatus.RESERVED && !reservationRemoved")); } double distance = Distance.computeDistance(value.CurrentLocationLatitude, value.CurrentLocationLongitude, parkingPlace.Location.Latitude, parkingPlace.Location.Longitude); if (distance > MAX_DISTANCE_FOR_TAKING) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } parkingPlace.Status = ParkingPlaceStatus.TAKEN; paidParkingPlace = new PaidParkingPlace(parkingPlace, loggedUser, value.DateTimeAndroid, value.TicketType); paidParkingPlacesService.AddPaidParkingPlace(paidParkingPlace); lock (parkingPlace.Zone) { parkingPlace.Zone.Version++; parkingPlace.Zone.AddParkingPlaceChange(parkingPlace.Id, parkingPlace.Status); } } return(Request.CreateResponse(HttpStatusCode.OK, new PaidParkingPlaceDTO(paidParkingPlace))); }
protected override void Initialize() { _zoneRestriction = Source.OwningCard.Zone; }
static void Postfix() { IntVec3 c = UI.MouseCell(); Map map = Find.CurrentMap; if (!c.InBounds(map)) { return; } Rect rect; Vector2 BotLeft = new Vector2(15f, 65f); float num = 38f; Zone zone = c.GetZone(map); if (zone != null) { num += 19f; } float depth = map.snowGrid.GetDepth(c); if (depth > 0.03f) { num += 19f; } List <Thing> thingList = c.GetThingList(map); for (int i = 0; i < thingList.Count; i++) { Thing thing = thingList[i]; if (thing.def.category != ThingCategory.Mote) { num += 19f; } } RoofDef roof = c.GetRoof(map); if (roof != null) { num += 19f; } if (Settings.showDevReadout) { rect = new Rect(BotLeft.x, (float)UI.screenHeight - BotLeft.y - num, 999f, 999f); string label3 = "C: x-" + c.x.ToString() + " y-" + c.y.ToString() + " z-" + c.z.ToString(); Widgets.Label(rect, label3); num += 19f; Watcher watcher = map.GetComponent <Watcher>(); cellData cell = watcher.cellWeatherAffects[c]; rect = new Rect(BotLeft.x, (float)UI.screenHeight - BotLeft.y - num, 999f, 999f); string label2 = "Temperature: " + cell.temperature; Widgets.Label(rect, label2); num += 19f; rect = new Rect(BotLeft.x, (float)UI.screenHeight - BotLeft.y - num, 999f, 999f); string label4 = "Cell Info: Base Terrain " + cell.baseTerrain.defName + " Current Terrain " + cell.currentTerrain.defName + " | Wet " + cell.isWet.ToString() + " | Melt " + cell.isMelt.ToString() + " | Flooded " + cell.isFlooded.ToString() + " | Frozen " + cell.isFrozen.ToString() + " | Thawed " + cell.isThawed.ToString() + " | Getting Wet? " + cell.gettingWet.ToString(); Widgets.Label(rect, label4); num += 19f; rect = new Rect(BotLeft.x, (float)UI.screenHeight - BotLeft.y - num, 999f, 999f); string label6 = "TKKN_Wet " + cell.currentTerrain.HasTag("TKKN_Wet") + "TKKN_Swim " + cell.currentTerrain.HasTag("TKKN_Swim"); Widgets.Label(rect, label6); num += 19f; rect = new Rect(BotLeft.x, (float)UI.screenHeight - BotLeft.y - num, 999f, 999f); string label5 = "Cell Info: howWet " + cell.howWet.ToString() + " | How Wet (Plants) " + cell.howWetPlants.ToString() + " | How Packed " + cell.howPacked.ToString(); if (cell.weather != null) { if (cell.weather.wetTerrain != null) { label5 += " | T Wet " + cell.weather.wetTerrain.defName; } if (cell.weather.dryTerrain != null) { label5 += " | T Dry " + cell.weather.dryTerrain.defName; } if (cell.weather.freezeTerrain != null) { label5 += " | T Freeze " + cell.weather.freezeTerrain.defName; } } if (cell.originalTerrain != null) { label5 += " | Orig Terrain " + cell.originalTerrain.defName; } Widgets.Label(rect, label5); num += 19f; } depth = map.GetComponent <FrostGrid>().GetDepth(c); if (depth > 0.01f) { rect = new Rect(BotLeft.x, (float)UI.screenHeight - BotLeft.y - num, 999f, 999f); FrostCategory frostCategory = FrostUtility.GetFrostCategory(depth); string label2 = FrostUtility.GetDescription(frostCategory); Widgets.Label(rect, label2); // Widgets.Label(rect, label2 + " " + depth.ToString()); num += 19f; } }
//Returns the shortest distance between two nodes - all edge weights are 1 private List <Zone> dijkstra(Zone source, Zone destination, bool thermals) { int numZones = 25 * 25 * 25; float[] distances = new float[numZones]; DijkstraNode dSource = new DijkstraNode(source.id); DijkstraNode dDestination = new DijkstraNode(destination.id); for (int i = 0; i < numZones; i++) { distances[i] = Mathf.Infinity; } distances[dSource.identifier] = 0; //This uses two new classes: DijkstraNode is simply a pair of identifier and distance //DijkstraNodeComparator sorts DijkstraNodes by distance //so that the priority queue always returns the closest node List <DijkstraNode> dijkstraNodes = new List <DijkstraNode>(); //Start from the source node DijkstraNode currentNode = dSource; //while (!currentNode.equals(dDestination)) while (currentNode.identifier != dDestination.identifier) { //Get all edges from the current node List <Edge> newEdges = new List <Edge>(); // Flatten 3d neighbour array to 1d GameObject[,,] neigh = weather.zonesByID[currentNode.identifier].neighbours; List <GameObject> flatNeigh = new List <GameObject>(); for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { for (int l = 0; l < 3; l++) { if (neigh[j, k, l]) { flatNeigh.Add(neigh[j, k, l]); } } } } foreach (GameObject n in flatNeigh) { Zone newZone = n.GetComponent <Zone>() as Zone; if (newZone.terrain == false) { float edgeCost = drone.edgeCost(weather.zonesByID[currentNode.identifier], weather.zonesByID[newZone.id], thermals); Edge newEdge = new Edge(currentNode.identifier, newZone.id, edgeCost); newEdges.Add(newEdge); } } //Convert edge destinations to DijkstraNodes with the updated distance foreach (Edge e in newEdges) { DijkstraNode newDNode = new DijkstraNode(e.endIdentifier); newDNode.distance = currentNode.distance + e.distance; newDNode.previousNode = currentNode; //Check if node in question has already been added into the search tree with a //longer route. If yes, replace it with a shorter one if (dijkstraNodes.Contains(newDNode) && newDNode.distance < distances[newDNode.identifier]) { //equals() has been defined for DNodes based on identifier attribute dijkstraNodes.Remove(newDNode); distances[newDNode.identifier] = newDNode.distance; dijkstraNodes.Add(newDNode); } else if (distances[newDNode.identifier] == Mathf.Infinity) { distances[newDNode.identifier] = newDNode.distance; dijkstraNodes.Add(newDNode); } } //Sort list dijkstraNodes.Sort(new DijkstraNodeComparator()); currentNode = dijkstraNodes[0]; dijkstraNodes.Remove(currentNode); } //Once the destionation node is currentNode, return the distance List <Zone> shortestPath = new List <Zone>(); DijkstraNode backwardsNode = currentNode; while (backwardsNode != dSource) { shortestPath.Add(weather.zonesByID[backwardsNode.identifier]); backwardsNode = backwardsNode.previousNode; } shortestPath.Reverse(); return(shortestPath); }