diff --git a/neo/modelsrc/weapons/README.md b/neo/modelsrc/weapons/README.md index b795f6ea..ce5a8a2a 100644 --- a/neo/modelsrc/weapons/README.md +++ b/neo/modelsrc/weapons/README.md @@ -3,25 +3,235 @@ The Tachi viewmodels are the first weapons maintained under these conventions. Expect the folder layout, scripts and steps here to change as more weapons are added. -Each model has a source folder here, such as `jinrai_tachi/`, containing one `.blend` file and one `.qc` file. -The scripts take the names of the source folders to work on. +## Change an animation (quick recipe) +For example, a new pose in a slot of the Tachi. Run the commands from this folder. + +1. Open the file with the Viewmodel panel: `blender viewmodels.blend --python viewmodel_tools.py`. In the 3D + Viewport, press N and pick the **Viewmodel** tab. +2. Pick the scene `jinrai_tachi` (top right) and the slot in Dope Sheet > Action Editor > Slot. The panel shows the + slot's kind: **authored** (a new slot: edit freely) or **shipped** (keep the original; see Exporting animations). + Click **Frame range to slot**. **Team** shows the other team's arms; the same keys move both. +3. Pose and key the bones. Click **Check slot**: it selects any bone a range-of-motion limit stops. +4. If such a pose is meant: click **Free selected bones**, key the pose, then click **Widen to this slot** and type + the reason. This adds a line to `rom_widen.json` and refreshes the limits of every rig (about 8 s). +5. Click **Export gun**. It saves the file and exports the gun's project. The status bar shows the result; the + terminal has every line. Read any `PACE WARN` (Exporting animations). +6. Commit `viewmodels.blend`, the changed SMDs, and `rom_widen.json` and `rom_spec.json` if a limit was widened. + +Layout: + +- `viewmodels.blend`: the Blender file for every viewmodel. It holds one **scene** per gun, called a project: + `jinrai_tachi`. Each scene has one rig and one action, and both teams' arms (see One scene per gun). +- `PROJECT/` (such as `jinrai_tachi/`): the project's `.qc`, `reference.smd` and `anims/*.smd` (written by the + export). The scripts take project names. +- `nsf_GUN/` (such as `nsf_tachi/`): the NSF model's `.qc`, `reference.smd` and its shipped clips in `anims/`. It has + no scene and is never exported: it compiles from these SMDs. +- `GUN/viewmodel.qci` (such as `tachi/viewmodel.qci`): the QC lines both team models of a gun share. Each team's `.qc` + sets only `$modelname` and includes this file. +- `arms/textures/` (Jinrai and NSF arms, shared by every weapon) and `GUN/textures/`: preview images the `.blend` loads. +- `rom_limits.py`, `rom_spec.json` and `rom_widen.json`: the range-of-motion limits on the rigs (see + Range-of-motion limits). +- `merge_teams.py`: the one-time merge of the two team scenes of each gun into one (already applied; kept for the + record and for a gun added later with two scenes). +- `viewmodel_tools.py`: the Viewmodel sidebar panel (see Change an animation). It is not installed: load it with + `blender viewmodels.blend --python viewmodel_tools.py`, or, with the file open, Text Editor > Open > + `viewmodel_tools.py` > Run Script. It always uses the scripts beside the open `.blend`. + +Run the scripts from this folder (`neo/modelsrc/weapons`). + +Requirements: Blender 5.2.3 or newer with Blender Source Tools 3.4.3 or newer enabled; Python 3 and Valve's +`studiomdl.exe` (Source SDK Base 2013 Multiplayer) for compiling. + +### One scene per gun + +Each gun has one scene, `jinrai_GUN`: one rig (`jinrai_GUN_rig`) and one action (`jinrai_GUN_animations`). Both +teams' arm meshes are skinned to that rig, so a key moves both. Each team's mesh is in its own collection, +`jinrai_GUN_preview` and `nsf_GUN_preview`; one is visible at a time. + +- **Team toggle:** click **Team** in the Viewmodel panel, or click the eye of the two collections in the Outliner. + It changes only what the viewport shows; the export does not depend on it. +- **Author every slot and marker once**, in that scene. +- **The NSF model has no scene.** It compiles from its shipped SMDs in `nsf_GUN/anims/` (the original NSF clips, + never rewritten). +- The shipped slots (`reload`, `draw`, ...) stay the original clips. The export fails when a shipped slot's SMD would + change, unless it runs with `--edit-shipped`; then the changed clip goes to both teams (see Exporting animations). +- `reference.smd` was not changed by the merge: each team's compiled model keeps its own rest pose. + +| term | meaning | +| :-- | :-- | +| sequence | one animation the game plays, such as `reload`. One SMD file in `anims/`, one `$sequence` line in the `.qc`. | +| slot | one animation inside the single Blender action of a project. One slot becomes one SMD, named like the slot. | +| marker | a named flag on the Blender timeline. | +| flag | a plain command-line option such as `--game`. | + + +## Working in Blender + +1. Open `viewmodels.blend` and pick the project in the **Scene** selector at the top right (for example + `jinrai_tachi`). The `README_ANIMATOR` text block (Text Editor) summarizes the rules. +2. All animations of a project live in **one action** (`PROJECT_animations`, such as `jinrai_tachi_animations`), one + slot per sequence. To work on a slot: select the project's armature (`PROJECT_rig`), open an Action Editor + (Dope Sheet > Action Editor), and pick the slot in the **Slot** dropdown beside the action name. To add a slot, use + the new-slot button next to that dropdown and give it the sequence name. Do not rename existing slots: the `.qc` + and the weapon script use the names. The action browser lists every project's action; keep each rig on its own. +3. Pose the bones of the two arms: `bone forearm01` / `bone hand01` (and the finger bones under `bone hand01`) + for one arm, `bone forearm` / `bone hand` for the other, under the roots `Dummy01` and `Dummy02`. + Key them at the frames you edit. +4. Click **Team** to check the pose on the other team's arms. Save, then export (next section). + +Success looks like `EXPORTED ...` (or `KEPT ...`) for each SMD. A failure prints one `EXPORT FAILED: ...` line. + +### Preview camera + +Each scene's camera (`PROJECT_camera`) shows the viewmodel as a player sees it in game on a 16:9 screen +(1920x1080), with default settings and the player standing still. To look through it: + +1. Move the mouse over the 3D Viewport. +2. Press Numpad 0, or pick View > Cameras > Active Camera. +3. To leave the camera view, rotate the view with the middle mouse button. + +The player's field of view setting (75 to 90) does not change the picture: the game draws the viewmodel with its own +field of view. The camera matches the game this way: + +- The game puts the model at the player's eye, then moves it by `ViewModelOffset` (`forward`, `right`, `up`) in + `game/neo/scripts/weapon_GUN.txt`. The camera moves by the opposite amount instead, so the export is unchanged. + Forward in Blender is -Y, right is -X, up is +Z, so the camera sits at (right, forward, -up): Tachi (5, 5, 0). + It looks along -Y with +Z up. +- The lens has a vertical field of view of 46.83 degrees (Sensor Fit: Vertical). That is the game's `VMFov` of 60, + which Source measures horizontally on a 4:3 screen. The game reads `VMFov` at the top level of the weapon script + (60 if absent); the `fov` key inside `ViewModelOffset` is not used. +- If a gun's `ViewModelOffset` or `VMFov` changes, move the camera or change its lens to match. + +Units: one Blender unit is one Hammer unit. Blender Source Tools writes Blender coordinates to the SMD unchanged; +the "m" that Blender shows is only its label for the metric system at unit scale 1. So the offsets from the weapon +script can be typed into Blender as they are. + + + +### Range-of-motion limits + +Each rig's bones carry limits that stop a pose outside the range the bone moves through in the shipped clips. They +prevent a finger that bends backwards or a charging handle that leaves its rail. + +- A limited bone has two constraints, `ROM:loc` (Limit Location) and `ROM:rot` (Limit Rotation), in Local Space with + *Affect Transform* on: a drag, a rotation or a typed value stops at the limit. The bone's Transform panel also + locks the axes the bone never moves on (for example, a charging handle moves on one axis only). +- The limit is the bone's range in the shipped slots of its gun, plus 0.05 units and 0.5 degrees. Bones + that move freely (`Dummy01`, the forearms, magazines) have no limit. +- The melee slot (`melee01`, or `melee` on the M41 family) swings the gun parts freely. Their `ROM:*` influence is + keyed to 0 in that slot and to 1 in the others, so the Influence field shows as keyed. +- Bone collection `ROM limited` (Armature > Bone Collections) holds the limited bones: show or select them there. +- To mute one constraint, click its eye icon in the Bone Constraints tab. To mute or unmute all of them, use + **Mute limits** / **Unmute** in the Viewmodel panel, or, with Blender closed (it saves the file): + `blender -b viewmodels.blend --python rom_limits.py -- mute-on` (or `mute-off`). Muted or not, the export is the same. + Muting leaves the transform locks on; **Free selected bones** clears them too. +- A key that is already outside a limit (pasted, or moved in the Graph Editor) shows clamped in the viewport only. + The Graph Editor shows the key as it is, and the export fails on it (next section). + +The limits come from `rom_spec.json`; do not edit the constraints by hand. To widen a limit for an authored pose, +use **Widen to this slot** in the Viewmodel panel, or add a line to `rom_widen.json`: the gun (folder name without +the team prefix), the bone, the slots the limit must cover, and the reason. For example: + +```json + {"gun": "tachi", "bone": "bone index 06", "slots": ["SLOT"], "why": "the reason the pose is meant"}, +``` + +The margins are in `rom_limits.py`. After an edit by hand, close Blender and run: + +```sh +blender -b viewmodels.blend --python-exit-code 1 --python rom_limits.py -- spec +blender -b viewmodels.blend --python-exit-code 1 --python rom_limits.py -- apply +``` + +`spec` writes `rom_spec.json` from the keyed poses of the shipped slots (the slots the project's `.qc` compiles from +its own `anims/`); `apply` puts its limits on the rigs and saves `viewmodels.blend`. A new shipped slot or a new gun +needs both. `apply` deletes and re-adds every `ROM:*` constraint, so it can run again at any time. Commit +`rom_spec.json` with `viewmodels.blend`. `rom_spec.json` has one section per gun. ## Exporting animations -To export from Blender to SMD, for example for both Tachi projects, run: +To export from Blender to SMD, for example for the Tachi, run: ```sh -blender --background --python-exit-code 1 --python export_viewmodels.py -- jinrai_tachi nsf_tachi +blender --background --python-exit-code 1 --python export_viewmodels.py -- jinrai_tachi ``` +Name the `jinrai_GUN` project; an `nsf_GUN` project has no scene and the export refuses it. + +Before it writes any SMD, the export checks the range-of-motion limits: it plays every frame of every slot of the +listed projects and fails when a limit clamps a key. The message names the project, slot, bone, frames and how far +past the limit the key is. Fix the key, or, if the pose is meant, widen the limit (a line in `rom_widen.json`, then +`spec` and `apply`). `rom_limits.py -- check` runs the same check alone. The export itself runs with `ROM:*` muted: +an active constraint changes the exported numbers slightly even when it clamps nothing, so the SMDs are the keys. + +The shipped slots stay the original clips. After Source Tools writes them, the export compares each shipped SMD with +the file it replaced: + +- A difference of float round-off only (2e-6 or less): the old file is put back and the export prints `KEPT`. +- A real change: every shipped SMD of the project is put back and the export fails, naming the slot, frame and bone. + Undo the edit in Blender (File > Revert, or delete the keys). +- A change you mean: add `--edit-shipped` after the project names. The export prints `SHIPPED CHANGED` for each + changed file and copies it into `nsf_GUN/anims/` when the NSF `.qc` compiles that slot, so the NSF model plays the + edited clip too. + +After the export, the export checks the pace of each authored slot (a slot the project's `.qc` does not compile +from its own `anims/`) against the shipped clips of the project, leaving out `fire*` and `melee*`. It prints `PACE WARN` +with the slot, bone and frames where a bone moves more than 10 % faster than in any of them: + +- hands, forearms and the gun: world speed in units per frame; the gun also its world turn in degrees per frame; +- fingers: their turn on the hand; +- parts on the gun (slide, magazine): their motion on the gun, since the gun carrying them is judged + itself. + +Bones that move no vertex of `reference.smd` (`Dummy01`, `Muzzle`, `Eject`, ...) are not seen and are skipped. A +warning does not fail the export. Compare the motion with the shipped clip it imitates; if it reads too fast, spread +the move over more frames. + ## Compiling models -Set `--compiler` to Source SDK Base 2013 Multiplayer's `studiomdl.exe`, and `--game` to the neo game directory containing `gameinfo.txt`: +`--compiler` is Source SDK Base 2013 Multiplayer's `studiomdl.exe` (the 32-bit one in `bin/`). `--game` is a game +directory that contains `gameinfo.txt`: the `game/neo` folder of a neo checkout. neoAssets has no `gameinfo.txt`, so it +cannot be used. The compile writes the models into that directory's `models/weapons/`, not into the source tree. + +```sh +python compile_viewmodels.py jinrai_tachi nsf_tachi --compiler "C:/Program Files (x86)/Steam/steamapps/common/Source SDK Base 2013 Multiplayer/bin/studiomdl.exe" --game "C:/src/neo/game/neo" +``` + +On Linux, run `studiomdl.exe` with Wine. Pass this wrapper script as `--compiler`; it turns path arguments into +Windows paths, which studiomdl needs: + +```bash +#!/bin/bash +args=() +for arg in "$@"; do + if [ -e "$arg" ]; then args+=("$(winepath -w "$arg")"); else args+=("$arg"); fi +done +exec wine "$HOME/sdk2013mp/bin/studiomdl.exe" "${args[@]}" +``` ```sh -python compile_viewmodels.py jinrai_tachi nsf_tachi --compiler "C:/Program Files (x86)/Steam/steamapps/common/Source SDK Base 2013 Multiplayer/bin/studiomdl.exe" --game "C:/path/to/neo/game/neo" +python3 compile_viewmodels.py jinrai_tachi nsf_tachi --compiler ~/bin/studiomdl-wine --game ~/src/neo/game/neo ``` -To save the compiled models in neoAssets, copy the generated files (`v_*_tachi.*` for the Tachi) from the neo game directory's `models/weapons/` folder to `neo/models/weapons/`. +Then copy the generated files (`v_*_tachi.*` for the Tachi) from the game directory's +`models/weapons/` to neoAssets `neo/models/weapons/`. The compile overwrites older models in the game directory. + + +## Adding a gun + +Files in neoAssets (this repo): + +- `neo/modelsrc/weapons/viewmodels.blend`: one scene `jinrai_GUN`. Start from a copy of a similar scene + (Scene selector > New Scene > Full Copy), name the scene, rig and action after the project (`jinrai_GUN`, + `jinrai_GUN_rig`, `jinrai_GUN_animations`), and set the scene's Source Engine Export path to `//jinrai_GUN/`. Name + the camera `jinrai_GUN_camera` and place it from the gun's `ViewModelOffset` (see Preview camera). The export finds + the rig and the action by these names and fails for a project that does not follow them. Import the NSF preview + into a second scene `nsf_GUN` with its own rig, then run `merge_teams.py -- GUN` to move it onto the Jinrai rig. +- `neo/modelsrc/weapons/TEAM_GUN/`: the `.qc`, `reference.smd` and `anims/`, for each team (the NSF `anims/` holds + the shipped clips). +- `neo/modelsrc/weapons/GUN/viewmodel.qci`: the QC lines the two teams share. +- `neo/modelsrc/weapons/rom_spec.json`: once the shipped slots are in, run `rom_limits.py -- spec` and `apply` + (Range-of-motion limits) so the new rigs get their limits. +- `neo/models/weapons/v_TEAM_GUN.*`: the compiled models. diff --git a/neo/modelsrc/weapons/tachi/textures/jinrai_armsheet1.png b/neo/modelsrc/weapons/arms/textures/jinrai_armsheet1.png similarity index 100% rename from neo/modelsrc/weapons/tachi/textures/jinrai_armsheet1.png rename to neo/modelsrc/weapons/arms/textures/jinrai_armsheet1.png diff --git a/neo/modelsrc/weapons/tachi/textures/jinrai_armsheet2.png b/neo/modelsrc/weapons/arms/textures/jinrai_armsheet2.png similarity index 100% rename from neo/modelsrc/weapons/tachi/textures/jinrai_armsheet2.png rename to neo/modelsrc/weapons/arms/textures/jinrai_armsheet2.png diff --git a/neo/modelsrc/weapons/tachi/textures/nsf_armsheet1.png b/neo/modelsrc/weapons/arms/textures/nsf_armsheet1.png similarity index 100% rename from neo/modelsrc/weapons/tachi/textures/nsf_armsheet1.png rename to neo/modelsrc/weapons/arms/textures/nsf_armsheet1.png diff --git a/neo/modelsrc/weapons/tachi/textures/nsf_armsheet2.png b/neo/modelsrc/weapons/arms/textures/nsf_armsheet2.png similarity index 100% rename from neo/modelsrc/weapons/tachi/textures/nsf_armsheet2.png rename to neo/modelsrc/weapons/arms/textures/nsf_armsheet2.png diff --git a/neo/modelsrc/weapons/compile_viewmodels.py b/neo/modelsrc/weapons/compile_viewmodels.py index c964d052..5942c333 100644 --- a/neo/modelsrc/weapons/compile_viewmodels.py +++ b/neo/modelsrc/weapons/compile_viewmodels.py @@ -1,8 +1,8 @@ """Compile exported viewmodel SMDs using Valve's Source SDK 2013 studiomdl. -Run with Python 3: compile_viewmodels.py SOURCE [SOURCE ...] --compiler PATH --game PATH +Run with Python 3: compile_viewmodels.py PROJECT [PROJECT ...] --compiler PATH --game PATH -Each SOURCE is a folder beside this script that contains one .qc file. +Each PROJECT is a folder beside this script that contains one .qc file (it may $include a shared GUN/viewmodel.qci). The game path must contain gameinfo.txt. Compilation uses a temporary game configuration because SDK tools cannot resolve the client's appid search path. The resulting model files are copied to the chosen destination, while gameinfo.txt is not changed @@ -17,8 +17,8 @@ def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('sources', nargs='+', metavar='SOURCE', - help='Source folder beside this script, such as jinrai_tachi') + parser.add_argument('sources', nargs='+', metavar='PROJECT', + help='Project folder beside this script, such as jinrai_tachi') parser.add_argument('--compiler', type=Path, required=True, help='Path to studiomdl.exe in the Source SDK Base 2013 Multiplayer bin folder') parser.add_argument('--game', type=Path, required=True, @@ -35,7 +35,7 @@ def main(): for source in args.sources: found = sorted((root / source).glob('*.qc')) if len(found) != 1: - parser.error('Source folder must contain one .qc file: ' + source) + parser.error('Project folder must contain one .qc file: ' + source) qcs.append(found[0]) with tempfile.TemporaryDirectory(prefix='neo-viewmodel-') as temporary: staging = Path(temporary) diff --git a/neo/modelsrc/weapons/export_viewmodels.py b/neo/modelsrc/weapons/export_viewmodels.py index aa920e00..581b21a5 100644 --- a/neo/modelsrc/weapons/export_viewmodels.py +++ b/neo/modelsrc/weapons/export_viewmodels.py @@ -1,33 +1,329 @@ """Export saved viewmodel Blender sources with Blender Source Tools. -Run: blender --background --python-exit-code 1 --python export_viewmodels.py -- SOURCE [SOURCE ...] -Each SOURCE is a folder beside this script that contains one .blend file. -Requires Blender 5.2.2 and Blender Source Tools 3.4.3 or newer. -This helper reads .blend sources, and writes SMD exports. +Run: blender --background --python-exit-code 1 --python export_viewmodels.py -- PROJECT [PROJECT ...] [--edit-shipped] +Each PROJECT (such as jinrai_tachi) is a scene of viewmodels.blend beside this script, exported into the folder +of the same name, which holds the project's .qc, reference.smd and anims/. A gun has one scene, jinrai_GUN: one rig +and one action, with both teams' preview meshes (the Team toggle shows one). The NSF project nsf_GUN has no scene: it +compiles from its shipped SMDs on disk. +Requires Blender 5.2.3 or newer and Blender Source Tools 3.4.3 or newer. +This helper reads viewmodels.blend, and writes SMD exports. +glue.py beside this script, when present, adds glued clips and reload phase times (its docstring has the rules). +Before any SMD is written, the range-of-motion check of rom_limits.py runs over every slot of the listed projects +and fails the export when a ROM:* constraint clamps a keyed pose; the export itself runs with ROM:* muted, so the +SMDs are the keyed poses (an active Local-Space constraint changes them by float round-off even when nothing clamps). +The shipped slots (the SMDs the project's .qc compiles from its own anims/) stay the original clips: after Source +Tools writes them, a rewrite that differs only by float round-off gets its old bytes back (KEPT), and a real change +puts every shipped SMD back and fails the export, naming the slot, frame and bone. To change a shipped clip on purpose, +add --edit-shipped after the projects: the export then prints SHIPPED CHANGED and copies the changed SMD into the NSF +project too (nsf_GUN/anims/, when its .qc compiles that slot), so both teams play the edited clip. +After the export, each authored slot (a slot the .qc does not compile from the project's own anims/) is compared with +the shipped non-fire, non-melee clips of its project: a PACE WARN names the slot, bone and frames where the slot moves +a bone more than 10 % faster than any of them: hands and the gun by world speed (the gun also by world turn), fingers +by their local turn, parts on the gun by their motion on the gun. Bones that move no vertex of reference.smd (Dummy01, +Muzzle, ...) are skipped. A warning does not fail the export. +viewmodels.blend is never saved. """ from pathlib import Path +import math +import re import sys import bpy +from mathutils import Euler +sys.dont_write_bytecode = True +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import rom_limits +if (Path(__file__).resolve().parent / 'glue.py').is_file(): + import glue +else: + glue = None -def export_project(project): - bpy.ops.wm.open_mainfile(filepath=str(project)) - bpy.ops.preferences.addon_enable(module='io_scene_valvesource') +SOURCE = 'viewmodels.blend' +FPS = 30 + + +def read_frames(path): + """The header up to 'skeleton', and the frames as lists of bone lines.""" + lines = path.read_text(encoding='ascii').splitlines() + start = lines.index('skeleton') + frames = [] + for line in lines[start + 1:]: + if line.startswith('time '): + frames.append([]) + elif line != 'end': + frames[-1].append(line) + return lines[:start + 1], frames + + +SHIPPED_SMD = re.compile(r'"anims/([^"/]+)\.smd"') # a $sequence of the project's own SMDs, not ../jinrai_GUN/anims/ +INCLUDE = re.compile(r'^\$include\s+"([^"]+)"', re.M) + + +def qc_text(folder): + """The project's .qc with its $include files, as one text.""" + texts, pending = [], [next(folder.glob('*.qc'))] + while pending: + path = pending.pop(0) + text = path.read_text(encoding='ascii') + texts.append(text) + pending += [(folder / include).resolve() for include in INCLUDE.findall(text)] + return '\n'.join(texts) + + +def shipped_slots(folder): + """The slots the project's qc compiles from its own anims/.""" + return set(SHIPPED_SMD.findall(qc_text(folder))) + + +def read_markers(scene): + return {marker.name: marker.frame for marker in scene.timeline_markers} + + +def project_rig(scene): + """The scene's rig, failing unless it holds the project's own action.""" + if scene.name.startswith('nsf_'): + raise RuntimeError('Scene %s: NSF projects have no scene since the team merge; export jinrai_%s' % ( + scene.name, scene.name[4:])) + rig_name, action_name = scene.name + '_rig', scene.name + '_animations' # named after the project + rig = scene.objects.get(rig_name) + if rig is None or rig.type != 'ARMATURE': + raise RuntimeError('Scene %s has no armature named %s' % (scene.name, rig_name)) + action = rig.animation_data.action if rig.animation_data else None + if action is None or action.name != action_name: + raise RuntimeError('Scene %s: rig %s has action %s but needs %s. In Blender, select the rig, open ' + 'Dope Sheet > Action Editor and pick %s, then save; or use File > Revert' % ( + scene.name, rig_name, action.name if action else 'none', action_name, action_name)) + return rig + + +def check_images(): missing = [image.filepath for image in bpy.data.images if image.source == 'FILE' and not image.packed_file and not Path(bpy.path.abspath(image.filepath)).is_file()] if missing: raise RuntimeError('Missing preview images: ' + ', '.join(missing)) - folder = project.parent + + +def check_limits(scenes): + """Fail when a range-of-motion limit clamps a keyed pose: the SMD would not show what the viewport shows.""" + clamps = [rom_limits.clamp_text(scene.name, clamp) for scene in scenes for clamp in rom_limits.find_clamps(scene)] + if clamps: + raise RuntimeError('Range-of-motion limits clamp %d keyed poses. Fix the keys, or if the pose is meant, widen ' + 'the limit (an entry in rom_widen.json, then rom_limits.py spec and apply):\n %s' % ( + len(clamps), '\n '.join(clamps))) + print('ROM CHECK', len(scenes), 'projects, no clamped pose') + + +PACE_MARGIN = 1.10 # an authored slot may move a bone up to 10 % faster than any shipped non-fire clip does +PACE_FLOOR = 0.3 # u/frame or deg/frame: slower peaks are never flagged +PACE_TURN_FLOOR = 2.0 # deg/frame: a gun or gun part turning slower than this is never flagged + + +def turn_degrees(matrix, earlier): + """The rotation between two bone matrices, in degrees (0 to 180: a quaternion and its negation are one turn).""" + angle = math.degrees(matrix.to_quaternion().rotation_difference(earlier.to_quaternion()).angle) + return min(angle, 360 - angle) + + +def clip_speeds(path): + """({bone: {measure: (peak per frame, frame)}}, {bone: parent bone}) of one SMD. Measures: 'move' (world + position, u/frame), 'shift' (local position, u/frame), 'turn' (local rotation, deg/frame) and 'spin' (world + rotation, deg/frame).""" + from mathutils import Matrix + lines = path.read_text(encoding='ascii').splitlines() + nodes = {} + for line in lines[lines.index('nodes') + 1:lines.index('end')]: + index, name, parent = re.match(r'(\d+) "([^"]*)" (-?\d+)', line).groups() + nodes[index] = (name, parent) + peaks, previous = {}, None + for number, frame in enumerate(read_frames(path)[1]): + world, local = {}, {} + for line in frame: + index, *values = line.split() + values = list(map(float, values)) + local[index] = Matrix.Translation(values[:3]) @ Euler(values[3:]).to_matrix().to_4x4() + for index in nodes: # SMD lists parents before children + parent = nodes[index][1] + world[index] = world[parent] @ local[index] if parent in world else local[index] + if previous: + for index, (name, _) in nodes.items(): + speeds = { + 'move': (world[index].to_translation() - previous[0][index].to_translation()).length, + 'shift': (local[index].to_translation() - previous[1][index].to_translation()).length, + 'turn': turn_degrees(local[index], previous[1][index]), + 'spin': turn_degrees(world[index], previous[0][index]), + } + bone = peaks.setdefault(name, {}) + for measure, speed in speeds.items(): + if speed > bone.get(measure, (0.0, 0))[0]: + bone[measure] = speed, number + previous = world, local + return peaks, {name: nodes[parent][0] if parent in nodes else None for name, parent in nodes.values()} + + +def skin_bones(folder): + """The bones that move vertices of the project's reference.smd. The others (Dummy01, Muzzle, Eject, ...) are + never seen: the pace check skips them.""" + lines = (folder / 'reference.smd').read_text(encoding='ascii').splitlines() + names = dict(re.match(r'\s*(\d+) "([^"]*)"', line).groups() + for line in lines[lines.index('nodes') + 1:lines.index('end')]) + used = set() + for line in lines[lines.index('triangles') + 1:]: + values = line.split() + if len(values) == 9: # no links: the vertex follows its parent bone + used.add(values[0]) + elif len(values) > 9: + used.update(values[10 + 2 * link] for link in range(int(values[9])) if float(values[11 + 2 * link]) > 0) + return {names[index] for index in used} + + +def pace_measures(bone, parent, seen): + """(role, [(measure, unit, floor)]) judged for a bone of the set seen (skin_bones). The hands and forearms go by + world speed and the fingers by their local turn. The gun goes by world speed and world turn. A part on the gun (a + bolt handle, a parked magazine) goes by its motion on the gun: the gun carrying it is judged itself.""" + if bone not in seen: + return 'unseen', [] + if bone.startswith(rom_limits.ARM_PREFIX): + if 'hand' in bone or 'forearm' in bone: + return 'arm', [('move', 'u/f', PACE_FLOOR)] + return 'finger', [('turn', 'deg/f local', PACE_FLOOR)] + if parent not in seen or parent.startswith(rom_limits.ARM_PREFIX): # the gun, held by the hand or the root + return 'gun', [('move', 'u/f', PACE_FLOOR), ('spin', 'deg/f world', PACE_TURN_FLOOR)] + return 'gun part', [('shift', 'u/f on the gun', PACE_FLOOR), ('turn', 'deg/f on the gun', PACE_TURN_FLOOR)] + + +def check_pace(folder, authored): + """Warn when an authored slot moves a bone faster than every shipped non-fire, non-melee clip of the project. + A warning does not fail the export: compare the motion with the shipped clip it imitates.""" + anims = folder / 'anims' + envelope = {} + for slot in sorted(shipped_slots(folder)): + if slot.startswith(('fire', 'melee')) or not (anims / (slot + '.smd')).is_file(): + continue # recoil and melee are not hand-paced motion + for bone, peaks in clip_speeds(anims / (slot + '.smd'))[0].items(): + limit = envelope.setdefault(bone, {}) + for measure, (speed, frame) in peaks.items(): + if speed > limit.get(measure, (0.0, ''))[0]: + limit[measure] = speed, slot + warned, seen = 0, skin_bones(folder) + for slot in authored: + peaks_of, parents = clip_speeds(anims / (slot + '.smd')) + for bone, peaks in peaks_of.items(): + role, measures = pace_measures(bone, parents[bone], seen) + for measure, unit, floor in measures: + peak, frame = peaks.get(measure, (0.0, 0)) + limit, source = envelope.get(bone, {}).get(measure, (0.0, 'none')) + if peak <= floor or peak <= PACE_MARGIN * max(limit, floor): + continue + warned += 1 + print('PACE WARN %s slot %s %s "%s" f%d-%d: %.2f %s, shipped peak %.2f in %s (+%d %%): spread the ' + 'move over more frames if it reads too fast' % ( + folder.name, slot, role, bone, frame - 1, frame, peak, unit, limit, source, + round(100 * (peak / max(limit, floor) - 1)))) + print('PACE', folder.name, len(authored), 'authored slots,', warned, 'warnings') + + +SHIPPED_TOLERANCE = 2e-6 # Blender's float round-off in the printed SMD digits (the Tachi drift is 1e-6) +EDIT_SHIPPED = '--edit-shipped' + + +def smd_change(old, new): + """None when two SMD texts hold the same poses within SHIPPED_TOLERANCE, else (frame, bone, difference).""" + old_lines, new_lines = old.splitlines(), new.splitlines() + if len(old_lines) != len(new_lines): + return ('-', '-', 'frame count %d -> %d' % (old_lines.count('end'), new_lines.count('end'))) + frame, names = None, dict(re.findall(r'^(\d+) "([^"]*)"', old, re.M)) + for a, b in zip(old_lines, new_lines): + if a == b: + frame = a[5:] if a.startswith('time ') else frame + continue + x, y = a.split(), b.split() + try: + worst = max(abs(float(i) - float(j)) for i, j in zip(x[1:], y[1:])) + except ValueError: + return (frame, '-', 'text %r -> %r' % (a, b)) + if len(x) != len(y) or x[0] != y[0] or worst > SHIPPED_TOLERANCE: + return (frame, '"%s"' % names.get(x[0], x[0]), '%.4f' % worst) + return None + + +def guard_shipped(folder, before, allow): + """Keep the shipped SMDs original: restore round-off-only rewrites byte for byte, and fail on a real change + unless the export was run with --edit-shipped. Return the changed SMDs (allowed changes only).""" + changed = [] + for path, old in before.items(): + new = path.read_bytes() + if new == old: + continue + change = smd_change(old.decode('ascii'), new.decode('ascii')) + if change is None: + path.write_bytes(old) + print('KEPT %s/anims/%s (round-off only)' % (folder.name, path.name)) + continue + changed.append((path, old, change)) + if not changed: + return [] + if allow: + for path, _, (frame, bone, difference) in changed: + print('SHIPPED CHANGED %s/anims/%s frame %s bone %s: %s' % ( + folder.name, path.name, frame, bone, difference)) + return [path for path, _, _ in changed] + for path, old, _ in changed: + path.write_bytes(old) + raise RuntimeError('Shipped slots of %s changed: %s. Shipped slots stay the original clip; the SMDs were put ' + 'back. Undo the edit in Blender (File > Revert, or delete the keys), or, if the change is ' + 'meant, export again with %s (both teams then get the edited clip)' % ( + folder.name, '; '.join('%s frame %s bone %s by %s' % ((p.stem,) + c) for p, _, c in changed), + EDIT_SHIPPED)) + + +def nsf_project(folder): + """The NSF project folder of a Jinrai project, or None. It has no scene: it compiles from its own shipped SMDs.""" + partner = folder.parent / ('nsf_' + folder.name.partition('_')[2]) + return partner if folder.name.startswith('jinrai_') and partner.is_dir() else None + + +def copy_shipped(folder, changed): + """Copy the shipped SMDs an --edit-shipped export changed into the NSF project, where its .qc compiles them.""" + partner = nsf_project(folder) + if partner is None: + return + compiled = shipped_slots(partner) + for path in changed: + if path.stem in compiled: + (partner / 'anims' / path.name).write_bytes(path.read_bytes()) + print('SHIPPED CHANGED %s/anims/%s (copied from %s)' % (partner.name, path.name, folder.name)) + + +def open_scenes(path, keep=None): + """Open the source file; with keep, drop the other scenes so Source Tools exports the kept one.""" + bpy.ops.wm.open_mainfile(filepath=str(path)) + bpy.ops.preferences.addon_enable(module='io_scene_valvesource') + if keep is None: + return bpy.data.scenes + for scene in list(bpy.data.scenes): + if scene.name != keep: + bpy.data.scenes.remove(scene) + return bpy.context.scene + + +def export_project(folder, scene, allow_shipped=False): + if scene.render.fps != FPS or scene.render.fps_base != 1: + raise RuntimeError('Scene %s must play at %d fps' % (scene.name, FPS)) reference = folder / 'reference.smd' reference_bytes = reference.read_bytes() - armature = next(obj for obj in bpy.context.scene.objects if obj.type == 'ARMATURE') + armature = project_rig(scene) + rom_limits.set_mute(scene, True) # this copy of the file is never saved expected = [folder / 'anims' / (slot.name_display + '.smd') for slot in armature.animation_data.action.slots] previous = {path: path.stat().st_mtime_ns if path.exists() else None for path in expected} + before = {path: path.read_bytes() for path in (folder / 'anims' / (slot + '.smd') for slot in shipped_slots(folder)) + if path.is_file()} + name = scene.name result = bpy.ops.export_scene.smd(export_scene=True) + scene = bpy.data.scenes[name] # the export replaces the scene's Python object if result != {'FINISHED'}: raise RuntimeError('Source Tools export failed: ' + str(result)) if any(not path.is_file() or path.stat().st_mtime_ns == previous[path] @@ -35,19 +331,39 @@ def export_project(project): raise RuntimeError('Source Tools did not freshly export every expected SMD') if reference.read_bytes() != reference_bytes: raise RuntimeError('The preview mesh must not overwrite reference.smd') - print('EXPORTED', project.name, len(expected), 'animation SMD files; reference retained') + changed = guard_shipped(folder, before, allow_shipped) + print('EXPORTED', scene.name, len(expected), 'animation SMD files; reference retained') + copy_shipped(folder, changed) + if glue: + glue.after_export(folder, scene) + shipped = shipped_slots(folder) + check_pace(folder, [path.stem for path in expected if path.stem not in shipped]) if __name__ == '__main__': root = Path(__file__).resolve().parent - sources = sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else [] - if not sources: - raise RuntimeError('List the source folders to export after --') - projects = [] - for source in sources: - found = sorted((root / source).glob('*.blend')) - if len(found) != 1: - raise RuntimeError('Source folder must contain one .blend file: ' + source) - projects.append(found[0]) - for project in projects: - export_project(project) + projects = sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else [] + allow_shipped = EDIT_SHIPPED in projects + projects = [project for project in projects if project != EDIT_SHIPPED] + if not projects: + raise RuntimeError('List the projects to export after --') + try: + found = open_scenes(root / SOURCE) + merged = [project for project in projects if project.startswith('nsf_')] + if merged: + raise RuntimeError('%s: an NSF project has no scene; it compiles from its shipped SMDs and the Jinrai glued ' + 'clips. Export %s' % (', '.join(merged), ', '.join('jinrai_' + p[4:] for p in merged))) + unknown = [project for project in projects if project not in found or not (root / project).is_dir()] + if unknown: + raise RuntimeError('No scene and folder named ' + ', '.join(unknown)) + for project in projects: + project_rig(found[project]) + check_images() + check_limits([found[project] for project in projects]) + for project in projects: + export_project(root / project, open_scenes(root / SOURCE, keep=project), allow_shipped) + if glue: + glue.build_post_export(root) + except RuntimeError as problem: + print('EXPORT FAILED:', problem) + sys.exit(1) diff --git a/neo/modelsrc/weapons/jinrai_tachi/v_jinrai_tachi.blend b/neo/modelsrc/weapons/jinrai_tachi/v_jinrai_tachi.blend deleted file mode 100644 index 6ab17d8b..00000000 Binary files a/neo/modelsrc/weapons/jinrai_tachi/v_jinrai_tachi.blend and /dev/null differ diff --git a/neo/modelsrc/weapons/jinrai_tachi/v_jinrai_tachi.qc b/neo/modelsrc/weapons/jinrai_tachi/v_jinrai_tachi.qc index 8e1cb796..c083f108 100644 --- a/neo/modelsrc/weapons/jinrai_tachi/v_jinrai_tachi.qc +++ b/neo/modelsrc/weapons/jinrai_tachi/v_jinrai_tachi.qc @@ -1,75 +1,2 @@ $modelname "weapons/v_jinrai_tachi.mdl" -$cdmaterials "models/Weapons/" -$body "body" "reference.smd" -$definebone "Dummy01" "" -2.277793 -6.712466 -19.960323 -0.000000 89.999978 0.000000 0 0 0 0 0 0 -$definebone "bone forearm01" "Dummy01" -6.973125 11.498295 -10.988396 -31.114590 90.939514 89.978900 0 0 0 0 0 0 -$definebone "bone hand01" "bone forearm01" -0.035541 -23.756721 -0.084862 -0.042628 -1.058999 -0.805063 0 0 0 0 0 0 -$definebone "bone middle 05" "bone hand01" 0.273360 -3.765809 -0.387136 -0.000000 -0.000001 -0.000000 0 0 0 0 0 0 -$definebone "bone middle 06" "bone middle 05" 0.000002 -3.784243 -0.191475 -10.216125 -0.000002 -0.116826 0 0 0 0 0 0 -$definebone "bone middle 07" "bone middle 06" 0.024372 -3.235442 0.175100 -0.154929 0.133554 -12.925470 0 0 0 0 0 0 -$definebone "bone middle 08" "bone middle 07" -0.111963 -3.553718 0.074803 4.989030 0.902865 -18.339691 0 0 0 0 0 0 -$definebone "bone index 05" "bone hand01" 1.858448 -3.773904 0.198660 -14.044973 4.338951 -0.000000 0 0 0 0 0 0 -$definebone "bone index 06" "bone index 05" 0.000004 -3.784240 -0.191475 5.207097 -1.406557 -6.343559 0 0 0 0 0 0 -$definebone "bone index 07" "bone index 06" 0.074586 -3.334557 0.036040 -0.154928 0.133556 -12.948845 0 0 0 0 0 0 -$definebone "bone index 08" "bone index 07" -0.033768 -2.966134 0.050352 1.496623 2.758618 -18.165053 0 0 0 0 0 0 -$definebone "bone ring 05" "bone hand01" -1.407701 -3.765813 -0.387136 0.000000 -5.445049 0.000000 0 0 0 0 0 0 -$definebone "bone ring 06" "bone ring 05" 0.000002 -3.784244 -0.191475 -7.169937 1.442592 -0.480196 0 0 0 0 0 0 -$definebone "bone ring 07" "bone ring 06" 0.038987 -2.749642 0.107386 -1.660432 -2.201248 -12.888514 0 0 0 0 0 0 -$definebone "bone ring 08" "bone ring 07" 0.013190 -3.474698 0.024520 1.138697 2.167728 -31.676656 0 0 0 0 0 0 -$definebone "bone pinky 05" "bone hand01" -2.992724 -3.619925 0.091621 -0.000000 -9.635662 -0.000000 0 0 0 0 0 0 -$definebone "bone pinky 06" "bone pinky 05" -0.231696 -2.899982 -0.226467 -7.169938 1.442592 -2.020135 0 0 0 0 0 0 -$definebone "bone pinky 07" "bone pinky 06" 0.047093 -3.464708 0.060474 0.392362 0.981704 -12.970447 0 0 0 0 0 0 -$definebone "bone pinky 08" "bone pinky 07" -0.012931 -2.746934 0.096229 -4.151539 3.541852 -14.719691 0 0 0 0 0 0 -$definebone "bone thumb 04" "bone hand01" 2.231814 -1.416993 1.590842 -38.208904 65.612956 -60.895681 0 0 0 0 0 0 -$definebone "bone thumb 05" "bone thumb 04" 0.316679 -3.892339 -0.185575 -33.168527 -11.613910 -10.910492 0 0 0 0 0 0 -$definebone "bone thumb 06" "bone thumb 05" 0.269053 -3.933444 0.328680 5.133243 -12.418461 -13.006143 0 0 0 0 0 0 -$definebone "bone forearm" "Dummy01" 12.577013 11.498295 1.716358 31.114527 -89.060440 -89.978894 0 0 0 0 0 0 -$definebone "bone hand" "bone forearm" 0.035544 23.756721 -0.084859 -14.678660 2.606786 -11.549912 0 0 0 0 0 0 -$definebone "bone middle 1" "bone hand" -0.273364 3.765811 0.387137 0.000003 0.000001 0.000002 0 0 0 0 0 0 -$definebone "bone middle 2" "bone middle 1" -0.000001 3.784237 0.191473 -8.198563 3.499229 -25.560163 0 0 0 0 0 0 -$definebone "bone middle 3" "bone middle 2" -0.024372 3.235442 -0.175100 -0.154925 0.133562 -71.831997 0 0 0 0 0 0 -$definebone "bone middle 4" "bone middle 3" 0.111963 3.553717 -0.074805 4.989024 0.902872 -78.199574 0 0 0 0 0 0 -$definebone "bone index 1" "bone hand" -1.858449 3.773898 -0.198660 -14.044967 4.338953 0.000002 0 0 0 0 0 0 -$definebone "bone index 2" "bone index 1" -0.000001 3.784236 0.191477 5.346332 -0.276393 -7.004521 0 0 0 0 0 0 -$definebone "bone index 3" "bone index 2" -0.074585 3.334558 -0.036042 -0.154921 0.133558 -12.832018 0 0 0 0 0 0 -$definebone "bone index 4" "bone index 3" 0.033765 2.966134 -0.050352 1.496628 2.758624 -49.071600 0 0 0 0 0 0 -$definebone "bone ring 1" "bone hand" 1.407699 3.765804 0.387136 0.000003 -5.445046 0.000002 0 0 0 0 0 0 -$definebone "bone ring 2" "bone ring 1" -0.000003 3.784241 0.191476 -6.664011 2.311486 -40.444693 0 0 0 0 0 0 -$definebone "bone ring 3" "bone ring 2" -0.038986 2.749646 -0.107382 -1.660430 -2.201242 -72.795031 0 0 0 0 0 0 -$definebone "bone ring 4" "bone ring 3" -0.013189 3.474696 -0.024517 1.138692 2.167730 -81.536477 0 0 0 0 0 0 -$definebone "bone pinky 1" "bone hand" 2.992723 3.619924 -0.091623 0.000004 -9.635659 0.000002 0 0 0 0 0 0 -$definebone "bone pinky 2" "bone pinky 1" 0.231693 2.899976 0.226466 -7.169932 1.442595 -41.833261 0 0 0 0 0 0 -$definebone "bone pinky 3" "bone pinky 2" -0.047095 3.464705 -0.060474 0.392365 0.981709 -77.830297 0 0 0 0 0 0 -$definebone "bone pinky 4" "bone pinky 3" 0.012933 2.746925 -0.096229 -4.151539 3.541855 -65.579491 0 0 0 0 0 0 -$definebone "bone thumb 1" "bone hand" -2.231816 1.416988 -1.590842 -46.604322 61.384001 -55.069086 0 0 0 0 0 0 -$definebone "bone thumb 2" "bone thumb 1" -0.316676 3.892338 0.185578 -33.168533 -11.613905 -33.910502 0 0 0 0 0 0 -$definebone "bone thumb 3" "bone thumb 2" -0.269053 3.933444 -0.328678 5.133236 -12.418460 -66.142942 0 0 0 0 0 0 -$definebone "magrel" "bone hand" -1.389966 15.611851 -2.785499 87.000140 -92.999972 90.000075 0 0 0 0 0 0 -$definebone "slide" "magrel" 0.000001 1.764277 6.216676 0.000004 0.000004 0.000001 0 0 0 0 0 0 -$definebone "Eject" "slide" -0.120959 -0.439801 -0.840956 -10.016456 178.846850 0.201737 0 0 0 0 0 0 -$definebone "body" "magrel" 0.000000 -0.000001 -0.000000 0.000004 0.000004 0.000001 0 0 0 0 0 0 -$definebone "catch2" "body" 0.000001 0.367147 3.416009 0.000004 0.000004 0.000001 0 0 0 0 0 0 -$definebone "bullet_eject01" "body" -0.000000 4.833648 3.431723 0.000004 0.000004 0.000001 0 0 0 0 0 0 -$definebone "trigger" "magrel" 0.000000 1.612491 2.633620 0.000004 0.000004 0.000001 0 0 0 0 0 0 -$definebone "mag" "magrel" -0.059484 7.270134 1.720140 0.000004 0.000004 7.999981 0 0 0 0 0 0 -$definebone "bullet2" "mag" 0.059484 -7.270135 -1.720142 0.000004 0.000003 0.000002 0 0 0 0 0 0 -$definebone "Main" "magrel" -0.000622 3.390026 5.182981 -1.337800 -89.989460 89.981534 0 0 0 0 0 0 -$definebone "Muzzle" "Main" 16.557522 -0.000008 -0.000003 -0.000004 0.041881 0.000005 0 0 0 0 0 0 -$attachment "muzzle" "Muzzle" 0.0000 -0.0000 0.0000 rotate 0.000 -0.000 -0.000 -$attachment "eject" "Eject" 0.0000 -0.0000 0.0000 rotate -0.000 -0.000 0.000 -$sequence "idle01" "anims/idle01.smd" activity ACT_VM_IDLE 1 fps 30 fadein 0.20 fadeout 0.20 loop node "0" -$sequence "idle01empty" "anims/idle01empty.smd" activity ACT_VM_IDLE_EMPTY 1 fps 30 fadein 0.20 fadeout 0.20 loop node "0" -$sequence "fire" "anims/fire.smd" activity ACT_VM_PRIMARYATTACK 1 fps 30 fadein 0.20 fadeout 0.20 snap node "2" { event AE_MUZZLEFLASH 0 "PISTOL MUZZLE" } -$sequence "fire1" "anims/fire1.smd" activity ACT_VM_RECOIL1 1 fps 30 fadein 0.20 fadeout 0.20 snap node "2" { event AE_MUZZLEFLASH 0 "PISTOL MUZZLE" } -$sequence "fire2" "anims/fire2.smd" activity ACT_VM_RECOIL2 1 fps 30 fadein 0.20 fadeout 0.20 snap node "2" { event AE_MUZZLEFLASH 0 "PISTOL MUZZLE" } -$sequence "fire3" "anims/fire3.smd" activity ACT_VM_RECOIL3 1 fps 30 fadein 0.20 fadeout 0.20 snap node "2" { event AE_MUZZLEFLASH 0 "PISTOL MUZZLE" } -$sequence "fireempty" "anims/fireempty.smd" activity ACT_VM_DRYFIRE 1 fps 30 fadein 0.20 fadeout 0.20 node "2" -$sequence "draw" "anims/draw.smd" activity ACT_VM_DRAW 1 fps 30 fadein 0.20 fadeout 0.20 snap node "0" -$sequence "drawempty" "anims/drawempty.smd" fps 30 fadein 0.20 fadeout 0.20 node "0" -$sequence "reload" "anims/reload.smd" activity ACT_VM_RELOAD 1 fps 30 fadein 0.20 fadeout 0.20 node "0" -$sequence "holster" "anims/holster.smd" activity ACT_VM_HOLSTER 1 fps 30 fadein 0.20 fadeout 0.20 node "0" -$sequence "holsterempty" "anims/holsterempty.smd" activity ACT_VM_HOLSTER 1 fps 30 fadein 0.20 fadeout 0.20 node "0" -$sequence "idletolow" "anims/idletolow.smd" activity ACT_VM_LOWERED_TO_IDLE 1 fps 30 fadein 0.20 fadeout 0.20 transition "0" "1" -$sequence "lowtoidle" "anims/lowtoidle.smd" activity ACT_VM_IDLE_TO_LOWERED 1 fps 30 fadein 0.20 fadeout 0.20 transition "1" "0" -$sequence "lowidle" "anims/lowidle.smd" activity ACT_VM_IDLE_LOWERED 1 fps 30 fadein 0.20 fadeout 0.20 loop node "1" -$sequence "reloadempty" "anims/reloadempty.smd" activity ACT_VM_RELOAD_EMPTY 1 fps 30 fadein 0.20 fadeout 0.20 node "0" +$include "../tachi/viewmodel.qci" diff --git a/neo/modelsrc/weapons/merge_teams.py b/neo/modelsrc/weapons/merge_teams.py new file mode 100644 index 00000000..a1f1b90a --- /dev/null +++ b/neo/modelsrc/weapons/merge_teams.py @@ -0,0 +1,187 @@ +"""Merge the two team scenes of each gun into one: one rig and one action, both teams' arms. + +Run from this folder (Blender 5.2.3 or newer, Blender Source Tools 3.4.3 or newer): + blender -b viewmodels.blend --python-exit-code 1 --python merge_teams.py -- [GUN ...] [--dry-run] +Without GUN, every gun that still has an nsf_GUN scene. --dry-run checks and reports but does not save. + +Per gun, the jinrai_GUN scene keeps its rig and action. The NSF preview mesh (arms and gun) moves into that scene, +parented and skinned to the kept rig (its Armature modifier points at the kept rig; the vertex groups keep their bone +names). Each team's preview mesh stays in its own collection, jinrai_GUN_preview and nsf_GUN_preview: the team +toggle is that collection's visibility (Outliner eye, or Team in the Viewmodel panel). The NSF collection starts +hidden. Then the nsf_GUN scene, rig, armature, action and camera are deleted. The NSF project folder is not touched: +it compiles from its shipped SMDs on disk. + +Preview-only re-bind: where a bone's rest pose differs between the two rigs (the SRS Release bone, 22 deg; the MilSO +arm and slide bones, 0.006 u), the NSF vertices weighted to it are moved by the rest difference, so the kept rig poses +them as the NSF rig did. +reference.smd is never written; the compiled NSF model keeps its own rest pose. + +Gate: for every shipped slot of the NSF scene, at 4 frames, the NSF arms posed by the kept rig must match the NSF arms +posed by the NSF rig within ARMS_TOLERANCE. Any gun over it fails the run before anything is saved. +Runtime: ~1 min for all 19 guns. +""" +from pathlib import Path +import sys + +import bpy +import numpy as np + +sys.dont_write_bytecode = True +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import rom_limits + +ARMS_TOLERANCE = 0.03 # units: well above the team clip differences (M41 0.026 u at the muzzle), far below a visible pose +REST_TOLERANCE = 1e-3 # units or matrix entries: a smaller rest difference needs no re-bind +ARMS_MATERIAL = 'armsheet' # the arm materials (jinrai_armsheet1, nsf_armsheet2.004, ...) +TEAM_KEY = 'team' # custom property on each team collection and preview mesh + + +def slot_frames(rig): + """{slot name: 4 frames spread over the slot's keys}.""" + frames = {} + for slot, _, first, last in rom_limits.slot_bags(rig): + frames[slot.name_display] = sorted({first, first + (last - first) // 3, first + 2 * (last - first) // 3, last}) + return frames + + +def posed(scene, mesh, rig, slot, frame): + """World positions [n, 3] of the evaluated mesh with the rig on slot at frame.""" + rig.animation_data.action_slot = next(s for s in rig.animation_data.action.slots if s.name_display == slot) + scene.frame_set(frame) + depsgraph = scene.view_layers[0].depsgraph + depsgraph.update() + evaluated = mesh.evaluated_get(depsgraph) + data = evaluated.data + co = np.empty(len(data.vertices) * 3) + data.vertices.foreach_get('co', co) + co = co.reshape(-1, 3) + matrix = np.array(evaluated.matrix_world) + return co @ matrix[:3, :3].T + matrix[:3, 3] + + +def arm_vertices(mesh): + """Indices of the vertices on arm-material faces.""" + arms = {index for index, slot in enumerate(mesh.material_slots) + if slot.material and ARMS_MATERIAL in slot.material.name} + return sorted({v for polygon in mesh.data.polygons if polygon.material_index in arms for v in polygon.vertices}) + + +def rebind(mesh, kept, old): + """Move the vertices weighted to bones whose rest differs between the rigs by that difference (weighted blend); + return the bones whose vertices moved.""" + to_rig = old.matrix_world.inverted() @ mesh.matrix_world + moved = {} + for group in mesh.vertex_groups: + bone_old, bone_kept = old.data.bones.get(group.name), kept.data.bones.get(group.name) + if bone_old is None or bone_kept is None: + continue + if np.abs(np.array(bone_old.matrix_local) - np.array(bone_kept.matrix_local)).max() < REST_TOLERANCE: + continue + moved[group.index] = (group.name, bone_kept.matrix_local @ bone_old.matrix_local.inverted()) + if not moved: + return [] + from_rig, used = to_rig.inverted(), set() + for vertex in mesh.data.vertices: + links = [(g.group, g.weight) for g in vertex.groups if g.weight > 0] + total = sum(weight for _, weight in links) + hits = [(moved[group][1], weight / total) for group, weight in links if group in moved] + if not hits: + continue + used.update(moved[group][0] for group, _ in links if group in moved) + at = to_rig @ vertex.co + shift = sum(((change @ at - at) * share for change, share in hits), at * 0) + vertex.co = from_rig @ (at + shift) + return sorted(used) + + +def merge_gun(gun): + """Merge nsf_GUN into jinrai_GUN; return (arms max delta, whole-mesh max delta, worst slot/frame, re-bound bones).""" + kept_scene, old_scene = bpy.data.scenes['jinrai_' + gun], bpy.data.scenes['nsf_' + gun] + kept, old = kept_scene.objects['jinrai_%s_rig' % gun], old_scene.objects['nsf_%s_rig' % gun] + mesh = old_scene.objects['nsf_%s_preview' % gun] + team_collection = bpy.data.collections['nsf_%s_preview' % gun] + old_camera = old_scene.camera + arms = arm_vertices(mesh) + window = bpy.context.window + window.scene = old_scene + frames = slot_frames(old) + reference = {(slot, frame): posed(old_scene, mesh, old, slot, frame) for slot in frames for frame in frames[slot]} + kept_slots = {slot.name_display for slot in kept.animation_data.action.slots} + missing = sorted(set(frames) - kept_slots) + if missing: + raise RuntimeError('%s: NSF slots %s are missing from the Jinrai action' % (gun, missing)) + + old_scene.collection.children.unlink(team_collection) + kept_scene.collection.children.link(team_collection) + relative = old.matrix_world.inverted() @ mesh.matrix_world + bound = rebind(mesh, kept, old) + mesh.parent = kept + mesh.matrix_world = kept.matrix_world @ relative + for modifier in mesh.modifiers: + if modifier.type == 'ARMATURE': + modifier.object = kept + for collection, team in ((team_collection, 'nsf'), (bpy.data.collections['jinrai_%s_preview' % gun], 'jinrai')): + collection[TEAM_KEY] = team + for obj in collection.objects: + obj[TEAM_KEY] = team + + window.scene = kept_scene + restore = kept.animation_data.action_slot, kept_scene.frame_current + worst_arms = worst_all = 0.0 + worst_at = None + for (slot, frame), before in reference.items(): + delta = np.linalg.norm(posed(kept_scene, mesh, kept, slot, frame) - before, axis=1) + if delta[arms].max() > worst_arms: + worst_arms, worst_at = float(delta[arms].max()), (slot, frame) + worst_all = max(worst_all, float(delta.max())) + kept.animation_data.action_slot = restore[0] + kept_scene.frame_set(restore[1]) + layer = kept_scene.view_layers[0].layer_collection.children[team_collection.name] + layer.hide_viewport = True + team_collection.hide_render = True + + action, armature = old.animation_data.action, old.data + bpy.data.scenes.remove(old_scene) + bpy.data.objects.remove(old) + bpy.data.armatures.remove(armature) + bpy.data.actions.remove(action) + if old_camera is not None: + camera = old_camera.data + bpy.data.objects.remove(old_camera) + if camera.users == 0: + bpy.data.cameras.remove(camera) + return worst_arms, worst_all, worst_at, bound, len(reference), len(arms) + + +def main(): + arguments = sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else [] + dry = '--dry-run' in arguments + guns = [a for a in arguments if a != '--dry-run'] or sorted( + s.name[4:] for s in bpy.data.scenes if s.name.startswith('nsf_')) + bpy.ops.preferences.addon_enable(module='io_scene_valvesource') + failed = [] + for gun in guns: + arms, whole, at, bound, samples, count = merge_gun(gun) + verdict = 'PASS' if arms <= ARMS_TOLERANCE else 'FAIL' + failed += [gun] if verdict == 'FAIL' else [] + print('MERGED %-9s %s arms max %.4f u at %s (%d samples, %d arm vertices); whole mesh max %.4f u; re-bound %s' % ( + gun, verdict, arms, at, samples, count, whole, bound or 'none')) + if failed: + raise RuntimeError('NSF arms moved over %.2f u on %s: nothing saved' % (ARMS_TOLERANCE, ', '.join(failed))) + if dry: + print('DRY RUN: not saved') + return + bpy.data.orphans_purge(do_recursive=True) # the removed rigs' bone shapes; a save drops one level only + bpy.ops.wm.save_mainfile() + backup = Path(bpy.data.filepath + '1') + if backup.exists(): + backup.unlink() + print('SAVED', bpy.data.filepath) + + +if __name__ == '__main__': + try: + main() + except RuntimeError as problem: + print('MERGE FAILED:', problem) + sys.exit(1) diff --git a/neo/modelsrc/weapons/nsf_tachi/v_nsf_tachi.blend b/neo/modelsrc/weapons/nsf_tachi/v_nsf_tachi.blend deleted file mode 100644 index 88e7aa9f..00000000 Binary files a/neo/modelsrc/weapons/nsf_tachi/v_nsf_tachi.blend and /dev/null differ diff --git a/neo/modelsrc/weapons/nsf_tachi/v_nsf_tachi.qc b/neo/modelsrc/weapons/nsf_tachi/v_nsf_tachi.qc index 3ef1a93b..bb1d4090 100644 --- a/neo/modelsrc/weapons/nsf_tachi/v_nsf_tachi.qc +++ b/neo/modelsrc/weapons/nsf_tachi/v_nsf_tachi.qc @@ -1,75 +1,2 @@ $modelname "weapons/v_nsf_tachi.mdl" -$cdmaterials "models/Weapons/" -$body "body" "reference.smd" -$definebone "Dummy01" "" -2.277793 -6.712466 -19.960323 -0.000000 89.999978 0.000000 0 0 0 0 0 0 -$definebone "bone forearm01" "Dummy01" -6.973125 11.498295 -10.988396 -31.114590 90.939514 89.978900 0 0 0 0 0 0 -$definebone "bone hand01" "bone forearm01" -0.035541 -23.756721 -0.084862 -0.042628 -1.058999 -0.805063 0 0 0 0 0 0 -$definebone "bone middle 05" "bone hand01" 0.273360 -3.765809 -0.387136 -0.000000 -0.000001 -0.000000 0 0 0 0 0 0 -$definebone "bone middle 06" "bone middle 05" 0.000002 -3.784243 -0.191475 -10.216125 -0.000002 -0.116826 0 0 0 0 0 0 -$definebone "bone middle 07" "bone middle 06" 0.024372 -3.235442 0.175100 -0.154929 0.133554 -12.925470 0 0 0 0 0 0 -$definebone "bone middle 08" "bone middle 07" -0.111963 -3.553718 0.074803 4.989030 0.902865 -18.339691 0 0 0 0 0 0 -$definebone "bone index 05" "bone hand01" 1.858448 -3.773904 0.198660 -14.044973 4.338951 -0.000000 0 0 0 0 0 0 -$definebone "bone index 06" "bone index 05" 0.000004 -3.784240 -0.191475 5.207097 -1.406557 -6.343559 0 0 0 0 0 0 -$definebone "bone index 07" "bone index 06" 0.074586 -3.334557 0.036040 -0.154928 0.133556 -12.948845 0 0 0 0 0 0 -$definebone "bone index 08" "bone index 07" -0.033768 -2.966134 0.050352 1.496623 2.758618 -18.165053 0 0 0 0 0 0 -$definebone "bone ring 05" "bone hand01" -1.407701 -3.765813 -0.387136 0.000000 -5.445049 0.000000 0 0 0 0 0 0 -$definebone "bone ring 06" "bone ring 05" 0.000002 -3.784244 -0.191475 -7.169937 1.442592 -0.480196 0 0 0 0 0 0 -$definebone "bone ring 07" "bone ring 06" 0.038987 -2.749642 0.107386 -1.660432 -2.201248 -12.888514 0 0 0 0 0 0 -$definebone "bone ring 08" "bone ring 07" 0.013190 -3.474698 0.024520 1.138697 2.167728 -31.676656 0 0 0 0 0 0 -$definebone "bone pinky 05" "bone hand01" -2.992724 -3.619925 0.091621 -0.000000 -9.635662 -0.000000 0 0 0 0 0 0 -$definebone "bone pinky 06" "bone pinky 05" -0.231696 -2.899982 -0.226467 -7.169938 1.442592 -2.020135 0 0 0 0 0 0 -$definebone "bone pinky 07" "bone pinky 06" 0.047093 -3.464708 0.060474 0.392362 0.981704 -12.970447 0 0 0 0 0 0 -$definebone "bone pinky 08" "bone pinky 07" -0.012931 -2.746934 0.096229 -4.151539 3.541852 -14.719691 0 0 0 0 0 0 -$definebone "bone thumb 04" "bone hand01" 2.231814 -1.416993 1.590842 -38.208904 65.612956 -60.895681 0 0 0 0 0 0 -$definebone "bone thumb 05" "bone thumb 04" 0.316679 -3.892339 -0.185575 -33.168527 -11.613910 -10.910492 0 0 0 0 0 0 -$definebone "bone thumb 06" "bone thumb 05" 0.269053 -3.933444 0.328680 5.133243 -12.418461 -13.006143 0 0 0 0 0 0 -$definebone "bone forearm" "Dummy01" 12.577013 11.498295 1.716358 31.114527 -89.060440 -89.978894 0 0 0 0 0 0 -$definebone "bone hand" "bone forearm" 0.035544 23.756721 -0.084859 -14.678660 2.606786 -11.549912 0 0 0 0 0 0 -$definebone "bone middle 1" "bone hand" -0.273364 3.765811 0.387137 0.000003 0.000001 0.000002 0 0 0 0 0 0 -$definebone "bone middle 2" "bone middle 1" -0.000001 3.784237 0.191473 -8.198563 3.499229 -25.560163 0 0 0 0 0 0 -$definebone "bone middle 3" "bone middle 2" -0.024372 3.235442 -0.175100 -0.154925 0.133562 -71.831997 0 0 0 0 0 0 -$definebone "bone middle 4" "bone middle 3" 0.111963 3.553717 -0.074805 4.989024 0.902872 -78.199574 0 0 0 0 0 0 -$definebone "bone index 1" "bone hand" -1.858449 3.773898 -0.198660 -14.044967 4.338953 0.000002 0 0 0 0 0 0 -$definebone "bone index 2" "bone index 1" -0.000001 3.784236 0.191477 5.346332 -0.276393 -7.004521 0 0 0 0 0 0 -$definebone "bone index 3" "bone index 2" -0.074585 3.334558 -0.036042 -0.154921 0.133558 -12.832018 0 0 0 0 0 0 -$definebone "bone index 4" "bone index 3" 0.033765 2.966134 -0.050352 1.496628 2.758624 -49.071600 0 0 0 0 0 0 -$definebone "bone ring 1" "bone hand" 1.407699 3.765804 0.387136 0.000003 -5.445046 0.000002 0 0 0 0 0 0 -$definebone "bone ring 2" "bone ring 1" -0.000003 3.784241 0.191476 -6.664011 2.311486 -40.444693 0 0 0 0 0 0 -$definebone "bone ring 3" "bone ring 2" -0.038986 2.749646 -0.107382 -1.660430 -2.201242 -72.795031 0 0 0 0 0 0 -$definebone "bone ring 4" "bone ring 3" -0.013189 3.474696 -0.024517 1.138692 2.167730 -81.536477 0 0 0 0 0 0 -$definebone "bone pinky 1" "bone hand" 2.992723 3.619924 -0.091623 0.000004 -9.635659 0.000002 0 0 0 0 0 0 -$definebone "bone pinky 2" "bone pinky 1" 0.231693 2.899976 0.226466 -7.169932 1.442595 -41.833261 0 0 0 0 0 0 -$definebone "bone pinky 3" "bone pinky 2" -0.047095 3.464705 -0.060474 0.392365 0.981709 -77.830297 0 0 0 0 0 0 -$definebone "bone pinky 4" "bone pinky 3" 0.012933 2.746925 -0.096229 -4.151539 3.541855 -65.579491 0 0 0 0 0 0 -$definebone "bone thumb 1" "bone hand" -2.231816 1.416988 -1.590842 -46.604322 61.384001 -55.069086 0 0 0 0 0 0 -$definebone "bone thumb 2" "bone thumb 1" -0.316676 3.892338 0.185578 -33.168533 -11.613905 -33.910502 0 0 0 0 0 0 -$definebone "bone thumb 3" "bone thumb 2" -0.269053 3.933444 -0.328678 5.133236 -12.418460 -66.142942 0 0 0 0 0 0 -$definebone "magrel" "bone hand" -1.389966 15.611851 -2.785499 87.000140 -92.999972 90.000075 0 0 0 0 0 0 -$definebone "slide" "magrel" 0.000001 1.764277 6.216676 0.000004 0.000004 0.000001 0 0 0 0 0 0 -$definebone "Eject" "slide" -0.120959 -0.439801 -0.840956 -10.016456 178.846850 0.201737 0 0 0 0 0 0 -$definebone "body" "magrel" 0.000000 -0.000001 -0.000000 0.000004 0.000004 0.000001 0 0 0 0 0 0 -$definebone "catch2" "body" 0.000001 0.367147 3.416009 0.000004 0.000004 0.000001 0 0 0 0 0 0 -$definebone "bullet_eject01" "body" -0.000000 4.833648 3.431723 0.000004 0.000004 0.000001 0 0 0 0 0 0 -$definebone "trigger" "magrel" 0.000000 1.612491 2.633620 0.000004 0.000004 0.000001 0 0 0 0 0 0 -$definebone "mag" "magrel" -0.059484 7.270134 1.720140 0.000004 0.000004 7.999981 0 0 0 0 0 0 -$definebone "bullet2" "mag" 0.059484 -7.270135 -1.720142 0.000004 0.000003 0.000002 0 0 0 0 0 0 -$definebone "Main" "magrel" -0.000622 3.390026 5.182981 -1.337800 -89.989460 89.981534 0 0 0 0 0 0 -$definebone "Muzzle" "Main" 16.557522 -0.000008 -0.000003 -0.000004 0.041881 0.000005 0 0 0 0 0 0 -$attachment "muzzle" "Muzzle" 0.0000 -0.0000 0.0000 rotate 0.000 -0.000 -0.000 -$attachment "eject" "Eject" 0.0000 -0.0000 0.0000 rotate -0.000 -0.000 0.000 -$sequence "idle01" "anims/idle01.smd" activity ACT_VM_IDLE 1 fps 30 fadein 0.20 fadeout 0.20 loop node "0" -$sequence "idle01empty" "anims/idle01empty.smd" activity ACT_VM_IDLE_EMPTY 1 fps 30 fadein 0.20 fadeout 0.20 loop node "0" -$sequence "fire" "anims/fire.smd" activity ACT_VM_PRIMARYATTACK 1 fps 30 fadein 0.20 fadeout 0.20 snap node "2" { event AE_MUZZLEFLASH 0 "PISTOL MUZZLE" } -$sequence "fire1" "anims/fire1.smd" activity ACT_VM_RECOIL1 1 fps 30 fadein 0.20 fadeout 0.20 snap node "2" { event AE_MUZZLEFLASH 0 "PISTOL MUZZLE" } -$sequence "fire2" "anims/fire2.smd" activity ACT_VM_RECOIL2 1 fps 30 fadein 0.20 fadeout 0.20 snap node "2" { event AE_MUZZLEFLASH 0 "PISTOL MUZZLE" } -$sequence "fire3" "anims/fire3.smd" activity ACT_VM_RECOIL3 1 fps 30 fadein 0.20 fadeout 0.20 snap node "2" { event AE_MUZZLEFLASH 0 "PISTOL MUZZLE" } -$sequence "fireempty" "anims/fireempty.smd" activity ACT_VM_DRYFIRE 1 fps 30 fadein 0.20 fadeout 0.20 node "2" -$sequence "draw" "anims/draw.smd" activity ACT_VM_DRAW 1 fps 30 fadein 0.20 fadeout 0.20 snap node "0" -$sequence "drawempty" "anims/drawempty.smd" fps 30 fadein 0.20 fadeout 0.20 node "0" -$sequence "reload" "anims/reload.smd" activity ACT_VM_RELOAD 1 fps 30 fadein 0.20 fadeout 0.20 node "0" -$sequence "holster" "anims/holster.smd" activity ACT_VM_HOLSTER 1 fps 30 fadein 0.20 fadeout 0.20 node "0" -$sequence "holsterempty" "anims/holsterempty.smd" activity ACT_VM_HOLSTER 1 fps 30 fadein 0.20 fadeout 0.20 node "0" -$sequence "idletolow" "anims/idletolow.smd" activity ACT_VM_LOWERED_TO_IDLE 1 fps 30 fadein 0.20 fadeout 0.20 transition "0" "1" -$sequence "lowtoidle" "anims/lowtoidle.smd" activity ACT_VM_IDLE_TO_LOWERED 1 fps 30 fadein 0.20 fadeout 0.20 transition "1" "0" -$sequence "lowidle" "anims/lowidle.smd" activity ACT_VM_IDLE_LOWERED 1 fps 30 fadein 0.20 fadeout 0.20 loop node "1" -$sequence "reloadempty" "anims/reloadempty.smd" activity ACT_VM_RELOAD_EMPTY 1 fps 30 fadein 0.20 fadeout 0.20 node "0" +$include "../tachi/viewmodel.qci" diff --git a/neo/modelsrc/weapons/rom_limits.py b/neo/modelsrc/weapons/rom_limits.py new file mode 100644 index 00000000..83d5af5c --- /dev/null +++ b/neo/modelsrc/weapons/rom_limits.py @@ -0,0 +1,505 @@ +"""Range-of-motion limits on the viewmodel rigs: write rom_spec.json, put its limits on the rigs, check them. + +Run from this folder (Blender 5.2.3 or newer, Blender Source Tools 3.4.3 or newer): + blender -b viewmodels.blend --python-exit-code 1 --python rom_limits.py -- COMMAND [PROJECT ...] +COMMAND: + spec write rom_spec.json from the keyed poses of the shipped slots (the slots the project's .qc compiles + from its own anims/). Changes nothing in viewmodels.blend. Runtime ~7 s for every project. + apply put the limits of rom_spec.json on the rigs and save viewmodels.blend. Runtime ~4 s. + check change nothing; list every (slot, bone) whose constrained pose differs from its keys (a clamp); + exit code 3 if any. export_viewmodels.py runs this check before it writes any SMD. ~12 s for all. + mute-on, mute-off mute or unmute every ROM:* constraint and save viewmodels.blend. +Without PROJECT, every project scene. check also takes --plant PROJECT/BONE:SLOT:FRAME:AXIS:DEGREES, which keys a +test rotation in memory first (to see the check fail). + +Each limited bone gets ROM:loc (Limit Location) and ROM:rot (Limit Rotation), Local Space, Affect Transform on, and +transform locks on the axes it never moves. The limit is the bone's range in the shipped slots of its gun (the one +rig of the gun's scene, jinrai_GUN; the NSF preview mesh follows that rig) plus a margin. Gun bones take their range without the melee slot, +which swings them freely; their ROM:* influence is keyed to 0 in that slot. Bones that move freely (roots, +forearms, magazines) get no limit. rom_widen.json lists the authored poses a limit is widened to cover, with the +reason (one entry per line: gun, bone, slots, why). +apply deletes and re-adds every ROM:* constraint, so a second run changes nothing. +""" +from pathlib import Path +import json +import math +import sys + +import bpy +from mathutils import Euler + +sys.dont_write_bytecode = True # importing export_viewmodels must not leave __pycache__ in the tree + +ROOT = Path(__file__).resolve().parent +SPEC = ROOT / 'rom_spec.json' +PREFIX = 'ROM:' +COLLECTION = 'ROM limited' +MARGIN_UNITS, MARGIN_DEGREES = 0.05, 0.5 # above the keys' own noise, below a visible pose change +STILL_UNITS, STILL_DEGREES = 0.02, 0.2 # a bone moving less than this on an axis is locked there +LINE = 0.05 # a motion whose second spread is below this share of the first runs along one axis +CLAMP_UNITS, CLAMP_DEGREES = 1e-4, 0.01 # above the float round-off of an active constraint (4e-5 u, 1.1e-4 deg) +ARM_PREFIX = 'bone ' +MELEE = 'melee' +WIDEN_FILE = ROOT / 'rom_widen.json' # authored poses a limit is widened to cover: one entry per line + + +def read_widen(): + """{(gun, bone): (slots, reason)} from rom_widen.json: the authored poses a limit is widened to cover. The pose is + meant; the limit follows it.""" + widen = {} + if not WIDEN_FILE.is_file(): + return widen + for entry in json.loads(WIDEN_FILE.read_text(encoding='ascii')): + if set(entry) != {'gun', 'bone', 'slots', 'why'} or not entry['slots'] or not entry['why'].strip(): + raise RuntimeError('%s: each entry needs gun, bone, slots and a reason (why): %s' % ( + WIDEN_FILE.name, entry)) + key = (entry['gun'], entry['bone']) + if key in widen: + raise RuntimeError('%s lists %s / %s twice: merge the entries' % ((WIDEN_FILE.name,) + key)) + widen[key] = (tuple(entry['slots']), entry['why']) + return widen + + +def write_widen(widen): + """Write rom_widen.json, one entry per line and sorted, so a new widening is a one-line diff.""" + rows = [json.dumps({'gun': gun, 'bone': bone, 'slots': sorted(slots), 'why': why}) + for (gun, bone), (slots, why) in sorted(widen.items())] + WIDEN_FILE.write_text('[\n' + ',\n'.join(' ' + row for row in rows) + '\n]\n', encoding='ascii') + + +def add_widen(gun, bone, slots, why): + """Widen one bone's limit to cover the given slots, with the reason; earlier slots and reasons are kept.""" + widen = read_widen() + old_slots, old_why = widen.get((gun, bone), ((), '')) + reasons = old_why if why in old_why.split('; ') else '; '.join(filter(None, (old_why, why))) + widen[(gun, bone)] = (tuple(sorted(set(old_slots) | set(slots))), reasons) + write_widen(widen) + WIDEN.clear() + WIDEN.update(widen) + + +WIDEN = read_widen() + + +def project_scenes(names): + scenes = [scene for scene in bpy.data.scenes if scene.objects.get(scene.name + '_rig')] + if names: + missing = sorted(set(names) - {scene.name for scene in scenes}) + if missing: + raise RuntimeError('No project scene named ' + ', '.join(missing)) + scenes = [scene for scene in scenes if scene.name in names] + return scenes + + +def rig_of(scene): + return scene.objects[scene.name + '_rig'] + + +def gun_of(project): + return project.partition('_')[2] + + +def slot_bags(rig): + """(slot, channelbag, first frame, last frame) for every slot of the rig's action; the frames of the pose keys.""" + action = rig.animation_data.action + strip = action.layers[0].strips[0] + for slot in action.slots: + bag = strip.channelbag(slot) + frames = [key.co[0] for curve in bag.fcurves if PREFIX not in curve.data_path for key in curve.keyframe_points] + yield slot, bag, int(round(min(frames))), int(round(max(frames))) + + +def is_limited(pose_bone): + return any(c.name.startswith(PREFIX) and not c.mute and c.influence > 0 for c in pose_bone.constraints) + + +# ---- spec ---- + +def keyed_poses(scene): + """{slot: array [frames, bones, 7]} of the keyed local pose (location, normalized quaternion wxyz), read from + the F-curves before any constraint, and the bones' rest matrices relative to their parents.""" + import numpy as np + rig = rig_of(scene) + names = [bone.name for bone in rig.data.bones] + poses = {} + for slot, bag, first, last in slot_bags(rig): + curves = {(curve.data_path, curve.array_index): curve for curve in bag.fcurves} + frames = range(first, last + 1) + values = np.zeros((len(frames), len(names), 7)) + values[:, :, 3] = 1.0 + for index, name in enumerate(names): + for offset, path, count in ((0, 'location', 3), (3, 'rotation_quaternion', 4)): + for axis in range(count): + curve = curves.get(('pose.bones["%s"].%s' % (name, path), axis)) + if curve is not None: + values[:, index, offset + axis] = [curve.evaluate(frame) for frame in frames] + quaternions = values[:, :, 3:] + values[:, :, 3:] = quaternions / np.linalg.norm(quaternions, axis=2, keepdims=True) + poses[slot.name_display] = values + rest = [] + for bone in rig.data.bones: + matrix = bone.matrix_local if bone.parent is None else bone.parent.matrix_local.inverted() @ bone.matrix_local + rest.append(np.array(matrix)) + return names, poses, np.array(rest) + + +EULER_ORDERS = {'XYZ': ((0, 1, 2), 0), 'XZY': ((0, 2, 1), 1), 'YXZ': ((1, 0, 2), 1), + 'YZX': ((1, 2, 0), 0), 'ZXY': ((2, 0, 1), 0), 'ZYX': ((2, 1, 0), 1)} + + +def quaternion_matrices(q): + import numpy as np + w, x, y, z = (q[..., i] for i in range(4)) + m = np.empty(q.shape[:-1] + (3, 3)) + m[..., 0, 0] = 1 - 2 * (y * y + z * z); m[..., 0, 1] = 2 * (x * y - w * z); m[..., 0, 2] = 2 * (x * z + w * y) + m[..., 1, 0] = 2 * (x * y + w * z); m[..., 1, 1] = 1 - 2 * (x * x + z * z); m[..., 1, 2] = 2 * (y * z - w * x) + m[..., 2, 0] = 2 * (x * z - w * y); m[..., 2, 1] = 2 * (y * z + w * x); m[..., 2, 2] = 1 - 2 * (x * x + y * y) + return m + + +def matrix_eulers(m, order): + """Blender's mat3_normalized_to_eulO in numpy (the angles Limit Rotation limits), radians [..., 3].""" + import numpy as np + (i, j, k), parity = EULER_ORDERS[order] + c = lambda a, b: m[..., b, a] + cy = np.hypot(c(i, i), c(i, j)) + first, second = np.zeros(m.shape[:-2] + (3,)), np.zeros(m.shape[:-2] + (3,)) + big = cy > 16.0 * np.finfo(np.float32).eps + first[..., i] = np.where(big, np.arctan2(c(j, k), c(k, k)), np.arctan2(-c(k, j), c(j, j))) + first[..., j] = np.arctan2(-c(i, k), cy) + first[..., k] = np.where(big, np.arctan2(c(i, j), c(i, i)), 0.0) + second[..., i] = np.where(big, np.arctan2(-c(j, k), -c(k, k)), first[..., i]) + second[..., j] = np.where(big, np.arctan2(-c(i, k), -cy), first[..., j]) + second[..., k] = np.where(big, np.arctan2(-c(i, j), -c(i, i)), first[..., k]) + if parity: + first, second = -first, -second + pick = np.abs(first).sum(-1) > np.abs(second).sum(-1) + return np.where(pick[..., None], second, first) + + +def rotation_vectors(q): + import numpy as np + q = np.where(q[..., :1] < 0, -q, q) + sine = np.linalg.norm(q[..., 1:], axis=-1) + angle = 2 * np.arctan2(sine, q[..., 0]) + return q[..., 1:] * np.where(sine > 1e-12, angle / np.maximum(sine, 1e-12), 2.0)[..., None] + + +def arc(degrees): + """The shortest circular range [low, high] (low < high) that holds every angle.""" + import numpy as np + a = np.sort(np.mod(degrees, 360.0)) + gaps = np.diff(np.concatenate([a, [a[0] + 360]])) + widest = int(np.argmax(gaps)) + low = (a[(widest + 1) % len(a)] + 180) % 360 - 180 + return float(low), float(low + 360.0 - gaps[widest]) + + +def motion_class(samples): + """fixed, rail, hinge, rail+hinge, free_translate, free_rotate or free, from the spread of the motion.""" + import numpy as np + + def spreads(x): + centered = x - x.mean(0) + return np.linalg.svd(centered, compute_uv=False) / math.sqrt(len(x)) if len(x) > 1 else np.zeros(3) + + location, rotation = samples[:, :3], np.degrees(rotation_vectors(samples[:, 3:])) + moves = np.ptp(location, 0).max() > STILL_UNITS, np.ptp(rotation, 0).max() > STILL_DEGREES + lines = [move and s[1] < LINE * s[0] for move, s in zip(moves, (spreads(location), spreads(rotation)))] + if not any(moves): + return 'fixed' + if not moves[1]: + return 'rail' if lines[0] else 'free_translate' + if not moves[0]: + return 'hinge' if lines[1] else 'free_rotate' + return 'rail+hinge' if all(lines) else 'free' + + +def limits(samples, label): + """The spec entry of a bone that moves through samples [n, 7]: Euler order with the smallest summed range, + locked axes, and Limit Location / Limit Rotation ranges widened by the margin, rounded outward.""" + import numpy as np + if label == 'free': + return {'cls': 'free'} + matrices = quaternion_matrices(samples[:, 3:]) + best = None + for order in EULER_ORDERS: + eulers = np.degrees(matrix_eulers(matrices, order)) + ranges = [arc(eulers[:, axis]) for axis in range(3)] + total = sum(high - low for low, high in ranges) + if best is None or total < best[0] - 0.01: + best = (total, order, ranges) + location = samples[:, :3] + spin = np.ptp(np.degrees(rotation_vectors(samples[:, 3:])), 0) + down = lambda x, digits: math.floor(x * 10 ** digits) / 10 ** digits + up = lambda x, digits: math.ceil(x * 10 ** digits) / 10 ** digits + return {'cls': label, 'order': best[1], + 'lock_loc': [bool(np.ptp(location[:, axis]) < STILL_UNITS) for axis in range(3)], + 'lock_rot': [bool(s < STILL_DEGREES) for s in spin], + 'loc': [[down(location[:, axis].min() - MARGIN_UNITS, 3), up(location[:, axis].max() + MARGIN_UNITS, 3)] + for axis in range(3)], + 'rot_deg': [[down(low - MARGIN_DEGREES, 2), up(high + MARGIN_DEGREES, 2)] for low, high in best[2]]} + + +def outside(entry, samples): + """Whether any sample lies outside the entry's limits.""" + import numpy as np + eulers = np.degrees(matrix_eulers(quaternion_matrices(samples[:, 3:]), entry['order'])) + for axis in range(3): + low, high = entry['loc'][axis] + if ((samples[:, axis] < low) | (samples[:, axis] > high)).any(): + return True + low, high = entry['rot_deg'][axis] + middle = (low + high) / 2 + wrapped = (eulers[:, axis] - middle + 180) % 360 - 180 + middle + if ((wrapped < low) | (wrapped > high)).any(): + return True + return False + + +def bone_entry(project, bone, data, is_arm): + """The limit of one bone of a gun's project.""" + import numpy as np + own = data[project] + + def samples(slots): + return [own['poses'][s][:, own['names'].index(bone)] for s in slots if s in own['poses']] + + widened = WIDEN.get((gun_of(project), bone)) + calm = samples([s for s in own['shipped'] if not s.startswith(MELEE)]) + melee = samples([s for s in own['shipped'] if s.startswith(MELEE)]) + extra = samples(widened[0]) if widened else [] + label = motion_class(np.concatenate(calm)) + shipped = calm + melee + if is_arm: + entry = limits(np.concatenate(shipped + extra), label) + else: + entry = limits(np.concatenate(calm + extra), label) + if label != 'free' and melee and outside(entry, np.concatenate(melee)): + entry['exempt_slots'] = sorted(s for s in own['shipped'] if s.startswith(MELEE)) + if extra and label != 'free': + entry['why'] = widened[1] + return entry + + +def make_spec(scenes): + import export_viewmodels + data = {} + for scene in scenes: + names, poses, rest = keyed_poses(scene) + shipped = sorted(export_viewmodels.shipped_slots(ROOT / scene.name) & set(poses)) + data[scene.name] = dict(names=names, poses=poses, rest=rest, shipped=shipped) + spec = {'version': 3, 'space': 'LOCAL', 'margin': {'loc': MARGIN_UNITS, 'rot_deg': MARGIN_DEGREES}, + 'lock_eps': {'loc': STILL_UNITS, 'rot_deg': STILL_DEGREES}, + 'note': 'written by rom_limits.py spec from the shipped slots; change rom_widen.json or rom_limits.py, ' + 'not this file', + 'guns': {}} + for project in sorted(data): + if gun_of(project) in spec['guns']: + raise RuntimeError('Two scenes for gun %s: one scene per gun (run merge_teams.py)' % gun_of(project)) + bones = {bone: bone_entry(project, bone, data, bone.startswith(ARM_PREFIX)) for bone in data[project]['names']} + spec['guns'][gun_of(project)] = {'project': project, 'bones': bones} + print('SPEC', project, len(data[project]['shipped']), 'shipped slots', + sorted(set(data[project]['poses']) - set(data[project]['shipped'])), 'left out') + SPEC.write_text(spec_text(spec), encoding='ascii') + print('WROTE', SPEC.name, len(spec['guns']), 'guns') + + +def spec_text(spec): + """JSON with one bone per line, keys sorted: a limit change is a one-line diff.""" + def bones(entries, indent): + rows = ['%s %s: %s' % (indent, json.dumps(b), json.dumps(entries[b], sort_keys=True)) for b in sorted(entries)] + return '{\n' + ',\n'.join(rows) + '\n' + indent + '}' + head = [' %s: %s' % (json.dumps(k), json.dumps(v, sort_keys=True)) for k, v in sorted(spec.items()) if k != 'guns'] + guns = [] + for gun in sorted(spec['guns']): + section = spec['guns'][gun] + guns.append(' %s: {\n "project": %s,\n "bones": %s\n }' % ( + json.dumps(gun), json.dumps(section['project']), bones(section['bones'], ' '))) + text = '{\n' + ',\n'.join(head + [' "guns": {\n' + ',\n'.join(guns) + '\n }']) + '\n}\n' + assert json.loads(text) == json.loads(json.dumps(spec)) + return text + + +# ---- apply, mute, check ---- + +def spec_entry(spec, project, bone): + section = spec['guns'].get(gun_of(project)) + if section is None or section.get('project') != project: + raise RuntimeError('rom_spec.json has no gun section for %s: run rom_limits.py spec' % project) + entry = section['bones'].get(bone) + if entry is None: + raise RuntimeError('rom_spec.json has no entry for %s / %s: run rom_limits.py spec' % (project, bone)) + return entry + + +def apply_limits(scene, spec): + rig = rig_of(scene) + collection = rig.data.collections_all.get(COLLECTION) or rig.data.collections.new(COLLECTION) + exempt = {} + for pose_bone in rig.pose.bones: + for constraint in [c for c in pose_bone.constraints if c.name.startswith(PREFIX)]: + pose_bone.constraints.remove(constraint) + entry = spec_entry(spec, scene.name, pose_bone.name) + if entry['cls'] == 'free': + pose_bone.lock_location = pose_bone.lock_rotation = (False,) * 3 + collection.unassign(pose_bone.bone) + continue + location = pose_bone.constraints.new('LIMIT_LOCATION') + location.name = PREFIX + 'loc' + for axis, name in enumerate('xyz'): + setattr(location, 'use_min_' + name, True) + setattr(location, 'use_max_' + name, True) + setattr(location, 'min_' + name, entry['loc'][axis][0]) + setattr(location, 'max_' + name, entry['loc'][axis][1]) + rotation = pose_bone.constraints.new('LIMIT_ROTATION') + rotation.name = PREFIX + 'rot' + rotation.euler_order = entry['order'] + rotation.use_legacy_behavior = False + for axis, name in enumerate('xyz'): + setattr(rotation, 'use_limit_' + name, True) + setattr(rotation, 'min_' + name, math.radians(entry['rot_deg'][axis][0])) + setattr(rotation, 'max_' + name, math.radians(entry['rot_deg'][axis][1])) + for constraint in (location, rotation): + constraint.owner_space = 'LOCAL' + constraint.use_transform_limit = True + constraint.influence = 1.0 + constraint.mute = False + pose_bone.lock_location = entry['lock_loc'] + pose_bone.lock_rotation = entry['lock_rot'] + collection.assign(pose_bone.bone) + if entry.get('exempt_slots'): + exempt[pose_bone.name] = set(entry['exempt_slots']) + for slot, bag, first, last in slot_bags(rig): + for curve in [curve for curve in bag.fcurves if PREFIX in curve.data_path]: + bag.fcurves.remove(curve) + for bone in sorted(exempt): + for name in (PREFIX + 'loc', PREFIX + 'rot'): + curve = bag.fcurves.new('pose.bones["%s"].constraints["%s"].influence' % (bone, name)) + key = curve.keyframe_points.insert(first, 0.0 if slot.name_display in exempt[bone] else 1.0) + key.interpolation = 'CONSTANT' + limited = sum(1 for pose_bone in rig.pose.bones if is_limited(pose_bone)) + print('APPLIED', scene.name, limited, 'limited bones,', len(exempt), 'free in the melee slot') + + +def set_mute(scene, mute): + for pose_bone in rig_of(scene).pose.bones: + for constraint in pose_bone.constraints: + if constraint.name.startswith(PREFIX): + constraint.mute = mute + + +def plant_key(scene, text): + """Key a test rotation (degrees about a local axis) on BONE:SLOT:FRAME:AXIS:DEGREES; never saved.""" + bone, slot_name, frame, axis, degrees = text.split(':') + rig = rig_of(scene) + action = rig.animation_data.action + slot = next(s for s in action.slots if s.name_display == slot_name) + bag = action.layers[0].strips[0].channelbag(slot) + rig.animation_data.action_slot = slot + scene.frame_set(int(frame)) + turn = Euler((0, 0, 0)) + turn['xyz'.index(axis)] = math.radians(float(degrees)) + rotation = rig.pose.bones[bone].rotation_quaternion @ turn.to_quaternion() + for index in range(4): + curve = bag.fcurves.find('pose.bones["%s"].rotation_quaternion' % bone, index=index) + curve.keyframe_points.insert(int(frame), rotation[index]) + print('PLANTED', scene.name, text) + + +def find_clamps(scene, slots=None): + """[(slot, bone, first frame, last frame, frames, worst units, worst degrees)] where an active ROM constraint + moves the evaluated pose off the keyed pose. Leaves the rig on its first slot.""" + rig = rig_of(scene) + if not any(is_limited(pose_bone) for pose_bone in rig.pose.bones): + return [] + with bpy.context.temp_override(scene=scene, view_layer=scene.view_layers[0]): + depsgraph = bpy.context.evaluated_depsgraph_get() # a background scene has none until asked + clamps = [] + for slot, bag, first, last in slot_bags(rig): + if slots is not None and slot.name_display not in slots: + continue + rig.animation_data.action_slot = slot + worst = {} + for frame in range(first, last + 1): + scene.frame_set(frame) + evaluated = rig.evaluated_get(depsgraph) + for pose_bone in evaluated.pose.bones: + if not is_limited(pose_bone): + continue + local = evaluated.convert_space(pose_bone=pose_bone, matrix=pose_bone.matrix, + from_space='POSE', to_space='LOCAL') + keyed = pose_bone.matrix_basis + units = (local.to_translation() - keyed.to_translation()).length + angle = local.to_quaternion().rotation_difference(keyed.to_quaternion()).angle + degrees = math.degrees(min(angle, 2 * math.pi - angle)) + if units > CLAMP_UNITS or degrees > CLAMP_DEGREES: + w = worst.setdefault(pose_bone.name, [frame, frame, 0, 0.0, 0.0]) + w[1] = frame + w[2] += 1 + w[3] = max(w[3], units) + w[4] = max(w[4], degrees) + clamps += [(slot.name_display, bone) + tuple(w) for bone, w in sorted(worst.items())] + rig.animation_data.action_slot = rig.animation_data.action.slots[0] + return clamps + + +def clamp_text(project, clamp): + slot, bone, first, last, count, units, degrees = clamp + return '%s slot %s bone "%s" frames %d-%d (%d clamped): %.4f u, %.3f deg past its limit' % ( + project, slot, bone, first, last, count, units, degrees) + + +def main(): + arguments = sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else [] + if not arguments: + raise RuntimeError('Name a command: spec, apply, check, mute-on or mute-off') + command, names, plants = arguments[0], [], [] + rest = iter(arguments[1:]) + for argument in rest: + if argument == '--plant': + plants.append(next(rest)) + else: + names.append(argument) + bpy.ops.preferences.addon_enable(module='io_scene_valvesource') + sys.path.insert(0, str(ROOT)) + scenes = project_scenes(names) + if command == 'spec': + make_spec(scenes) + return + if command in ('apply', 'mute-on', 'mute-off'): + spec = json.loads(SPEC.read_text(encoding='ascii')) if command == 'apply' else None + for scene in scenes: + if spec: + apply_limits(scene, spec) + else: + set_mute(scene, command == 'mute-on') + print('MUTED' if command == 'mute-on' else 'UNMUTED', scene.name) + bpy.ops.wm.save_mainfile() + backup = Path(bpy.data.filepath + '1') + if backup.exists(): + backup.unlink() + print('SAVED', bpy.data.filepath) + return + if command != 'check': + raise RuntimeError('Unknown command ' + command) + found = 0 + for scene in scenes: + for text in plants: + if text.startswith(scene.name + '/'): + plant_key(scene, text.partition('/')[2]) + clamps = find_clamps(scene) + for clamp in clamps: + print('CLAMP', clamp_text(scene.name, clamp)) + print('CHECK', scene.name, len(clamps), 'clamped (slot, bone) pairs') + found += len(clamps) + if found: + sys.exit(3) + + +if __name__ == '__main__': + try: + main() + except RuntimeError as problem: + print('ROM FAILED:', problem) + sys.exit(1) diff --git a/neo/modelsrc/weapons/rom_spec.json b/neo/modelsrc/weapons/rom_spec.json new file mode 100644 index 00000000..c7ec434d --- /dev/null +++ b/neo/modelsrc/weapons/rom_spec.json @@ -0,0 +1,68 @@ +{ + "lock_eps": {"loc": 0.02, "rot_deg": 0.2}, + "margin": {"loc": 0.05, "rot_deg": 0.5}, + "note": "written by rom_limits.py spec from the shipped slots; change rom_widen.json or rom_limits.py, not this file", + "space": "LOCAL", + "version": 3, + "guns": { + "tachi": { + "project": "jinrai_tachi", + "bones": { + "Dummy01": {"cls": "free"}, + "Eject": {"cls": "fixed", "loc": [[-0.051, 0.05], [-0.051, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.5, 0.51], [-0.5, 0.51]]}, + "Main": {"cls": "fixed", "loc": [[-0.051, 0.05], [-0.05, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.5, 0.51]]}, + "Muzzle": {"cls": "fixed", "loc": [[-0.051, 0.051], [-0.051, 0.05], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.5, 0.51], [-0.51, 0.5]]}, + "body": {"cls": "fixed", "loc": [[-0.051, 0.051], [-0.051, 0.051], [-0.051, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.5, 0.51]]}, + "bone forearm": {"cls": "free"}, + "bone forearm01": {"cls": "free"}, + "bone hand": {"cls": "free_rotate", "loc": [[-0.051, 0.05], [-0.05, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [false, false, false], "order": "YXZ", "rot_deg": [[-2.37, 18.83], [-0.51, 21.82], [-33.95, 18.91]]}, + "bone hand01": {"cls": "free_rotate", "loc": [[-0.051, 0.05], [-0.051, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [false, false, false], "order": "XZY", "rot_deg": [[-0.5, 41.84], [-9.27, 74.12], [-13.98, 12.78]]}, + "bone index 05": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.05, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.5, 0.51]]}, + "bone index 06": {"cls": "hinge", "loc": [[-0.051, 0.05], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-15.43, 0.5], [-0.5, 0.51], [-0.51, 0.5]]}, + "bone index 07": {"cls": "hinge", "loc": [[-0.051, 0.051], [-0.051, 0.051], [-0.051, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-25.39, 0.51], [-0.51, 0.5], [-0.5, 0.51]]}, + "bone index 08": {"cls": "hinge", "loc": [[-0.051, 0.05], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-20.41, 0.5], [-0.5, 0.51], [-0.51, 0.5]]}, + "bone index 1": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.5, 0.51], [-0.5, 0.51]]}, + "bone index 2": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.5, 0.51]]}, + "bone index 3": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.051, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.51, 0.5], [-0.5, 0.51], [-0.51, 0.5]]}, + "bone index 4": {"cls": "hinge", "loc": [[-0.051, 0.05], [-0.051, 0.051], [-0.051, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-30.51, 0.5], [-0.5, 0.51], [-0.5, 0.51]]}, + "bone middle 05": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.05, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.51, 0.5], [-0.51, 0.51], [-0.5, 0.51]]}, + "bone middle 06": {"cls": "hinge", "loc": [[-0.051, 0.051], [-0.051, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-25.39, 0.51], [-0.5, 0.51], [-0.51, 0.5]]}, + "bone middle 07": {"cls": "hinge", "loc": [[-0.05, 0.051], [-0.05, 0.051], [-0.051, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-20.41, 0.51], [-0.51, 0.5], [-0.5, 0.51]]}, + "bone middle 08": {"cls": "hinge", "loc": [[-0.051, 0.05], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-30.36, 0.5], [-0.5, 0.51], [-0.51, 0.5]]}, + "bone middle 1": {"cls": "fixed", "loc": [[-0.051, 0.051], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.5, 0.51], [-0.5, 0.51]]}, + "bone middle 2": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.5, 0.51]]}, + "bone middle 3": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.05, 0.051], [-0.051, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.51, 0.5], [-0.5, 0.51], [-0.5, 0.51]]}, + "bone middle 4": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.051, 0.05], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.51, 0.5]]}, + "bone pinky 05": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.051, 0.05], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.5, 0.51]]}, + "bone pinky 06": {"cls": "hinge", "loc": [[-0.051, 0.05], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-40.32, 0.5], [-0.5, 0.51], [-0.51, 0.5]]}, + "bone pinky 07": {"cls": "hinge", "loc": [[-0.05, 0.051], [-0.051, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-30.36, 0.51], [-0.5, 0.51], [-0.51, 0.5]]}, + "bone pinky 08": {"cls": "hinge", "loc": [[-0.05, 0.051], [-0.051, 0.051], [-0.051, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-30.36, 0.51], [-0.51, 0.5], [-0.51, 0.5]]}, + "bone pinky 1": {"cls": "fixed", "loc": [[-0.051, 0.051], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.5, 0.51], [-0.5, 0.51]]}, + "bone pinky 2": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.051, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.5, 0.51]]}, + "bone pinky 3": {"cls": "fixed", "loc": [[-0.051, 0.051], [-0.05, 0.051], [-0.051, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.51, 0.5], [-0.5, 0.51], [-0.5, 0.51]]}, + "bone pinky 4": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.051, 0.05], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.51, 0.5]]}, + "bone ring 05": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.051, 0.05], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.5, 0.51]]}, + "bone ring 06": {"cls": "hinge", "loc": [[-0.051, 0.05], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-30.37, 0.5], [-0.5, 0.51], [-0.51, 0.5]]}, + "bone ring 07": {"cls": "hinge", "loc": [[-0.051, 0.051], [-0.051, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-20.41, 0.51], [-0.5, 0.51], [-0.51, 0.5]]}, + "bone ring 08": {"cls": "hinge", "loc": [[-0.05, 0.051], [-0.051, 0.05], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-30.36, 0.51], [-0.5, 0.51], [-0.51, 0.5]]}, + "bone ring 1": {"cls": "fixed", "loc": [[-0.051, 0.051], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.5, 0.51], [-0.5, 0.51]]}, + "bone ring 2": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.051, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.5, 0.51], [-0.51, 0.5]]}, + "bone ring 3": {"cls": "fixed", "loc": [[-0.051, 0.05], [-0.05, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.51, 0.5], [-0.5, 0.51], [-0.5, 0.51]]}, + "bone ring 4": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.051, 0.05], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.5, 0.51], [-0.51, 0.5]]}, + "bone thumb 04": {"cls": "free_rotate", "loc": [[-0.05, 0.051], [-0.05, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [false, false, false], "order": "ZYX", "rot_deg": [[-0.5, 19.96], [-5.0, 0.91], [-16.75, 6.35]]}, + "bone thumb 05": {"cls": "hinge", "loc": [[-0.051, 0.05], [-0.051, 0.05], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-10.5, 7.92], [-0.5, 0.51], [-0.5, 0.51]]}, + "bone thumb 06": {"cls": "hinge", "loc": [[-0.051, 0.05], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-17.43, 4.98], [-0.5, 0.51], [-0.51, 0.5]]}, + "bone thumb 1": {"cls": "hinge", "loc": [[-0.05, 0.051], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, false], "order": "XYZ", "rot_deg": [[-0.5, 0.53], [-0.51, 0.56], [-5.5, 0.5]]}, + "bone thumb 2": {"cls": "hinge", "loc": [[-0.05, 0.051], [-0.05, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-10.51, 10.5], [-0.5, 0.51], [-0.5, 0.51]]}, + "bone thumb 3": {"cls": "hinge", "loc": [[-0.05, 0.051], [-0.051, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-0.5, 48.5], [-0.5, 0.51], [-0.51, 0.5]]}, + "bullet2": {"cls": "fixed", "loc": [[-0.05, 0.051], [-0.05, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.51], [-0.51, 0.5]]}, + "bullet_eject01": {"cls": "fixed", "loc": [[-0.051, 0.05], [-0.05, 0.051], [-0.051, 0.05]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.51, 0.5]]}, + "catch2": {"cls": "hinge", "loc": [[-0.051, 0.05], [-0.05, 0.051], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [false, true, true], "order": "XYZ", "rot_deg": [[-0.51, 5.5], [-0.51, 0.5], [-0.5, 0.51]]}, + "mag": {"cls": "free"}, + "magrel": {"cls": "fixed", "loc": [[-0.051, 0.05], [-0.051, 0.05], [-0.05, 0.051]], "lock_loc": [true, true, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.51, 0.5]]}, + "slide": {"cls": "rail", "loc": [[-0.051, 0.05], [-0.05, 3.504], [-0.05, 0.051]], "lock_loc": [true, false, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.5, 0.51]]}, + "trigger": {"cls": "rail", "loc": [[-0.051, 0.05], [-0.05, 1.047], [-0.051, 0.051]], "lock_loc": [true, false, true], "lock_rot": [true, true, true], "order": "XYZ", "rot_deg": [[-0.5, 0.51], [-0.51, 0.5], [-0.5, 0.51]]} + } + } + } +} diff --git a/neo/modelsrc/weapons/rom_widen.json b/neo/modelsrc/weapons/rom_widen.json new file mode 100644 index 00000000..fe51488c --- /dev/null +++ b/neo/modelsrc/weapons/rom_widen.json @@ -0,0 +1 @@ +[] diff --git a/neo/modelsrc/weapons/tachi/viewmodel.qci b/neo/modelsrc/weapons/tachi/viewmodel.qci new file mode 100644 index 00000000..720dc3ed --- /dev/null +++ b/neo/modelsrc/weapons/tachi/viewmodel.qci @@ -0,0 +1,74 @@ +$cdmaterials "models/Weapons/" +$body "body" "reference.smd" +$definebone "Dummy01" "" -2.277793 -6.712466 -19.960323 -0.000000 89.999978 0.000000 0 0 0 0 0 0 +$definebone "bone forearm01" "Dummy01" -6.973125 11.498295 -10.988396 -31.114590 90.939514 89.978900 0 0 0 0 0 0 +$definebone "bone hand01" "bone forearm01" -0.035541 -23.756721 -0.084862 -0.042628 -1.058999 -0.805063 0 0 0 0 0 0 +$definebone "bone middle 05" "bone hand01" 0.273360 -3.765809 -0.387136 -0.000000 -0.000001 -0.000000 0 0 0 0 0 0 +$definebone "bone middle 06" "bone middle 05" 0.000002 -3.784243 -0.191475 -10.216125 -0.000002 -0.116826 0 0 0 0 0 0 +$definebone "bone middle 07" "bone middle 06" 0.024372 -3.235442 0.175100 -0.154929 0.133554 -12.925470 0 0 0 0 0 0 +$definebone "bone middle 08" "bone middle 07" -0.111963 -3.553718 0.074803 4.989030 0.902865 -18.339691 0 0 0 0 0 0 +$definebone "bone index 05" "bone hand01" 1.858448 -3.773904 0.198660 -14.044973 4.338951 -0.000000 0 0 0 0 0 0 +$definebone "bone index 06" "bone index 05" 0.000004 -3.784240 -0.191475 5.207097 -1.406557 -6.343559 0 0 0 0 0 0 +$definebone "bone index 07" "bone index 06" 0.074586 -3.334557 0.036040 -0.154928 0.133556 -12.948845 0 0 0 0 0 0 +$definebone "bone index 08" "bone index 07" -0.033768 -2.966134 0.050352 1.496623 2.758618 -18.165053 0 0 0 0 0 0 +$definebone "bone ring 05" "bone hand01" -1.407701 -3.765813 -0.387136 0.000000 -5.445049 0.000000 0 0 0 0 0 0 +$definebone "bone ring 06" "bone ring 05" 0.000002 -3.784244 -0.191475 -7.169937 1.442592 -0.480196 0 0 0 0 0 0 +$definebone "bone ring 07" "bone ring 06" 0.038987 -2.749642 0.107386 -1.660432 -2.201248 -12.888514 0 0 0 0 0 0 +$definebone "bone ring 08" "bone ring 07" 0.013190 -3.474698 0.024520 1.138697 2.167728 -31.676656 0 0 0 0 0 0 +$definebone "bone pinky 05" "bone hand01" -2.992724 -3.619925 0.091621 -0.000000 -9.635662 -0.000000 0 0 0 0 0 0 +$definebone "bone pinky 06" "bone pinky 05" -0.231696 -2.899982 -0.226467 -7.169938 1.442592 -2.020135 0 0 0 0 0 0 +$definebone "bone pinky 07" "bone pinky 06" 0.047093 -3.464708 0.060474 0.392362 0.981704 -12.970447 0 0 0 0 0 0 +$definebone "bone pinky 08" "bone pinky 07" -0.012931 -2.746934 0.096229 -4.151539 3.541852 -14.719691 0 0 0 0 0 0 +$definebone "bone thumb 04" "bone hand01" 2.231814 -1.416993 1.590842 -38.208904 65.612956 -60.895681 0 0 0 0 0 0 +$definebone "bone thumb 05" "bone thumb 04" 0.316679 -3.892339 -0.185575 -33.168527 -11.613910 -10.910492 0 0 0 0 0 0 +$definebone "bone thumb 06" "bone thumb 05" 0.269053 -3.933444 0.328680 5.133243 -12.418461 -13.006143 0 0 0 0 0 0 +$definebone "bone forearm" "Dummy01" 12.577013 11.498295 1.716358 31.114527 -89.060440 -89.978894 0 0 0 0 0 0 +$definebone "bone hand" "bone forearm" 0.035544 23.756721 -0.084859 -14.678660 2.606786 -11.549912 0 0 0 0 0 0 +$definebone "bone middle 1" "bone hand" -0.273364 3.765811 0.387137 0.000003 0.000001 0.000002 0 0 0 0 0 0 +$definebone "bone middle 2" "bone middle 1" -0.000001 3.784237 0.191473 -8.198563 3.499229 -25.560163 0 0 0 0 0 0 +$definebone "bone middle 3" "bone middle 2" -0.024372 3.235442 -0.175100 -0.154925 0.133562 -71.831997 0 0 0 0 0 0 +$definebone "bone middle 4" "bone middle 3" 0.111963 3.553717 -0.074805 4.989024 0.902872 -78.199574 0 0 0 0 0 0 +$definebone "bone index 1" "bone hand" -1.858449 3.773898 -0.198660 -14.044967 4.338953 0.000002 0 0 0 0 0 0 +$definebone "bone index 2" "bone index 1" -0.000001 3.784236 0.191477 5.346332 -0.276393 -7.004521 0 0 0 0 0 0 +$definebone "bone index 3" "bone index 2" -0.074585 3.334558 -0.036042 -0.154921 0.133558 -12.832018 0 0 0 0 0 0 +$definebone "bone index 4" "bone index 3" 0.033765 2.966134 -0.050352 1.496628 2.758624 -49.071600 0 0 0 0 0 0 +$definebone "bone ring 1" "bone hand" 1.407699 3.765804 0.387136 0.000003 -5.445046 0.000002 0 0 0 0 0 0 +$definebone "bone ring 2" "bone ring 1" -0.000003 3.784241 0.191476 -6.664011 2.311486 -40.444693 0 0 0 0 0 0 +$definebone "bone ring 3" "bone ring 2" -0.038986 2.749646 -0.107382 -1.660430 -2.201242 -72.795031 0 0 0 0 0 0 +$definebone "bone ring 4" "bone ring 3" -0.013189 3.474696 -0.024517 1.138692 2.167730 -81.536477 0 0 0 0 0 0 +$definebone "bone pinky 1" "bone hand" 2.992723 3.619924 -0.091623 0.000004 -9.635659 0.000002 0 0 0 0 0 0 +$definebone "bone pinky 2" "bone pinky 1" 0.231693 2.899976 0.226466 -7.169932 1.442595 -41.833261 0 0 0 0 0 0 +$definebone "bone pinky 3" "bone pinky 2" -0.047095 3.464705 -0.060474 0.392365 0.981709 -77.830297 0 0 0 0 0 0 +$definebone "bone pinky 4" "bone pinky 3" 0.012933 2.746925 -0.096229 -4.151539 3.541855 -65.579491 0 0 0 0 0 0 +$definebone "bone thumb 1" "bone hand" -2.231816 1.416988 -1.590842 -46.604322 61.384001 -55.069086 0 0 0 0 0 0 +$definebone "bone thumb 2" "bone thumb 1" -0.316676 3.892338 0.185578 -33.168533 -11.613905 -33.910502 0 0 0 0 0 0 +$definebone "bone thumb 3" "bone thumb 2" -0.269053 3.933444 -0.328678 5.133236 -12.418460 -66.142942 0 0 0 0 0 0 +$definebone "magrel" "bone hand" -1.389966 15.611851 -2.785499 87.000140 -92.999972 90.000075 0 0 0 0 0 0 +$definebone "slide" "magrel" 0.000001 1.764277 6.216676 0.000004 0.000004 0.000001 0 0 0 0 0 0 +$definebone "Eject" "slide" -0.120959 -0.439801 -0.840956 -10.016456 178.846850 0.201737 0 0 0 0 0 0 +$definebone "body" "magrel" 0.000000 -0.000001 -0.000000 0.000004 0.000004 0.000001 0 0 0 0 0 0 +$definebone "catch2" "body" 0.000001 0.367147 3.416009 0.000004 0.000004 0.000001 0 0 0 0 0 0 +$definebone "bullet_eject01" "body" -0.000000 4.833648 3.431723 0.000004 0.000004 0.000001 0 0 0 0 0 0 +$definebone "trigger" "magrel" 0.000000 1.612491 2.633620 0.000004 0.000004 0.000001 0 0 0 0 0 0 +$definebone "mag" "magrel" -0.059484 7.270134 1.720140 0.000004 0.000004 7.999981 0 0 0 0 0 0 +$definebone "bullet2" "mag" 0.059484 -7.270135 -1.720142 0.000004 0.000003 0.000002 0 0 0 0 0 0 +$definebone "Main" "magrel" -0.000622 3.390026 5.182981 -1.337800 -89.989460 89.981534 0 0 0 0 0 0 +$definebone "Muzzle" "Main" 16.557522 -0.000008 -0.000003 -0.000004 0.041881 0.000005 0 0 0 0 0 0 +$attachment "muzzle" "Muzzle" 0.0000 -0.0000 0.0000 rotate 0.000 -0.000 -0.000 +$attachment "eject" "Eject" 0.0000 -0.0000 0.0000 rotate -0.000 -0.000 0.000 +$sequence "idle01" "anims/idle01.smd" activity ACT_VM_IDLE 1 fps 30 fadein 0.20 fadeout 0.20 loop node "0" +$sequence "idle01empty" "anims/idle01empty.smd" activity ACT_VM_IDLE_EMPTY 1 fps 30 fadein 0.20 fadeout 0.20 loop node "0" +$sequence "fire" "anims/fire.smd" activity ACT_VM_PRIMARYATTACK 1 fps 30 fadein 0.20 fadeout 0.20 snap node "2" { event AE_MUZZLEFLASH 0 "PISTOL MUZZLE" } +$sequence "fire1" "anims/fire1.smd" activity ACT_VM_RECOIL1 1 fps 30 fadein 0.20 fadeout 0.20 snap node "2" { event AE_MUZZLEFLASH 0 "PISTOL MUZZLE" } +$sequence "fire2" "anims/fire2.smd" activity ACT_VM_RECOIL2 1 fps 30 fadein 0.20 fadeout 0.20 snap node "2" { event AE_MUZZLEFLASH 0 "PISTOL MUZZLE" } +$sequence "fire3" "anims/fire3.smd" activity ACT_VM_RECOIL3 1 fps 30 fadein 0.20 fadeout 0.20 snap node "2" { event AE_MUZZLEFLASH 0 "PISTOL MUZZLE" } +$sequence "fireempty" "anims/fireempty.smd" activity ACT_VM_DRYFIRE 1 fps 30 fadein 0.20 fadeout 0.20 node "2" +$sequence "draw" "anims/draw.smd" activity ACT_VM_DRAW 1 fps 30 fadein 0.20 fadeout 0.20 snap node "0" +$sequence "drawempty" "anims/drawempty.smd" fps 30 fadein 0.20 fadeout 0.20 node "0" +$sequence "reload" "anims/reload.smd" activity ACT_VM_RELOAD 1 fps 30 fadein 0.20 fadeout 0.20 node "0" +$sequence "holster" "anims/holster.smd" activity ACT_VM_HOLSTER 1 fps 30 fadein 0.20 fadeout 0.20 node "0" +$sequence "holsterempty" "anims/holsterempty.smd" activity ACT_VM_HOLSTER 1 fps 30 fadein 0.20 fadeout 0.20 node "0" +$sequence "idletolow" "anims/idletolow.smd" activity ACT_VM_LOWERED_TO_IDLE 1 fps 30 fadein 0.20 fadeout 0.20 transition "0" "1" +$sequence "lowtoidle" "anims/lowtoidle.smd" activity ACT_VM_IDLE_TO_LOWERED 1 fps 30 fadein 0.20 fadeout 0.20 transition "1" "0" +$sequence "lowidle" "anims/lowidle.smd" activity ACT_VM_IDLE_LOWERED 1 fps 30 fadein 0.20 fadeout 0.20 loop node "1" +$sequence "reloadempty" "anims/reloadempty.smd" activity ACT_VM_RELOAD_EMPTY 1 fps 30 fadein 0.20 fadeout 0.20 node "0" diff --git a/neo/modelsrc/weapons/viewmodel_tools.py b/neo/modelsrc/weapons/viewmodel_tools.py new file mode 100644 index 00000000..80f70dd4 --- /dev/null +++ b/neo/modelsrc/weapons/viewmodel_tools.py @@ -0,0 +1,325 @@ +"""Viewmodel tools: a 3D Viewport sidebar tab (N panel > Viewmodel) for viewmodels.blend. + +Load it with the file, from this folder (nothing is installed, and the file is always the one in the repository): + blender viewmodels.blend --python viewmodel_tools.py +Or, with viewmodels.blend already open: Text Editor > Open > viewmodel_tools.py > Run Script. +It imports rom_limits.py and export_viewmodels.py from the folder of the open .blend. + +The panel shows the project (one scene per gun: one rig and one action move both teams' arms), the team shown, +the active slot and its kind: shipped (keep the original clip) or authored (new motion). Buttons: +- Team: show the other team's arms (flips the eye of the jinrai_GUN_preview and nsf_GUN_preview collections, which + the Outliner also shows). Nothing exported depends on it. +- Frame range to slot: set the scene frame range to the active slot's keys and list its markers. +- Check slot: the export's range-of-motion check on the active slot only; selects the clamped bones. +- Mute limits / Unmute: every ROM:* constraint of the scene. Transform locks stay on. +- Free selected bones: mute ROM:* and clear the transform locks of the selected bones, to key a pose past the + shipped range. Widen (or rom_limits.py apply) puts the limits back. +- Widen to this slot: ask for the reason, add the selected bones and the active slot to rom_widen.json, then rewrite + rom_spec.json and the limits of every rig in this session (~8 s). Save the .blend afterwards. +- Export gun: save the .blend, then run export_viewmodels.py for the gun's project in a background Blender (~20 s, + with glue.py's preview rebuild) and show its result lines (the terminal, or Window > Toggle System Console, has + them all). The NSF model needs no export: it compiles from its shipped SMDs (and, with glue.py, the Jinrai glued + clips). +Runtime of the panel itself: nothing measurable; the .qc files are read once per project and cached. +""" +import json +import subprocess +import sys +from pathlib import Path + +import bpy + +bl_info = {'name': 'Viewmodel tools (NT;RE)', 'blender': (5, 2, 0), 'category': 'Animation', + 'location': '3D Viewport > Sidebar > Viewmodel'} + +RESULT_LINES = ('ROM CHECK', 'EXPORTED', 'KEPT', 'SHIPPED', 'PACE', 'EXPORT FAILED', ' ') +TEAM_KEY = 'team' # custom property merge_teams.py sets on each team's preview collection +KIND_CACHE = {} # (project, slot) -> kind text; the .qc files do not change while Blender runs + + +def tools(): + """(folder, rom_limits, export_viewmodels) from the folder of the open .blend.""" + root = Path(bpy.data.filepath).parent + if not (root / 'rom_limits.py').is_file(): + raise RuntimeError('Open viewmodels.blend from neo/modelsrc/weapons first') + if str(root) not in sys.path: + sys.path.insert(0, str(root)) + sys.dont_write_bytecode = True + import rom_limits + import export_viewmodels + return root, rom_limits, export_viewmodels + + +def project(context): + scene = context.scene + return scene, scene.objects.get(scene.name + '_rig') + + +def active_slot(rig): + data = rig.animation_data if rig else None + return data.action_slot.name_display if data and data.action_slot else None + + +def slot_kind(scene, slot): + key = (scene.name, slot) + if key not in KIND_CACHE: + root, _, export = tools() + folder = root / scene.name + if not folder.is_dir(): + KIND_CACHE[key] = 'not a project' + elif slot in export.shipped_slots(folder): + KIND_CACHE[key] = 'shipped: keep the original clip' + else: + KIND_CACHE[key] = 'authored: new motion' + return KIND_CACHE[key] + + +def team_layers(scene): + """{team: layer collection} of the scene's team preview collections.""" + return {layer.collection[TEAM_KEY]: layer for layer in scene.view_layers[0].layer_collection.children + if TEAM_KEY in layer.collection} + + +def shown_team(scene): + shown = [team for team, layer in team_layers(scene).items() if not layer.hide_viewport] + return ' + '.join(sorted(shown)) or 'none' + + +def show_team(scene, team): + """Show one team's preview collection and hide the others, in the viewport and in renders.""" + for name, layer in team_layers(scene).items(): + layer.hide_viewport = name != team + layer.collection.hide_render = name != team + + +def keep_view(scene, rig): + """Remember the active slot and frame, which the checks move.""" + slot, frame = rig.animation_data.action_slot, scene.frame_current + + def restore(): + rig.animation_data.action_slot = slot + scene.frame_set(frame) + return restore + + +class ProjectOperator(bpy.types.Operator): + @classmethod + def poll(cls, context): + _, rig = project(context) + return active_slot(rig) is not None + + +class VM_OT_slot_range(ProjectOperator): + """Set the scene frame range to the keys of the active slot and list the slot's markers""" + bl_idname = 'viewmodel.slot_range' + bl_label = 'Frame range to slot' + + def execute(self, context): + _, rom, _ = tools() + scene, rig = project(context) + name = active_slot(rig) + for slot, _, first, last in rom.slot_bags(rig): + if slot.name_display == name: + scene.frame_start, scene.frame_end = first, last + own = sorted((m.frame, m.name) for m in scene.timeline_markers if m.name.partition(':')[0] == name) + text = 'RANGE %s f%d-%d; markers: %s' % (name, scene.frame_start, scene.frame_end, + ', '.join('%s f%d' % (n, f) for f, n in own) or 'none') + print(text) + self.report({'INFO'}, text) + return {'FINISHED'} + + +class VM_OT_check_slot(ProjectOperator): + """Run the export's range-of-motion check on the active slot and select the clamped bones""" + bl_idname = 'viewmodel.check_slot' + bl_label = 'Check slot' + + def execute(self, context): + _, rom, _ = tools() + scene, rig = project(context) + restore, name = keep_view(scene, rig), active_slot(rig) + clamps = rom.find_clamps(scene, slots={name}) + restore() + for pose_bone in rig.pose.bones: + pose_bone.select = any(clamp[1] == pose_bone.name for clamp in clamps) + if not clamps: + print('CHECK', scene.name, name, 'no clamped pose') + self.report({'INFO'}, 'CHECK %s: no clamped pose' % name) + return {'FINISHED'} + for clamp in clamps: + print('CLAMP', rom.clamp_text(scene.name, clamp)) + self.report({'WARNING'}, 'CLAMP ' + rom.clamp_text(scene.name, clamp)) + self.report({'WARNING'}, '%d clamped bones selected: fix the keys, or Free and Widen if the pose is meant' + % len(clamps)) + return {'FINISHED'} + + +class VM_OT_mute(ProjectOperator): + """Mute or unmute every ROM:* constraint of this scene; the transform locks stay on""" + bl_idname = 'viewmodel.mute' + bl_label = 'Mute limits' + mute: bpy.props.BoolProperty(default=True) + + def execute(self, context): + _, rom, _ = tools() + rom.set_mute(context.scene, self.mute) + text = ('MUTED ' if self.mute else 'UNMUTED ') + context.scene.name + print(text) + self.report({'INFO'}, text) + return {'FINISHED'} + + +class VM_OT_free_selected(ProjectOperator): + """Mute the limits and clear the transform locks of the selected bones, to key a pose past the shipped range""" + bl_idname = 'viewmodel.free_selected' + bl_label = 'Free selected bones' + + def execute(self, context): + _, rom, _ = tools() + _, rig = project(context) + freed = [] + for pose_bone in rig.pose.bones: + if not pose_bone.select: + continue + for constraint in pose_bone.constraints: + if constraint.name.startswith(rom.PREFIX): + constraint.mute = True + pose_bone.lock_location = pose_bone.lock_rotation = (False,) * 3 + freed.append(pose_bone.name) + if not freed: + self.report({'ERROR'}, 'Select the bones to free first (Pose Mode)') + return {'CANCELLED'} + text = 'FREED %s: key the pose, then Widen to this slot' % ', '.join(freed) + print(text) + self.report({'INFO'}, text) + return {'FINISHED'} + + +class VM_OT_widen(ProjectOperator): + """Widen the limits of the selected bones to cover their keys in the active slot (recorded in rom_widen.json)""" + bl_idname = 'viewmodel.widen' + bl_label = 'Widen to this slot' + why: bpy.props.StringProperty(name='Reason', description='Why the pose is meant (kept in rom_spec.json)') + + def invoke(self, context, event): + return context.window_manager.invoke_props_dialog(self, width=500) + + def execute(self, context): + _, rom, _ = tools() + scene, rig = project(context) + bones = [pose_bone.name for pose_bone in rig.pose.bones if pose_bone.select] + if not self.why.strip(): + self.report({'ERROR'}, 'Give a reason: it goes into rom_widen.json and rom_spec.json beside the limit') + return {'CANCELLED'} + if not bones: + self.report({'ERROR'}, 'Select the bones to widen first (Pose Mode)') + return {'CANCELLED'} + slot, gun = active_slot(rig), rom.gun_of(scene.name) + for bone in bones: + rom.add_widen(gun, bone, [slot], self.why.strip()) + scenes = rom.project_scenes([]) + restores = [keep_view(other, rom.rig_of(other)) for other in scenes] + rom.make_spec(scenes) + spec = json.loads(rom.SPEC.read_text(encoding='ascii')) + for other in scenes: + rom.apply_limits(other, spec) + clamps = rom.find_clamps(scene, slots={slot}) + for restore in restores: + restore() + text = 'WIDENED %s for %s/%s; rom_widen.json and rom_spec.json rewritten; %d clamps left. Save the file.' % ( + ', '.join(bones), gun, slot, len(clamps)) + print(text) + self.report({'WARNING'} if clamps else {'INFO'}, text) + return {'FINISHED'} + + +class VM_OT_team(bpy.types.Operator): + """Show the other team's arms (the eye of the team preview collections); nothing exported depends on it""" + bl_idname = 'viewmodel.team' + bl_label = 'Team' + + @classmethod + def poll(cls, context): + return len(team_layers(context.scene)) > 1 + + def execute(self, context): + teams = sorted(team_layers(context.scene)) + shown = shown_team(context.scene) + team = teams[(teams.index(shown) + 1) % len(teams)] if shown in teams else teams[0] + show_team(context.scene, team) + self.report({'INFO'}, 'TEAM %s shown' % team) + return {'FINISHED'} + + +class VM_OT_export_gun(ProjectOperator): + """Save the .blend, then export this gun's project in a background Blender""" + bl_idname = 'viewmodel.export_gun' + bl_label = 'Export gun' + + def execute(self, context): + root, _, export = tools() + projects = [context.scene.name] + bpy.ops.wm.save_mainfile() + run = subprocess.run([bpy.app.binary_path, '--background', '--python-exit-code', '1', '--python', + str(root / 'export_viewmodels.py'), '--'] + projects, + cwd=root, capture_output=True, text=True) + shown = RESULT_LINES + (export.glue.RESULT_LINES if export.glue else ()) + for line in run.stdout.splitlines(): + if line.startswith(shown): + print(line) + self.report({'ERROR'} if line.startswith('EXPORT FAILED') else {'INFO'}, line) + verdict = 'EXPORT %s %s (exit code %d)' % (' '.join(projects), 'FAILED' if run.returncode else 'done', + run.returncode) + print(verdict) + self.report({'ERROR'} if run.returncode else {'INFO'}, verdict) + return {'CANCELLED'} if run.returncode else {'FINISHED'} + + +class VM_PT_panel(bpy.types.Panel): + bl_label = 'Viewmodel' + bl_space_type = 'VIEW_3D' + bl_region_type = 'UI' + bl_category = 'Viewmodel' + + def draw(self, context): + layout = self.layout + scene, rig = project(context) + if rig is None: + layout.label(text='Pick a project scene (top right)') + return + _, rom, _ = tools() + slot = active_slot(rig) + layout.label(text='Project: ' + scene.name) + row = layout.row() + row.label(text='Arms: ' + shown_team(scene)) + row.operator(VM_OT_team.bl_idname, icon='HIDE_OFF') + layout.label(text='Slot: %s' % (slot or 'none')) + layout.label(text=slot_kind(scene, slot) if slot else 'Pick a slot in the Action Editor') + muted = any(c.mute for b in rig.pose.bones for c in b.constraints if c.name.startswith(rom.PREFIX)) + layout.label(text='Limits: ' + ('some muted' if muted else 'on')) + layout.operator(VM_OT_slot_range.bl_idname, icon='PREVIEW_RANGE') + layout.operator(VM_OT_check_slot.bl_idname, icon='CHECKMARK') + row = layout.row() + row.operator(VM_OT_mute.bl_idname, text='Mute limits').mute = True + row.operator(VM_OT_mute.bl_idname, text='Unmute').mute = False + layout.operator(VM_OT_free_selected.bl_idname, icon='UNLOCKED') + layout.operator(VM_OT_widen.bl_idname, icon='CON_ROTLIMIT') + layout.operator(VM_OT_export_gun.bl_idname, icon='EXPORT') + + +CLASSES = (VM_OT_team, VM_OT_slot_range, VM_OT_check_slot, VM_OT_mute, VM_OT_free_selected, VM_OT_widen, VM_OT_export_gun, + VM_PT_panel) + + +def register(): + for cls in CLASSES: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(CLASSES): + bpy.utils.unregister_class(cls) + + +if __name__ == '__main__': + register() diff --git a/neo/modelsrc/weapons/viewmodels.blend b/neo/modelsrc/weapons/viewmodels.blend new file mode 100644 index 00000000..1c49436e Binary files /dev/null and b/neo/modelsrc/weapons/viewmodels.blend differ