private ScreenHelpers() { _hwnd = Win32Helpers.GetForegroundWindow(); _windowId = _hwnd.ToString(); #if UNITY_EDITOR _gameWindow = GetMainGameView(); #endif }
public MySafeHandle(IntPtr handleValue) : base(IntPtr.Zero, true) { handle = handleValue; if (handle != handleValue) { throw new Exception("Handle value is not assigned correctly, handleValue = " + handleValue + ", Handle = " + handle.ToString()); } }
private static void DisableWarden(IntPtr parWardenPtr1) { //var second = Memory.Reader.Read<IntPtr>(parWardenPtr1); var wardenModuleStart = parWardenPtr1.ReadAs <IntPtr>(); var memScanPtr = IntPtr.Add(wardenModuleStart, (int)Ptr.Warden.WardenMemScanStart); var pageScanPtr = IntPtr.Add(wardenModuleStart, (int)Ptr.Warden.WardenPageScan); Console.WriteLine(pageScanPtr.ToString("X")); if (pageScanPtr != WardensPageScanFuncPtr) { var CurrentBytes = Memory.Reader.ReadBytes(pageScanPtr, 5); //var CurrrentBytes = (tmpPtr).ReadAs<Byte>(); //How do I read 5 bytes? var isEqual = CurrentBytes.SequenceEqual(PageScanOriginalBytes); if (!isEqual) { return; } if (AddrToWardenPageScan == IntPtr.Zero) { _wardenPageScanDelegate = WardenPageScanHook; AddrToWardenPageScan = Marshal.GetFunctionPointerForDelegate(_wardenPageScanDelegate); if (WardenPageScanDetourPtr == IntPtr.Zero) { // IntPtr readBase, int readOffset, IntPtr writeTo string[] asmCode = { SendOvers.WardenPageScanDetour[0], SendOvers.WardenPageScanDetour[1], SendOvers.WardenPageScanDetour[2], SendOvers.WardenPageScanDetour[3], SendOvers.WardenPageScanDetour[4], SendOvers.WardenPageScanDetour[5], SendOvers.WardenPageScanDetour[6], SendOvers.WardenPageScanDetour[7], SendOvers.WardenPageScanDetour[8], SendOvers.WardenPageScanDetour[9].Replace("[|addr|]", ((uint)AddrToWardenPageScan).ToString()), SendOvers.WardenPageScanDetour[10], SendOvers.WardenPageScanDetour[11], SendOvers.WardenPageScanDetour[12], SendOvers.WardenPageScanDetour[13].Replace("[|addr|]",((uint)wardenModuleStart + 0x2B2C).ToString()) }; WardenPageScanDetourPtr = Memory.InjectAsm(asmCode, "WardenPageScanDetour"); } } Memory.InjectAsm((uint)pageScanPtr, "jmp 0x" + WardenPageScanDetourPtr.ToString("X"), "WardenPageScanJmp"); WardensPageScanFuncPtr = pageScanPtr; } if (memScanPtr != WardensMemScanFuncPtr) { var CurrentBytes = Memory.Reader.ReadBytes(memScanPtr, 5); //var CurrrentBytes = (tmpPtr).ReadAs<Byte>(); //How do I read 5 bytes? var isEqual = CurrentBytes.SequenceEqual(MemScanOriginalBytes); if (!isEqual) { return; } if (AddrToWardenMemCpy == IntPtr.Zero) { _wardenMemCpyDelegate = WardenMemCpyHook; AddrToWardenMemCpy = Marshal.GetFunctionPointerForDelegate(_wardenMemCpyDelegate); if (WardenMemCpyDetourPtr == IntPtr.Zero) { string[] asmCodeOnline = { SendOvers.WardenMemCpyDetour[0], SendOvers.WardenMemCpyDetour[1], SendOvers.WardenMemCpyDetour[2], SendOvers.WardenMemCpyDetour[3], SendOvers.WardenMemCpyDetour[4], SendOvers.WardenMemCpyDetour[5], SendOvers.WardenMemCpyDetour[6], SendOvers.WardenMemCpyDetour[7], SendOvers.WardenMemCpyDetour[8], SendOvers.WardenMemCpyDetour[9], SendOvers.WardenMemCpyDetour[10], SendOvers.WardenMemCpyDetour[11], SendOvers.WardenMemCpyDetour[12], SendOvers.WardenMemCpyDetour[13].Replace("[|addr|]","0x" + ((uint)AddrToWardenMemCpy).ToString("X")), SendOvers.WardenMemCpyDetour[14], SendOvers.WardenMemCpyDetour[15], SendOvers.WardenMemCpyDetour[16], SendOvers.WardenMemCpyDetour[17], SendOvers.WardenMemCpyDetour[18].Replace("[|addr|]","0x" + ((uint)(memScanPtr + 0x24)).ToString("X")) }; WardenMemCpyDetourPtr = Memory.InjectAsm(asmCodeOnline, "WardenMemCpyDetour"); } } Memory.InjectAsm((uint)memScanPtr, "jmp 0x" + WardenMemCpyDetourPtr.ToString("X"), "WardenMemCpyJmp"); WardensMemScanFuncPtr = memScanPtr; } }
/// <summary> /// Retrieves the shader texture binding for the given helper handle. /// </summary> public ResourceSet GetImageResourceSet(IntPtr imGuiBinding) { if (!_viewsById.TryGetValue(imGuiBinding, out ResourceSetInfo tvi)) { throw new InvalidOperationException("No registered ImGui binding with id " + imGuiBinding.ToString()); } return(tvi.ResourceSet); }
public static int WaitSyncKHR(IntPtr dpy, IntPtr sync, int flags) { int retValue; Debug.Assert(Delegates.peglWaitSyncKHR != null, "peglWaitSyncKHR not implemented"); retValue = Delegates.peglWaitSyncKHR(dpy, sync, flags); LogFunction("eglWaitSyncKHR(0x{0}, 0x{1}, {2}) = {3}", dpy.ToString("X8"), sync.ToString("X8"), flags, retValue); DebugCheckErrors(retValue); return(retValue); }
/// <devdoc> /// <para> /// Called by the class to create a socket to accept an /// incoming request. /// </para> /// </devdoc> //protected Socket(IntPtr fd) { private Socket(IntPtr fd) { //new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); // // this should never happen, let's check anyway // if (fd==SocketErrors.InvalidSocketIntPtr) { throw new ArgumentException(SR.GetString(SR.net_InvalidSocketHandle, fd.ToString())); } m_Handle = fd; addressFamily = Sockets.AddressFamily.Unknown; socketType = Sockets.SocketType.Unknown; protocolType = Sockets.ProtocolType.Unknown; }
private void PauseSound(IntPtr tag, bool paused) { foreach (var sound in soundInstanceList) { if (sound.AudioTag == tag.ToString()) { sound.Pause(paused); } } }
/// <summary> /// Initializes a new instance of the <see cref="EyeXViewportBoundsProvider"/> class. /// </summary> protected EyeXViewportBoundsProvider() { _hwnd = FindWindowWithThreadProcessId(); GameWindowId = _hwnd.ToString(); }
public void Update(LogicManager logic, SplitterSettings settings) { if (!EnableLogging) { return; } lock (currentValues) { DateTime date = DateTime.Now; IntPtr savedGame = logic.Memory.SavedGame(); bool updateLog = savedGame != IntPtr.Zero; foreach (LogObject key in Enum.GetValues(typeof(LogObject))) { string previous = currentValues[key]; string current = null; switch (key) { case LogObject.CurrentSplit: current = $"{logic.CurrentSplit} ({GetCurrentSplit(logic, settings)})"; break; case LogObject.Pointers: current = logic.Memory.GamePointers(); break; case LogObject.Version: current = MemoryManager.Version.ToString(); break; case LogObject.Loading: current = logic.Memory.IsLoading().ToString(); break; case LogObject.Scene: current = logic.Memory.SceneName(); break; case LogObject.SavedGame: current = savedGame.ToString("X"); break; case LogObject.TotalTime: current = updateLog ? logic.Memory.TotalPlayTime().ToString() : previous; break; case LogObject.SceneType: current = logic.Memory.GameSceneType().ToString(); break; case LogObject.Quests: if (updateLog) { CheckItems <Quest>(key, currentQuests, logic.Memory.Quests()); } break; case LogObject.Chests: if (updateLog) { CheckItems <GuidItem>(key, currentChests, logic.Memory.Chests()); } break; case LogObject.Spells: if (updateLog) { CheckItems <Spell>(key, currentSpells, logic.Memory.Spells()); } break; case LogObject.Keys: if (updateLog) { CheckItems <GuidItem>(key, currentKeys, logic.Memory.Keys()); } break; case LogObject.Equipment: if (updateLog) { CheckItems <Equipment>(key, currentEquipment, logic.Memory.Equipment()); } break; case LogObject.Gold: current = updateLog ? logic.Memory.Gold().ToString() : previous; break; case LogObject.Level: current = updateLog ? logic.Memory.Level().ToString() : previous; break; case LogObject.Experience: current = updateLog ? logic.Memory.Experience().ToString() : previous; break; case LogObject.Dungeons: current = updateLog ? logic.Memory.DungeonsCleared().ToString() : previous; break; case LogObject.RoyalArts: current = updateLog ? logic.Memory.PlayerRoyalArts().ToString() : previous; break; case LogObject.FinalQuest: current = updateLog ? logic.Memory.FinalQuestCompleted().ToString() : previous; break; case LogObject.Catnap: current = updateLog ? logic.Memory.Catnap().ToString() : previous; break; } if (previous != current) { AddEntryUnlocked(new ValueLogEntry(date, key, previous, current)); currentValues[key] = current; } } } }
public static void ReleaseTexImageEXT(IntPtr dpy, IntPtr drawable, int buffer) { Debug.Assert(Delegates.pglXReleaseTexImageEXT != null, "pglXReleaseTexImageEXT not implemented"); Delegates.pglXReleaseTexImageEXT(dpy, drawable, buffer); LogFunction("glXReleaseTexImageEXT(0x{0}, 0x{1}, {2})", dpy.ToString("X8"), drawable.ToString("X8"), buffer); }
public static void BindTexImageEXT(IntPtr dpy, IntPtr drawable, int buffer, int[] attrib_list) { unsafe { fixed(int *p_attrib_list = attrib_list) { Debug.Assert(Delegates.pglXBindTexImageEXT != null, "pglXBindTexImageEXT not implemented"); Delegates.pglXBindTexImageEXT(dpy, drawable, buffer, p_attrib_list); LogFunction("glXBindTexImageEXT(0x{0}, 0x{1}, {2}, {3})", dpy.ToString("X8"), drawable.ToString("X8"), buffer, LogValue(attrib_list)); } } }
public static bool SignalSyncKHR(IntPtr dpy, IntPtr sync, uint mode) { bool retValue; Debug.Assert(Delegates.peglSignalSyncKHR != null, "peglSignalSyncKHR not implemented"); retValue = Delegates.peglSignalSyncKHR(dpy, sync, mode); LogFunction("eglSignalSyncKHR(0x{0}, 0x{1}, {2}) = {3}", dpy.ToString("X8"), sync.ToString("X8"), mode, retValue); DebugCheckErrors(retValue); return(retValue); }
public static bool GetSyncAttribKHR(IntPtr dpy, IntPtr sync, int attribute, [Out] int[] value) { bool retValue; unsafe { fixed(int *p_value = value) { Debug.Assert(Delegates.peglGetSyncAttribKHR != null, "peglGetSyncAttribKHR not implemented"); retValue = Delegates.peglGetSyncAttribKHR(dpy, sync, attribute, p_value); LogFunction("eglGetSyncAttribKHR(0x{0}, 0x{1}, {2}, {3}) = {4}", dpy.ToString("X8"), sync.ToString("X8"), attribute, LogValue(value), retValue); } } DebugCheckErrors(retValue); return(retValue); }
public static bool StreamConsumerReleaseKHR(IntPtr dpy, IntPtr stream) { bool retValue; Debug.Assert(Delegates.peglStreamConsumerReleaseKHR != null, "peglStreamConsumerReleaseKHR not implemented"); retValue = Delegates.peglStreamConsumerReleaseKHR(dpy, stream); LogFunction("eglStreamConsumerReleaseKHR(0x{0}, 0x{1}) = {2}", dpy.ToString("X8"), stream.ToString("X8"), retValue); DebugCheckErrors(retValue); return(retValue); }
/// <summary> /// Timer event when looking for Demul Process (auto-Hook and auto-close) /// </summary> protected virtual void tProcess_Tick(Object Sender, EventArgs e) { if (!_ProcessHooked) { try { Process[] processes = Process.GetProcessesByName(_Target_Process_Name); if (processes.Length > 0) { _TargetProcess = processes[0]; _ProcessHandle = _TargetProcess.Handle; _TargetProcess_MemoryBaseAddress = _TargetProcess.MainModule.BaseAddress; ProcessModuleCollection c = _TargetProcess.Modules; foreach (ProcessModule m in c) { if (m.ModuleName.ToLower().Equals("paddemul.dll")) { _PadDemul_ModuleBaseAddress = m.BaseAddress; if (_PadDemul_ModuleBaseAddress != IntPtr.Zero) { _ProcessHooked = true; if (_DisableWindow) { //Disabling left-click for resize-bug upper left corner //DisableWindow(true); ApplyMouseHook(); } WriteLog("Attached to Process " + _Target_Process_Name + ".exe, ProcessHandle = " + _ProcessHandle); WriteLog("Demul.exe = 0x" + _TargetProcess_MemoryBaseAddress.ToString("X8") + ", padDemul.dll = 0x" + _PadDemul_ModuleBaseAddress.ToString("X8")); if (_DemulVersion.Equals("057") || _DemulVersion.Equals("058")) { SetHack_057(); } else if (_DemulVersion.Equals("07a")) { SetHack_07(); } break; } } } } } catch { WriteLog("Error trying to hook " + _Target_Process_Name + ".exe"); } } else { Process[] processes = Process.GetProcessesByName(_Target_Process_Name); if (processes.Length <= 0) { _ProcessHooked = false; _TargetProcess = null; _ProcessHandle = IntPtr.Zero; _TargetProcess_MemoryBaseAddress = IntPtr.Zero; WriteLog(_Target_Process_Name + ".exe closed"); Environment.Exit(0); } else { if (_WidescreenHack && _ListWidescreenHacks.Count > 0) { foreach (WidescreenData d in _ListWidescreenHacks) { int RatioValue = BitConverter.ToInt32(ReadBytes(d.Address, 4), 0); if (RatioValue == d.DefaultValue) { WriteBytes(d.Address, BitConverter.GetBytes(d.WidescreenValue)); WriteLog("Widescreen Hack : wrote 0x" + d.WidescreenValue.ToString("X8") + " to address 0x" + d.Address.ToString("X8")); } } } } } }
public EffectKeyValue(string key, IntPtr value) { this.key = key; this.value = value.ToString(); }
// // Is guaranteed to be called only once. If called with a non-zero userToken, the context is not flowed. // protected override void Complete(IntPtr userToken) { GlobalLog.Print("ContextAwareResult#" + ValidationHelper.HashString(this) + "::Complete() _Context(set):" + (_Context != null).ToString() + " userToken:" + userToken.ToString()); // If no flowing, just complete regularly. if ((_Flags & StateFlags.PostBlockStarted) == 0) { base.Complete(userToken); return; } // At this point, IsCompleted is set and CompletedSynchronously is fixed. If it's synchronous, then we want to hold // the completion for the CaptureOrComplete() call to avoid the context flow. If not, we know CaptureOrComplete() has completed. if (CompletedSynchronously) { return; } ExecutionContext context = _Context; if (userToken != IntPtr.Zero || context == null) { base.Complete(userToken); return; } ExecutionContext.Run((_Flags & StateFlags.ThreadSafeContextCopy) != 0 ? context.CreateCopy() : context, new ContextCallback(CompleteCallback), null); }
public static int Event_eventGroupMsg(int subType, int msgId, long fromGroup, long fromQQ, string fromAnonymous, IntPtr msg, int font) { if (Event_eventGroupMsgHandler != null) { CQGroupMessageEventArgs args = new CQGroupMessageEventArgs(AppData.CQApi, AppData.CQLog, 2, 2, "群消息处理", "_eventGroupMsg", 30000, subType, msgId, fromGroup, fromQQ, fromAnonymous, msg.ToString(CQApi.DefaultEncoding), false); Event_eventGroupMsgHandler(typeof(CQEventExport), args); return((int)(args.Handler ? CQMessageHandler.Intercept : CQMessageHandler.Ignore)); } return(0); }
private static void VerifyPointer(IntPtr ptr, long expected) { Assert.Equal(expected, ptr.ToInt64()); int expected32 = (int)expected; if (expected32 != expected) { Assert.Throws<OverflowException>(() => ptr.ToInt32()); return; } int i = ptr.ToInt32(); Assert.Equal(expected32, ptr.ToInt32()); Assert.Equal(expected.ToString(), ptr.ToString()); Assert.Equal(expected.ToString("x"), ptr.ToString("x")); Assert.Equal(ptr, new IntPtr(expected)); Assert.True(ptr == new IntPtr(expected)); Assert.False(ptr != new IntPtr(expected)); Assert.NotEqual(ptr, new IntPtr(expected + 1)); Assert.False(ptr == new IntPtr(expected + 1)); Assert.True(ptr != new IntPtr(expected + 1)); }
/// <summary> /// Timer event when looking for Process (auto-Hook and auto-close) /// </summary> protected override void tProcess_Elapsed(Object Sender, EventArgs e) { if (!_ProcessHooked) { try { Process[] processes = Process.GetProcessesByName(_Target_Process_Name); if (processes.Length > 0) { _TargetProcess = processes[0]; _ProcessHandle = _TargetProcess.Handle; _TargetProcess_MemoryBaseAddress = _TargetProcess.MainModule.BaseAddress; ProcessModuleCollection c = _TargetProcess.Modules; foreach (ProcessModule m in c) { if (m.ModuleName.ToLower().Equals("gpudx11.dll")) { _GpuModuleBaseAddress = m.BaseAddress; Logger.WriteLog("gpuDX11.dll base address = 0x" + _GpuModuleBaseAddress.ToString("X8")); _GpuDisplayType_Offset = 0x0007F9DC; break; } else if (m.ModuleName.ToLower().Equals("gpudx11old.dll")) { _GpuModuleBaseAddress = m.BaseAddress; Logger.WriteLog("gpuDX11old.dll base address = 0x" + _GpuModuleBaseAddress.ToString("X8")); _GpuDisplayType_Offset = 0x0005F920; break; } else if (m.ModuleName.ToLower().StartsWith("gpudx") && m.ModuleName.ToLower().EndsWith(".dll")) { _GpuModuleBaseAddress = m.BaseAddress; Logger.WriteLog("Only found " + m.ModuleName.ToLower() + " loaded. Incompatible module, reverting to old method"); } } if (_TargetProcess_MemoryBaseAddress != IntPtr.Zero && _GpuModuleBaseAddress != IntPtr.Zero) { Logger.WriteLog("Attached to Process " + _Target_Process_Name + ".exe, ProcessHandle = " + _ProcessHandle); Logger.WriteLog(_Target_Process_Name + ".exe = 0x" + _TargetProcess_MemoryBaseAddress.ToString("X8")); if (!_DisableInputHack) { SetHack(); } else { Logger.WriteLog("Input Hack disabled"); } _ProcessHooked = true; RaiseGameHookedEvent(); } } } catch { Logger.WriteLog("Error trying to hook " + _Target_Process_Name + ".exe"); } } else { Process[] processes = Process.GetProcessesByName(_Target_Process_Name); if (processes.Length <= 0) { _ProcessHooked = false; _TargetProcess = null; _ProcessHandle = IntPtr.Zero; _TargetProcess_MemoryBaseAddress = IntPtr.Zero; Logger.WriteLog(_Target_Process_Name + ".exe closed"); Application.Exit(); } } }
private void StopSound(IntPtr tag) { foreach (var sound in soundInstanceList) { if (sound.AudioTag == tag.ToString()) { sound.Stop(); } } }
/// <summary>Handler called when a FDBFuture becomes ready</summary> /// <param name="futureHandle">Handle on the future that became ready</param> /// <param name="parameter">Paramter to the callback (unused)</param> private static void FutureCompletionCallback(IntPtr futureHandle, IntPtr parameter) { #if DEBUG_FUTURES Debug.WriteLine("Future<" + typeof(T).Name + ">.Callback(0x" + futureHandle.ToString("x") + ", " + parameter.ToString("x") + ") has fired on thread #" + Thread.CurrentThread.ManagedThreadId.ToString()); #endif var future = (FdbFutureSingle <T>)GetFutureFromCallbackParameter(parameter); if (future != null) { UnregisterCallback(future); future.HandleCompletion(fromCallback: true); } }
internal static IPHostEntry NativeToHostEntry(IntPtr nativePointer) { #endif // // marshal pointer to struct // hostent Host = (hostent)Marshal.PtrToStructure(nativePointer, typeof(hostent)); IPHostEntry HostEntry = new IPHostEntry(); if (Host.h_name != IntPtr.Zero) { HostEntry.HostName = Marshal.PtrToStringAnsi(Host.h_name); GlobalLog.Print("HostEntry.HostName: " + HostEntry.HostName); } // decode h_addr_list to ArrayList of IP addresses. // The h_addr_list field is really a pointer to an array of pointers // to IP addresses. Loop through the array, and while the pointer // isn't NULL read the IP address, convert it to an IPAddress class, // and add it to the list. ArrayList TempList = new ArrayList(); int IPAddressToAdd; string AliasToAdd; IntPtr currentArrayElement; // // get the first pointer in the array // currentArrayElement = Host.h_addr_list; nativePointer = Marshal.ReadIntPtr(currentArrayElement); while (nativePointer != IntPtr.Zero) { // // if it's not null it points to an IPAddress, // read it... // IPAddressToAdd = Marshal.ReadInt32(nativePointer); #if BIGENDIAN // IP addresses from native code are always a byte array // converted to int. We need to convert the address into // a uniform integer value. IPAddressToAdd = (int)( ((uint)IPAddressToAdd << 24) | (((uint)IPAddressToAdd & 0x0000FF00) << 8) | (((uint)IPAddressToAdd >> 8) & 0x0000FF00) | ((uint)IPAddressToAdd >> 24) ); #endif GlobalLog.Print("currentArrayElement: " + currentArrayElement.ToString() + " nativePointer: " + nativePointer.ToString() + " IPAddressToAdd:" + IPAddressToAdd.ToString()); // // ...and add it to the list // TempList.Add(new IPAddress(IPAddressToAdd)); // // now get the next pointer in the array and start over // currentArrayElement = IntPtrHelper.Add(currentArrayElement, IntPtr.Size); nativePointer = Marshal.ReadIntPtr(currentArrayElement); } HostEntry.AddressList = new IPAddress[TempList.Count]; TempList.CopyTo(HostEntry.AddressList, 0); // // Now do the same thing for the aliases. // TempList.Clear(); currentArrayElement = Host.h_aliases; nativePointer = Marshal.ReadIntPtr(currentArrayElement); while (nativePointer != IntPtr.Zero) { GlobalLog.Print("currentArrayElement: " + ((long)currentArrayElement).ToString() + "nativePointer: " + ((long)nativePointer).ToString()); // // if it's not null it points to an Alias, // read it... // AliasToAdd = Marshal.PtrToStringAnsi(nativePointer); // // ...and add it to the list // TempList.Add(AliasToAdd); // // now get the next pointer in the array and start over // currentArrayElement = IntPtrHelper.Add(currentArrayElement, IntPtr.Size); nativePointer = Marshal.ReadIntPtr(currentArrayElement); } HostEntry.Aliases = new string[TempList.Count]; TempList.CopyTo(HostEntry.Aliases, 0); return HostEntry; } // NativeToHostEntry
/// <summary> /// Converts the numeric value of the <see cref="FIMETADATA"/> object /// to its equivalent string representation. /// </summary> /// <returns>The string representation of the value of this instance.</returns> public override string ToString() { return(data.ToString()); }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Verify ctor can set correct handle value for constructor with parameters"); try { IntPtr ptr = new IntPtr(TestLibrary.Generator.GetInt32(-55)); MySafeHandle msf = new MySafeHandle(ptr); if (msf.Handle != ptr) { TestLibrary.TestFramework.LogError("002.1", "Ctor can not set correct handle value"); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] msf.Handle = " + msf.Handle.ToString() + ", desiredValue = " + ptr.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
/// <summary> /// gets a list of devices by vendor and product ID /// </summary> /// <returns></returns> protected static unsafe List <DeviceListItem> getDeviceList(UInt16 vendorId, UInt16[] productIdArray) { var list = new List <DeviceListItem>(); IntPtr *device_list; int count = LibUsb.throwIfError(UsbDevice.libusbGetDeviceList(LibUsb.context, out device_list), "Error from libusb_get_device_list."); int i; for (i = 0; i < count; i++) { IntPtr device = device_list[i]; foreach (UInt16 productId in productIdArray) { if (LibUsb.deviceMatchesVendorProduct(device, vendorId, productId)) { IntPtr device_handle; LibUsb.throwIfError(UsbDevice.libusbOpen(device, out device_handle), "Error connecting to device to get serial number (" + (i + 1) + " of " + count + ", " + device.ToString("x8") + ")."); string serialNumber = LibUsb.getSerialNumber(device_handle); list.Add(new DeviceListItem(device, "#" + serialNumber, serialNumber, productId)); UsbDevice.libusbClose(device_handle); } } } // Free device list without unreferencing. // Unreference/free the individual devices in the // DeviceListItem destructor. UsbDevice.libusbFreeDeviceList(device_list, 0); return(list); }
/// <summary> /// Converts the numeric value of the <see cref="fi_handle"/> object /// to its equivalent string representation. /// </summary> /// <returns>The string representation of the value of this instance.</returns> public override string ToString() { return(handle.ToString()); }
// Enables/disables all top-level Controls on this thread internal void Enable(bool state) { if (!_onlyWinForms && !state) { _activeHwnd = UnsafeNativeMethods.GetActiveWindow(); Control activatingControl = ThreadContext.FromCurrent().ActivatingControl; if (activatingControl != null) { _focusedHwnd = activatingControl.Handle; } else { _focusedHwnd = UnsafeNativeMethods.GetFocus(); } } for (int i = 0; i < _windowCount; i++) { IntPtr hWnd = _windows[i]; Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : Changing enabled on window: " + hWnd.ToString() + " : " + state.ToString()); if (UnsafeNativeMethods.IsWindow(new HandleRef(null, hWnd))) { SafeNativeMethods.EnableWindow(new HandleRef(null, hWnd), state); } } // OpenFileDialog is not returning the focus the way other dialogs do. // Important that we re-activate the old window when we are closing // our modal dialog. // // edit mode forever with Excel application // But, DON'T change other people's state when we're simply // responding to external MSOCM events about modality. When we are, // we are created with a TRUE for onlyWinForms. if (!_onlyWinForms && state) { if (_activeHwnd != IntPtr.Zero && UnsafeNativeMethods.IsWindow(new HandleRef(null, _activeHwnd))) { UnsafeNativeMethods.SetActiveWindow(new HandleRef(null, _activeHwnd)); } if (_focusedHwnd != IntPtr.Zero && UnsafeNativeMethods.IsWindow(new HandleRef(null, _focusedHwnd))) { UnsafeNativeMethods.SetFocus(new HandleRef(null, _focusedHwnd)); } } }
private static void OnTick(int counter, EventArgs args) { if (processHandle == IntPtr.Zero) //if we still don't have a handle to the process { var wndHnd = Memory.FindWindowClassName("UnityWndClass"); //try finding the window of the process (check if it's spawned and loaded) if (wndHnd != IntPtr.Zero) //if it exists { var calcPid = Memory.GetPIDFromHWND(wndHnd); //get the PID of that same process if (calcPid > 0) //if we got the PID { processHandle = Memory.ZwOpenProcess(PROCESS_ALL_ACCESS, calcPid); //get full access to the process so we can use it later if (processHandle != IntPtr.Zero) { //if we got access to the game, check if it's x64 bit, this is needed when reading pointers, since their size is 4 for x86 and 8 for x64 isWow64Process = Memory.IsProcess64Bit(processHandle); //here you can scan for signatures and stuff, it happens only once on "attach" } } } } else //else we have a handle, lets check if we should close it, or use it { var wndHnd = Memory.FindWindowClassName("UnityWndClass"); if (wndHnd != IntPtr.Zero) //window still exists, so handle should be valid? let's keep using it { //the lines of code below execute every 33ms outside of the renderer thread, heavy code can be put here if it's not render dependant gameProcessExists = true; isGameOnTop = Renderer.IsGameOnTop(wndHnd); isOverlayOnTop = Overlay.IsOnTop(); if (GameAssembly_dll == IntPtr.Zero) { GameAssembly_dll = Memory.ZwGetModule(processHandle, "GameAssembly.dll", isWow64Process); GameAssembly_dll_size = Memory.ZwGetModuleSize(processHandle, "GameAssembly.dll", isWow64Process); Console.WriteLine($"Found GameAssembly.dll: {GameAssembly_dll.ToString("X")}"); } //since we're not drawing, the rest of the code can be put here. if (clientPtr == IntPtr.Zero) { clientPtr = Memory.ZwFindSignature(processHandle, GameAssembly_dll, GameAssembly_dll_size, "45 33 C9 45 33 C0 33 D2 41 0F B6 CE", 0x14); Console.WriteLine($"Found clientPtr: {clientPtr.ToString("X")}"); } else { if (characterBasePtr == IntPtr.Zero) { characterBasePtr = Memory.ZwFindSignature(processHandle, GameAssembly_dll, GameAssembly_dll_size, "33 C0 48 8B 5C 24 40 48 83 C4 20 5D C3 48 8D", 0x10); Console.WriteLine($"Found characterBasePtr: {characterBasePtr.ToString("X")}"); } else { if (characterPtr == IntPtr.Zero) { //characterPtr = Memory.ZwFindSignatureBase(processHandle, IntPtr.Zero, IntPtr.Zero, "00 00 18 41 00 00 18 41 00 00 E0 40 CD CC 4C 3E 00 00 A0 40 00 00 E0 40 00 00 00 41 00 00 00 41 00"); //just to get the base of the character allocation data //9.50 9.50 7.00 0.20 5.00 7.00 8.00 or ... 41180000 41180000 40E00000 3E4CCCCD 40A00000 40E00000 41000000 characterPtr = SDKUtil.ZwReadPointerChain(processHandle, (IntPtr)(characterBasePtr.ToInt64() + 8), isWow64Process, 0xB58, 0x88); if (characterPtr != IntPtr.Zero) { Console.WriteLine($"FOUND Character Base Ptr: {characterPtr.ToString("X")}"); } else { if (lastTime + 1000 < Memory.TickCount) { lastTime = Memory.TickCount; Console.WriteLine("FAILED TO FIND Character Base Ptr :("); } } } else { //we are in game and got char ptr ... continue with menu modifications every tick IntPtr timeToRunNextCharacterControllerDataCheckPTR = SDKUtil.ZwReadPointerChain(processHandle, clientPtr, isWow64Process, 0xB8, 0x0, 0xC8, 0x10, 0x30, 0x1D8); //Console.WriteLine(timeToRunNextCharacterControllerDataCheck.ToString("X")); if (timeToRunNextCharacterControllerDataCheckPTR != IntPtr.Zero) { var timeToRunNextCharacterControllerDataCheck = Memory.ZwReadFloat(processHandle, (IntPtr)timeToRunNextCharacterControllerDataCheckPTR.ToInt64() + 0x10); if ((timeToRunNextCharacterControllerDataCheck > 0) && (timeToRunNextCharacterControllerDataCheck < 100000000.0f)) { Memory.ZwWriteFloat(processHandle, (IntPtr)(timeToRunNextCharacterControllerDataCheckPTR.ToInt64() + 0x10), 100000000.0f); } else { var doublecheck = Memory.ZwReadFloat(processHandle, (IntPtr)timeToRunNextCharacterControllerDataCheckPTR.ToInt64() + 0x10); if (doublecheck == 100000000.0f) { //DelayAction.Queue(() => writeCheatosz(processHandle, characterPtr), 5000.0f); writeCheatos(processHandle, characterPtr, false); } } } else { //writeCheatos(processHandle, characterPtr, true); } } } } } else //else most likely the process is dead, clean up { Memory.CloseHandle(processHandle); //close the handle to avoid leaks processHandle = IntPtr.Zero; //set it like this just in case for C# logic gameProcessExists = false; GameAssembly_dll = IntPtr.Zero; GameAssembly_dll_size = IntPtr.Zero; characterBasePtr = IntPtr.Zero; characterPtr = IntPtr.Zero; clientPtr = IntPtr.Zero; } } }
/// <summary>Starts a timer which is responsible for periodically looking for the game's process.</summary> private void StartLookingForGameProcess() { // Define the callback function to be used for the timer TimerCallback timerCallback = ( object state ) => { // Force timer's task to be executed in the SAME THREAD as the MainWindow this.Dispatcher.Invoke(() => { // This flag controls whether the timer used for looking for the game's process should be restarted or not bool bRestartLookForGameTimer = true; // Try to find the game's process Process gameProcess = Process.GetProcessesByName(GAME_PROCESS_NAME).FirstOrDefault(); if (gameProcess != null) { // Try to attach to the game's process if (GameMemoryIO.AttachToProcess(gameProcess)) { // Inject the trainer's code and variables into the game's memory! GameMemoryInjector.Inject(); // When the game's process exits, the MainWindow's dispatcher is used to invoke the DetachFromGame() method // in the same thread which "runs" our MainWindow GameMemoryIO.TargetProcess.EnableRaisingEvents = true; GameMemoryIO.TargetProcess.Exited += (caller, args) => { this.Dispatcher.Invoke(() => { this.DetachFromGame(); }); }; // Register all of the memory alteration sets that the trainer has IntPtr mainModuleAddress = GameMemoryIO.TargetProcess.MainModule.BaseAddress; RegisterMemoryAlterationSets(mainModuleAddress); // Enable the cheats that the user has checked in the trainer's interface foreach (ECheat curEnabledCheat in m_enabledCheats) { GameMemoryInjector.SetMemoryAlterationsActive(curEnabledCheat, true); } // In DEBUG mode, print some debugging information that might be interesting when developing cheats #if DEBUG int longestCodeCaveNameLength = 0; foreach (ECodeCave curCodeCave in Enum.GetValues(typeof(ECodeCave))) { longestCodeCaveNameLength = Math.Max(longestCodeCaveNameLength, curCodeCave.ToString().Length); } int longestVariableNameLength = 0; foreach (EVariable curVariable in Enum.GetValues(typeof(EVariable))) { longestVariableNameLength = Math.Max(longestVariableNameLength, curVariable.ToString().Length); } Console.WriteLine("[INJECTED: {0}]", DateTime.Now.ToString("yyyy-MM-dd HH':'mm':'ss")); Console.WriteLine("PID: {0}", GameMemoryIO.TargetProcess.Id.ToString("X8")); Console.WriteLine("Main Module: {0} (base address: 0x{1})", GameMemoryIO.TargetProcess.MainModule.ModuleName, mainModuleAddress.ToString("X8")); Console.WriteLine("Injected CODE CAVES:"); foreach (ECodeCave curCodeCave in Enum.GetValues(typeof(ECodeCave))) { Console.WriteLine(" {0}: 0x{1}", curCodeCave.ToString().PadLeft(longestCodeCaveNameLength), GameMemoryInjector.GetInjectedCodeCaveAddress(curCodeCave).ToString("X8")); } Console.WriteLine("Injected VARIABLES:"); foreach (EVariable curVariable in Enum.GetValues(typeof(EVariable))) { Console.WriteLine(" {0}: 0x{1}", curVariable.ToString().PadLeft(longestVariableNameLength), GameMemoryInjector.GetInjectedVariableAddress(curVariable).ToString("X8")); } Console.WriteLine(); #endif // The timer which looks for the game shouldn't be restarted, as the game has already been found bRestartLookForGameTimer = false; } else { // Show a message box telling the user that the trainer has failed to attach to the game's process. MessageBox.Show(this, Properties.Resources.strMsgFailedToAttach, Properties.Resources.strMsgFailedToAttachCaption, MessageBoxButton.OK, MessageBoxImage.Exclamation); } } // RESTART the timer as a ONE-SHOT timer if (bRestartLookForGameTimer) { m_gameSearchTimer.Change(TIMER_LOOK_FOR_GAME_PROCESS_PERIOD_MS, Timeout.Infinite); } }); }; // Start the timer as a ONE-SHOT timer m_gameSearchTimer = new Timer(timerCallback, null, TIMER_LOOK_FOR_GAME_PROCESS_PERIOD_MS, Timeout.Infinite); }
public static IntPtr CreateStreamProducerSurfaceKHR(IntPtr dpy, IntPtr config, IntPtr stream, int[] attrib_list) { IntPtr retValue; unsafe { fixed(int *p_attrib_list = attrib_list) { Debug.Assert(Delegates.peglCreateStreamProducerSurfaceKHR != null, "peglCreateStreamProducerSurfaceKHR not implemented"); retValue = Delegates.peglCreateStreamProducerSurfaceKHR(dpy, config, stream, p_attrib_list); LogFunction("eglCreateStreamProducerSurfaceKHR(0x{0}, 0x{1}, 0x{2}, {3}) = {4}", dpy.ToString("X8"), config.ToString("X8"), stream.ToString("X8"), LogValue(attrib_list), retValue.ToString("X8")); } } DebugCheckErrors(retValue); return(retValue); }
public static void DestroyGLXPbufferSGIX(IntPtr dpy, IntPtr pbuf) { Debug.Assert(Delegates.pglXDestroyGLXPbufferSGIX != null, "pglXDestroyGLXPbufferSGIX not implemented"); Delegates.pglXDestroyGLXPbufferSGIX(dpy, pbuf); LogFunction("glXDestroyGLXPbufferSGIX(0x{0}, 0x{1})", dpy.ToString("X8"), pbuf.ToString("X8")); DebugCheckErrors(null); }
private static void TestPointer(IntPtr p, long expected) { long l = p.ToInt64(); Assert.Equal(l, expected); int expected32 = (int)expected; if (expected32 != expected) { Assert.Throws<OverflowException>(() => { int i = p.ToInt32(); }); return; } { int i = p.ToInt32(); Assert.Equal(i, expected32); } string s = p.ToString(); string sExpected = expected.ToString(); Assert.Equal(s, sExpected); s = p.ToString("x"); sExpected = expected.ToString("x"); Assert.Equal(s, sExpected); bool b; b = (p == new IntPtr(expected)); Assert.True(b); b = (p == new IntPtr(expected + 1)); Assert.False(b); b = (p != new IntPtr(expected)); Assert.False(b); b = (p != new IntPtr(expected + 1)); Assert.True(b); }
public static int QueryGLXPbufferSGIX(IntPtr dpy, IntPtr pbuf, int attribute, UInt32[] value) { int retValue; unsafe { fixed(UInt32 *p_value = value) { Debug.Assert(Delegates.pglXQueryGLXPbufferSGIX != null, "pglXQueryGLXPbufferSGIX not implemented"); retValue = Delegates.pglXQueryGLXPbufferSGIX(dpy, pbuf, attribute, p_value); LogFunction("glXQueryGLXPbufferSGIX(0x{0}, 0x{1}, {2}, {3}) = {4}", dpy.ToString("X8"), pbuf.ToString("X8"), attribute, LogValue(value), retValue); } } DebugCheckErrors(retValue); return(retValue); }
void CopyMonitoringInConsole(ErrorCode in_errorCode, ErrorLevel in_errorLevel, uint in_playingID, IntPtr in_gameObjID, string in_msg) { string msg = "Wwise: " + in_msg; if (in_gameObjID != (IntPtr)AkSoundEngine.AK_INVALID_GAME_OBJECT) { GameObject obj = EditorUtility.InstanceIDToObject((int)in_gameObjID) as GameObject; string name = obj != null ? obj.ToString() : in_gameObjID.ToString(); msg += "(Object: " + name + ")"; } if (in_errorLevel == ErrorLevel.ErrorLevel_Error) Debug.LogError(msg); else{ //Debug.Log(msg); } }
public static void GetSelectedEventSGIX(IntPtr dpy, IntPtr drawable, [Out] UInt32[] mask) { unsafe { fixed(UInt32 *p_mask = mask) { Debug.Assert(Delegates.pglXGetSelectedEventSGIX != null, "pglXGetSelectedEventSGIX not implemented"); Delegates.pglXGetSelectedEventSGIX(dpy, drawable, p_mask); LogFunction("glXGetSelectedEventSGIX(0x{0}, 0x{1}, {2})", dpy.ToString("X8"), drawable.ToString("X8"), LogValue(mask)); } } DebugCheckErrors(null); }
public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: DangerousGetHandle should return handle value for valid safe handle"); try { int randValue = TestLibrary.Generator.GetInt32(-55); IntPtr desiredValue = new IntPtr(randValue); SafeHandle handle = new MySafeInValidHandle(desiredValue); IntPtr handleValue = handle.DangerousGetHandle(); if (handleValue != desiredValue) { TestLibrary.TestFramework.LogError("004.1", "DangerousGetHandle returns wrong handle value for valid safe handle"); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] handleValue = " + handleValue.ToString() + ", desiredValue = " + desiredValue.ToString()); retVal = false; } handleValue = handle.DangerousGetHandle(); if (handleValue != desiredValue) { TestLibrary.TestFramework.LogError("004.2", "DangerousGetHandle returns wrong handle value for valid safe handle"); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] handleValue = " + handleValue.ToString() + ", desiredValue = " + desiredValue.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
public static IntPtr CreateGLXPbufferSGIX(IntPtr dpy, IntPtr config, UInt32 width, UInt32 height, int[] attrib_list) { IntPtr retValue; unsafe { fixed(int *p_attrib_list = attrib_list) { Debug.Assert(Delegates.pglXCreateGLXPbufferSGIX != null, "pglXCreateGLXPbufferSGIX not implemented"); retValue = Delegates.pglXCreateGLXPbufferSGIX(dpy, config, width, height, p_attrib_list); LogFunction("glXCreateGLXPbufferSGIX(0x{0}, 0x{1}, {2}, {3}, {4}) = {5}", dpy.ToString("X8"), config.ToString("X8"), width, height, LogValue(attrib_list), retValue.ToString("X8")); } } DebugCheckErrors(retValue); return(retValue); }
private bool CheckSound(IntPtr tag) { bool playing = false; foreach (var sound in soundInstanceList) { if (sound.AudioTag == tag.ToString()) { playing |= sound.CheckPlaying(); } } return playing; }
public static bool QueryVideoCaptureDeviceNV(IntPtr hDc, IntPtr hDevice, int iAttribute, int[] piValue) { bool retValue; unsafe { fixed(int *p_piValue = piValue) { Debug.Assert(Delegates.pwglQueryVideoCaptureDeviceNV != null, "pwglQueryVideoCaptureDeviceNV not implemented"); retValue = Delegates.pwglQueryVideoCaptureDeviceNV(hDc, hDevice, iAttribute, p_piValue); LogFunction("wglQueryVideoCaptureDeviceNV(0x{0}, 0x{1}, {2}, {3}) = {4}", hDc.ToString("X8"), hDevice.ToString("X8"), iAttribute, LogValue(piValue), retValue); } } DebugCheckErrors(retValue); return(retValue); }
private void PlaySound(IntPtr tag, int data, float volume, float pan, float pitch, bool mode3D, float x, float y, float z, float distance) { if (data <= 0) { return; } SoundResource resource = soundList[data - 1]; if (resource == null) { return; } foreach (var instance in soundInstanceList) { if (!instance.CheckPlaying()) { instance.Play(tag.ToString(), resource.Audio, volume, pan, pitch, mode3D, x, y, z, distance); break; } } }
public static bool ReleaseVideoCaptureDeviceNV(IntPtr hDc, IntPtr hDevice) { bool retValue; Debug.Assert(Delegates.pwglReleaseVideoCaptureDeviceNV != null, "pwglReleaseVideoCaptureDeviceNV not implemented"); retValue = Delegates.pwglReleaseVideoCaptureDeviceNV(hDc, hDevice); LogFunction("wglReleaseVideoCaptureDeviceNV(0x{0}, 0x{1}) = {2}", hDc.ToString("X8"), hDevice.ToString("X8"), retValue); DebugCheckErrors(retValue); return(retValue); }
// This method is guaranteed to be called only once. If called with a non-zero userToken, the context is not flowed. protected override void Complete(IntPtr userToken) { if (GlobalLog.IsEnabled) { GlobalLog.Print("ContextAwareResult#" + LoggingHash.HashString(this) + "::Complete() _Context(set):" + (_context != null).ToString() + " userToken:" + userToken.ToString()); } // If no flowing, just complete regularly. if ((_flags & StateFlags.PostBlockStarted) == 0) { base.Complete(userToken); return; } // At this point, IsCompleted is set and CompletedSynchronously is fixed. If it's synchronous, then we want to hold // the completion for the CaptureOrComplete() call to avoid the context flow. If not, we know CaptureOrComplete() has completed. if (CompletedSynchronously) { return; } ExecutionContext context = _context; // If the context is being abandoned or wasn't captured (SuppressFlow, null AsyncCallback), just // complete regularly, as long as CaptureOrComplete() has finished. // if (userToken != IntPtr.Zero || context == null) { base.Complete(userToken); return; } ExecutionContext.Run(context, s => ((ContextAwareResult)s).CompleteCallback(), this); }
public static UInt32 EnumerateVideoCaptureDevicesNV(IntPtr hDc, IntPtr[] phDeviceList) { UInt32 retValue; unsafe { fixed(IntPtr *p_phDeviceList = phDeviceList) { Debug.Assert(Delegates.pwglEnumerateVideoCaptureDevicesNV != null, "pwglEnumerateVideoCaptureDevicesNV not implemented"); retValue = Delegates.pwglEnumerateVideoCaptureDevicesNV(hDc, p_phDeviceList); LogFunction("wglEnumerateVideoCaptureDevicesNV(0x{0}, {1}) = {2}", hDc.ToString("X8"), LogValue(phDeviceList), retValue); } } DebugCheckErrors(retValue); return(retValue); }
public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Call Ctor with IntPtr reference and set trackResurrection to true"); try { Object desiredValue = IntPtr.Zero; WeakReference reference = new WeakReference(desiredValue, true); if ((reference.TrackResurrection != true) || (!reference.Target.Equals(desiredValue))) { TestLibrary.TestFramework.LogError("006.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() + ", reference.Target = " + reference.Target.ToString() + ", desiredValue = " + desiredValue.ToString()); retVal = false; } desiredValue = new IntPtr(TestLibrary.Generator.GetInt32(-55)); reference = new WeakReference(desiredValue, false); if ((reference.TrackResurrection != false) || (!reference.Target.Equals(desiredValue))) { TestLibrary.TestFramework.LogError("006.2", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() + ", reference.Target = " + reference.Target.ToString() + ", desiredValue = " + desiredValue.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
public override string ToString() { //x16は書式で、xが16進数で表示、16が表示桁数 return($"IntPtr({hWnd.ToString("x16")}), Rect({Rect}), 可視{IsVisible}, Text({Text})"); }
void CopyMonitoringInConsole(ErrorCode in_errorCode, ErrorLevel in_errorLevel, uint in_playingID, IntPtr in_gameObjID, string in_msg) { // Only log when logging from the engine is enabled. The callback remains active when the flag is disabled to ensure // it can be toggled on and off in a lively manner in Unity. if (engineLogging) { string msg = "Wwise: " + in_msg; if (in_gameObjID != (IntPtr)AkSoundEngine.AK_INVALID_GAME_OBJECT) { GameObject obj = EditorUtility.InstanceIDToObject((int)in_gameObjID) as GameObject; string name = obj != null ? obj.ToString() : in_gameObjID.ToString(); msg += "(Object: " + name + ")"; } if (in_errorLevel == ErrorLevel.ErrorLevel_Error) Debug.LogError(msg); else Debug.Log(msg); } }
public void InitMogre() { //----------------------------------------------------- // 1 enter ogre //----------------------------------------------------- root = new Root(); //----------------------------------------------------- // 2 configure resource paths //----------------------------------------------------- //----------------------------------------------------- // 3 Configures the application and creates the window //----------------------------------------------------- #if DEBUG root.LoadPlugin("RenderSystem_Direct3D9_d"); #else root.LoadPlugin("RenderSystem_Direct3D9"); #endif bool foundit = false; foreach (RenderSystem rs in root.GetAvailableRenderers()) { root.RenderSystem = rs; String rname = root.RenderSystem.Name; if (rname == "Direct3D9 Rendering Subsystem") { foundit = true; break; } } if (!foundit) { return; //we didn't find it... Raise exception? } //we found it, we might as well use it! root.RenderSystem.SetConfigOption("Full Screen", "No"); root.RenderSystem.SetConfigOption("Video Mode", string.Format("{0} x {1} @ 32-bit colour", windowSize.Width, windowSize.Height)); root.Initialise(false); // other plugins #if DEBUG root.LoadPlugin("Plugin_CgProgramManager_d"); root.LoadPlugin("Plugin_OctreeSceneManager_d"); #else root.LoadPlugin("Plugin_CgProgramManager"); root.LoadPlugin("Plugin_OctreeSceneManager"); #endif NameValuePairList misc = new NameValuePairList(); misc["externalWindowHandle"] = hWnd.ToString(); window = root.CreateRenderWindow("Simple Mogre Form Window", 0, 0, false, misc); ResourceGroupManager.Singleton.InitialiseAllResourceGroups(); //----------------------------------------------------- // 4 Create the SceneManager // // ST_GENERIC = octree // ST_EXTERIOR_CLOSE = simple terrain // ST_EXTERIOR_FAR = nature terrain (depreciated) // ST_EXTERIOR_REAL_FAR = paging landscape // ST_INTERIOR = Quake3 BSP //----------------------------------------------------- sceneMgr = root.CreateSceneManager(SceneType.ST_GENERIC, "SceneMgr"); sceneMgr.AmbientLight = new ColourValue(0.5f, 0.5f, 0.5f); //----------------------------------------------------- // 5 Create the camera //----------------------------------------------------- camera = sceneMgr.CreateCamera("SimpleCamera"); camera.NearClipDistance = 0.1f; camera.AutoAspectRatio = true; viewport = window.AddViewport(camera); viewport.BackgroundColour = new ColourValue(0.25f, 0.25f, 0.25f, 1.0f); root.FrameStarted += new FrameListener.FrameStartedHandler(MogreFrameStarted); }
// A method for completing the IO with a result // and invoking the user's callback. // Used by derived classes to pass context into an overridden Complete(). Useful // for determining the 'winning' thread in case several may simultaneously call // the equivalent of InvokeCallback(). protected void ProtectedInvokeCallback(object result, IntPtr userToken) { GlobalLog.Print("LazyAsyncResult#" + ValidationHelper.HashString(this) + "::ProtectedInvokeCallback() result = " + (result is Exception? ((Exception)result).Message: result == null? "<null>": result.ToString()) + ", userToken:" + userToken.ToString()); // Critical to disallow DBNull here - it could result in a stuck spinlock in WaitForCompletion. if (result == DBNull.Value) { throw new ArgumentNullException("result"); } #if DEBUG // Always safe to ask for the state now. _ProtectState = false; #endif if ((m_IntCompleted & ~c_HighBit) == 0 && (Interlocked.Increment(ref m_IntCompleted) & ~c_HighBit) == 1) { // DBNull.Value is used to guarantee that the first caller wins, // even if the result was set to null. if (m_Result == DBNull.Value) m_Result = result; // Does this need a memory barrier to be sure this thread gets the m_Event if it's set? I don't think so // because the Interlockeds on m_IntCompleted/m_Event should serve as the barrier. ManualResetEvent asyncEvent = (ManualResetEvent) m_Event; if (asyncEvent != null) { try { asyncEvent.Set(); } catch (ObjectDisposedException) { // Simply ignore this exception - There is apparently a rare race condition // where the event is disposed before the completion method is called. } } Complete(userToken); } }
public override string ToString() { return("0x" + Pointer.ToString("x")); }
// A method for completing the IO with a result and invoking the user's callback. // Used by derived classes to pass context into an overridden Complete(). Useful // for determining the 'winning' thread in case several may simultaneously call // the equivalent of InvokeCallback(). protected void ProtectedInvokeCallback(object result, IntPtr userToken) { if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::ProtectedInvokeCallback() result = " + (result is Exception ? ((Exception)result).Message : result == null ? "<null>" : result.ToString()) + ", userToken:" + userToken.ToString()); } // Critical to disallow DBNull here - it could result in a stuck spinlock in WaitForCompletion. if (result == DBNull.Value) { throw new ArgumentNullException("result"); } #if DEBUG // Always safe to ask for the state now. _protectState = false; #endif if ((_intCompleted & ~HighBit) == 0 && (Interlocked.Increment(ref _intCompleted) & ~HighBit) == 1) { // DBNull.Value is used to guarantee that the first caller wins, // even if the result was set to null. if (_result == DBNull.Value) { _result = result; } ManualResetEvent asyncEvent = (ManualResetEvent)_event; if (asyncEvent != null) { try { asyncEvent.Set(); } catch (ObjectDisposedException) { // Simply ignore this exception - There is apparently a rare race condition // where the event is disposed before the completion method is called. } } Complete(userToken); } }
public virtual bool runTest() { Console.Error.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; Int32 iValue; IntPtr ip1; try { strLoc = "Loc_743wg"; iValue = 16; ip1 = new IntPtr(iValue); iCountTestcases++; if(ip1.ToString() != iValue.ToString()){ iCountErrors++; Console.WriteLine("Err_2975sf! Wrong value returned"); } strLoc = "Loc_0084wf"; iValue = 0; ip1 = new IntPtr(iValue); iCountTestcases++; if(ip1.ToString() != iValue.ToString()){ iCountErrors++; Console.WriteLine("Err_974325sdg! Wrong value returned"); } strLoc = "Loc_00s42f"; iValue = -15; ip1 = new IntPtr(iValue); iCountTestcases++; if(ip1.ToString() != iValue.ToString()){ iCountErrors++; Console.WriteLine("Err_9374fzdg! Wrong value returned, " + ip1.ToString()); } strLoc = "Loc_93476sdg"; iValue = Int32.MaxValue; ip1 = new IntPtr(iValue); iCountTestcases++; if(ip1.ToString() != iValue.ToString()){ iCountErrors++; Console.WriteLine("Err_07536tsg! Wrong value returned"); } iValue = Int32.MinValue; ip1 = new IntPtr(iValue); if(ip1.ToString() != iValue.ToString()){ iCountErrors++; Console.WriteLine("Err_9875wrsg! Wrong value returned"); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine(s_strTFAbbrev +" Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general); } if ( iCountErrors == 0 ) { Console.Error.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.Error.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }