#!/usr/bin/env bash
# Plan 46: plan 45's frame profile (tools/bin/frame-profile) over the rink's views and TICKRATEs, one
# run at a time (the GPU's times stay clean), then the table (tools/perf/profile_table.py). GAME TIMING
# UNLOCKED: 30 HZ per view; 2D and 3D FOLLOW at 60 and 240 HZ (a settings file in frame-profile's
# scratch data folder, removed after). Needs the desktop (Xvfb and its GPU).
#   tools/bin/profile-batch PREFIX [SECONDS=90] [--quick]
#     --quick   2D and 3D FOLLOW only (30, 60, 240 HZ)
# Output: out/perf/PREFIX_<run>.csv / .txt, out/perf/PREFIX.log, out/perf/PREFIX.table.
source "$(dirname "${BASH_SOURCE[0]}")/_common.sh"
prefix=""; secs=90; quick=0
while (( $# )); do
  case "$1" in
    --quick) quick=1; shift ;;
    *) if [[ -z "$prefix" ]]; then prefix="$1"; else secs="$1"; fi; shift ;;
  esac
done
[[ -n "$prefix" ]] || { echo "usage: profile-batch PREFIX [SECONDS] [--quick]" >&2; exit 2; }
here="$(dirname "${BASH_SOURCE[0]}")"
out="$MW_ROOT/out/perf"
cfg="$out/userdata/mightyweenie/settings.cfg"
log="$out/$prefix.log"
mkdir -p "$out" "$(dirname "$cfg")"
: > "$log"
runs=()
run() {  # run NAME SECONDS ARGS...
  local name="${prefix}_$1"; shift
  echo "== $(date +%T) $name $*" >> "$log"
  "$here/frame-profile" "$name" "$@" --xvfb >> "$log" 2>&1
  echo "   rc $?" >> "$log"
  runs+=("$name")
}
rate() { printf '[game]\n\ntick_rate="UNLOCKED"\ntick_hz="%s HZ"\n' "$1" > "$cfg"; }
rm -f "$cfg"
"$here/frame-profile" "${prefix}_warm" 20 --view 7 --xvfb >> "$log" 2>&1     # the disk and shader caches
run 2d "$secs" --view 0
run follow "$secs" --view 7
if (( ! quick )); then
  run 2d_wide "$secs" --view 0 --wide
  run tv "$secs" --view 2
  run cinematic "$secs" --view 6
  run ext2d "$secs" --view 9
  run ext3d "$secs" --view 8
  run follow_wide "$secs" --view 7 --wide
fi
rate 60; run 2d_60hz "$secs" --view 0; run follow_60hz "$secs" --view 7
rate 240; run 2d_240hz "$secs" --view 0; run follow_240hz "$secs" --view 7
rm -f "$cfg"
python3 "$MW_ROOT/tools/perf/profile_table.py" "$out" "${runs[@]}" | tee "$out/$prefix.table"
