diff --git a/CHANGELOG.md b/CHANGELOG.md index e190aed..753fd96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +# Unreleased + +- Speed up installed VPK indexing and primary animation graph lookup without changing asset validation or graph collision handling. +- Reuse the evaluated Blender scene for all character checks at a given frame and prepare cloth proxy skinning data once per rig. +- Reuse the checked shader inventory between models and carry verified map file identities from the export worker to Blender. +- Write sprite and trail particle curves in batches and keep visibility keys at lifetime transitions. + # 0.3.0b36 - Midtown from deadlockrigs 1.0.7 - Build maps with Sirsyorrz's deadlockrigs release 1.0.7 and the official Source 2 Viewer 21.1 release, both run unmodified. Map > Build from game downloads and checks them. diff --git a/agr/animation.py b/agr/animation.py index ee0e963..c782ac3 100644 --- a/agr/animation.py +++ b/agr/animation.py @@ -134,7 +134,7 @@ def __init__(self, table: dict): self.tick = -float('inf') self.cached = None - def at(self, tick: int) -> tuple[dict, list[str]]: + def at(self, tick: int) -> tuple[dict, list[str], dict[int, list[str]]]: if tick < self.tick: raise AnimationError('Recipe input is not ordered by replay tick') self.tick = tick @@ -151,7 +151,11 @@ def at(self, tick: int) -> tuple[dict, list[str]]: raise AnimationError('Animation task registry is empty or sparse') assets = {r['name']: self.parse_asset(r) for r in self.state.get('AnimAssetData', {}).values()} - self.cached = assets, [tasks[i]['name'] for i in range(len(tasks))] + graphs_by_id: dict[int, list[str]] = {} + for name in assets: + if name.endswith('.vnmgraph'): + graphs_by_id.setdefault(resource_id(name), []).append(name) + self.cached = assets, [tasks[i]['name'] for i in range(len(tasks))], graphs_by_id return self.cached @@ -538,9 +542,9 @@ def evaluate_segment(segment_path: Path, output: Path, assets: Path, for row in selected_raw: if row['demo_tick'] > desired[-1]: break - recorded, registry = timeline.at(row['demo_tick']) + recorded, registry, graphs_by_id = timeline.at(row['demo_tick']) primary = int(_field(row, 'm_primaryGraphId')) - matches = [g for g in recorded if g.endswith('.vnmgraph') and resource_id(g) == primary] + matches = graphs_by_id.get(primary, ()) if len(matches) != 1: raise AnimationError(f'Asset pack has no graph/skeleton mapping for primary graph ID {primary}') current = matches[0] diff --git a/agr/asset_converter.py b/agr/asset_converter.py index bf3822c..aa7c2e0 100644 --- a/agr/asset_converter.py +++ b/agr/asset_converter.py @@ -189,9 +189,10 @@ def model(self, resource_path, provider): # Material texture channels are discovered from compiled shader files, # not just RERL dependencies. Without these, VRF can silently omit normal # textures and mispack roughness while still producing a valid GLB. - shaders = sorted(p for p in provider.resources if p.endswith('.vcs')) - for path in shaders: - resolved = provider.resolve(path) + inventory = getattr(provider, 'compiled_shaders', None) + shaders = inventory() if inventory else tuple( + provider.resolve(path) for path in sorted(provider.resources) if path.endswith('.vcs')) + for resolved in shaders: records[resolved.resource_path] = resolved inputs = {p: r.sha256 for p, r in sorted(records.items())} settings = {'format': 'glb', 'materials': True, 'rig': True, @@ -204,7 +205,21 @@ def build(temp): for p, resolved in records.items(): target = tree / p target.parent.mkdir(parents=True, exist_ok=True) - shutil.copyfile(resolved.local_path, target) + if p.endswith('.vcs'): + try: + shader = resolved.local_path.read_bytes() + except FileNotFoundError: + shader = None + if shader is None or hashlib.sha256(shader).hexdigest() != resolved.sha256: + refreshed = provider.resolve(p) + if refreshed.sha256 != resolved.sha256: + raise ConversionError(f'Game shader changed during model conversion: {p}') + shader = refreshed.local_path.read_bytes() + if hashlib.sha256(shader).hexdigest() != resolved.sha256: + raise ConversionError(f'Cached game shader changed during model conversion: {p}') + target.write_bytes(shader) + else: + shutil.copyfile(resolved.local_path, target) gameinfo = tree / 'gameinfo.gi' # VRF's --game loader does not expand this engine token for loose # cache trees. An explicit private path works on both drive layouts. diff --git a/agr/blender_fe_proxy_bones.py b/agr/blender_fe_proxy_bones.py index 4a0f8cd..3ed0a96 100644 --- a/agr/blender_fe_proxy_bones.py +++ b/agr/blender_fe_proxy_bones.py @@ -7,7 +7,7 @@ def bake_fe_proxy_bones(rig, definition, frames, fps, collection=None, *, unit_s import bpy import numpy as np from mathutils import Matrix, Quaternion, Vector - from .fe_proxy_bones import proxy_bone_outputs, uniform_proxy_colliders, weighted_rigid_delta, skin_proxy_goals, project_proxy_rods + from .fe_proxy_bones import ProxyGoalSkinner, proxy_bone_outputs, uniform_proxy_colliders, weighted_rigid_delta, project_proxy_rods from .cloth_proxy_settings import proxy_pin_weights from .blender_fe_proxy import _capsule_mesh from .blender_scene import _curve @@ -78,11 +78,12 @@ def source_matrix(row): pin=proxy.vertex_groups.new(name='AGR authored proxy goal pins') for i,weight in enumerate(proxy_pin_weights(data,definition.get('blender_goal_pins','authored_strength'))): if weight>0:pin.add([i],weight,'REPLACE') + skinner = ProxyGoalSkinner(data, rig.data.bones.keys(), unit_scale) poses=[];worlds=[];goals=[] for frame in frames: scene.frame_set(frame);bpy.context.view_layer.update() poses.append({bone.name:bone.matrix.copy() for bone in rig.pose.bones});worlds.append(rig.matrix_world.copy()) - goals.append(skin_proxy_goals(data,poses[-1],unit_scale)) + goals.append(skinner.evaluate(poses[-1])) # Cloth pins follow exact DMX-inverse-bind skinning. The independently # imported rig can relocate weapon bones, so its rest inverse is invalid # for these source-space proxy vertices. diff --git a/agr/blender_scene.py b/agr/blender_scene.py index 1eba792..b90483d 100644 --- a/agr/blender_scene.py +++ b/agr/blender_scene.py @@ -123,6 +123,8 @@ def _init_blender(): def _action_channels(obj, name): + import bpy + action = bpy.data.actions.new(name) obj.animation_data_create() if hasattr(action, "slots"): @@ -136,6 +138,8 @@ def _action_channels(obj, name): def _curve(channels, obj, path, component, frames, values, constant=False, steps=None): + import numpy as np + curve = channels.new(path, index=component) curve.keyframe_points.add(len(frames)) curve.keyframe_points.foreach_set("co", np.column_stack((frames, values)).astype(np.float32).ravel()) @@ -747,11 +751,11 @@ def _review_setup(scene, positions): def build_scene(segment, assets, output, fps=64, partial=False, particle_runtime=None, shot_hero=None, character_shader=None, character_only=False, allow_partial_lighting=False, external_map=None, map_viewport_proxy=False, map_project_scene=None, pending_world_receivers=False, - shot_package=None, shot_reconstruction_map=None): + shot_package=None, shot_reconstruction_map=None, map_parent_receipt=None): _init_blender() if external_map is not None: from agr.external_map import validate_map_library - library = validate_map_library(external_map) + library = validate_map_library(external_map, parent_receipt=map_parent_receipt) if library.get('format') == 'renderlock-map-v2': from agr.blender_map_scene import build_map_first return build_map_first(build_scene, segment, assets, output, library=library, @@ -1059,13 +1063,22 @@ def mark(name): tick = marker.get("tick") if tick is not None and data["start_tick"] <= tick <= data["end_tick"]: scene.timeline_markers.new(str(marker.get("label", marker.get("name", "Replay event"))), frame=round(tick_frame(tick, data["start_tick"], data["tick_rate"], fps))) - for entry in report["entities"]: - root = bpy.data.objects[entry["root"]] + diagnostic_roots = [(entry, bpy.data.objects[entry["root"]]) + for entry in report["entities"]] + for entry, _ in diagnostic_roots: entry["transform_checks"] = [] - for frame in sorted({1.0, scene["agr_end_frame_exact"], (1 + scene["agr_end_frame_exact"]) / 2}): + if diagnostic_roots: + end_frame = scene["agr_end_frame_exact"] + for frame in sorted({1.0, end_frame, (1 + end_frame) / 2}): scene.frame_set(math.floor(frame), subframe=frame % 1) - evaluated = root.evaluated_get(bpy.context.evaluated_depsgraph_get()) - entry["transform_checks"].append({"frame": frame, "location": list(evaluated.location), "rotation_euler_radians": list(evaluated.rotation_euler), "world_matrix": [list(row) for row in evaluated.matrix_world]}) + depsgraph = bpy.context.evaluated_depsgraph_get() + for entry, root in diagnostic_roots: + evaluated = root.evaluated_get(depsgraph) + entry["transform_checks"].append({ + "frame": frame, "location": list(evaluated.location), + "rotation_euler_radians": list(evaluated.rotation_euler), + "world_matrix": [list(row) for row in evaluated.matrix_world], + }) if poses_requested: baked = sum(entry.get('pose', {}).get('status') == 'baked' for entry in report['entities']) report['coverage']['skeletal_animation'] = { @@ -1116,6 +1129,7 @@ def main(argv=None): parser.add_argument('--external-map',type=Path) parser.add_argument('--map-viewport-proxy',action='store_true') parser.add_argument('--map-project-scene',type=Path,help=argparse.SUPPRESS) + parser.add_argument('--map-parent-receipt', nargs=2, help=argparse.SUPPRESS) parser.add_argument('--map-texture-tier',choices=('auto','full','1024'),default='auto') parser.add_argument('--map-crop-margin',type=float,default=120.0) parser.add_argument('--shot-package', type=Path, @@ -1132,10 +1146,15 @@ def main(argv=None): from agr import blender_map_scene blender_map_scene.MAP_OPTIONS.update(texture_tier=args.map_texture_tier, crop_margin=args.map_crop_margin) + receipt = None + if args.external_map is not None and args.map_parent_receipt: + from agr.map_package import read_parent_receipt + receipt = read_parent_receipt(*args.map_parent_receipt) attach_blender_log(args.output) return build_scene(args.segment, args.assets, args.output, args.fps, args.partial,args.particle_runtime, args.shot_hero,args.character_shader,args.character_only,args.partial_lighting,args.external_map, args.map_viewport_proxy,args.map_project_scene, + map_parent_receipt=receipt, shot_package=args.shot_package, shot_reconstruction_map=(json.loads(args.shot_reconstruction_map.read_text(encoding='utf-8')) if args.shot_reconstruction_map else None)) diff --git a/agr/blender_simulated_effects.py b/agr/blender_simulated_effects.py index 87d32cf..0124291 100644 --- a/agr/blender_simulated_effects.py +++ b/agr/blender_simulated_effects.py @@ -264,6 +264,24 @@ def numeric(value): raise ValueError('Invalid particle age or sprite sequence') +def _write_particle_curves(obj, facing_helper, frames, values, radii, boundaries): + from .blender_scene import _action_channels, _curve + + _, channels = _action_channels(obj, obj.name + ' | particle samples') + for path, track in zip(('location', 'scale', 'rotation_quaternion', 'color'), zip(*values)): + for index, component in enumerate(zip(*track)): + _curve(channels, obj, path, index, frames, component) + if radii: + _curve(channels, obj, '["agr_trail_radius"]', 0, frames, radii) + for path in ('hide_render', 'hide_viewport'): + setattr(obj, path, True) + _curve(channels, obj, path, 0, (boundaries[0], frames[0], boundaries[1]), (1, 0, 1), constant=True) + if facing_helper is not None: + _, facing_channels = _action_channels(facing_helper, facing_helper.name + ' | particle samples') + for index, component in enumerate(zip(*(sample[0] for sample in values))): + _curve(facing_channels, facing_helper, 'location', index, frames, component) + + def collect_system_samples(simulation): """Retain live array order and empty samples for whole-system renderers.""" systems = {} @@ -854,6 +872,12 @@ def build_rope_layer(index,renderer): rotation=obj.constraints.new('COPY_ROTATION');rotation.target=facing_helper rotation.name='AGR camera facing before particle roll' rotation.mix_mode='BEFORE';rotation.owner_space='WORLD';rotation.target_space='WORLD' + first=1+(samples[0][0]-simulation['start_tick'])*frame_step;last=1+(samples[-1][0]-simulation['start_tick'])*frame_step + # Keep the legacy insertion behavior when Blender can merge nearby + # float32 keys. Light data and node socket animations keep their own actions. + boundaries = (first-frame_step, last+frame_step) + bulk = not light and frame_step >= .02 and max(map(abs, boundaries)) < frame_step * 2**20 + frames, values, radii = [], [], [] for tick,step,p in samples: frame=1+(tick-simulation['start_tick'])*frame_step obj.location=Vector(p['position'])*unit_scale @@ -885,7 +909,9 @@ def build_rope_layer(index,renderer): obj.rotation_quaternion=Vector((1,0,0)).rotation_difference(Vector(direction)) obj.location-=Vector(direction)*length*renderer.get('m_flForwardShift',0)*unit_scale obj.scale=(max(1e-9,length*unit_scale),1,max(1e-9,radius*unit_scale)) - obj['agr_trail_radius']=float(radius*unit_scale);obj.keyframe_insert('["agr_trail_radius"]',frame=frame) + obj['agr_trail_radius']=float(radius*unit_scale) + if bulk:radii.append(obj['agr_trail_radius']) + else:obj.keyframe_insert('["agr_trail_radius"]',frame=frame) else: radius=p['radius']*render_scalar(renderer.get('m_flRadiusScale'),context=context,default=1)*unit_scale obj.scale=(radius,radius,radius) @@ -893,23 +919,29 @@ def build_rope_layer(index,renderer): obj.rotation_quaternion=Vector((0,0,1)).rotation_difference(Vector(p['normal']).normalized())@Quaternion((0,0,1),p['rotation'][2]) else: facing_helper.location=obj.location - facing_helper.keyframe_insert('location',frame=frame) + if not bulk:facing_helper.keyframe_insert('location',frame=frame) obj.rotation_quaternion=Quaternion((0,0,1),p['rotation'][2]) + if bulk: + frames.append(frame) + values.append((tuple(obj.location), tuple(obj.scale), tuple(obj.rotation_quaternion), tuple(obj.color))) + continue for prop in ('location','scale','rotation_quaternion','color'):obj.keyframe_insert(prop,frame=frame) obj.hide_render=False;obj.hide_viewport=False obj.keyframe_insert('hide_render',frame=frame);obj.keyframe_insert('hide_viewport',frame=frame) - first=1+(samples[0][0]-simulation['start_tick'])*frame_step;last=1+(samples[-1][0]-simulation['start_tick'])*frame_step # Samples are one replay tick apart, regardless of output FPS. A # whole output-frame offset stretches low-FPS tails and clips high-FPS ones. - boundaries = (first-frame_step, last+frame_step) - for frame in boundaries: - obj.hide_render=True;obj.hide_viewport=True;obj.keyframe_insert('hide_render',frame=frame);obj.keyframe_insert('hide_viewport',frame=frame) + if bulk: + _write_particle_curves(obj, facing_helper, frames, values, radii, boundaries) + else: + for frame in boundaries: + obj.hide_render=True;obj.hide_viewport=True;obj.keyframe_insert('hide_render',frame=frame);obj.keyframe_insert('hide_viewport',frame=frame) if light: for frame in boundaries:data.energy=0;data.keyframe_insert('energy',frame=frame) _linear(data) if range_socket is not None:_linear(data.node_tree) - _linear(obj) - if facing_helper is not None:_linear(facing_helper) + if not bulk: + _linear(obj) + if facing_helper is not None:_linear(facing_helper) if not light: # The released renderer has literal/constant scalar support, # not the development renderer's dynamic per-sample contexts. diff --git a/agr/cli.py b/agr/cli.py index 20219fa..cabb175 100644 --- a/agr/cli.py +++ b/agr/cli.py @@ -831,6 +831,10 @@ def set_stage(name): if external_map is not None: command += ['--external-map', external_map['path']] if external_map.get('format') == 'renderlock-map-v2': + from .map_package import write_parent_receipt + receipt_path = work / 'verified-map.json' + receipt_digest = write_parent_receipt(external_map, receipt_path) + command += ['--map-parent-receipt', str(receipt_path), receipt_digest] command += ['--map-project-scene', str(output)] # Defaults also cover callers that build the arguments themselves (the app window). command += ['--map-texture-tier', getattr(args, 'map_texture_tier', None) or 'auto', diff --git a/agr/external_map.py b/agr/external_map.py index 472c7c3..eb13e3d 100644 --- a/agr/external_map.py +++ b/agr/external_map.py @@ -49,7 +49,7 @@ def validate_map_blender(report, library=None): raise ValueError('External map: choose Blender 5.2 LTS for the new prepared map workflow.') -def validate_map_library(path): +def validate_map_library(path, *, parent_receipt=None): """Require the supported unmodified download before expensive preparation.""" try: path = Path(path).expanduser().resolve() @@ -62,7 +62,7 @@ def validate_map_library(path): except (ValueError, AttributeError): prepared = False if prepared: - return map_package.library_identity(path) + return map_package.library_identity(path, parent_receipt=parent_receipt) before = path.stat() sizes = {MAP_BLEND_BYTES, *(entry['bytes'] for entry in _LEGACY_MAPS.values())} if path.suffix.lower() != '.blend' or not path.is_file() or before.st_size not in sizes: diff --git a/agr/fe_proxy_bones.py b/agr/fe_proxy_bones.py index 7a15ce7..4426f2a 100644 --- a/agr/fe_proxy_bones.py +++ b/agr/fe_proxy_bones.py @@ -11,41 +11,82 @@ def skin_proxy_goals(proxy, bone_matrices, unit_scale=.0254): cannot serve as inverse binds for an independently reconstructed FE proxy. Returned points are in the imported rig's local metre coordinate system. """ - vertices=np.asarray(proxy['vertices'],dtype=float);count=len(vertices) - binds=proxy.get('joint_rest_transforms');names=proxy['joint_names'];slots=proxy['joint_count'] - if (vertices.shape!=(count,3) or not np.isfinite(vertices).all() - or not isinstance(binds,list) or len(binds)!=len(names) - or len(set(names))!=len(names) or type(slots) is not int or not 1<=slots<=16 - or len(proxy['blend_indices'])!=count*slots or len(proxy['blend_weights'])!=count*slots - or not np.isfinite(unit_scale) or unit_scale<=0): - raise ValueError('Invalid source inverse-bind proxy arrays') - C=np.array([[0.,1,0,0],[-1.,0,0,0],[0,0,1,0],[0,0,0,1]]) - vertices=np.column_stack((vertices*unit_scale,np.ones(count)))@C.T - matrices={} - for name,row in zip(names,binds): - if name not in bone_matrices:continue - rest=np.asarray(row,dtype=float);pose=np.asarray(bone_matrices[name],dtype=float) - if (rest.shape!=(4,4) or pose.shape!=(4,4) or not np.isfinite(rest).all() - or not np.isfinite(pose).all() or abs(np.linalg.det(rest[:3,:3]))<1e-8): - raise ValueError('Invalid source proxy joint bind/pose transform') - rest=rest.copy();rest[:3,3]*=unit_scale - matrices[name]=pose@np.linalg.inv(C@rest) - points=[] - for i,vertex in enumerate(vertices): - point=np.zeros(3);total=0. - for slot in range(slots): - k=i*slots+slot;weight=proxy['blend_weights'][k];index=proxy['blend_indices'][k] - if (type(index) is not int or not 0<=index1e-8: - name=names[index] - if name not in matrices:raise ValueError('Source proxy skin bone is absent: '+name) - point+=(matrices[name]@vertex)[:3]*weight;total+=weight - if total<=1e-8 or total>1.001: + return ProxyGoalSkinner(proxy, bone_matrices, unit_scale).evaluate(bone_matrices) + + +class ProxyGoalSkinner: + """Prepare source bind and influence data once for an animated rig.""" + + def __init__(self, proxy, bone_names, unit_scale): + vertices = np.asarray(proxy['vertices'], dtype=float) + count = len(vertices) + binds = proxy.get('joint_rest_transforms') + names, slots = proxy['joint_names'], proxy['joint_count'] + indices, weights = proxy['blend_indices'], proxy['blend_weights'] + if (vertices.shape != (count, 3) or not np.isfinite(vertices).all() + or not isinstance(binds, list) or len(binds) != len(names) + or len(set(names)) != len(names) or type(slots) is not int or not 1 <= slots <= 16 + or len(indices) != count * slots or len(weights) != count * slots + or not np.isfinite(unit_scale) or unit_scale <= 0): + raise ValueError('Invalid source inverse-bind proxy arrays') + + basis = np.array([[0., 1, 0, 0], [-1., 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) + vertices = np.column_stack((vertices * unit_scale, np.ones(count))) @ basis.T + inverse_binds = {} + for name, row in zip(names, binds): + if name not in bone_names: + continue + rest = np.array(row, dtype=float) + if (rest.shape != (4, 4) or not np.isfinite(rest).all() + or abs(np.linalg.det(rest[:3, :3])) < 1e-8): + raise ValueError('Invalid source proxy joint bind/pose transform') + rest[:3, 3] *= unit_scale + inverse_binds[name] = np.linalg.inv(basis @ rest) + + if any(type(index) is not int or not 0 <= index < len(names) for index in indices): + raise ValueError('Invalid source proxy joint influence') + weights = np.asarray(weights) + if weights.shape != (count * slots,) or not np.isfinite(weights).all() or np.any(weights < 0): + raise ValueError('Invalid source proxy joint influence') + active = weights > 1e-8 + joint_indices = np.asarray(indices, dtype=np.intp)[active] + by_name = {name: i for i, name in enumerate(inverse_binds)} + matrix_indices = np.array([by_name.get(name, -1) for name in names], dtype=np.intp)[joint_indices] + missing = np.flatnonzero(matrix_indices < 0) + if missing.size: + raise ValueError('Source proxy skin bone is absent: ' + names[joint_indices[missing[0]]]) + + vertex_indices = np.flatnonzero(active) // slots + totals = np.zeros(count) + np.add.at(totals, vertex_indices, weights[active]) + if np.any(totals <= 1e-8) or np.any(totals > 1.001): raise ValueError('Source proxy skin weights have invalid total influence') - points.append(point/total) - return np.asarray(points) + + self._names = tuple(inverse_binds) + self._inverse_binds = np.asarray(list(inverse_binds.values())) + self._matrix_indices = matrix_indices + self._vertex_indices = vertex_indices + self._vertices = vertices[vertex_indices, :, None] + self._weights = weights[active, None] + self._totals = totals[:, None] + + def evaluate(self, bone_matrices): + poses = [] + for name in self._names: + if name not in bone_matrices: + raise ValueError('Source proxy skin bone is absent: ' + name) + pose = np.asarray(bone_matrices[name], dtype=float) + if pose.shape != (4, 4) or not np.isfinite(pose).all(): + raise ValueError('Invalid source proxy joint bind/pose transform') + poses.append(pose) + if not len(self._totals): + return np.empty(0) + + transforms = np.asarray(poses) @ self._inverse_binds + transformed = (transforms[self._matrix_indices] @ self._vertices)[:, :3, 0] + points = np.zeros((len(self._totals), 3)) + np.add.at(points, self._vertex_indices, transformed * self._weights) + return points / self._totals def proxy_bone_outputs(proxy, physics): diff --git a/agr/game_assets.py b/agr/game_assets.py index cd41a90..b4740cd 100644 --- a/agr/game_assets.py +++ b/agr/game_assets.py @@ -20,6 +20,14 @@ from typing import Iterable import zlib +from .path_io import file_identity + +_RESERVED_RESOURCE_NAMES = frozenset({ + "con", "prn", "aux", "nul", *(f"com{i}" for i in range(1, 10)), + *(f"lpt{i}" for i in range(1, 10)), +}) +_FORBIDDEN_RESOURCE_CHARACTERS = re.compile(r'[\x00-\x1f<>"|?*]') + class GameAssetError(ValueError): """A resource, installation, or cache could not be validated.""" @@ -44,15 +52,13 @@ def safe_resource_path(value: str) -> str: path = value.replace("\\", "/") if path.startswith("/") or ":" in path: raise GameAssetError(f"Absolute resource path is not allowed: {value!r}") - parts = path.split("/") - reserved = {"con", "prn", "aux", "nul", *(f"com{i}" for i in range(1, 10)), - *(f"lpt{i}" for i in range(1, 10))} - for part in parts: - if (part in ("", ".", "..") or part[-1:] in (" ", ".") - or any(ord(c) < 32 or c in '<>"|?*' for c in part) - or part.split(".", 1)[0].lower() in reserved): + if _FORBIDDEN_RESOURCE_CHARACTERS.search(path): + raise GameAssetError(f"Unsafe resource path: {value!r}") + for part in path.split("/"): + if (part in ("", ".", "..") or part.endswith((" ", ".")) + or part.partition(".")[0].lower() in _RESERVED_RESOURCE_NAMES): raise GameAssetError(f"Unsafe resource path: {value!r}") - return "/".join(parts).lower() + return path.lower() def _compiled_candidate(path: str) -> str: @@ -269,17 +275,19 @@ def assert_unchanged(self): if (st.st_size, st.st_mtime_ns) != self.signature: raise GameAssetError(f"Game archive changed during this job; restart after the update: {self.path}") + def payload_path(self, entry: VPKEntry) -> Path: + if not entry.length or entry.archive_index == 0x7FFF: + return self.path + if not self.path.name.endswith("_dir.vpk"): + raise GameAssetError(f"External VPK chunks require a _dir.vpk archive: {self.path}") + return self.path.with_name(self.path.name[:-8] + f"_{entry.archive_index:03d}.vpk") + def read(self, entry: VPKEntry) -> bytes: self.assert_unchanged() payload = b"" if entry.length: - if entry.archive_index == 0x7FFF: - path, offset = self.path, self.data_offset + entry.offset - else: - if not self.path.name.endswith("_dir.vpk"): - raise GameAssetError(f"External VPK chunks require a _dir.vpk archive: {self.path}") - path = self.path.with_name(self.path.name[:-8] + f"_{entry.archive_index:03d}.vpk") - offset = entry.offset + path = self.payload_path(entry) + offset = entry.offset + (self.data_offset if entry.archive_index == 0x7FFF else 0) if not path.is_file(): raise MissingResourceError(f"Missing numbered VPK chunk for {entry.resource_path}: {path}") before = path.stat() @@ -509,6 +517,33 @@ def resolve(self, resource_path: str) -> ResolvedResource: return ResolvedResource(entry.resource_path, path, digest, entry.archive, dependencies, PurePosixPath(entry.resource_path).suffix) + def compiled_shaders(self): + """Reuse the verified inventory within this mounted game snapshot.""" + cached = getattr(self, '_compiled_shaders', None) + if cached is not None: + records, identities = cached + try: + if all(file_identity(path) == expected for path, expected in identities.items()): + return records + except OSError: + pass + names = sorted(name for name in self.resources if name.endswith('.vcs')) + paths = set() + for name in names: + entry = self.resources[name] + paths.add(entry.archive) + paths.add(self._archives_by_path[entry.archive].payload_path(entry)) + try: + before = {path: file_identity(path) for path in paths} + except OSError: + # Resolve reports the exact resource and missing archive chunk. + return tuple(self.resolve(name) for name in names) + records = tuple(self.resolve(name) for name in names) + if any(file_identity(path) != expected for path, expected in before.items()): + raise GameAssetError('Game shader archives changed during validation; restart after the update.') + self._compiled_shaders = records, before + return records + def resource_identity(self, resource_path: str) -> dict: """Hash a CRC-verified mounted payload without materializing another copy.""" entry = self.lookup(resource_path) diff --git a/agr/installed_animation.py b/agr/installed_animation.py index 44aafb7..b8ed6c6 100644 --- a/agr/installed_animation.py +++ b/agr/installed_animation.py @@ -15,7 +15,6 @@ from .animation import (AnimationError, _bind, _field, _hash, _identity, _graph_change_error, _inside, _load_table, _read, _select_rows, _skeleton, _TableTimeline, _trim_prehistory) -from .vendor.resource_hash import resource_id def _resource(value: str, suffix: str) -> str: @@ -156,9 +155,9 @@ def get_skeleton(name): entry = None selected = [] for row in chosen: - recorded, registry = timeline.at(row['demo_tick']) + recorded, registry, graphs_by_id = timeline.at(row['demo_tick']) primary = int(_field(row, 'm_primaryGraphId')) - matches = [g for g in recorded if g.endswith('.vnmgraph') and resource_id(g) == primary] + matches = graphs_by_id.get(primary, ()) if len(matches) != 1: raise AnimationError(f'Missing or ambiguous recorded primary graph ID {primary}') graph_name = _resource(matches[0], '.vnmgraph') diff --git a/agr/map_package.py b/agr/map_package.py index 8fc95bb..e4f56a3 100644 --- a/agr/map_package.py +++ b/agr/map_package.py @@ -8,6 +8,8 @@ import re import shutil +from .path_io import file_identity + FORMAT = 'renderlock-map-v2' # deadlockrigs 1.0.7, map builder 26, run unmodified with the Source 2 Viewer 21.1 release. BUILDER_COMMIT = '74ddb41198d67f99b831e704434ffaed54528ab3' @@ -133,7 +135,46 @@ def validate_document(doc): return doc -def load_package(path): +def _accept_parent_receipt(receipt, folder, digest, doc): + if not isinstance(receipt, dict) or receipt.get('manifest_sha256') != digest or receipt.get('folder') != str(folder): + return None + rows = receipt.get('identities') + if not isinstance(rows, list) or len(rows) != len(doc['files']): + return None + identities = [] + for row, saved in zip(doc['files'], rows): + target = folder.joinpath(*relative_path(row['file']).parts).resolve() + if not target.is_relative_to(folder): + return None + actual = file_identity(target) + if saved != [str(target), list(actual)] or actual[2] != row['bytes']: + return None + identities.append((str(target), actual)) + return identities + + +def write_parent_receipt(library, destination): + package = load_package(library['path']) + key = (str(package['folder']), package['manifest_sha256']) + if package['manifest_sha256'] != library['manifest_sha256']: + raise _fail('The prepared map identity changed after it was selected.') + receipt = dict(folder=key[0], manifest_sha256=key[1], identities=_VERIFIED_PACKAGES[key]['identities']) + raw = json.dumps(receipt).encode('utf-8') + destination.write_bytes(raw) + return hashlib.sha256(raw).hexdigest() + + +def read_parent_receipt(path, digest): + try: + raw = Path(path).read_bytes() + if hashlib.sha256(raw).hexdigest() == digest: + return json.loads(raw) + except (OSError, ValueError): + pass + return None + + +def load_package(path, *, parent_receipt=None): """Require every declared byte; no basename search or caller count overrides.""" library = Path(path).expanduser().resolve() folder = library if library.is_dir() else library.parent @@ -144,27 +185,28 @@ def load_package(path): raw = manifest.read_bytes() manifest_sha256 = hashlib.sha256(raw).hexdigest() cached = _VERIFIED_PACKAGES.get((str(folder), manifest_sha256)) - identity = lambda s: (s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns) if cached is not None: try: - if all(identity(Path(name).stat()) == expected for name, expected in cached['identities']): + if all(file_identity(Path(name)) == expected for name, expected in cached['identities']): return copy.deepcopy(cached['package']) except OSError: pass doc = validate_document(json.loads(raw)) - identities = [] - for row in doc['files']: - target = folder.joinpath(*relative_path(row['file']).parts).resolve() - if not target.is_relative_to(folder): - raise _fail('A prepared map resource leaves its folder.') - before = target.stat() - if not target.is_file() or before.st_size != row['bytes'] or file_hash(target) != row['sha256']: - raise _fail('A prepared map resource is missing or changed: ' + row['file']) - after = target.stat() - if identity(before) != identity(after): - raise _fail('A prepared map resource changed during validation: ' + row['file']) - identities.append((str(target), identity(after))) - if not all(identity(Path(name).stat()) == expected for name, expected in identities): + identities = _accept_parent_receipt(parent_receipt, folder, manifest_sha256, doc) + if identities is None: + identities = [] + for row in doc['files']: + target = folder.joinpath(*relative_path(row['file']).parts).resolve() + if not target.is_relative_to(folder): + raise _fail('A prepared map resource leaves its folder.') + before = file_identity(target) + if before[2] != row['bytes'] or file_hash(target) != row['sha256']: + raise _fail('A prepared map resource is missing or changed: ' + row['file']) + after = file_identity(target) + if before != after: + raise _fail('A prepared map resource changed during validation: ' + row['file']) + identities.append((str(target), after)) + if not all(file_identity(Path(name)) == expected for name, expected in identities): raise _fail('Prepared map resources changed while validating the package.') package = dict(folder=folder, document=doc, manifest_sha256=manifest_sha256) # Repeated checks within one job reuse verified bytes only while every @@ -177,8 +219,8 @@ def load_package(path): raise _fail('Keep the complete extracted map package together, including textures, lightmaps and map-package.json.') from exc -def library_identity(path): - package = load_package(path) +def library_identity(path, *, parent_receipt=None): + package = load_package(path, parent_receipt=parent_receipt) doc = package['document'] if doc['source']['kind'] == 'hosted_snapshot' and package['manifest_sha256'] not in HOSTED_MANIFESTS: raise _fail('This hosted map snapshot is not qualified by this RenderLock version.') diff --git a/agr/path_io.py b/agr/path_io.py index e1bdf5c..bebc371 100644 --- a/agr/path_io.py +++ b/agr/path_io.py @@ -2,6 +2,21 @@ from __future__ import annotations import os +import stat + +if os.name == 'nt': + import ctypes + from ctypes import wintypes + from msvcrt import get_osfhandle + + class _FileBasicInfo(ctypes.Structure): + _fields_ = [(name, ctypes.c_int64) for name in + ('creation_time', 'access_time', 'write_time', 'change_time')] + _fields_.append(('attributes', wintypes.DWORD)) + + _get_file_info = ctypes.WinDLL('kernel32', use_last_error=True).GetFileInformationByHandleEx + _get_file_info.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) + _get_file_info.restype = wintypes.BOOL def native_path(path): @@ -20,3 +35,20 @@ def native_path(path): if absolute.startswith("\\\\"): return "\\\\?\\UNC\\" + absolute[2:] return "\\\\?\\" + absolute + + +def file_identity(path): + """Return the current identity of a regular file, including metadata changes.""" + if os.name == 'nt': + with open(native_path(path), 'rb', buffering=0) as stream: + info = _FileBasicInfo() + if not _get_file_info(get_osfhandle(stream.fileno()), 0, ctypes.byref(info), ctypes.sizeof(info)): + raise ctypes.WinError(ctypes.get_last_error()) + details = os.fstat(stream.fileno()) + changed = info.change_time # Windows stat's ctime is creation time. + else: + details = os.stat(path) + changed = details.st_ctime_ns + if not stat.S_ISREG(details.st_mode): + raise OSError(f'Expected a regular file: {path}') + return details.st_dev, details.st_ino, details.st_size, details.st_mtime_ns, changed diff --git a/tests/test_animation.py b/tests/test_animation.py index b784c13..c957290 100644 --- a/tests/test_animation.py +++ b/tests/test_animation.py @@ -8,7 +8,7 @@ import numpy as np import pytest -from agr.animation import AnimationError, _bind, _bone_name_aliases, evaluate_segment +from agr.animation import AnimationError, _bind, _bone_name_aliases, _TableTimeline, evaluate_segment from agr.vendor.resource_hash import resource_id @@ -303,3 +303,26 @@ def test_earlier_table_snapshot_used_before_later_update(workspace): path = evaluate_segment(inputs/'segment.json', root/'output', assets) with np.load(json.loads(path.read_text())['entities'][0]['pose_file']) as poses: assert poses['t'][0,0,0] == 10. + + +def test_graph_index_preserves_collisions_and_tracks_table_updates(workspace): + root, assets, inputs = workspace + table = json.loads((inputs/'animation_tables.json').read_text()) + graph = table['initial_tables']['AnimAssetData'][0] + collision = dict(graph, index=2, name='graphs/TEST.vnmgraph') + replacement = dict(collision, name='graphs/other.vnmgraph') + table['animation_table_updates'] = [ + dict(collision, tick=11, table='AnimAssetData'), + dict(replacement, tick=12, table='AnimAssetData'), + ] + timeline = _TableTimeline(table) + primary = resource_id(graph['name']) + assert timeline.at(10)[2][primary] == [graph['name']] + assert timeline.at(11)[2][primary] == [graph['name'], collision['name']] + assert timeline.at(12)[2] == { + primary: [graph['name']], + resource_id(replacement['name']): [replacement['name']], + } + write(inputs/'animation_tables.json', table) + with pytest.raises(AnimationError, match='has no graph/skeleton mapping'): + evaluate_segment(inputs/'segment.json', root/'output', assets) diff --git a/tests/test_fe_proxy_bones.py b/tests/test_fe_proxy_bones.py index e0aaeb1..77df6b9 100644 --- a/tests/test_fe_proxy_bones.py +++ b/tests/test_fe_proxy_bones.py @@ -1,7 +1,7 @@ import numpy as np import pytest -from agr.fe_proxy_bones import proxy_bone_outputs, uniform_proxy_colliders, weighted_rigid_delta, skin_proxy_goals, project_proxy_rods +from agr.fe_proxy_bones import ProxyGoalSkinner, proxy_bone_outputs, uniform_proxy_colliders, weighted_rigid_delta, skin_proxy_goals, project_proxy_rods def fixture(): @@ -66,6 +66,29 @@ def test_attachment_goals_use_source_inverse_bind_after_importer_relocates_rig() skin_proxy_goals(proxy,{}) +def test_prepared_skinner_reuses_influences_with_new_poses(): + identity = np.eye(4) + rest = identity.copy() + rest[:3, 3] = [2., 0., 0.] + proxy = dict(vertices=[[3., 2., 0.], [2., 0., 0.]], + joint_names=['a', 'b', 'unused'], joint_count=3, + joint_rest_transforms=[identity.tolist(), rest.tolist(), []], + blend_indices=[1, 0, 1, 1, 0, 2], + blend_weights=[.2, .5, .1, .2, .6, 1e-9]) + skinner = ProxyGoalSkinner(proxy, {'a', 'b'}, 1.) + for offset in (4., -6.): + pose = identity.copy() + pose[:3, 3] = [offset, 0., 0.] + goals = skinner.evaluate({'a': identity, 'b': pose}) + expected = [[3. + .3 / .8 * (offset - 2.), 2., 0.], + [2. + .2 / .8 * (offset - 2.), 0., 0.]] + np.testing.assert_allclose(goals, expected, atol=1e-12) + with pytest.raises(ValueError, match='joint bind/pose transform'): + skinner.evaluate({'a': identity, 'b': np.full((4, 4), np.nan)}) + with pytest.raises(ValueError, match='skin bone is absent: b'): + skinner.evaluate({'a': identity}) + + def test_authored_proxy_rods_retain_exact_domain_lengths_and_pinned_endpoints(): proxy=dict(vertices=[[0,0,0],[1,0,0],[2,0,0]],fe_node_indices=[0,1,2]) physics={'m_pFeModel':dict(m_NodeInvMasses=[0,1,1],m_Rods=[ diff --git a/tests/test_game_assets.py b/tests/test_game_assets.py index 9625fb6..4c91238 100644 --- a/tests/test_game_assets.py +++ b/tests/test_game_assets.py @@ -200,6 +200,28 @@ def test_cache_verification_update_retains_old_content_and_no_hardlinks(tmp_path assert first.local_path.read_bytes() == compiled() +def test_shader_inventory_reuses_payload_and_rechecks_changed_chunk(tmp_path, monkeypatch): + root = installation(tmp_path, {'shader/test.vcs': b'original'}, external=True) + provider = GameAssetProvider(root, tmp_path / 'cache') + read = VPKArchive.read + calls = [] + + def tracked_read(archive, entry): + calls.append(entry.resource_path) + return read(archive, entry) + + monkeypatch.setattr(VPKArchive, 'read', tracked_read) + first = provider.compiled_shaders() + assert provider.compiled_shaders() == first + assert calls == ['shader/test.vcs'] + chunk = root / 'game/citadel/pak01_000.vpk' + saved = chunk.stat() + chunk.write_bytes(b'changed!') + os.utime(chunk, ns=(saved.st_atime_ns, saved.st_mtime_ns)) + with pytest.raises(GameAssetError, match='CRC32 mismatch'): + provider.compiled_shaders() + + def test_crc_and_numbered_chunk_missing_are_explicit(tmp_path): root = installation(tmp_path, {"models/test.vmdl_c": compiled()}, external=True) provider = GameAssetProvider(root, tmp_path / "cache") @@ -214,9 +236,25 @@ def test_crc_and_numbered_chunk_missing_are_explicit(tmp_path): assert report["missing"] and "numbered VPK chunk" in report["missing"][0]["reason"] -def test_reject_unsafe_resource_paths(): - with pytest.raises(GameAssetError): - safe_resource_path("x/../../escape") +@pytest.mark.parametrize(("path", "message"), [ + ("x/../../escape", "Unsafe"), + ("C:/absolute", "Absolute"), + ("/absolute", "Absolute"), + ("x//empty", "Unsafe"), + ("x/LPT9.vmdl_c", "Unsafe"), + ("x/trailing./model", "Unsafe"), + ("x/trailing /model", "Unsafe"), + ("x/needle?", "Unsafe"), + ("x/control\x1f", "Unsafe"), + ("x/null\x00", "Invalid"), +]) +def test_reject_unsafe_resource_paths(path, message): + with pytest.raises(GameAssetError, match=message): + safe_resource_path(path) + + +def test_resource_paths_keep_canonical_names(): + assert safe_resource_path("Models\\Rem/COM0.VMDL_C") == "models/rem/com0.vmdl_c" def test_index_rejects_traversal_duplicate_and_bad_bounds(tmp_path): diff --git a/tests/test_prepared_map_package.py b/tests/test_prepared_map_package.py index 1c4e634..d3502a8 100644 --- a/tests/test_prepared_map_package.py +++ b/tests/test_prepared_map_package.py @@ -1,6 +1,7 @@ import copy import hashlib import json +import os import pytest @@ -42,6 +43,36 @@ def test_portable_local_package_verifies_every_file_and_ignores_caller_inventory assert packages.library_identity(moved/packages.LIBRARY)['sha256']==doc['library']['sha256'] +def test_parent_receipt_skips_hashing_only_the_unchanged_package(prepared, tmp_path, monkeypatch): + folder, _ = prepared + library = folder / packages.LIBRARY + expected = packages.library_identity(library) + receipt_file = tmp_path / 'verified.json' + digest = packages.write_parent_receipt(expected, receipt_file) + receipt = packages.read_parent_receipt(receipt_file, digest) + assert receipt is not None + receipt_file.write_bytes(receipt_file.read_bytes() + b' ') + assert packages.read_parent_receipt(receipt_file, digest) is None + monkeypatch.setattr(packages, '_VERIFIED_PACKAGES', {}) + paths = [] + original = packages.file_hash + + def tracked_hash(path): + paths.append(path.name) + return original(path) + + monkeypatch.setattr(packages, 'file_hash', tracked_hash) + assert packages.library_identity(library, parent_receipt=receipt) == expected + assert paths == [] + texture = folder / 'textures/wall.png' + saved = texture.stat() + texture.write_bytes(b'fixture PIXELS') + os.utime(texture, ns=(saved.st_atime_ns, saved.st_mtime_ns)) + with pytest.raises(ValueError, match='resource is missing or changed'): + packages.library_identity(library, parent_receipt=receipt) + assert 'wall.png' in paths + + @pytest.mark.parametrize('change',['changed']) def test_broken_package_is_refused_before_blender(prepared,change): folder,doc=prepared