Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion broken_patterns.txt
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
Could not rename nvgArc
Could not rename cTkRigidBody::SetAngularVelocity
Could not rename cEgSceneGraphResource::ParseData
Could not rename cTkResourceManager::GetDefaultResource
Could not rename cEgDrawGeometry::Draw
Could not rename cEgRenderer::DrawRenderables
Could not rename cEgGeometryResource::CreateVertexInfoForHash
Could not rename GeometryStreaming::cEgGeometryStreamer::RequestStream
Could not rename GeometryStreaming::cEgGeometryStreamer::OnBufferLoadFinish
Could not rename EgInstancedModelExtension::cEgInstancedMeshNode::RenderAsync
Could not rename cTkResourceManager::GetDefaultResource
2 changes: 1 addition & 1 deletion nmspy/_internal_mods/textChatManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@


@no_gui
class textChatManager(Mod):
class _INTERNAL_textChatManager(Mod):
@terminal_command("Say some words.", "example")
def say(self, *words):
logger.info(f"I am saying the words: {' '.join(words)}")
Expand Down
1 change: 0 additions & 1 deletion nmspy/data/enums/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
eFrontendPage,
eNGuiInputButtonState,
eNGuiInputType,
eWarpState,
eWeaponMode,
)

Expand Down
15 changes: 0 additions & 15 deletions nmspy/data/enums/internal_enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,21 +319,6 @@ class eNGuiInputType(IntEnum):
Held = 0xFF # -0x1


class eWarpState(IntEnum):
# These are just the definitions from 4.13, but I don't think they've changed...
# This seems to cycle from 0 -> 8 sequentially whilst warping and resets to 0 when the warp is fully
# complete.
None_ = 0x0
Charge = 0x1
EnterTunnel = 0x2
WarpTunnel = 0x3
WaitForGeneration = 0x4
RespawnPlayer = 0x5
ExitTunnel = 0x6
WarpSlowdown = 0x7
RenderDebug = 0x8


class eWeaponMode(IntEnum):
# All from 4.13 but I don't think they've changed yet?
# TODO: Long-winded way to test: Log states from cGcPlayerWeapon.meWeaponMode and compare to what it shows
Expand Down
91 changes: 70 additions & 21 deletions nmspy/data/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,8 +340,9 @@ class eLayoutChangeEvent(IntEnum):
Value = 0x8
ColourPreset = 0x9

mvParallaxOffset: Annotated[basic.Vector2f, 0x20]
mpElementData: Annotated[_Pointer[nmse.cGcNGuiElementData], 0x48]
meLayoutChangeEvent: Annotated[c_enum8[eLayoutChangeEvent], 0x51]
meLayoutChangeEvent: Annotated[c_enum8[eLayoutChangeEvent], 0x52]

@function_hook("48 83 EC ? 48 8B 41 ? 45 85 C0")
def GetPosition(
Expand All @@ -364,6 +365,11 @@ def SetPosition(
def Render(self, this: "_Pointer[cGcNGuiElement]"): ...


@partial_struct
class cGcNGuiGraphic(cGcNGuiElement):
mpGraphicData: Annotated[_Pointer[nmse.cGcNGuiGraphicData], 0x58]


@partial_struct
class cGcNGuiText(cGcNGuiElement):
# Found in cGcNGuiText::EditElement
Expand Down Expand Up @@ -1177,17 +1183,17 @@ def cGcPlayerFleetManager(self, this: "_Pointer[cGcPlayerFleetManager]"): ...

@partial_struct
class cGcGalacticVoxelCoordinate(Structure):
mX: Annotated[int, Field(c_int16)]
mZ: Annotated[int, Field(c_int16)]
mY: Annotated[int, Field(c_int16)]
mbValid: Annotated[bool, Field(c_bool)]
mX: Annotated[int, Field(c_int16, 0x0)]
mZ: Annotated[int, Field(c_int16, 0x2)]
mY: Annotated[int, Field(c_int16, 0x4)]
mbValid: Annotated[bool, Field(c_bool, 0x6)]


@partial_struct
class cGcGalacticSolarSystemAddress(Structure):
mVoxelCoordinate: Annotated[cGcGalacticVoxelCoordinate, Field(cGcGalacticVoxelCoordinate)]
mSolarIndex: Annotated[int, Field(c_uint16)]
mIteration: Annotated[int, Field(c_uint16)]
mVoxelCoordinate: Annotated[cGcGalacticVoxelCoordinate, 0x0]
mSolarIndex: Annotated[int, Field(c_uint16, 0x8)]
mIteration: Annotated[int, Field(c_uint16, 0xA)]


@partial_struct
Expand Down Expand Up @@ -1656,7 +1662,7 @@ def SetToPosition(
@function_hook("48 89 4C 24 ? 55 41 55 48 8D AC 24 ? ? ? ? 48 81 EC ? ? ? ? 45 33 ED")
def RenderInventoryEditor(self, this: "_Pointer[cGcPlayer]"): ...

@function_hook("48 8B C4 48 89 48 ? 55 41 55 41 57 48 8D A8 ? ? ? ? 48 81 EC ? ? ? ? 48 89 58")
@function_hook("48 8B C4 55 41 54 41 55 48 8D A8")
def RenderNGui(self, this: "_Pointer[cGcPlayer]"): ...

@function_hook(
Expand All @@ -1670,6 +1676,9 @@ def GetSpaceship(self, this: "_Pointer[cGcPlayer]"): ...
@function_hook("48 8B C4 48 89 58 ? 57 48 81 EC ? ? ? ? 0F 10 81")
def SetFacing(self, this: "_Pointer[cGcPlayer]", lDir: _Pointer[basic.cTkVector3]): ...

@function_hook("40 55 53 56 57 41 54 41 55 48 8D AC 24")
def UpdateAction(self, this: "_Pointer[cGcPlayer]", lfStep: Annotated[float, c_float]): ...


class cGcPlanetGenerationInputData(nmse.cGcPlanetGenerationInputData):
@function_hook(
Expand Down Expand Up @@ -2322,18 +2331,6 @@ class cGcWarpJumpTarget(Structure):

@partial_struct
class cGcSpaceshipWarp(Structure):
mJumpTarget: Annotated[cGcWarpJumpTarget, 0x10]
# The offset for this can be found under cGcPortalComponent::Prepare near the bottom, below the
# "cGcPortalComponent" string. However, its a really screwy offset to calculate since you
# first need the Offsets of cGcSimulation from cGcApplication, as well as the offset for
# cGcSpaceshipWarp from cGcSimulation, since the binary uses the cGcApplication global.
meWarpState: Annotated[c_enum8[enums.eWarpState], 0x98]
mePulseDriveState: Annotated[c_enum32[enums.EPulseDriveState], 0xA4]
mfPulseDriveTimer: Annotated[float, Field(c_float, 0xB4)]
mfPulseDriveFuelTimer: Annotated[float, Field(c_float, 0xB8)]
mfPulseDriveTimer: Annotated[float, Field(c_float, 0x1A8)]
mfPulseDriveFuelTimer: Annotated[float, Field(c_float, 0x1AC)]

class eWarpEffectType(IntEnum):
# Might not be right. The below is from 4.13 with any known modifications.
Normal = 0x0
Expand All @@ -2351,6 +2348,29 @@ class eWarpEffectType(IntEnum):
FreighterMegaWarp = 0xC
FakePortalTeleport = 0xD

class eWarpState(IntEnum):
# These are just the definitions from 4.13, but I don't think they've changed...
# This seems to cycle from 0 -> 8 sequentially whilst warping and resets to 0 when the warp is fully
# complete.
None_ = 0x0
Charge = 0x1
EnterTunnel = 0x2
WarpTunnel = 0x3
WaitForGeneration = 0x4
RespawnPlayer = 0x5
ExitTunnel = 0x6
WarpSlowdown = 0x7
RenderDebug = 0x8

mJumpTarget: Annotated[cGcWarpJumpTarget, 0x10]
meWarpState: Annotated[c_enum32[eWarpState], 0x9C]
mfWarpTimeTotal: Annotated[float, Field(c_float, 0xA8)]
mePulseDriveState: Annotated[c_enum32[enums.EPulseDriveState], 0xAC]
mfPulseDriveTimer: Annotated[float, Field(c_float, 0xBC)]
mfPulseDriveFuelTimer: Annotated[float, Field(c_float, 0xC0)]
mWarpInDestinationTM: Annotated[basic.cTkMatrix34, 0x4A0]
meCurrentWarpEffect: Annotated[c_enum32[eWarpEffectType], 0x5F0]

@function_hook("40 55 56 48 8D AC 24 ? ? ? ? 48 81 EC ? ? ? ? 8B 81")
def Update(
self,
Expand Down Expand Up @@ -2521,6 +2541,9 @@ def Update(self, this: "_Pointer[cGcPlayerHUD]", lfTimeStep: Annotated[float, c_
@function_hook("48 89 5C 24 ? 48 89 74 24 ? 55 57 41 54 41 56 41 57 48 8B EC 48 83 EC ? 4C 8D B1")
def LoadData(self, this: "_Pointer[cGcPlayerHUD]"): ...

@function_hook("40 55 56 48 8D 6C 24 ? 48 81 EC ? ? ? ? 8B 05")
def RenderHeadsUp(self, this: "_Pointer[cGcPlayerHUD]"): ...


class cGcQuickMenu(Structure):
@function_hook(
Expand Down Expand Up @@ -5732,6 +5755,32 @@ def Update(
): ...


@partial_struct
class cGcPlayerWeaponWheel(Structure):
mIsTouchOnlyInterface: Annotated[bool, Field(c_bool, 0x7D)]

@function_hook("40 57 48 81 EC ? ? ? ? 83 79 ? ? 48 8B F9 75")
def Open(self, this: "_Pointer[cGcPlayerWeaponWheel]"): ...

@function_hook("40 57 41 54 48 83 EC ? 0F 29 74 24")
def UpdateInternal(
self,
this: "_Pointer[cGcPlayerWeaponWheel]",
a2: c_uint64,
a3: c_uint64, # This or the one above is cGcPlayerWeaponWheel::sButtonInput
) -> c_uint32:
"""Internal update call for the weapon wheel. Return value is used for something."""
...

@function_hook("48 8B C4 F3 0F 11 50 ? 48 89 50 ? 55 41 54")
def RenderAt(
self,
this: "_Pointer[cGcPlayerWeaponWheel]",
lPosition: _Pointer[basic.Vector2f],
a3: Annotated[float, c_float],
): ...


# Dummy values to copy and paste to make adding new things quicker...
# class name(Structure):
# @function_hook("")
Expand Down
167 changes: 167 additions & 0 deletions nmspy/data/xml_mixin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
# This will contain all the "modded types".
# These are basically community custom versions of all the types which can be found in MBINCompiler.

import types
import typing
import xml.etree.ElementTree as etree
from dataclasses import fields
from enum import Enum
from os import PathLike
from typing import Any, ClassVar, TypeVar, Union

T = TypeVar("T", bound="XmlMixin")

XML_DECLARATION = '<?xml version="1.0" encoding="utf-8"?>\n'
ROOT_TAG = "Data"
ITEM_TAG = "Property"


def _is_list(type_: Any) -> bool:
# Determine whether the type of the object is a list or not.
return type_ is list or typing.get_origin(type_) is list


def _strip_optional(type_: Any) -> Any:
# Strip out any Optional cases (so `T | None` -> `T`).
origin = typing.get_origin(type_)
if origin is Union or origin is types.UnionType:
args = [a for a in typing.get_args(type_) if a is not type(None)]
if len(args) == 1:
return args[0]
return type_


class XmlMixin:
"""
Mixin for dataclasses that reads/writes them as a tree of <Property> elements.

Supported field types: str, int, float, bool, Enum, other dataclasses that
also use XmlMixin, ``list[T]`` of any of these previous types, and optional types.
Note that optional types will not be written out if they are set to None.
Empty lists will be written as an empty element to distinguish it from None.
"""

# Keep track of already handled classes so that we can avoid having to re-parse them every time we come
# across them.
_registry: ClassVar[dict[str, type]] = {}

def __init_subclass__(cls, **kwargs: Any):
super().__init_subclass__(**kwargs)
XmlMixin._registry[cls.__name__] = cls

@classmethod
def _hints(cls) -> dict[str, Any]:
# Get the type hints for the class.
return typing.get_type_hints(cls, localns={cls.__name__: cls, **cls._registry})

def _write_fields(self, parent: etree.Element):
# Loop over the fields, encode them and add them to the parent.
hints = self._hints()
for f in fields(self): # type: ignore[arg-type]
if not f.init:
continue
child = self._encode(f.name, hints[f.name], getattr(self, f.name))
if child is not None:
parent.append(child)

@classmethod
def _encode(cls, name: str, type_: Any, value: Any) -> etree.Element | None:
# Encode the values in the class with some name, type and value.
# When value is None, it will also just return None.
if value is None:
return None
type_ = _strip_optional(type_)
el = etree.Element(ITEM_TAG, name=name)

if _is_list(type_):
(item_type,) = typing.get_args(type_) or (Any,)
for item in value:
child = cls._encode(name, item_type, item)
if child is not None:
el.append(child)
elif isinstance(value, XmlMixin):
el.set("value", type(value).__name__)
value._write_fields(el)
elif isinstance(value, Enum):
el.set("value", value.name)
elif isinstance(value, bool):
el.set("value", "true" if value else "false")
else:
el.set("value", str(value))
return el

@classmethod
def _from_element(cls: type[T], root: etree.Element) -> T:
# Read the template and read the fields in it.
template = root.get("template")
target = cls._registry.get(template, cls) if template else cls
if not issubclass(target, cls):
target = cls
return target._read_fields(root) # type: ignore[return-value]

@classmethod
def _read_fields(cls: type[T], element: etree.Element) -> T:
# Iterate over the fields and decode them, constructing the class instance.
hints = cls._hints()
by_name = {c.get("name"): c for c in element if c.tag == ITEM_TAG}
kwargs: dict[str, Any] = {}
for f in fields(cls): # type: ignore[arg-type]
if f.init and f.name in by_name:
kwargs[f.name] = cls._decode(hints[f.name], by_name[f.name])
return cls(**kwargs) # type: ignore[call-arg]

@classmethod
def _decode(cls, type_: Any, element: etree.Element) -> Any:
# Main decode method. This will take the type as defined by the dataclass definition, and the element
# which is to be decoded, and decode it based on this type info.
# The result will be a concrete python object with the value.
type_ = _strip_optional(type_)

if _is_list(type_):
(item_tp,) = typing.get_args(type_) or (Any,)
return [cls._decode(item_tp, c) for c in element if c.tag == ITEM_TAG]

if isinstance(type_, type) and issubclass(type_, XmlMixin):
# `value` holds the concrete class name, allowing subclasses.
target = cls._registry.get(element.get("value", ""), type_)
if not issubclass(target, type_):
target = type_
return target._read_fields(element)

# Read the raw value from the xml and convert to a python type.
raw = element.get("value", "")
if type_ is bool:
return raw.strip().lower() in ("true", "1", "yes")
if isinstance(type_, type) and issubclass(type_, Enum):
return type_[raw]
if type_ in (int, float, str):
return type_(raw)
if type_ is Any:
return raw
return type_(raw)

@classmethod
def read(cls: type[T], source: str | PathLike[str] | typing.IO[bytes]) -> T:
"""Read the class data from a source file."""
tree = etree.parse(source)
if (root := tree.getroot()) is not None:
return cls._from_element(root)
else:
raise ValueError("Root of tree cannot be empty.")

@classmethod
def from_string(cls: type[T], text: str | bytes) -> T:
"""Read the class data from the string representation."""
return cls._from_element(etree.fromstring(text))

def to_string(self) -> str:
"""Write the current object to a string."""
root = etree.Element(ROOT_TAG, template=type(self).__name__)
self._write_fields(root)
etree.indent(root, space=" ")
return XML_DECLARATION + etree.tostring(root, encoding="unicode") + "\n"

def write(self, path: str | PathLike[str]):
"""Write the current object to the provided file path."""
with open(path, "w", newline="\n") as f:
f.write(self.to_string())
12 changes: 12 additions & 0 deletions nmspy/data/xml_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from dataclasses import dataclass, field

from nmspy.data.xml_mixin import XmlMixin


@dataclass
class mdModInfo(XmlMixin):
Name: str = ""
Authors: list[str] = field(default_factory=list)
Description: str = ""
Version: str = ""
IncludedMods: list["mdModInfo"] | None = None
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ classifiers = [
dependencies = [
"pymhf[http_api,gui]==0.2.5"
]
version = "184069.0"
version = "184271.0"

[dependency-groups]
dev = [
Expand Down
Loading
Loading