cs2df 3.0.3__tar.gz → 3.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {cs2df-3.0.3 → cs2df-3.1.0}/PKG-INFO +1 -1
- {cs2df-3.0.3 → cs2df-3.1.0}/pyproject.toml +1 -1
- {cs2df-3.0.3 → cs2df-3.1.0}/src/cs2df/__init__.py +1 -1
- {cs2df-3.0.3 → cs2df-3.1.0}/src/cs2df/cli.py +21 -12
- {cs2df-3.0.3 → cs2df-3.1.0}/src/cs2df/events.py +7 -1
- cs2df-3.1.0/src/cs2df/merge.py +189 -0
- {cs2df-3.0.3 → cs2df-3.1.0}/src/cs2df/package.py +36 -0
- {cs2df-3.0.3 → cs2df-3.1.0}/src/cs2df/parse.py +2 -3
- {cs2df-3.0.3 → cs2df-3.1.0}/src/cs2df/streams.py +9 -48
- cs2df-3.1.0/tests/test_merge.py +68 -0
- {cs2df-3.0.3 → cs2df-3.1.0}/tests/test_replay_boundaries.py +27 -0
- {cs2df-3.0.3 → cs2df-3.1.0}/uv.lock +1 -1
- {cs2df-3.0.3 → cs2df-3.1.0}/.gitignore +0 -0
- {cs2df-3.0.3 → cs2df-3.1.0}/README.md +0 -0
- {cs2df-3.0.3 → cs2df-3.1.0}/src/cs2df/enums.py +0 -0
- {cs2df-3.0.3 → cs2df-3.1.0}/src/cs2df/rounds.py +0 -0
- {cs2df-3.0.3 → cs2df-3.1.0}/src/cs2df/validate.py +0 -0
- {cs2df-3.0.3 → cs2df-3.1.0}/tests/test_cli_batch.py +0 -0
- {cs2df-3.0.3 → cs2df-3.1.0}/tests/test_round_windows.py +0 -0
- {cs2df-3.0.3 → cs2df-3.1.0}/tests/test_version_consistency.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: cs2df
|
|
3
|
-
Version: 3.0
|
|
3
|
+
Version: 3.1.0
|
|
4
4
|
Summary: Reference exporter & validator CLI for cs2-demo-format v3 (CS2 demo → ZIP data package)
|
|
5
5
|
Project-URL: Homepage, https://github.com/Starfie1d1272/cs2-demo-format
|
|
6
6
|
Project-URL: Repository, https://github.com/Starfie1d1272/cs2-demo-format
|
|
@@ -12,6 +12,7 @@ import argparse
|
|
|
12
12
|
import builtins
|
|
13
13
|
import json
|
|
14
14
|
import os
|
|
15
|
+
import re
|
|
15
16
|
import sys
|
|
16
17
|
import time
|
|
17
18
|
from concurrent.futures import ProcessPoolExecutor, as_completed
|
|
@@ -27,7 +28,9 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
27
28
|
sub = parser.add_subparsers(dest="command", required=True)
|
|
28
29
|
|
|
29
30
|
p_exp = sub.add_parser("export", help="export a CS2 .dem to a v3 ZIP package")
|
|
30
|
-
p_exp.add_argument("demo",
|
|
31
|
+
p_exp.add_argument("demo", nargs="+",
|
|
32
|
+
help="path to the .dem file; pass multiple split parts "
|
|
33
|
+
"(…-p1.dem …-p2.dem) of ONE match to merge them")
|
|
31
34
|
p_exp.add_argument("-o", "--output", default=None,
|
|
32
35
|
help="output zip path (default: <demo>.zip next to the input)")
|
|
33
36
|
p_exp.add_argument("--research", action="store_true",
|
|
@@ -78,16 +81,20 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
78
81
|
|
|
79
82
|
|
|
80
83
|
def _cmd_export(args) -> int:
|
|
81
|
-
from .package import
|
|
84
|
+
from .package import export_demo_merged
|
|
82
85
|
|
|
83
|
-
|
|
84
|
-
if not
|
|
85
|
-
|
|
86
|
+
dems = [Path(d) for d in args.demo]
|
|
87
|
+
missing = [str(d) for d in dems if not d.exists()]
|
|
88
|
+
if missing:
|
|
89
|
+
print(f"ERROR: demo not found: {', '.join(missing)}", file=sys.stderr)
|
|
86
90
|
return 1
|
|
87
91
|
if not _compress_level_ok(args.compress_level):
|
|
88
92
|
print("ERROR: --compress-level must be between 0 and 9", file=sys.stderr)
|
|
89
93
|
return 1
|
|
90
|
-
|
|
94
|
+
# 多段合并时输出名去掉 -pN 后缀,落到第一段同目录。
|
|
95
|
+
first = dems[0]
|
|
96
|
+
default_stem = re.sub(r"-p\d+$", "", first.stem)
|
|
97
|
+
out = Path(args.output) if args.output else first.with_name(default_stem + ".zip")
|
|
91
98
|
|
|
92
99
|
t0 = time.perf_counter()
|
|
93
100
|
progress = None
|
|
@@ -95,12 +102,14 @@ def _cmd_export(args) -> int:
|
|
|
95
102
|
def progress(stage: str, frac: float) -> None:
|
|
96
103
|
print(f" [{frac * 100:5.1f}%] {stage}")
|
|
97
104
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
105
|
+
if len(dems) > 1:
|
|
106
|
+
print(f"合并 {len(dems)} 段 → {out.name}")
|
|
107
|
+
data, _match_meta = export_demo_merged([str(d) for d in dems], research=args.research,
|
|
108
|
+
sample_rate=args.sample_rate,
|
|
109
|
+
window_before_ms=args.window_before,
|
|
110
|
+
window_after_ms=args.window_after,
|
|
111
|
+
compress_level=args.compress_level,
|
|
112
|
+
progress=progress)
|
|
104
113
|
out.write_bytes(data)
|
|
105
114
|
dt = time.perf_counter() - t0
|
|
106
115
|
print(f"wrote {out} ({len(data) / 1e6:.2f} MB) in {dt:.1f}s")
|
|
@@ -160,7 +160,13 @@ def build_players(raw: dict) -> PlayerDirectory:
|
|
|
160
160
|
if not sid or sid in seen or not _is_valid_steamid(sid):
|
|
161
161
|
continue
|
|
162
162
|
seen.add(sid)
|
|
163
|
-
|
|
163
|
+
# team_num 可能为 NaN(polars float 缺失列)——典型是有合法 steamid 但无队伍的
|
|
164
|
+
# 教练/观察员。注意 NaN 在 Python 中为真值,`NaN or 0` 仍是 NaN,int(NaN) 会抛
|
|
165
|
+
# ValueError,必须显式判 None/NaN 后跳过(等价于无 teamKey)。
|
|
166
|
+
tn = r.get("team_num")
|
|
167
|
+
if tn is None or tn != tn:
|
|
168
|
+
continue
|
|
169
|
+
team_key = team_num_to_key.get(int(tn))
|
|
164
170
|
if not team_key:
|
|
165
171
|
continue
|
|
166
172
|
out.append({"steamId64": sid, "name": str(r.get("name") or sid), "teamKey": team_key})
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Merge split GOTV recordings of ONE match into a single parse_demo() output.
|
|
2
|
+
|
|
3
|
+
HLTV occasionally splits one match's GOTV demo into parts (``…-p1.dem``,
|
|
4
|
+
``…-p2.dem``). Across parts the round COUNTER is global (part 2 already starts at
|
|
5
|
+
round 3), but the TICK clock restarts from ~0 in every file. We therefore:
|
|
6
|
+
|
|
7
|
+
1. parse each part with :func:`cs2df.parse.parse_demo`;
|
|
8
|
+
2. shift every tick in each later part past the previous parts' span, so the
|
|
9
|
+
merged timeline is strictly monotonic (within-part tick deltas — and thus
|
|
10
|
+
reaction times, round spans, duel windows — are preserved by a constant shift);
|
|
11
|
+
3. concatenate the event streams and per-frame DataFrames;
|
|
12
|
+
4. keep match metadata / roster from the first part (the true match start).
|
|
13
|
+
|
|
14
|
+
The merged dict has the exact shape :func:`parse_demo` returns, so
|
|
15
|
+
:func:`cs2df.package.build_package` re-derives coherent per-match artifacts
|
|
16
|
+
(player-stats, clutches, …) over the union — no per-artifact merge logic needed.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
# Metadata / roster taken from the first part, never shifted or concatenated.
|
|
24
|
+
_META_FIRST = {
|
|
25
|
+
"_timings", "header", "tickrate", "sample_rate", "match_start_tick",
|
|
26
|
+
"team_a_name", "team_b_name", "player_info",
|
|
27
|
+
}
|
|
28
|
+
# Event lists: list[dict]; shift any of these tick-bearing keys present on a row.
|
|
29
|
+
_EVENT_LISTS = {
|
|
30
|
+
"round_starts", "round_freeze_ends", "round_ends",
|
|
31
|
+
"deaths", "hurts", "fires", "blinds",
|
|
32
|
+
"bomb_planted", "bomb_defused", "bomb_exploded", "bomb_beginplant",
|
|
33
|
+
"bomb_begindefuse", "bomb_dropped", "bomb_pickup",
|
|
34
|
+
"grenade_detonations", "inferno_expires", "smoke_expires",
|
|
35
|
+
"grenade_throws", "grenade_trajectories",
|
|
36
|
+
"round_side_samples", "economy_raw",
|
|
37
|
+
}
|
|
38
|
+
_ROW_TICK_KEYS = ("tick", "destroy_tick", "start_tick")
|
|
39
|
+
# Round-structure lists are ownership-filtered, never tick-trimmed; the rest are
|
|
40
|
+
# combat/effect events that get trimmed of a resumed part's pre-live residue.
|
|
41
|
+
_ROUND_LISTS = {"round_starts", "round_freeze_ends", "round_ends"}
|
|
42
|
+
_DF_KEYS = {"fire_velocity_df", "replay_df", "duel_df"}
|
|
43
|
+
_INT_TICK_LISTS = {"replay_ticks", "freeze_ticks"}
|
|
44
|
+
_WINDOW_LISTS = {"duel_windows"} # list[tuple[start, end]]
|
|
45
|
+
|
|
46
|
+
# Inter-part gap, in seconds, inserted between segments so spans never touch.
|
|
47
|
+
_GAP_SECONDS = 8
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _round_of(row: dict[str, Any], is_end: bool) -> int:
|
|
51
|
+
"""Actual round number for a round_* event from its total_rounds_played.
|
|
52
|
+
|
|
53
|
+
total_rounds_played at round_end == that round's number; at round_start /
|
|
54
|
+
round_freeze_end it is N-1 for round N. Mirrors cs2df.rounds._rn semantics.
|
|
55
|
+
"""
|
|
56
|
+
trp = int(row.get("total_rounds_played") or 0)
|
|
57
|
+
return trp if is_end else trp + 1
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _max_tick(raw: dict[str, Any]) -> int:
|
|
61
|
+
"""Largest tick observed in a part (used to compute the next part's offset)."""
|
|
62
|
+
cands = [0]
|
|
63
|
+
for key in ("round_ends", "round_freeze_ends", "grenade_throws"):
|
|
64
|
+
for row in raw.get(key) or []:
|
|
65
|
+
for tk in ("tick", "destroy_tick"):
|
|
66
|
+
v = row.get(tk)
|
|
67
|
+
if isinstance(v, (int, float)) and v > 0:
|
|
68
|
+
cands.append(int(v))
|
|
69
|
+
for key in _INT_TICK_LISTS:
|
|
70
|
+
cands.extend(int(t) for t in (raw.get(key) or []) if t)
|
|
71
|
+
for key in _DF_KEYS:
|
|
72
|
+
df = raw.get(key)
|
|
73
|
+
if df is not None and hasattr(df, "columns") and "tick" in getattr(df, "columns", []) and len(df):
|
|
74
|
+
cands.append(int(df["tick"].max()))
|
|
75
|
+
return max(cands)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _shift_part(raw: dict[str, Any], off: int) -> None:
|
|
79
|
+
"""Add ``off`` to every tick in ``raw`` in place (off == 0 → no-op)."""
|
|
80
|
+
if off == 0:
|
|
81
|
+
return
|
|
82
|
+
for key in _EVENT_LISTS:
|
|
83
|
+
for row in raw.get(key) or []:
|
|
84
|
+
for tk in _ROW_TICK_KEYS:
|
|
85
|
+
v = row.get(tk)
|
|
86
|
+
if isinstance(v, (int, float)) and v > 0:
|
|
87
|
+
row[tk] = int(v) + off
|
|
88
|
+
for key in _DF_KEYS:
|
|
89
|
+
df = raw.get(key)
|
|
90
|
+
if df is not None and hasattr(df, "columns") and "tick" in getattr(df, "columns", []):
|
|
91
|
+
df = df.copy()
|
|
92
|
+
df["tick"] = df["tick"] + off
|
|
93
|
+
raw[key] = df
|
|
94
|
+
for key in _INT_TICK_LISTS:
|
|
95
|
+
lst = raw.get(key)
|
|
96
|
+
if lst:
|
|
97
|
+
raw[key] = [int(t) + off for t in lst]
|
|
98
|
+
for key in _WINDOW_LISTS:
|
|
99
|
+
lst = raw.get(key)
|
|
100
|
+
if lst:
|
|
101
|
+
raw[key] = [(int(s) + off, int(e) + off) for s, e in lst]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def merge_raw(parts: list[dict[str, Any]]) -> dict[str, Any]:
|
|
105
|
+
"""Merge per-part parse_demo() outputs into one (parts in play order)."""
|
|
106
|
+
if not parts:
|
|
107
|
+
raise ValueError("merge_raw: no parts")
|
|
108
|
+
if len(parts) == 1:
|
|
109
|
+
return parts[0]
|
|
110
|
+
|
|
111
|
+
# 1. shift each part past the previous parts' span.
|
|
112
|
+
running = 0
|
|
113
|
+
for part in parts:
|
|
114
|
+
_shift_part(part, running)
|
|
115
|
+
running += _max_tick(part) + part.get("tickrate", 64) * _GAP_SECONDS
|
|
116
|
+
|
|
117
|
+
# 1b. round ownership: a part only owns rounds past the previous parts'. When a
|
|
118
|
+
# GOTV recording resumes it re-emits a few warmup/restart round_* events with low
|
|
119
|
+
# total_rounds_played; those would collide in build_rounds' per-round tick maps
|
|
120
|
+
# (e.g. overwriting an earlier part's freeze tick and getting the seam round
|
|
121
|
+
# dropped as bogus). Drop each later part's round_* events for already-owned rounds.
|
|
122
|
+
prev_max = 0
|
|
123
|
+
for idx, part in enumerate(parts):
|
|
124
|
+
if idx > 0:
|
|
125
|
+
for key, is_end in (("round_ends", True), ("round_starts", False),
|
|
126
|
+
("round_freeze_ends", False)):
|
|
127
|
+
rows = part.get(key) or []
|
|
128
|
+
part[key] = [r for r in rows if _round_of(r, is_end) > prev_max]
|
|
129
|
+
# Trim combat/effect residue captured before this part's first live round
|
|
130
|
+
# (a resume starts mid-freeze and re-emits seam events the previous part
|
|
131
|
+
# already owns). Threshold = first owned round's freeze-end tick.
|
|
132
|
+
freezes = [int(r.get("tick") or 0) for r in part.get("round_freeze_ends") or []
|
|
133
|
+
if int(r.get("tick") or 0) > 0]
|
|
134
|
+
trim_before = min(freezes) if freezes else 0
|
|
135
|
+
if trim_before > 0:
|
|
136
|
+
for key in _EVENT_LISTS - _ROUND_LISTS:
|
|
137
|
+
rows = part.get(key) or []
|
|
138
|
+
part[key] = [r for r in rows
|
|
139
|
+
if not (0 < int(r.get("tick") or 0) < trim_before)]
|
|
140
|
+
ends = part.get("round_ends") or []
|
|
141
|
+
if ends:
|
|
142
|
+
prev_max = max([prev_max] + [_round_of(r, True) for r in ends])
|
|
143
|
+
|
|
144
|
+
# 2. assemble the merged dict.
|
|
145
|
+
merged: dict[str, Any] = {}
|
|
146
|
+
base = parts[0]
|
|
147
|
+
for key in _META_FIRST:
|
|
148
|
+
if key in base:
|
|
149
|
+
merged[key] = base[key]
|
|
150
|
+
|
|
151
|
+
for key in _EVENT_LISTS:
|
|
152
|
+
out: list[Any] = []
|
|
153
|
+
for part in parts:
|
|
154
|
+
out.extend(part.get(key) or [])
|
|
155
|
+
merged[key] = out
|
|
156
|
+
|
|
157
|
+
import pandas as pd # lazy: native dep
|
|
158
|
+
for key in _DF_KEYS:
|
|
159
|
+
frames = [part[key] for part in parts
|
|
160
|
+
if part.get(key) is not None and len(part[key])]
|
|
161
|
+
merged[key] = pd.concat(frames, ignore_index=True) if frames else base.get(key)
|
|
162
|
+
|
|
163
|
+
for key in _INT_TICK_LISTS:
|
|
164
|
+
seen: set[int] = set()
|
|
165
|
+
for part in parts:
|
|
166
|
+
seen.update(int(t) for t in (part.get(key) or []))
|
|
167
|
+
merged[key] = sorted(seen)
|
|
168
|
+
|
|
169
|
+
for key in _WINDOW_LISTS:
|
|
170
|
+
out_w: list[Any] = []
|
|
171
|
+
for part in parts:
|
|
172
|
+
out_w.extend(part.get(key) or [])
|
|
173
|
+
merged[key] = out_w
|
|
174
|
+
|
|
175
|
+
return merged
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def parse_and_merge(dem_paths: list[str], **parse_kwargs: Any) -> dict[str, Any]:
|
|
179
|
+
"""Parse each part with parse_demo() and merge into one raw dict."""
|
|
180
|
+
from .parse import parse_demo
|
|
181
|
+
progress = parse_kwargs.pop("progress", None)
|
|
182
|
+
n = len(dem_paths)
|
|
183
|
+
parts: list[dict[str, Any]] = []
|
|
184
|
+
for i, path in enumerate(dem_paths):
|
|
185
|
+
def _scaled(stage: str, frac: float, _i=i) -> None:
|
|
186
|
+
if progress is not None:
|
|
187
|
+
progress(f"[part {_i + 1}/{n}] {stage}", (_i + frac) / n)
|
|
188
|
+
parts.append(parse_demo(path, progress=_scaled if progress else None, **parse_kwargs))
|
|
189
|
+
return merge_raw(parts)
|
|
@@ -65,6 +65,42 @@ def export_demo(dem_path: str, *, research: bool = False, sample_rate: int = 8,
|
|
|
65
65
|
compress_level=compress_level)
|
|
66
66
|
|
|
67
67
|
|
|
68
|
+
def export_demo_merged(dem_paths: list[str], *, research: bool = False, sample_rate: int = 8,
|
|
69
|
+
window_before_ms: int = 2000, window_after_ms: int = 1000,
|
|
70
|
+
compress_level: int = 3,
|
|
71
|
+
progress: ProgressFn | None = None) -> tuple[bytes, dict]:
|
|
72
|
+
"""Parse several split GOTV parts of ONE match, merge, and build a single ZIP.
|
|
73
|
+
|
|
74
|
+
Use for HLTV demos split into ``…-p1.dem`` / ``…-p2.dem``: ticks are reconciled
|
|
75
|
+
onto a global timeline so the package's per-match derivations stay coherent.
|
|
76
|
+
"""
|
|
77
|
+
if len(dem_paths) == 1:
|
|
78
|
+
return export_demo(dem_paths[0], research=research, sample_rate=sample_rate,
|
|
79
|
+
window_before_ms=window_before_ms, window_after_ms=window_after_ms,
|
|
80
|
+
compress_level=compress_level, progress=progress)
|
|
81
|
+
from .merge import parse_and_merge
|
|
82
|
+
|
|
83
|
+
# Combined hash over all parts, in order, so the merged package has a stable id.
|
|
84
|
+
try:
|
|
85
|
+
h = hashlib.sha256()
|
|
86
|
+
for part in dem_paths:
|
|
87
|
+
h.update(_sha256_hex(part).encode("ascii"))
|
|
88
|
+
demo_hash: str | None = h.hexdigest()
|
|
89
|
+
except Exception:
|
|
90
|
+
demo_hash = None
|
|
91
|
+
|
|
92
|
+
scaled = (lambda stage, frac: progress(stage, frac * 0.9)) if progress else None
|
|
93
|
+
raw = parse_and_merge(list(dem_paths), sample_rate=sample_rate, research=research,
|
|
94
|
+
window_before_ms=window_before_ms,
|
|
95
|
+
window_after_ms=window_after_ms, progress=scaled)
|
|
96
|
+
if progress:
|
|
97
|
+
progress("build package", 0.92)
|
|
98
|
+
return build_package(raw, dem_paths[0], demo_hash,
|
|
99
|
+
window_before_ms=window_before_ms,
|
|
100
|
+
window_after_ms=window_after_ms,
|
|
101
|
+
compress_level=compress_level)
|
|
102
|
+
|
|
103
|
+
|
|
68
104
|
def build_package(raw: dict[str, Any], dem_path: str, demo_hash: str | None, *,
|
|
69
105
|
window_before_ms: int = 2000, window_after_ms: int = 1000,
|
|
70
106
|
compress_level: int = 3) -> tuple[bytes, dict]:
|
|
@@ -9,9 +9,8 @@ Performance notes (this module is the reference for fast producers):
|
|
|
9
9
|
~200k row dicts (`to_dict(orient="records")`), which dominated Python-side
|
|
10
10
|
time; v3's columnar layout makes that conversion unnecessary.
|
|
11
11
|
- `inventory` (a per-row list of strings, by far the most expensive tick prop)
|
|
12
|
-
is
|
|
13
|
-
|
|
14
|
-
inventory is only read at the ~24 freeze ticks for economy rows.
|
|
12
|
+
is extracted on the sampled replay grid for held utility and bomb-carrier
|
|
13
|
+
state, and at freeze ticks for economy rows.
|
|
15
14
|
- The research-profile duel windows reuse the already-parsed kill/damage ticks
|
|
16
15
|
to compute merged combat windows, then fetch them in ONE lean `parse_ticks`
|
|
17
16
|
call (6 props at full tick) instead of widening the main grid.
|
|
@@ -85,48 +85,6 @@ def _slice_by_tick(df, tick_values, start: int, end: int):
|
|
|
85
85
|
return df.iloc[left:right]
|
|
86
86
|
|
|
87
87
|
|
|
88
|
-
# ── bomb carrier timeline (replaces per-frame inventory parsing) ──────────────
|
|
89
|
-
|
|
90
|
-
def build_bomb_carrier_timeline(raw: dict, players: PlayerDirectory):
|
|
91
|
-
"""(transition_ticks, carrier_pidx) arrays for hasBomb lookups.
|
|
92
|
-
|
|
93
|
-
Derived from bomb lifecycle events: pickup → carrier, dropped/planted/
|
|
94
|
-
exploded/defused → no carrier. This replaces extracting the `inventory`
|
|
95
|
-
tick prop on the whole replay grid, which is the single most expensive
|
|
96
|
-
per-frame property in demoparser2.
|
|
97
|
-
"""
|
|
98
|
-
import numpy as np
|
|
99
|
-
|
|
100
|
-
transitions: list[tuple[int, int]] = [] # (tick, pidx or -1)
|
|
101
|
-
for rows_key, is_pickup in (("bomb_pickup", True), ("bomb_dropped", False),
|
|
102
|
-
("bomb_planted", False), ("bomb_exploded", False),
|
|
103
|
-
("bomb_defused", False)):
|
|
104
|
-
for r in raw.get(rows_key, []):
|
|
105
|
-
tick = int(r.get("tick") or 0)
|
|
106
|
-
if tick <= 0:
|
|
107
|
-
continue
|
|
108
|
-
if is_pickup:
|
|
109
|
-
idx = players.idx(_sid(r.get("user_steamid") or r.get("steamid")))
|
|
110
|
-
transitions.append((tick, idx if idx is not None else -1))
|
|
111
|
-
else:
|
|
112
|
-
transitions.append((tick, -1))
|
|
113
|
-
transitions.sort()
|
|
114
|
-
ticks = np.asarray([t for t, _ in transitions], dtype="int64")
|
|
115
|
-
carrier = np.asarray([c for _, c in transitions], dtype="int64")
|
|
116
|
-
return ticks, carrier
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
def _carrier_at(ticks, carrier, frame_ticks):
|
|
120
|
-
"""Vectorized carrier playerIndex (or -1) at each frame tick."""
|
|
121
|
-
import numpy as np
|
|
122
|
-
|
|
123
|
-
if len(ticks) == 0:
|
|
124
|
-
return np.full(len(frame_ticks), -1, dtype="int64")
|
|
125
|
-
pos = np.searchsorted(ticks, frame_ticks, side="right") - 1
|
|
126
|
-
out = np.where(pos >= 0, carrier[np.clip(pos, 0, None)], -1)
|
|
127
|
-
return out
|
|
128
|
-
|
|
129
|
-
|
|
130
88
|
# ── replay.json ───────────────────────────────────────────────────────────────
|
|
131
89
|
|
|
132
90
|
def build_replay(raw: dict, players: PlayerDirectory, round_model: _RoundModel,
|
|
@@ -155,10 +113,13 @@ def build_replay(raw: dict, players: PlayerDirectory, round_model: _RoundModel,
|
|
|
155
113
|
df["_plidx"] = df["last_place_name"].map(place_map).fillna(-1).astype("int64")
|
|
156
114
|
if "inventory" in df.columns:
|
|
157
115
|
df["_grenades"] = df["inventory"].map(lambda items: classify_inventory(items)[3])
|
|
116
|
+
df["_has_bomb"] = df["inventory"].map(
|
|
117
|
+
lambda items: isinstance(items, (list, tuple))
|
|
118
|
+
and any(normalize_weapon_name(item) == "c4" for item in items)
|
|
119
|
+
)
|
|
158
120
|
else:
|
|
159
121
|
df["_grenades"] = [[] for _ in range(len(df))]
|
|
160
|
-
|
|
161
|
-
bomb_ticks, bomb_carrier = build_bomb_carrier_timeline(raw, players)
|
|
122
|
+
df["_has_bomb"] = False
|
|
162
123
|
tick_values = df["tick"].to_numpy()
|
|
163
124
|
|
|
164
125
|
# projectile trajectories per round
|
|
@@ -190,7 +151,7 @@ def build_replay(raw: dict, players: PlayerDirectory, round_model: _RoundModel,
|
|
|
190
151
|
continue
|
|
191
152
|
player_tracks = []
|
|
192
153
|
for pidx, g in sl.groupby("_pidx", sort=True):
|
|
193
|
-
track = _player_track(g, grid, int(pidx)
|
|
154
|
+
track = _player_track(g, grid, int(pidx))
|
|
194
155
|
if track is not None:
|
|
195
156
|
player_tracks.append(track)
|
|
196
157
|
if not player_tracks:
|
|
@@ -219,7 +180,7 @@ def build_replay(raw: dict, players: PlayerDirectory, round_model: _RoundModel,
|
|
|
219
180
|
}
|
|
220
181
|
|
|
221
182
|
|
|
222
|
-
def _player_track(g, grid, pidx: int
|
|
183
|
+
def _player_track(g, grid, pidx: int) -> dict | None:
|
|
223
184
|
"""One player's columnar track aligned to the round grid.
|
|
224
185
|
|
|
225
186
|
Frames where the player has no row (dead/disconnected) repeat the last
|
|
@@ -260,8 +221,8 @@ def _player_track(g, grid, pidx: int, bomb_ticks, bomb_carrier) -> dict | None:
|
|
|
260
221
|
|
|
261
222
|
alive = (hp > 0).astype("int64")
|
|
262
223
|
has_kit = _num(aligned["has_defuser"], 0.0).to_numpy().astype(bool)
|
|
263
|
-
|
|
264
|
-
has_bomb =
|
|
224
|
+
has_bomb = aligned["_has_bomb"].fillna(False).to_numpy().astype(bool)
|
|
225
|
+
has_bomb = has_bomb & present & (alive == 1)
|
|
265
226
|
flags = (alive * FLAG_ALIVE
|
|
266
227
|
+ has_bomb.astype("int64") * FLAG_HAS_BOMB
|
|
267
228
|
+ (has_kit & present & (alive == 1)).astype("int64") * FLAG_HAS_DEFUSE_KIT)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from cs2df.merge import merge_raw
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _part(tickrate, round_ends, round_starts, round_freeze_ends, hurts):
|
|
7
|
+
return {
|
|
8
|
+
"tickrate": tickrate,
|
|
9
|
+
"round_ends": round_ends,
|
|
10
|
+
"round_starts": round_starts,
|
|
11
|
+
"round_freeze_ends": round_freeze_ends,
|
|
12
|
+
"hurts": hurts,
|
|
13
|
+
"deaths": [],
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_merge_two_parts_keeps_seam_round_shifts_ticks_and_trims_residue():
|
|
18
|
+
# Part 0 owns rounds 1-2 (total_rounds_played: end == round number).
|
|
19
|
+
part0 = _part(
|
|
20
|
+
64,
|
|
21
|
+
round_ends=[{"total_rounds_played": 1, "tick": 200},
|
|
22
|
+
{"total_rounds_played": 2, "tick": 460}],
|
|
23
|
+
round_starts=[{"total_rounds_played": 0, "tick": 50},
|
|
24
|
+
{"total_rounds_played": 1, "tick": 300}],
|
|
25
|
+
round_freeze_ends=[{"total_rounds_played": 0, "tick": 100},
|
|
26
|
+
{"total_rounds_played": 1, "tick": 360}],
|
|
27
|
+
hurts=[{"tick": 150}, {"tick": 400}],
|
|
28
|
+
)
|
|
29
|
+
# Part 1 owns rounds 3-4 with a LOCAL tick clock (restarts near 0) and resume
|
|
30
|
+
# residue: spurious low-trp round_* events (actual round 2, already owned) plus a
|
|
31
|
+
# phantom hurt at the very first tick.
|
|
32
|
+
part1 = _part(
|
|
33
|
+
64,
|
|
34
|
+
round_ends=[{"total_rounds_played": 2, "tick": 1}, # spurious (round 2)
|
|
35
|
+
{"total_rounds_played": 3, "tick": 200},
|
|
36
|
+
{"total_rounds_played": 4, "tick": 460}],
|
|
37
|
+
round_starts=[{"total_rounds_played": 1, "tick": 2}, # spurious (round 2)
|
|
38
|
+
{"total_rounds_played": 2, "tick": 5},
|
|
39
|
+
{"total_rounds_played": 3, "tick": 300}],
|
|
40
|
+
round_freeze_ends=[{"total_rounds_played": 1, "tick": 3}, # spurious
|
|
41
|
+
{"total_rounds_played": 2, "tick": 60},
|
|
42
|
+
{"total_rounds_played": 3, "tick": 360}],
|
|
43
|
+
hurts=[{"tick": 4}, {"tick": 120}, {"tick": 400}], # tick 4 == resume residue
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
merged = merge_raw([part0, part1])
|
|
47
|
+
|
|
48
|
+
# Seam round 2 survives; rounds are 1..4 with no gap/duplicate.
|
|
49
|
+
end_rounds = [int(r["total_rounds_played"]) for r in merged["round_ends"]]
|
|
50
|
+
assert end_rounds == [1, 2, 3, 4]
|
|
51
|
+
|
|
52
|
+
# Round ticks are strictly monotonic across the seam (part 1 shifted past part 0).
|
|
53
|
+
end_ticks = [r["tick"] for r in merged["round_ends"]]
|
|
54
|
+
assert end_ticks == sorted(end_ticks) and len(set(end_ticks)) == len(end_ticks)
|
|
55
|
+
assert end_ticks[1] < end_ticks[2] # part0's round 2 < part1's round 3
|
|
56
|
+
|
|
57
|
+
# Resume residue (the tick-4 phantom hurt) is trimmed; the 4 real hurts remain.
|
|
58
|
+
assert len(merged["hurts"]) == 4
|
|
59
|
+
# No hurt sits in the dead gap between part0's last tick and part1's first live round.
|
|
60
|
+
assert all(h["tick"] <= 460 or h["tick"] >= end_ticks[1] for h in merged["hurts"])
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_single_part_passthrough():
|
|
64
|
+
part = _part(64, [{"total_rounds_played": 1, "tick": 200}],
|
|
65
|
+
[{"total_rounds_played": 0, "tick": 50}],
|
|
66
|
+
[{"total_rounds_played": 0, "tick": 100}],
|
|
67
|
+
[{"tick": 150}])
|
|
68
|
+
assert merge_raw([part]) is part
|
|
@@ -54,6 +54,33 @@ def test_replay_round_extends_to_sample_before_next_round_start():
|
|
|
54
54
|
assert last_tick < 300
|
|
55
55
|
|
|
56
56
|
|
|
57
|
+
def test_replay_marks_round_start_bomb_carrier_from_inventory():
|
|
58
|
+
players = PlayerDirectory([
|
|
59
|
+
{"steamId64": "76561198000000001", "name": "p1", "teamKey": "teamA"},
|
|
60
|
+
])
|
|
61
|
+
round_model = _RoundModel(
|
|
62
|
+
windows=[
|
|
63
|
+
_RoundWindow(round_number=1, start_tick=50, freeze_end_tick=100, end_tick=200),
|
|
64
|
+
_RoundWindow(round_number=2, start_tick=300, freeze_end_tick=360, end_tick=460),
|
|
65
|
+
],
|
|
66
|
+
side_map={},
|
|
67
|
+
)
|
|
68
|
+
rows = [_replay_row(tick) for tick in range(360, 461, 16)]
|
|
69
|
+
for row in rows:
|
|
70
|
+
row["inventory"] = ["C4 Explosive"]
|
|
71
|
+
raw = {
|
|
72
|
+
"replay_df": pd.DataFrame(rows),
|
|
73
|
+
"grenade_trajectories": [],
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
replay = build_replay(raw, players, round_model, tickrate=128, sample_rate=8)
|
|
77
|
+
|
|
78
|
+
assert replay is not None
|
|
79
|
+
second_round = replay["rounds"][0]
|
|
80
|
+
assert second_round["roundNumber"] == 2
|
|
81
|
+
assert all(flags & 2 for flags in second_round["players"][0]["flags"])
|
|
82
|
+
|
|
83
|
+
|
|
57
84
|
def test_parse_replay_ticks_include_post_round_tail_before_next_start():
|
|
58
85
|
round_ends = [
|
|
59
86
|
{"total_rounds_played": 1, "tick": 200},
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|