Skip to content

Instantly share code, notes, and snippets.

@boformer
Created June 28, 2015 22:59
Show Gist options
  • Save boformer/9c92ddc01e4a63f6e499 to your computer and use it in GitHub Desktop.
Save boformer/9c92ddc01e4a63f6e499 to your computer and use it in GitHub Desktop.
using ColossalFramework;
using ColossalFramework.Threading;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using UnityEngine;
namespace LargerFootprints
{
public struct BuildingToolDetoursHolder
{
private static bool deployed = false;
private static RedirectCallsState _BuildingTool_CreateBuilding_state;
private static MethodInfo _BuildingTool_CreateBuilding_original;
private static MethodInfo _BuildingTool_CreateBuilding_detour;
public static void Deploy()
{
if (!deployed)
{
_BuildingTool_CreateBuilding_original = typeof(BuildingTool).GetMethod("CreateBuilding", BindingFlags.Instance | BindingFlags.NonPublic);
_BuildingTool_CreateBuilding_detour = typeof(BuildingToolDetoursHolder).GetMethod("CreateBuilding", BindingFlags.Instance | BindingFlags.NonPublic);
_BuildingTool_CreateBuilding_state = RedirectionHelper.RedirectCalls(_BuildingTool_CreateBuilding_original, _BuildingTool_CreateBuilding_detour);
deployed = true;
Debug.Log("LargerFootprints: BuildingTool Methods detoured!");
}
}
public static void Revert()
{
if (deployed)
{
RedirectionHelper.RevertRedirect(_BuildingTool_CreateBuilding_original, _BuildingTool_CreateBuilding_state);
_BuildingTool_CreateBuilding_original = null;
_BuildingTool_CreateBuilding_detour = null;
deployed = false;
Debug.Log("LargerFootprints: BuildingTool Methods restored!");
}
}
private ushort CreateBuilding(BuildingInfo info, Vector3 position, float angle, int relocating)
{
Debug.Log("CreateBuilding called.");
BuildingTool _this = ToolsModifierControl.GetTool<BuildingTool>();
ushort result = 0;
bool flag = (Singleton<ToolManager>.instance.m_properties.m_mode & ItemClass.Availability.Game) != ItemClass.Availability.None;
ulong[] collidingSegmentBuffer;
ulong[] collidingBuildingBuffer;
ToolController _m_toolController = (ToolController)typeof(BuildingTool).GetField("m_toolConroller", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(_this);
_m_toolController.BeginColliding(out collidingSegmentBuffer, out collidingBuildingBuffer);
try
{
float minY;
float num;
float num2;
Building.SampleBuildingHeight(position, angle, info.m_cellWidth, info.m_cellLength, info, out minY, out num, out num2);
ToolBase.ToolErrors errors = (ToolBase.ToolErrors)typeof(BuildingTool).GetMethod("CheckSpace", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(_this, new object[] { info, relocating, position, minY, num2 + info.m_size.y, angle, info.m_cellWidth, info.m_cellLength, false, collidingSegmentBuffer, collidingBuildingBuffer });
if (errors == ToolBase.ToolErrors.None)
{
if (flag)
{
int constructionCost = (int)typeof(BuildingTool).GetField("m_constructionCost", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(_this);
Singleton<EconomyManager>.instance.FetchResource(EconomyManager.Resource.Construction, constructionCost, info.m_class);
}
bool flag2 = false;
if (relocating != 0)
{
Singleton<BuildingManager>.instance.RelocateBuilding((ushort)relocating, position, angle);
InstanceID id = default(InstanceID);
id.Building = (ushort)relocating;
ThreadHelper.dispatcher.Dispatch(delegate
{
//_this.m_relocateCompleted(id);
});
result = (ushort)relocating;
relocating = 0;
typeof(BuildingTool).GetField("m_relocate", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(_this, 0);
flag2 = true;
}
else if (info.m_buildingAI.WorksAsNet())
{
float elevation = (float)typeof(BuildingTool).GetMethod("GetElevation", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(_this, new object[] { info });
Building building = default(Building);
building.m_buildIndex = Singleton<SimulationManager>.instance.m_currentBuildIndex;
building.m_position = position;
building.m_angle = angle;
building.m_width = (byte)info.m_cellWidth;
building.m_length = (byte)info.m_cellLength;
BuildingDecoration.LoadPaths(info, 0, ref building, elevation);
if (Mathf.Abs(elevation) < 1f)
{
BuildingDecoration.LoadProps(info, 0, ref building);
}
Singleton<SimulationManager>.instance.m_currentBuildIndex += 1u;
flag2 = true;
}
else if (Singleton<BuildingManager>.instance.CreateBuilding(out result, ref Singleton<SimulationManager>.instance.m_randomizer, info, position, angle, 0, Singleton<SimulationManager>.instance.m_currentBuildIndex))
{
Singleton<SimulationManager>.instance.m_currentBuildIndex += 1u;
flag2 = true;
}
if (flag2)
{
if (info.m_notUsedGuide != null)
{
info.m_notUsedGuide.Disable();
}
info.m_buildingAI.PlacementSucceeded();
Singleton<GuideManager>.instance.m_notEnoughMoney.Deactivate();
if (info.m_class.m_service > ItemClass.Service.Office)
{
int num3 = info.m_class.m_service - ItemClass.Service.Office - 1;
Singleton<GuideManager>.instance.m_serviceNotUsed[num3].Disable();
Singleton<GuideManager>.instance.m_serviceNeeded[num3].Deactivate();
Singleton<CoverageManager>.instance.CoverageUpdated(info.m_class.m_service, info.m_class.m_subService, info.m_class.m_level);
}
BuildingTool.DispatchPlacementEffect(info, position, angle, info.m_cellLength, false);
}
}
else
{
info.m_buildingAI.PlacementFailed();
}
}
finally
{
//this.m_toolController.EndColliding();
_m_toolController.EndColliding();
}
return result;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using UnityEngine;
namespace LargerFootprints
{
public static class BuildingDecorationDetoursHolder
{
private static bool deployed = false;
private static RedirectCallsState _BuildingDecoration_LoadDecorations_state;
private static MethodInfo _BuildingDecoration_LoadDecorations_original;
private static MethodInfo _BuildingDecoration_LoadDecorations_detour;
private static RedirectCallsState _BuildingDecoration_SaveDecorations_state;
private static MethodInfo _BuildingDecoration_SaveDecorations_original;
private static MethodInfo _BuildingDecoration_SaveDecorations_detour;
public static void Deploy()
{
if (!deployed)
{
_BuildingDecoration_LoadDecorations_original = typeof(BuildingDecoration).GetMethod("LoadDecorations", BindingFlags.Static | BindingFlags.Public);
_BuildingDecoration_LoadDecorations_detour = typeof(BuildingDecorationDetoursHolder).GetMethod("LoadDecorations", BindingFlags.Static | BindingFlags.Public);
_BuildingDecoration_LoadDecorations_state = RedirectionHelper.RedirectCalls(_BuildingDecoration_LoadDecorations_original, _BuildingDecoration_LoadDecorations_detour);
_BuildingDecoration_SaveDecorations_original = typeof(BuildingDecoration).GetMethod("SaveDecorations", BindingFlags.Static | BindingFlags.Public);
_BuildingDecoration_SaveDecorations_detour = typeof(BuildingDecorationDetoursHolder).GetMethod("SaveDecorations", BindingFlags.Static | BindingFlags.Public);
_BuildingDecoration_SaveDecorations_state = RedirectionHelper.RedirectCalls(_BuildingDecoration_SaveDecorations_original, _BuildingDecoration_SaveDecorations_detour);
deployed = true;
Debug.Log("LargerFootprints: BuildingDecoration Methods detoured!");
}
}
public static void Revert()
{
if (deployed)
{
RedirectionHelper.RevertRedirect(_BuildingDecoration_LoadDecorations_original, _BuildingDecoration_LoadDecorations_state);
_BuildingDecoration_LoadDecorations_original = null;
_BuildingDecoration_LoadDecorations_detour = null;
RedirectionHelper.RevertRedirect(_BuildingDecoration_SaveDecorations_original, _BuildingDecoration_SaveDecorations_state);
_BuildingDecoration_SaveDecorations_original = null;
_BuildingDecoration_SaveDecorations_detour = null;
deployed = false;
Debug.Log("LargerFootprints: BuildingDecoration Methods restored!");
}
}
public static void LoadDecorations(BuildingInfo source)
{
Debug.Log("LoadDecorations called.");
Building building = default(Building);
building.m_position = new Vector3(0f, 60f, 0f);
building.m_width = (byte)source.m_cellWidth;
building.m_length = (byte)source.m_cellLength;
BuildingDecoration.LoadPaths(source, 0, ref building, 0f);
BuildingDecoration.LoadProps(source, 0, ref building);
}
public static void SaveDecorations(BuildingInfo target)
{
Debug.Log("SaveDecorations called.");
Building building = default(Building);
building.m_position = new Vector3(0f, 60f, 0f);
building.m_width = (byte)target.m_cellWidth;
building.m_length = (byte)target.m_cellLength;
BuildingDecoration.SavePaths(target, 0, ref building);
BuildingDecoration.SaveProps(target, 0, ref building);
}
}
}
using ICities;
namespace LargerFootprints
{
public class LargerFootprintsMod : LoadingExtensionBase, IUserMod
{
public string Name
{
get
{
return "Larger Footprints";
}
}
public string Description
{
get { return "Create and use larger ploppable assets"; }
}
public override void OnCreated(ILoading loading)
{
BuildingDecorationDetoursHolder.Deploy();
BuildingToolDetoursHolder.Deploy();
}
public override void OnReleased()
{
BuildingDecorationDetoursHolder.Revert();
BuildingToolDetoursHolder.Revert();
}
}
}
/*
The MIT License (MIT)
Copyright (c) 2015 Sebastian Sch�ner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Reflection;
using System.Runtime.InteropServices;
namespace LargerFootprints
{
public struct RedirectCallsState
{
public byte a, b, c, d, e;
public ulong f;
}
/// <summary>
/// Helper class to deal with detours. This version is for Unity 5 x64 on Windows.
/// We provide three different methods of detouring.
/// </summary>
public static class RedirectionHelper
{
/// <summary>
/// Redirects all calls from method 'from' to method 'to'.
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
public static RedirectCallsState RedirectCalls(MethodInfo from, MethodInfo to)
{
// GetFunctionPointer enforces compilation of the method.
var fptr1 = from.MethodHandle.GetFunctionPointer();
var fptr2 = to.MethodHandle.GetFunctionPointer();
return PatchJumpTo(fptr1, fptr2);
}
public static RedirectCallsState RedirectCalls(RuntimeMethodHandle from, RuntimeMethodHandle to)
{
// GetFunctionPointer enforces compilation of the method.
var fptr1 = from.GetFunctionPointer();
var fptr2 = to.GetFunctionPointer();
return PatchJumpTo(fptr1, fptr2);
}
public static void RevertRedirect(MethodInfo from, RedirectCallsState state)
{
var fptr1 = from.MethodHandle.GetFunctionPointer();
RevertJumpTo(fptr1, state);
}
/// <summary>
/// Primitive patching. Inserts a jump to 'target' at 'site'. Works even if both methods'
/// callers have already been compiled.
/// </summary>
/// <param name="site"></param>
/// <param name="target"></param>
public static RedirectCallsState PatchJumpTo(IntPtr site, IntPtr target)
{
RedirectCallsState state = new RedirectCallsState();
// R11 is volatile.
unsafe
{
byte* sitePtr = (byte*)site.ToPointer();
state.a = *sitePtr;
state.b = *(sitePtr + 1);
state.c = *(sitePtr + 10);
state.d = *(sitePtr + 11);
state.e = *(sitePtr + 12);
state.f = *((ulong*) (sitePtr + 2));
*sitePtr = 0x49; // mov r11, target
*(sitePtr + 1) = 0xBB;
*((ulong*)(sitePtr + 2)) = (ulong)target.ToInt64();
*(sitePtr + 10) = 0x41; // jmp r11
*(sitePtr + 11) = 0xFF;
*(sitePtr + 12) = 0xE3;
}
return state;
}
public static void RevertJumpTo(IntPtr site, RedirectCallsState state)
{
unsafe
{
byte* sitePtr = (byte*)site.ToPointer();
*sitePtr = state.a; // mov r11, target
*(sitePtr + 1) = state.b;
*((ulong*)(sitePtr + 2)) = state.f;
*(sitePtr + 10) = state.c; // jmp r11
*(sitePtr + 11) = state.d;
*(sitePtr + 12) = state.e;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment