/// <summary> /// Possibly broken, hasn't been tested, don't consider reliable. Creates a linear weight pick emitted from a weight value, for example, a weight of 4 between 1 and 10 would mean you are most likely to get 4, and the chances lowering going in either direction of the number line. /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <param name="weight">The weight emitter</param> /// <returns></returns> public static int WeightedRandom(int min, int max, int weight = 0) { List <int> options = new List <int>(); bool valid = max > min; if (valid) { for (int i = min; i < max; i++) { for (int k = 0; k < Math.Abs(i - weight); k++) { options.Add(i); } } DebugExt.Log(options.ToString(), true); return(SRand.Range(0, options.Count)); } else { return(min); } }
static void Postfix(Road __instance, ref bool __result, Cell c) { try { if (__instance != null) { Mod.helper.Log("test"); Cell roadCell = World.inst.GetCellData(__instance.transform.position); if (roadCell != null && c != null) { CellMark markFrom = ElevationManager.GetCellMark(roadCell); CellMark markTo = ElevationManager.GetCellMark(c); if (markFrom != null && markTo != null) { if (ElevationManager.ValidTileForElevation(roadCell) && ElevationManager.ValidTileForElevation(c)) { if (!(markFrom.elevationTier - markTo.elevationTier == 1 || markFrom.elevationTier - markTo.elevationTier == 0)) { __result = false; } } } } } } catch (Exception ex) { DebugExt.HandleException(ex); } }
public static bool BlocksPathDirectional(Cell from, Cell to) { try { CellMark markFrom = ElevationManager.GetCellMark(from); CellMark markTo = ElevationManager.GetCellMark(to); Dictionary <Vector3, Direction> dirs = new Dictionary <Vector3, Direction>() { { new Vector3(1f, 0f, 0f), Direction.East }, { new Vector3(0f, 0f, 1f), Direction.South }, { new Vector3(-1f, 0f, 0f), Direction.West }, { new Vector3(0f, 0f, -1f), Direction.North }, }; Dictionary <Vector3, Diagonal> diagonals = new Dictionary <Vector3, Diagonal>() { { new Vector3(1f, 0f, 1f), Diagonal.SouthEast }, { new Vector3(1f, 0f, -1f), Diagonal.NorthEast }, { new Vector3(-1f, 0f, 1f), Diagonal.SouthWest }, { new Vector3(-1f, 0f, -1f), Diagonal.NorthWest }, }; if (markFrom != null && markTo != null) { if (markFrom.elevationTier > 0 || markTo.elevationTier > 0) { Vector3 diff = from.Center - to.Center; Vector3 diffNormalized = Vector3.ClampMagnitude(new Vector3(diff.x, 0f, diff.z), 1f); bool validCardinal = false; Direction dir = Direction.North; if (dirs.ContainsKey(diffNormalized)) { validCardinal = true; dir = dirs[diffNormalized]; } bool diagonal = diagonals.ContainsKey(diffNormalized); if (validCardinal && !diagonal) { if (markFrom.blockers.Contains(dir) || markTo.blockers.Contains(dir)) { return(true); } } } } } catch (Exception ex) { DebugExt.HandleException(ex); } return(false); }
public static void Init() { if (mInstance == null) { GameObject go = new GameObject("_DebugExt"); mInstance = go.AddComponent(typeof(DebugExt)) as DebugExt; DontDestroyOnLoad(go); } }
/// <summary> /// Broken do not use /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <param name="weight"></param> /// <param name="increment"></param> /// <returns></returns> public static float WeightedRandom(float min, float max, float weight = 0f, float increment = 1f) { List <float> options = new List <float>(); bool valid = max > min; if (valid) { DebugExt.Log("1", true); float total = Util.RoundToFactor(max - min, increment); int _break = (int)total + 1; for (float i = min; i < max; i += increment) { float num = Util.RoundToFactor(-Math.Abs(weight - i) + total, increment); DebugExt.Log("1-2: " + total, true); DebugExt.Log("1-2: " + i, true); DebugExt.Log("1-2: " + -Math.Abs(weight - i), true); int counter = 0; if (num != 0 && num != increment) { for (float k = 0; k < num; k += increment) { options.Add(Util.RoundToFactor(i, increment)); counter++; if (counter > _break) { options.Add(Util.RoundToFactor(i, increment)); break; } } } else { options.Add(Util.RoundToFactor(i, increment)); } DebugExt.Log("1-3: " + num, true); } DebugExt.Log(options.ToString(), true); return(SRand.Range(0, options.Count)); } else { DebugExt.Log("Invalid arguments: " + min.ToString() + ", " + max.ToString() + ", " + weight.ToString() + ", " + increment.ToString()); return(min); } }
static void Postfix(Building b, Vector3 newPos) { DebugExt.dLog("patch"); Cell cell = World.inst.GetCellData(b.transform.position); CellMark mark = ElevationManager.GetCellMark(cell); float leveling = mark.Elevation; if (cell != null && mark != null) { DebugExt.dLog(leveling.ToString()); b.transform.position = new Vector3(b.transform.position.x, b.transform.position.y + leveling, b.transform.position.z); } }
public override void Run() { base.Run(); if (!tornadoRunning) { tornadoRunning = true; DebugExt.Log("creating tornado"); int landmass = SRand.Range(0, World.inst.NumLandMasses); Vector3 pos = World.inst.cellsToLandmass[landmass].RandomElement().Center; tornado = SpawnFreeRoamTornado(pos); } }
private void DoSteal() { if (Player.inst.PlayerLandmassOwner.Gold > stealAmount) { Player.inst.PlayerLandmassOwner.Gold -= stealAmount; AmountStolen += stealAmount; } else { AmountStolen += Player.inst.PlayerLandmassOwner.Gold; Player.inst.PlayerLandmassOwner.Gold = 0; } DebugExt.Log("Thief has stolen " + stealAmount.ToString() + " from a treasury. ", false, KingdomLog.LogStatus.Neutral, target.transform.position); }
static void Postfix(CastleBlock __instance) { Cell c = __instance.GetComponent <Building>().GetCell(); CellMark mark = ElevationManager.GetCellMark(c); if (mark != null) { Cell[] neighborCells = new Cell[4]; Building b = __instance.GetComponent <Building>(); World.inst.GetNeighborCells(c, ref neighborCells); int idx = -1; for (int n = 0; n < c.OccupyingStructure.Count; n++) { if (c.OccupyingStructure[n] == b) { idx = n; break; } } float selfHeight = BuildingPlacePatch.GetAbsoluteStackHeightOfBuildingAtIndex(c, idx); DebugExt.dLog(" -- " + idx.ToString() + " -- "); DebugExt.dLog(selfHeight.ToString()); typeof(CastleBlock).GetMethod("ClearDoors", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(__instance, new object[] { }); for (int m = 0; m < neighborCells.Length; m++) { float otherHeight = BuildingPlacePatch.GetAbsoluteStackHeightTotal(neighborCells[m]); if (otherHeight > 0f) { DebugExt.dLog(otherHeight.ToString()); } Cell cell = neighborCells[m]; if (cell != null) { if (Mathf.Approximately(selfHeight - 0.5f, otherHeight) && otherHeight > 0) { DebugExt.dLog("Connection!"); typeof(CastleBlock).GetMethod("VisibleDoors", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(__instance, new object[] { true }); } } } } }
public static void CheckHomesForCrime() { try { List <IResidence> residences = Player.inst.Residentials; foreach (IResidence residence in residences) { CalcCrimeForHome(residence); } } catch (Exception ex) { DebugExt.HandleException(ex); } }
static void Postfix(Cell __instance, ref Vector3 __result) { try { CellMark mark = ElevationManager.GetCellMark(__instance); if (mark != null) { __result = new Vector3((float)__instance.x + 0.5f, mark.Elevation, (float)__instance.z + 0.5f); } } catch (Exception ex) { DebugExt.HandleException(ex); } }
static void Postfix(ArcherTower __instance, ref int __result, int maxHeight) { try { Cell cell = World.inst.GetCellData(__instance.transform.position); if (cell != null) { CellMark mark = ElevationManager.GetCellMark(cell); if (mark != null) { __result = Mathff.Clamp(__result + mark.elevationTier, 0, maxHeight); } } } catch (Exception ex) { DebugExt.HandleException(ex); } }
static void Postfix(ProjectileDefense __instance, ref int __result) { try { Cell cell = World.inst.GetCellData(__instance.transform.position); if (cell != null) { CellMark mark = ElevationManager.GetCellMark(cell); if (mark != null) { __result += mark.elevationTier; } } } catch (Exception ex) { DebugExt.HandleException(ex); } }
public static void DrawPlane(Plane plane, Vector3 centerPosition, Color color, float duration = 0, float length = 10.0f) { #if UNITY_EDITOR // pick a valid tangent value Vector3 tangent = Vector3.Dot(plane.normal, Vector3.up) < 0.5f ? Vector3.up : Vector3.left; Vector3 t1 = Vector3.Cross(plane.normal, tangent).normalized; Vector3 t2 = Vector3.Cross(plane.normal, t1).normalized; Vector3 position = centerPosition; DebugExt.DrawCross(position, color, length / 10, duration); Debug.DrawLine(position + (t1 + t2) * length, position + (t1 - t2) * length, color, duration); Debug.DrawLine(position + (-t1 + t2) * length, position + (-t1 - t2) * length, color, duration); Debug.DrawLine(position + (t1 + t2) * length, position + (-t1 + t2) * length, color, duration); Debug.DrawLine(position + (t1 - t2) * length, position + (-t1 - t2) * length, color, duration); #endif }
public static void GetDeviceStatus(string portName, string portSettings, int timeout, Action <Result, IPrinterStatus> action) { Task task = new Task(() => { Result result = Result.UnknownError; IPort port = null; IPrinterStatus printerStatus = null; try { result = Result.GetPortError; port = Port.GetPort(portName, portSettings, timeout); result = Result.GetParsedStatusError; printerStatus = port.GetParsedStatus(); result = Result.Success; } catch (Exception exception) { DebugExt.WriteLine(exception.Message); } finally { if (port != null) { Port.ReleasePort(port); port = null; } } Device.BeginInvokeOnMainThread(() => { action(result, printerStatus); }); }); task.Start(); }
static void Postfix(Pathfinder __instance, ref Pathfinder.Node __result, int sx, int sz, Vector3 start, Vector3 end, int teamId) { try { Cell cell = null; float num = float.MaxValue; int num2 = 1; int num3 = Mathf.Clamp(sx - num2, 0, World.inst.GridWidth - 1); int num4 = Mathf.Clamp(sx + num2, 0, World.inst.GridWidth - 1); int num5 = Mathf.Clamp(sz - num2, 0, World.inst.GridHeight - 1); int num6 = Mathf.Clamp(sz + num2, 0, World.inst.GridHeight - 1); for (int i = num3; i <= num4; i++) { for (int j = num5; j <= num6; j++) { Cell cellDataUnsafe = World.inst.GetCellDataUnsafe(i, j); if (cellDataUnsafe != null) { if (!__instance.blocksPath(cellDataUnsafe, teamId) && !PathingManager.BlockedCompletely(cellDataUnsafe)) { float num7 = Mathff.DistSqrdXZ(cellDataUnsafe.Center, start); if (num7 < num) { num = num7; cell = cellDataUnsafe; } } } } } if (cell != null) { __result = __instance.GetFieldValue <Pathfinder.Node[, ]>("pathGrid")[cell.x, cell.z]; return; } __result = null; } catch (Exception ex) { DebugExt.HandleException(ex); } }
void Update() { //Draw a circle facing one of global direction, with various parameters DebugExt.DrawCircle(Vector3.zero, Vector3.forward, 0.1f, Color.red); DebugExt.DrawCircle(Vector3.right, Vector3.up, 0.2f, Color.red); DebugExt.DrawCircle(Vector3.right * 2, Vector3.right, 0.4f, Color.red); //Draw a circle facing an arbitrary direction Vector3 randomVector = new Vector3(Random.value, Random.value, Random.value); DebugExt.DrawCircle(Vector3.right * 3, randomVector, 0.4f, Color.blue); //Draw a sphere facing global forward direction, with various parameters DebugExt.DrawSphere(Vector3.up, 0.01f, Color.magenta); DebugExt.DrawSphere(Vector3.up + Vector3.right, 0.05f, Color.magenta); DebugExt.DrawSphere(Vector3.up + Vector3.right * 2, 0.1f, Color.magenta); DebugExt.DrawSphere(Vector3.up + Vector3.right * 3, 0.5f, Color.magenta); //Draw a sphere facing an arbitrary direction DebugExt.DrawSphere(Vector3.up * 3, transform.forward, transform.up, 0.2f, Color.cyan, 32); }
public static float GetAbsoluteStackHeightTotal(Cell c) { CellMark mark = ElevationManager.GetCellMark(c); float i = 0; if (mark != null) { i = mark.Elevation; } bool flag = false; for (int count = 0; count < c.OccupyingStructure.Count; count++) { float stackRealHeight = 0f; if (c.OccupyingStructure[count].Stackable) { if (buildingRealStackHeights.ContainsKey(c.OccupyingStructure[count].UniqueName)) { DebugExt.dLog("stackable " + buildingRealStackHeights[c.OccupyingStructure[count].UniqueName].ToString()); stackRealHeight = buildingRealStackHeights[c.OccupyingStructure[count].UniqueName]; flag = true; } } i += stackRealHeight; } if (flag) { return(i); } else { return(0); } }
public static void SearchPrinter(string target, Action <IList <PortInfo> > action) { Task task = new Task(() => { IList <PortInfo> portInfoList = new List <PortInfo>(); try { portInfoList = Port.SearchPrinter(target); } catch (Exception exception) { DebugExt.WriteLine(exception.Message); } Device.BeginInvokeOnMainThread(() => { action(portInfoList); }); }); task.Start(); }
static void Postfix(PlacementMode __instance) { Mod.helper.Log("test"); if (__instance.IsPlacing()) { Mod.dLog("placing"); bool dragging = (bool)typeof(PlacementMode) .GetField("attemptedDrag", BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(__instance); if (!dragging) { Building b = __instance.GetHoverBuilding(); Cell cell = World.inst.GetCellData(b.transform.position); if (cell != null) { Cell other = FindClosestGroundTile(cell); if (other != null) { DebugExt.dLog("found close ground-level tile", false, other.Center); } } } } }
static void Postfix(Building PendingObj) { try { if (UnevenTerrain(PendingObj)) { DebugExt.dLog("Building on uneven terrain"); } else { Vector3 pos = PendingObj.transform.localPosition; Cell cell = PendingObj.GetCell(); CellMark mark = ElevationManager.GetCellMark(cell); float stackHeight = 0; if (PendingObj.Stackable) { stackHeight = GetStackHeightOfBuildingAtIndex(cell, cell.OccupyingStructure.IndexOf(PendingObj)); } if (PendingObj.CategoryName == "projectiletopper") { stackHeight = GetStackHeightTotal(cell); } if (mark != null) { PendingObj.transform.localPosition = new Vector3(pos.x, mark.Elevation + stackHeight, pos.z); PendingObj.UpdateShaderHeight(); } } } catch (Exception ex) { DebugExt.HandleException(ex); } }
public void DebugDraw() { DebugExt.DrawCross((normal * distance).ToVector3(), Color.green, 1, 10); }
// Update is called once per frame protected override void Update() { base.Update(); var currDirection = Direction; var directionVector = currDirection.ToVector2(); var endpoint = transform.position.xy(); //Swap prev points with current endpoints SwapPoints(); //Clear the endpoint and offset list endpointSize = 0; offsetSize = 0; //Init AddPoint(endpoint); AddOffset(-1); var movement = Time.deltaTime * LaserSpeed; bool gorillaTape = true; bool isMirror = false; // Set max iteration 20 to avoid infinite reflection for (var endpointIndex = 1; endpointIndex < MaxEndpoints; endpointIndex++) { var hit = Physics2D.Raycast(endpoint + directionVector, directionVector, 100); //TODO: change 100 to max level width //Debug.Log(endpointIndex); DebugExt.Assert(hit.collider != null); if (hit.collider == null) { break; // for robustness } string hitName = hit.collider.name; isMirror = hitName.StartsWith("Mirror"); var tPos = hit.collider.transform.position; if (directionVector.x.IsZero()) { //Adjust the hit point when hitting from below if (directionVector.y > 0 && !isMirror) { float offset = 0; float dist; if (hitName.StartsWith("Wall")) { offset = wallOffset; } else if (hitName.StartsWith("Gate")) { offset = gateOffset; } else if (hitName.StartsWith("Door")) { offset = doorOffset; } else if (hitName.StartsWith("Lever")) { offset = leverOffset; } else if (hitName.StartsWith("Trolley")) { offset = trolleyOffset; } else if (hitName.StartsWith("LaserEmitter")) { if (hit.collider.gameObject.GetComponent <LaserEmitter>().direction != Direction.Down) { offset = turretOffset; } } else { offset = otherOffset; } //Fixes issue for when object is too close to the laser //This assumes the object's collider is 1 unit high if ((dist = tPos.y - endpoint.y) < 1.5f) { offset -= 1.5f - dist; } endpoint.y = hit.point.y + offset; //gorillaTape = hit.point; } else { endpoint.y = hit.collider.transform.position.y; //Debug.Log("whoop-di-doo"); } } else { endpoint.x = hit.collider.transform.position.x; } Vector2?previousEndpoint = null; if (endpointIndex >= prevSize) { previousEndpoint = endpoints[endpointIndex - 1]; } else if (!endpoint.Equals(prevPoints[endpointIndex])) { previousEndpoint = prevPoints[endpointIndex]; var previousDirection = previousEndpoint.Value - prevPoints[endpointIndex - 1]; previousDirection.Normalize(); if (directionVector != previousDirection) { previousEndpoint = endpoints[endpointIndex - 1]; } } if (previousEndpoint.HasValue) { var newEndpoint = previousEndpoint.Value + movement * directionVector; var diff = Vector2.Dot(endpoint - newEndpoint, directionVector); if (diff > 0) { AddPoint(newEndpoint); break; } movement += diff; } AddPoint(endpoint); if (hit.transform.tag == "Player") { var player = hit.transform.GetComponent <PlayerController>(); if (player.IsAlive) { player.Die(); AudioManager.PlaySFX("Laser Hit"); } break; } else if (isMirror) { var mirror = hit.collider.GetComponent <Mirror>(); if (mirror != null) { var oldDirection = currDirection; currDirection = mirror.Reflect(currDirection); var sortingOrderOffset = oldDirection == Direction.Down || currDirection == Direction.Up ? -1 : 1; AddOffset(sortingOrderOffset); directionVector = currDirection.ToVector2(); continue; } } else if (hitName.StartsWith("Explosive")) { if (lastExplosiveID != hit.transform.GetInstanceID()) { lastExplosiveID = hit.transform.GetInstanceID(); ExplosionManager.Instance.Add(hit.collider.gameObject, hit.collider.transform.position); } } else if (hitName.StartsWith("Patient")) { var patient = hit.collider.GetComponent <Patient>(); if (patient != null) { patient.Kill(GameWorld.LevelOverReason.LaserKilledPatient); AudioManager.PlaySFX("Laser Hit"); } } var plant = hit.collider.GetComponent <Plant>(); if (plant != null) { plant.Break(); } break; } //Laser should be in front of the object when hitting from below if (directionVector.y > 0 && !isMirror) { AddOffset(5); } else { AddOffset(-5); } lineStrip.Draw(endpoints, offsets, endpointSize, LaserPositionOffset); //previousEndpoints = endpoints; }
static void Finalizer(Exception __exception) { DebugExt.HandleException(__exception); }
private void DrawDemo() { // Icon rendering DebugExt.DrawIcon(5f * Vector3.right, "locator.png"); // Red line DebugExt.DrawLine(Vector3.zero, Vector3.forward, Color.red); // Blue arrow DebugExt.DrawArrow(Vector3.left, 2f * Vector3.left, Color.blue); // Green bidirectional arrow DebugExt.DrawArrow(Vector3.right, 2f * Vector3.right, Color.green, 0, true); // Red circle normal to +Z axis DebugExt.DrawCircle(Vector3.up, 0.25f, Quaternion.identity, Color.red); // Blue semicircle normal to the +Y axis DebugExt.DrawCircle(Vector3.zero, 0.25f, Quaternion.identity, Color.blue, 180f); // Oriented box DebugExt.DrawBox( 2f * Vector3.up, 0.5f * Vector3.one, Quaternion.Euler(45f, 45f, 45f), Color.cyan ); // Simple sphere (2 circles) DebugExt.DrawSphere(Vector3.down, 0.5f, Color.blue); // Hemisphere pointed down the +X axis DebugExt.DrawHemisphere( 3f * Vector3.left, 0.5f, Quaternion.LookRotation(Vector3.right), Color.yellow ); DebugExt.DrawCapsule( 3f * Vector3.right, 3f * Vector3.right + Vector3.up, 0.5f, Color.magenta ); // Visualize a Physics.SphereCast // by a sphere representing the initial position and // an oriented capsule in the direction of the cast DebugExt.DrawSphereCast( 2f * Vector3.back, 0.5f, Vector3.back + Vector3.left, 2f, Color.cyan ); // Visualize a Physics.CapsuleCast DebugExt.DrawCapsuleCast( 3f * Vector3.forward, 3f * Vector3.forward + Vector3.right, 0.5f, Vector3.right, 3f, Color.red ); // Visualize a Physics.BoxCast DebugExt.DrawBoxCast( 2f * (Vector3.back + Vector3.right), 0.25f * Vector3.one, Vector3.back + Vector3.right, Quaternion.Euler(0, 45f, 45f), 2f, Color.yellow ); }
private void DebugStockEmpted() { DebugExt.DebugSpecifiedReport("Stock on stockpile labelled " + stockpile.label + " emptied.", stockEmptiedReport); }
private void DebugStockFilled() { DebugExt.DebugSpecifiedReport("Stock on stockpile labelled " + stockpile.label + " filled. Current stock: " + stockpile.currentStock, stockFilledReport); }
private void DebugStockChange(int change) { DebugExt.DebugSpecifiedReport("Stock on stockpile labelled " + stockpile.label + " changed by " + change + ". Current stock: " + stockpile.currentStock, stockChangedReport); }
public static void SendCommands(byte[] commands, string portName, string portSettings, int timeout, Action <Result> action) { Task task = new Task(() => { Result result = Result.UnknownError; IPort port = null; IPrinterStatus printerStatus; try { result = Result.GetPortError; port = Port.GetPort(portName, portSettings, timeout); result = Result.BeginCheckedBlockError; printerStatus = port.BeginCheckedBlock(); if (printerStatus.Offline) { throw new Exception("Printer is offline (BeginCheckedBlock)"); } result = Result.WritePortError; DateTime startDateTime = DateTime.Now; int total = 0; while (true) { int written = port.WritePort(commands, total, commands.Length - total); total += written; // if (total == commands.Length) if (total >= commands.Length) { break; } TimeSpan timeSpan = DateTime.Now - startDateTime; if (timeSpan.TotalMilliseconds >= 30000) // 30000mS!!! { throw new Exception("Write port timed out"); } } result = Result.EndCheckedBlockError; port.EndCheckedBlockTimeoutMillis = 30000; // 30000mS!!! printerStatus = port.EndCheckedBlock(); if (printerStatus.Offline) { throw new Exception("Printer is offline (EndCheckedBlock)"); } result = Result.Success; } catch (Exception exception) { DebugExt.WriteLine(exception.Message); } finally { if (port != null) { Port.ReleasePort(port); port = null; } } Device.BeginInvokeOnMainThread(() => { action(result); }); }); task.Start(); }
public void DebugDraw(Color color, float duration = 0) { DebugExt.DrawBox(min.ToVector3(), max.ToVector3(), color, duration); }