# SPDX-FileCopyrightText: 2026 OddsPrig RiggerSet contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Named Blender tools over a shared-memory JSON conduit. Never evaluates agent code."""
import bpy, os, json, math, traceback, array, struct
from mathutils import Vector, Quaternion

RS_IO = os.environ.get("RIGGERSET_TEST_IO", "/tmp/riggerset")
_RS_REV = 0
_RS_UNDO = []
_RS_BUSY = False
for _d in (RS_IO, RS_IO+"/in", RS_IO+"/out", RS_IO+"/cmd", RS_IO+"/ack", RS_IO+"/history"):
    os.makedirs(_d, exist_ok=True)
bpy.context.preferences.filepaths.use_scripts_auto_execute = False
bpy.context.preferences.edit.use_global_undo = True
bpy.context.preferences.edit.undo_steps = 24
bpy.context.preferences.filepaths.save_version = 0

def _rs_vec(v, n, lo, hi):
    if not isinstance(v, list) or len(v) != n or any(isinstance(x,bool) or not isinstance(x,(int,float)) or not math.isfinite(x) or x < lo or x > hi for x in v):
        raise ValueError("Invalid vector")
    return v

def _rs_num(v, lo, hi):
    if isinstance(v,bool) or not isinstance(v,(int,float)) or not math.isfinite(v) or v < lo or v > hi:
        raise ValueError("Number outside allowed range")
    return v

def _rs_obj(name):
    ob = bpy.data.objects.get(str(name))
    if ob is None:
        raise ValueError("Object not found")
    return ob

def _rs_control():
    try:
        with open(RS_IO+"/control.json") as handle: return json.load(handle)
    except Exception:
        return {"epoch":0,"paused":False}

def _rs_window():
    return next(iter(bpy.context.window_manager.windows),None)

def _rs_euler(target):
    if target.rotation_mode == "QUATERNION": return target.rotation_quaternion.to_euler("XYZ")
    if target.rotation_mode == "AXIS_ANGLE": return target.matrix_basis.to_euler("XYZ")
    return target.rotation_euler.copy()

def _rs_unlink(file):
    try: os.remove(file)
    except OSError: pass

def _rs_clear_undo():
    global _RS_UNDO
    for file in os.listdir(RS_IO+"/history"): _rs_unlink(RS_IO+"/history/"+file)
    _RS_UNDO=[]

def _rs_restore(file):
    try: bpy.ops.wm.open_mainfile(filepath=file,load_ui=False,use_scripts=False)
    finally: _rs_unlink(file)

def _rs_mode_object():
    ob = bpy.context.object
    if ob and ob.mode != "OBJECT" and bpy.ops.object.mode_set.poll():
        bpy.ops.object.mode_set(mode="OBJECT")

def _rs_glb_mergeable(file):
    # Reverse UV-only render splitting using Blender's importer. Keep authored
    # custom vertex attributes separate: Blender's merge option can drop them.
    with open(file,"rb") as handle:
        header=handle.read(20)
        if len(header)!=20 or header[:4]!=b"glTF": return False
        size,kind=struct.unpack_from("<II",header,12)
        if kind!=0x4e4f534a or size>16*1024*1024: return False
        data=json.loads(handle.read(size).decode("utf-8"))
    return not any(name.startswith("_") for mesh in data.get("meshes",[]) for primitive in mesh.get("primitives",[]) for name in primitive.get("attributes",{}))

def _rs_view_all():
    # A saved document may have been captured while its drawing view was parked.
    for window in bpy.context.window_manager.windows:
        if not any(area.type == "VIEW_3D" for area in window.screen.areas):
            parked = [area for area in window.screen.areas if area.type == "CONSOLE"]
            if parked: max(parked,key=lambda a:a.width*a.height).type = "VIEW_3D"
    # Frame the actual visible model, excluding importer bone-display helpers.
    points = [ob.matrix_world @ Vector(corner) for ob in bpy.context.scene.objects
              if ob.type == "MESH" and not ob.hide_viewport and not ob.hide_render and not ob.hide_get()
              for corner in ob.bound_box]
    center = None
    distance = None
    if points:
        minimum = Vector(tuple(min(p[i] for p in points) for i in range(3)))
        maximum = Vector(tuple(max(p[i] for p in points) for i in range(3)))
        center = (minimum + maximum) * .5
        distance = max((maximum - minimum).length * 1.5, .01)
    # Workbench texture mode uses the active image node, which may otherwise be the roughness map after glTF import.
    for mat in bpy.data.materials:
        if mat.use_nodes:
            link=next((link for link in mat.node_tree.links if link.to_node.type=="BSDF_PRINCIPLED" and link.to_socket.name=="Base Color" and link.from_node.type=="TEX_IMAGE"),None)
            if link: mat.node_tree.nodes.active=link.from_node
    for window in bpy.context.window_manager.windows:
        for area in window.screen.areas:
            if area.type == "VIEW_3D":
                for region in area.regions:
                    if region.type == "WINDOW":
                        try:
                            with bpy.context.temp_override(window=window,area=area,region=region):
                                bpy.ops.view3d.view_all(center=True)
                        except Exception:
                            pass
                area.spaces.active.shading.type = "SOLID"
                area.spaces.active.shading.color_type = "TEXTURE"
                area.spaces.active.shading.light = "STUDIO"
                area.spaces.active.region_3d.view_rotation=Quaternion((1,0,0),math.pi/2)
                area.spaces.active.region_3d.view_perspective="ORTHO"
                if center is not None:
                    area.spaces.active.region_3d.view_location=center
                    area.spaces.active.region_3d.view_distance=distance
                # The pinned port's bone-overlay draw path can bind stale SSBOs.
                # Open on the model; native overlay controls remain available.
                area.spaces.active.overlay.show_overlays=False
                area.tag_redraw()

_RS_PARKED_AREAS = []
def _rs_viewport(visible):
    global _RS_PARKED_AREAS
    if visible:
        for window,index in _RS_PARKED_AREAS:
            if window in bpy.context.window_manager.windows[:] and index < len(window.screen.areas):
                area=window.screen.areas[index]
                if area.type == "CONSOLE": area.type = "VIEW_3D"
        _RS_PARKED_AREAS=[]
        _rs_view_all()
    else:
        # The pinned port can invalidate its live Workbench buffers after export.
        # Park only our own 3D areas while the actual GLB viewer draws the model.
        for window in bpy.context.window_manager.windows:
            for index,area in enumerate(window.screen.areas):
                if area.type == "VIEW_3D":
                    _RS_PARKED_AREAS.append((window,index));area.type = "CONSOLE"
    return {"viewportVisible":visible,"revision":_RS_REV}

def _rs_inspect():
    objects = []
    for ob in list(bpy.context.scene.objects)[:500]:
        item = {"name":ob.name,"type":ob.type,"location":list(ob.location),"rotation":list(_rs_euler(ob)),"scale":list(ob.scale)}
        if ob.type == "MESH":
            item["visible"] = bool(ob.visible_get() and not ob.hide_render and not ob.hide_get())
            item["style"] = str(ob.get("riggerset_style", ""))
            item["styleSource"] = str(ob.get("riggerset_style_source", ""))
            item.update(vertices=len(ob.data.vertices),triangles=sum(max(0,len(p.vertices)-2) for p in ob.data.polygons),materials=[m.name for m in ob.data.materials if m])
            item["face"] = _rs_face_info(ob)
            item["armature"] = (_rs_contact_armature(ob).name if _rs_contact_armature(ob) else None)
            # Inspection includes hidden originals; physical-asset bounds exclude them.
            points = [ob.matrix_world @ Vector(v) for v in ob.bound_box] if len(ob.data.vertices) else []
            if points and all(math.isfinite(v) for point in points for v in point):
                item["bounds"] = {"min":[min(p[i] for p in points) for i in range(3)],
                                  "max":[max(p[i] for p in points) for i in range(3)]}
            item["matrixWorld"] = [list(row) for row in ob.matrix_world]
        elif ob.type == "ARMATURE":
            item["bones"] = [{"name":b.name,"parent":b.parent.name if b.parent else None,"rotation":list(_rs_euler(b)),"head":list(b.bone.head_local),"tail":list(b.bone.tail_local)} for b in list(ob.pose.bones)[:512]]
            item["motion"] = _rs_motion_info(ob)
            item["limbControls"] = _rs_limb_controls(ob)
            item["creatureMotion"] = {family:_rs_creature_info(ob,family) for family in ("bird","quadruped")}
            item["arthropodMotion"] = {family:_rs_arthropod_info(ob,family) for family in ("insect","flying-insect","arachnid")}
            item["matrixWorld"] = [list(row) for row in ob.matrix_world]
            item["animation"] = {"action":ob.animation_data.action.name if ob.animation_data and ob.animation_data.action else None,
                                 "hasAnimation":bool(ob.animation_data and (ob.animation_data.action or ob.animation_data.nla_tracks or ob.animation_data.drivers))}
        objects.append(item)
    scene = bpy.context.scene
    return {"revision":_RS_REV,"version":bpy.app.version_string,"objects":objects,
            "materials":[{"name":m.name,"color":list(m.diffuse_color),"roughness":m.roughness,"metallic":m.metallic} for m in list(bpy.data.materials)[:256]],
            "images":[{"name":i.name,"width":i.size[0],"height":i.size[1]} for i in list(bpy.data.images)[:128] if i.size[0]],
            "timeline":{"frame":scene.frame_current,"start":scene.frame_start,"end":scene.frame_end,"fps":scene.render.fps,"playing":bool(_rs_window() and _rs_window().screen.is_animation_playing)},
            "capabilities":{"glb":hasattr(bpy.ops.import_scene,"gltf"),"keyframes":True,"bonePose":True,"ik":False,"eevee":False}}

def _rs_checkpoint():
    _rs_mode_object()
    file = RS_IO+"/history/"+str(_RS_REV)+".blend"
    bpy.ops.wm.save_as_mainfile(filepath=file,copy=True,check_existing=False)
    _RS_UNDO.append(file)
    while len(_RS_UNDO)>5:
        old=_RS_UNDO.pop(0)
        try: os.remove(old)
        except OSError: pass








































# BEGIN RIGGERSET AUTOMATIC MOTION
# SPDX-License-Identifier: GPL-3.0-or-later
"""Conservative, name-independent upright biped recognition. Blender world Z is up."""
import math

def map_humanoid(bones):
    def fail(message): raise ValueError(message)
    def sub(a,b): return tuple(x-y for x,y in zip(a,b))
    def dot(a,b): return sum(x*y for x,y in zip(a,b))
    def length(a): return math.sqrt(dot(a,a))
    def unit(a):
        size=length(a)
        if size<1e-8: fail("The skeleton has coincident joints.")
        return tuple(v/size for v in a)
    def horizontal(a): return (a[0],a[1],0)
    if not isinstance(bones,list) or not 7<=len(bones)<=256: fail("Automatic motion supports a single humanoid rig with 7–256 joints.")
    by={}
    for bone in bones:
        if not isinstance(bone,dict) or not isinstance(bone.get('name'),str) or not bone['name'] or bone['name'] in by: fail("Skeleton joint names must be unique.")
        point=bone.get('head')
        if not isinstance(point,(tuple,list)) or len(point)!=3 or any(isinstance(v,bool) or not isinstance(v,(int,float)) or not math.isfinite(v) for v in point): fail("Skeleton joint positions must be finite 3D coordinates.")
        by[bone['name']]=bone
    children={name:[] for name in by}
    roots=[]
    for name,bone in by.items():
        parent=bone.get('parent')
        if parent is None: roots.append(name)
        elif not isinstance(parent,str) or parent not in by: fail("The skeleton has a missing parent.")
        else: children[parent].append(name)
    if len(roots)!=1: fail("Automatic motion needs one connected skeleton.")
    ordered=[];seen=set()
    def visit(name):
        if name in seen: fail("The skeleton contains a parent cycle.")
        seen.add(name);ordered.append(name)
        for child in children[name]: visit(child)
    visit(roots[0])
    if len(seen)!=len(by): fail("The skeleton is disconnected or cyclic.")
    points={name:tuple(b['head']) for name,b in by.items()}
    z=lambda name:points[name][2]
    low=min(map(z,by));high=max(map(z,by));height=high-low
    if height<1e-6: fail("The rig needs an upright body with distinct head and feet.")
    descendants={}
    for name in reversed(ordered): descendants[name]=[name]+[n for child in children[name] for n in descendants[child]]
    floor=lambda name:min(z(n) for n in descendants[name])
    ceiling=lambda name:max(z(n) for n in descendants[name])
    candidates=[]
    for name in ordered:
        down=[c for c in children[name] if z(name)-floor(c)>.3*height]
        above=[c for c in children[name] if ceiling(c)-z(name)>.25*height and c not in down]
        if .3*height<z(name)-low<.72*height and len(down)==2 and len(above)==1:
            candidates.append((name,down,above[0]))
    if len(candidates)!=1: fail("A clear upright torso and two separate legs were not found. Use manual posing for this rig.")
    hips,legs,spine=candidates[0]
    def chain_to(start,end):
        chain=[end]
        while chain[-1]!=start:
            parent=by[chain[-1]].get('parent')
            if parent is None: fail("The skeleton branch is disconnected.")
            chain.append(parent)
        return list(reversed(chain))
    leg_parts=[];facings=[]
    for start in legs:
        end=min(descendants[start],key=z)
        chain=chain_to(start,end)
        foot_index=next((i for i,n in enumerate(chain) if z(n)<=low+.09*height),len(chain)-1)
        if foot_index<2: fail("Each leg needs distinct upper-leg, knee and ankle joints.")
        thigh=chain[0];foot=chain[foot_index]
        knee=min(chain[1:foot_index],key=lambda n:abs(z(n)-(z(thigh)+z(foot))*.5))
        if z(thigh)-z(foot)<.27*height or not z(foot)+.08*height<z(knee)<z(thigh)-.08*height: fail("The leg proportions are not suitable for a humanoid starter motion.")
        leg_parts.append((thigh,knee,foot))
        toes=[n for n in descendants[foot] if n!=foot and abs(z(n)-z(foot))<.12*height]
        toe=max(toes,key=lambda n:length(horizontal(sub(points[n],points[foot]))),default=None)
        toe_direction=horizontal(sub(points[toe],points[foot])) if toe else (0,0,0)
        ratio=(z(knee)-z(foot))/(z(thigh)-z(foot))
        bend=horizontal(sub(points[knee],tuple(points[foot][i]+ratio*(points[thigh][i]-points[foot][i]) for i in range(3))))
        facing=toe_direction if length(toe_direction)>.035*height else bend
        if length(facing)>.015*height: facings.append(unit(facing))
    separation=horizontal(sub(points[leg_parts[0][2]],points[leg_parts[1][2]]))
    if not .04*height<length(separation)<.65*height: fail("The two feet need a clear bilateral stance.")
    facing_known=len(facings)==2 and dot(facings[0],facings[1])>.6
    if facing_known:
        forward=unit(tuple(a+b for a,b in zip(*facings)));left=unit((-forward[1],forward[0],0))
    else:
        left=unit(separation)
        dominant=0 if abs(left[0])>=abs(left[1]) else 1
        if left[dominant]>0: left=tuple(-v for v in left)
        forward=(left[1],-left[0],0)
    lateral=lambda name:dot(sub(points[name],points[hips]),left)
    sorted_legs=sorted(leg_parts,key=lambda p:lateral(p[0]),reverse=True)
    if lateral(sorted_legs[0][0])*lateral(sorted_legs[1][0])>=0: fail("The leg branches cross the body centre.")
    top=max(descendants[spine],key=z);torso=chain_to(spine,top)
    chest=None;arm_branches=[];neck=None
    knee_height=max(z(part[1]) for part in leg_parts)
    for name in torso:
        upper=[c for c in children[name] if ceiling(c)>z(name)+.1*height]
        sides=[]
        for child in children[name]:
            reach=max(descendants[child],key=lambda n:abs(lateral(n)-lateral(name)))
            if abs(lateral(reach)-lateral(name))>.2*height and floor(child)>knee_height+.04*height:
                sides.append(child)
        if len(sides)==2 and upper:
            left_reach=max(lateral(n) for n in descendants[sides[0]])-lateral(name)
            right_reach=min(lateral(n) for n in descendants[sides[1]])-lateral(name)
            if (min(lateral(n) for n in descendants[sides[0]])-lateral(name))*(max(lateral(n) for n in descendants[sides[1]])-lateral(name))>=0 and left_reach*right_reach>=0: continue
            necks=[c for c in upper if c not in sides]
            if len(necks)==1: chest,arm_branches,neck=name,sides,necks[0];break
    if chest is None: fail("A neck and two arms above the knees were not found. This rig needs manual posing.")
    roles={'hips':hips,'spine':spine,'chest':chest}
    head_chain=chain_to(neck,max(descendants[neck],key=z))
    roles['head']=next((n for n in head_chain if z(n)>z(chest)+.55*(high-z(chest))),head_chain[-1])
    for side,part in zip(('left','right'),sorted_legs):
        for role,name in zip(('thigh','shin','foot'),part): roles[side+'_'+role]=name
    for branch in arm_branches:
        reach=max(descendants[branch],key=lambda n:length(sub(points[n],points[chest])))
        chain=chain_to(branch,reach)
        if len(chain)>3 and length(sub(points[chain[0]],points[chest]))<.09*height: chain=chain[1:]
        if len(chain)<3: fail("Each arm needs distinct upper-arm, elbow and wrist joints.")
        arc=[0]
        for a,b in zip(chain,chain[1:]): arc.append(arc[-1]+length(sub(points[b],points[a])))
        wrist_index=next((i for i in range(2,len(chain)) if arc[i]>=arc[-1]*.72),len(chain)-1)
        upper=chain[0];hand=chain[wrist_index]
        elbow=min(range(1,wrist_index),key=lambda i:abs(arc[i]-arc[wrist_index]*.5))
        if arc[wrist_index]<.17*height or z(hand)<knee_height+.04*height: fail("The arm proportions do not match an upright humanoid.")
        side='left' if lateral(hand)>lateral(chest) else 'right'
        if side+'_hand' in roles: fail("The arm branches are not bilateral.")
        for role,name in zip(('upper_arm','forearm','hand'),(upper,chain[elbow],hand)): roles[side+'_'+role]=name
    primary=[value for key,value in roles.items() if key!='spine']
    if len(set(primary))!=len(primary): fail("The skeleton's primary body joints overlap.")
    return {'roles':roles,'left':list(left),'up':[0,0,1],'forward':list(forward),'height':height,'facing_known':facing_known}


# SPDX-License-Identifier: GPL-3.0-or-later
"""Editable, bounded starter poses and FK clips. Included in the named tool daemon."""

def _rs_motion_bones(ob):
    return [{"name":b.name,"parent":b.parent.name if b.parent else None,
             "head":list(ob.matrix_world @ b.head_local)} for b in ob.data.bones]


def _rs_motion_info(ob):
    try:
        match = map_humanoid(_rs_motion_bones(ob))
        return {"supported":True,"canWalk":match["facing_known"],"matchedBones":len(set(match["roles"].values()))}
    except (ValueError, KeyError, TypeError) as error:
        return {"supported":False,"canWalk":False,"reason":str(error)[:220]}


def _rs_motion_curves(action):
    # Blender 4.x legacy and Blender 5.x layered actions, including the browser port.
    if hasattr(action,"fcurves"):
        return list(action.fcurves)
    return [curve for layer in action.layers for strip in layer.strips
            for bag in getattr(strip,"channelbags",[]) for curve in bag.fcurves]


def _rs_apply_motion(a):
    ob = _rs_obj(a.get("armature",""))
    if ob.type != "ARMATURE": raise ValueError("Choose an armature for automatic motion.")
    if set(a)-{"armature","preset","duration","strength"}: raise ValueError("Unknown animation parameter")
    preset = a.get("preset")
    if preset not in ("idle","walk","wave","relaxed","rest"): raise ValueError("Choose idle, walk, wave, relaxed or rest.")
    duration = _rs_num(a.get("duration",3),.75,6)
    strength = _rs_num(a.get("strength",1),.25,1.25)
    match = map_humanoid(_rs_motion_bones(ob))
    if preset == "walk" and not match["facing_known"]:
        raise ValueError("The rig's facing direction is ambiguous. Use idle or wave, or refine the knee/foot layout first.")
    if ob.animation_data and (ob.animation_data.drivers or ob.animation_data.nla_tracks):
        raise ValueError("This rig has drivers or layered animation. Keep it in the manual editor; automatic presets need a simple rig.")
    if any(b.constraints for b in ob.pose.bones): raise ValueError("Automatic presets need a rig without active bone constraints.")
    scale = ob.matrix_world.to_scale()
    if min(scale)<=0 or max(scale)/min(scale)>1.001:
        raise ValueError("Apply the armature's non-uniform scale before adding automatic motion.")
    roles = match["roles"]
    bones = ob.pose.bones
    left,up,forward = (Vector(match[key]).normalized() for key in ("left","up","forward"))
    rest = {b.name:(ob.matrix_world @ b.bone.matrix_local).to_quaternion() for b in bones}
    heads = {b.name:ob.matrix_world @ b.bone.head_local for b in bones}
    identity = Quaternion((1,0,0,0))
    def direction(role,child): return (heads[roles[child]]-heads[roles[role]]).normalized()
    def aim(target,role,child,vector):
        target[roles[role]] = direction(role,child).rotation_difference(vector.normalized())
    def blend_direction(start,end,amount):
        start=start.normalized();end=end.normalized()
        return identity.slerp(start.rotation_difference(end),amount) @ start
    def turn(target,role,axis,angle):
        target[roles[role]] = Quaternion(axis,angle)
    # Parent first, even if the importer supplied bones in another order.
    ordered=[]
    def visit(b):
        ordered.append(b)
        for child in b.children: visit(child)
    for b in bones:
        if b.parent is None: visit(b)
    ob.animation_data_create()
    previous = ob.animation_data.action
    if previous: previous.use_fake_user=True
    action = bpy.data.actions.new("RiggerSet · "+preset.title())
    action.use_fake_user=True
    ob.animation_data.action=action
    scene=bpy.context.scene
    pose_only=preset in ("rest","relaxed")
    end=1 if pose_only else round(duration*24)+1
    scene.render.fps=24
    scene.frame_start=1
    scene.frame_end=max(2,end)
    captured=_rs_control().get("epoch")
    for bone in bones:
        bone.rotation_mode="QUATERNION"
        bone.rotation_quaternion=identity
        bone.location=(0,0,0)
        bone.scale=(1,1,1)
    keyed=set(roles.values())
    last={}
    for frame in range(1,end+1):
        if _rs_control().get("epoch") != captured: raise ValueError("Animation stopped; restoring the previous checkpoint.")
        t=0 if pose_only else (frame-1)/(end-1)
        phase=2*math.pi*t
        target={}
        if preset != "rest":
            walk=math.sin(phase)*strength if preset=="walk" else 0
            breathing=math.sin(phase)*strength*(.014 if preset=="idle" else .007)
            turn(target,"hips",forward,walk*.025)
            turn(target,"chest",left,breathing)
            turn(target,"head",up,breathing*.8)
            raised=0
            if preset=="wave":
                ramp=max(0,min(1,t/.24,(1-t)/.24))
                raised=ramp*ramp*(3-2*ramp)
                turn(target,"chest",forward,raised*.03)
                turn(target,"head",up,-raised*.12+breathing)
            for side,sign in (("left",1),("right",-1)):
                lateral=left*sign
                leg=walk*sign
                thigh_angle=.35*leg
                knee=.06+.55*max(0,leg)**2 if preset=="walk" else 0
                if preset=="walk":
                    aim(target,side+"_thigh",side+"_shin",-up*math.cos(thigh_angle)+forward*math.sin(thigh_angle))
                    shin_angle=thigh_angle-knee
                    aim(target,side+"_shin",side+"_foot",-up*math.cos(shin_angle)+forward*math.sin(shin_angle))
                    target[roles[side+"_foot"]]=identity
                arm=-leg*.5
                upper=lateral*.14-up*math.cos(arm)+forward*math.sin(arm)
                lower_angle=arm+(.18+.15*max(0,-leg) if preset=="walk" else .3)
                lower=lateral*.14-up*math.cos(lower_angle)+forward*math.sin(lower_angle)
                if preset=="wave" and side=="right":
                    # Spherical interpolation gives the lift a consistent angular path.
                    # Hold the arm up long enough for two distinct wrist/forearm waves.
                    gesture=math.sin(4*math.pi*(t-.24)/.52)*raised**3*strength
                    upper=blend_direction(upper,lateral*.92+up*.4,raised)
                    lower=blend_direction(lower,lateral*(.12+.3*gesture)+up+forward*.15,raised)
                    turn(target,side+"_hand",forward,gesture*.4)
                aim(target,side+"_upper_arm",side+"_forearm",upper)
                aim(target,side+"_forearm",side+"_hand",lower)
        world={};posed_heads={}
        for bone in ordered:
            name=bone.name
            inherited=rest[name] if bone.parent is None else world[bone.parent.name] @ rest[bone.parent.name].inverted() @ rest[name]
            posed_heads[name]=heads[name] if bone.parent is None else posed_heads[bone.parent.name]+world[bone.parent.name] @ rest[bone.parent.name].inverted() @ (heads[name]-heads[bone.parent.name])
            delta=target.get(name)
            quat=identity.copy() if delta is None else inherited.inverted() @ delta @ rest[name]
            quat.normalize()
            if name in last and last[name].dot(quat)<0: quat.negate()
            bone.rotation_quaternion=quat
            world[name]=inherited @ quat
            if name in keyed:
                bone.keyframe_insert(data_path="rotation_quaternion",frame=frame,group=name)
                last[name]=quat.copy()
        if preset=="walk":
            # Match the lower ankle to its rest height. This produces body rise/fall
            # from actual limb lengths; horizontal foot sliding remains editable FK.
            ankle_names=[roles[side+"_foot"] for side in ("left","right")]
            lift=min(heads[n].z for n in ankle_names)-min(posed_heads[n].z for n in ankle_names)
            offset=-left*(match["height"]*.012*math.sin(phase))+up*lift
            hip=bones[roles["hips"]]
            hip.location=(rest[hip.name].inverted() @ offset)/scale[0]
            hip.keyframe_insert(data_path="location",frame=frame,group=hip.name)
        if frame==1:
            for bone in bones:
                # Preserve the reset stance for bones outside the animation map too.
                bone.keyframe_insert(data_path="location",frame=1,group=bone.name)
                bone.keyframe_insert(data_path="scale",frame=1,group=bone.name)
                if bone.name not in keyed: bone.keyframe_insert(data_path="rotation_quaternion",frame=1,group=bone.name)
    for curve in _rs_motion_curves(action):
        for key in curve.keyframe_points: key.interpolation="LINEAR"
    action["riggerset_preset"]=preset
    action["riggerset_in_place"]=True
    action["riggerset_duration"]=0 if pose_only else (end-1)/24
    scene.frame_set(1)
    bpy.context.view_layer.update()
    return {"changed":"animation.preset","action":action.name,"frames":end,"matchedBones":len(keyed),
            "kind":"pose" if pose_only else "clip","inPlace":True}


# SPDX-License-Identifier: GPL-3.0-or-later
"""Inline before creature-motion.py; bpy/mathutils are supplied by the daemon.

Poles are armature-local DIRECTIONS, groundZ is world Z.  No IK or constraints
are installed.  Pure helpers deliberately have no bpy dependency.
"""
import contextlib
import json
import math
import re
import hashlib


def _rs_rg_args(a, allowed):
    if not isinstance(a, dict) or set(a) - set(allowed):
        raise ValueError("Unknown rig parameter.")


def _rs_rg_name(value, label="name"):
    if not isinstance(value, str) or not 1 <= len(value) <= 120 or any(ord(c) < 32 for c in value):
        raise ValueError("Invalid " + label + ".")
    return value


def _rs_rg_number(value, label="number", bound=1e9):
    if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or abs(value) > bound:
        raise ValueError(label + " must be finite and bounded.")
    return float(value)


def _rs_rg_vec(value, label="coordinate"):
    if not isinstance(value, (list, tuple)) or len(value) != 3:
        raise ValueError(label + " needs three finite values.")
    return tuple(_rs_rg_number(v, label) for v in value)


def _rs_rg_add(a, b): return tuple(x + y for x, y in zip(a, b))
def _rs_rg_sub(a, b): return tuple(x - y for x, y in zip(a, b))
def _rs_rg_mul(a, s): return tuple(x * s for x in a)
def _rs_rg_dot(a, b): return sum(x * y for x, y in zip(a, b))
def _rs_rg_length(a): return math.sqrt(_rs_rg_dot(a, a))
def _rs_rg_unit(a):
    size = _rs_rg_length(a)
    if size < 1e-10: raise ValueError("A limb direction has zero length.")
    return _rs_rg_mul(a, 1 / size)


def _rs_rg_pole(pole, axis):
    """A projected unit direction, never an arbitrary fallback bend plane."""
    pole, axis = _rs_rg_unit(pole), _rs_rg_unit(axis)
    projected = _rs_rg_sub(pole, _rs_rg_mul(axis, _rs_rg_dot(pole, axis)))
    if _rs_rg_length(projected) < 1e-4:
        raise ValueError("Pole direction is collinear with the limb; choose an off-axis bend direction.")
    return _rs_rg_unit(projected)


def _rs_rg_joint_plan(records, name, head, tail):
    """Move only the selected endpoints and endpoints sharing their junctions."""
    by = {r["name"]: dict(r, head=_rs_rg_vec(tuple(r["head"]), "rest head"),
                         tail=_rs_rg_vec(tuple(r["tail"]), "rest tail")) for r in records}
    if name not in by: raise ValueError("The selected bone does not exist.")
    head, tail = _rs_rg_vec(head, "head"), _rs_rg_vec(tail, "tail")
    changes = {name: {"head": head, "tail": tail}}
    bone = by[name]
    if bone.get("connected"):
        parent = bone.get("parent")
        if parent not in by: raise ValueError("A connected bone has no parent.")
        changes.setdefault(parent, {})["tail"] = head
        for sibling in records:
            if sibling.get("parent") == parent and sibling.get("connected"):
                changes.setdefault(sibling["name"], {})["head"] = head
    for child in records:
        if child.get("parent") == name and child.get("connected"):
            changes.setdefault(child["name"], {})["head"] = tail
    for n, endpoints in changes.items():
        by[n].update(endpoints)
        if _rs_rg_length(_rs_rg_sub(by[n]["tail"], by[n]["head"])) < 1e-6:
            raise ValueError("Joint edit would collapse bone " + n + ".")
    return changes, by


def _rs_rg_records(ob):
    editing = ob.mode == "EDIT"
    return [{"name": b.name, "head": tuple(b.head if editing else b.head_local),
             "tail": tuple(b.tail if editing else b.tail_local),
             "parent": b.parent.name if b.parent else None, "connected": b.use_connect}
            for b in (ob.data.edit_bones if editing else ob.data.bones)]


def _rs_rg_editable(ob, unique=False):
    if ob.library or ob.data.library or getattr(ob, "override_library", None) or not getattr(ob, "is_editable", True):
        raise ValueError("Linked or overridden data is unsupported; use a local editable object.")
    if unique and ob.data.users != 1:
        raise ValueError("Shared data is unsupported; make this object's data single-user first.")
    if ob.name not in bpy.context.view_layer.objects or ob.hide_get() or ob.hide_viewport:
        raise ValueError("The object must be visible in the current view layer.")


def _rs_rg_armature(name, unique=False):
    ob = _rs_obj(_rs_rg_name(name, "armature"))
    if ob.type != "ARMATURE": raise ValueError("Choose an armature.")
    if not 1 <= len(ob.data.bones) <= 256: raise ValueError("This tool supports 1–256 bones.")
    _rs_rg_editable(ob, unique)
    return ob


def _rs_rg_context_check():
    active = bpy.context.view_layer.objects.active
    if active and active.mode not in ("OBJECT", "POSE", "EDIT"):
        raise ValueError("Finish paint/sculpt mode before using rig controls.")
    if active and active.mode == "EDIT":
        if active.type not in ("MESH", "ARMATURE") or len(getattr(bpy.context, "objects_in_mode_unique_data", [active])) > 1:
            raise ValueError("Multi-object or unsupported edit mode is unsupported; finish the edit first.")


def _rs_rg_selection_state():
    active = bpy.context.view_layer.objects.active
    state = {"active": active, "selected": list(bpy.context.selected_objects),
             "mode": active.mode if active else "OBJECT", "bones": None, "activeBone": None,
             "activeBoneAvailable": False}
    if active and active.type == "ARMATURE":
        collection = active.data.edit_bones if active.mode == "EDIT" else active.data.bones
        # Blender 5.2 Bone omits legacy selection flags; EditBone can still expose
        # them. None means unavailable, distinct from a captured False flag.
        state["bones"] = [(b.name, *(getattr(b, prop, None) for prop in ("select", "select_head", "select_tail")))
                          for b in collection]
        state["activeBoneAvailable"] = hasattr(collection, "active")
        selected_bone = getattr(collection, "active", None)
        state["activeBone"] = selected_bone.name if selected_bone is not None else None
    return state


def _rs_rg_restore_selection(state):
    active = bpy.context.view_layer.objects.active
    if active and active.mode != "OBJECT": bpy.ops.object.mode_set(mode="OBJECT")
    for ob in list(bpy.context.selected_objects): ob.select_set(False)
    for ob in state["selected"]: ob.select_set(True)
    bpy.context.view_layer.objects.active = state["active"]
    if state["active"] and state["mode"] != "OBJECT": bpy.ops.object.mode_set(mode=state["mode"])
    if state["bones"] is not None:
        ob = state["active"]
        collection = ob.data.edit_bones if state["mode"] == "EDIT" else ob.data.bones
        for name, selected, head, tail in state["bones"]:
            bone = collection.get(name)
            if bone is not None:
                for prop, value in (("select", selected), ("select_head", head), ("select_tail", tail)):
                    if value is None or not hasattr(bone, prop): continue
                    readonly = getattr(bone, "is_property_readonly", None)
                    if readonly is not None and readonly(prop): continue
                    setattr(bone, prop, value)
        if state.get("activeBoneAvailable", True) and hasattr(collection, "active"):
            readonly = getattr(collection, "is_property_readonly", None)
            if readonly is None or not readonly("active"):
                collection.active = collection.get(state["activeBone"]) if state["activeBone"] else None


@contextlib.contextmanager
def _rs_rg_object_context(ob):
    _rs_rg_context_check()
    state = _rs_rg_selection_state()
    try:
        active = bpy.context.view_layer.objects.active
        if active and active.mode != "OBJECT": bpy.ops.object.mode_set(mode="OBJECT")
        for selected in list(bpy.context.selected_objects): selected.select_set(False)
        ob.select_set(True); bpy.context.view_layer.objects.active = ob
        yield
    finally:
        _rs_rg_restore_selection(state)


def _rs_rg_active_nla(data):
    return bool(data and getattr(data,"use_nla",True) and any(not getattr(track,"mute",False) and bool(getattr(track,"strips",(True,))) for track in data.nla_tracks))

def _rs_rg_no_animation(ob):
    for owner in (ob, ob.data):
        data = owner.animation_data
        if data and (data.action or data.drivers or _rs_rg_active_nla(data)):
            raise ValueError("Rest-joint editing cannot safely retain an action, drivers or NLA; use an unanimated rig copy.")
    if ob.constraints or any(b.constraints for b in ob.pose.bones):
        raise ValueError("Rest-joint editing cannot safely retain object/bone constraints.")
    for bone in ob.pose.bones:
        if any(abs(bone.matrix_basis[i][j] - (1 if i == j else 0)) > 1e-6 for i in range(4) for j in range(4)):
            raise ValueError("Return every pose bone to rest before adjusting rest joints.")
        if ob.mode != "EDIT" and any(abs(bone.matrix[i][j] - bone.bone.matrix_local[i][j]) > 1e-5 for i in range(4) for j in range(4)):
            raise ValueError("The evaluated pose is not rest; rest-joint editing was refused.")


def _rs_rg_digest(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8")).hexdigest()


def _rs_rg_matrix(ob):
    matrix = [[float(v) for v in row] for row in ob.matrix_world]
    if any(not math.isfinite(v) for row in matrix for v in row) or abs(ob.matrix_world.determinant()) < 1e-12:
        raise ValueError("The armature world transform is singular or non-finite.")
    return matrix


def _rs_rg_named_mirror(name):
    """Only explicit conventional names, never nearest bones or fuzzy matches."""
    for left, right in ((".L", ".R"), ("_L", "_R"), ("-L", "-R"), (".l", ".r"), ("_l", "_r")):
        if name.endswith(left): return name[:-len(left)] + right
        if name.endswith(right): return name[:-len(right)] + left
    for left, right in (("left", "right"), ("Left", "Right"), ("LEFT", "RIGHT")):
        for source, target in ((left, right), (right, left)):
            if name.startswith(source + "_"): return target + name[len(source):]
            if name.endswith("_" + source): return name[:-len(source)] + target
    return None


def _rs_rg_mirror_pairs(records):
    by = {b["name"]: b for b in records}; pairs = {}
    reflect = lambda p: (-p[0], p[1], p[2])
    size = max((_rs_rg_length(_rs_rg_sub(b["tail"], b["head"])) for b in records), default=1)
    tolerance = max(1e-6, size * 1e-4)
    for name, b in by.items():
        other = _rs_rg_named_mirror(name); c = by.get(other)
        if c is None or other == name or bool(b.get("connected")) != bool(c.get("connected")): continue
        if any(_rs_rg_length(_rs_rg_sub(reflect(b[k]), c[k])) > tolerance for k in ("head", "tail")): continue
        parent, peer_parent = b.get("parent"), c.get("parent")
        if parent != peer_parent and _rs_rg_named_mirror(parent or "") != peer_parent: continue
        # A shared parent must lie on the local mirror plane at both ends.
        if parent == peer_parent and parent and any(abs(by[parent][k][0]) > tolerance for k in ("head", "tail")): continue
        pairs[name] = other
    return pairs


def _rs_rg_snapshot(ob):
    return _rs_rg_digest({"armature": ob.name, "matrixWorld": _rs_rg_matrix(ob),
                          "bones": _rs_rg_records(ob), "controls": _rs_rg_controls_json(ob)})


def _rs_joint_inspect(a):
    """Bounded read-only preflight. No mode changes, action removal or pose reset."""
    _rs_rg_args(a, ("armature",))
    ob = _rs_obj(_rs_rg_name(a.get("armature"), "armature"))
    if ob.type != "ARMATURE" or not 1 <= len(ob.data.bones) <= 256:
        raise ValueError("Joint inspection supports an armature with 1–256 bones.")
    records = _rs_rg_records(ob); reason = None
    try:
        _rs_rg_context_check(); _rs_rg_editable(ob, unique=True); _rs_rg_no_animation(ob)
        if bpy.context.object and bpy.context.object.mode == "EDIT":
            raise ValueError("Finish Edit Mode before opening the exported visual joint view.")
        _rs_rg_matrix(ob)
    except ValueError as error: reason = str(error)
    return {"schema": 1, "armature": ob.name, "snapshot": _rs_rg_snapshot(ob),
            "matrixWorld": _rs_rg_matrix(ob), "bones": records, "editable": reason is None,
            "reason": reason, "mirrorPairs": _rs_rg_mirror_pairs(records),
            "space": "armature-local", "mirrorPlane": "local-X=0", "limitBones": 256}


def _rs_rg_batch_plan(records, name, head, tail, mirror=None):
    changes, _ = _rs_rg_joint_plan(records, name, head, tail)
    if mirror is not None:
        if _rs_rg_mirror_pairs(records).get(name) != mirror:
            raise ValueError("Mirror requires the explicit compatible named counterpart from inspection.")
        reflected = lambda p: (-p[0], p[1], p[2])
        other, _ = _rs_rg_joint_plan(records, mirror, reflected(head), reflected(tail))
        for n, endpoints in other.items():
            for endpoint, value in endpoints.items():
                existing = changes.setdefault(n, {}).get(endpoint)
                if existing is not None and _rs_rg_length(_rs_rg_sub(existing, value)) > 1e-7:
                    raise ValueError("The mirrored edit conflicts at a shared connected junction.")
                changes[n][endpoint] = value
    by = {b["name"]: dict(b) for b in records}
    for n, endpoints in changes.items(): by[n].update(endpoints)
    for n, b in by.items():
        if _rs_rg_length(_rs_rg_sub(b["tail"], b["head"])) < 1e-6:
            raise ValueError("Joint edit would collapse bone " + n + ".")
        if b.get("connected") and _rs_rg_length(_rs_rg_sub(b["head"], by[b["parent"]]["tail"])) > 1e-6:
            raise ValueError("Joint edit would split a connected junction.")
    return changes, by


def _rs_joint_plan(a):
    _rs_rg_args(a, ("armature", "bone", "head", "tail", "snapshot", "mirror"))
    ob = _rs_rg_armature(a.get("armature"), unique=True)
    _rs_rg_context_check(); _rs_rg_no_animation(ob)
    if bpy.context.object and bpy.context.object.mode == "EDIT":
        raise ValueError("Finish Edit Mode before planning visual rest-joint edits.")
    snapshot = _rs_rg_snapshot(ob)
    if not isinstance(a.get("snapshot"), str) or a["snapshot"] != snapshot:
        raise ValueError("The rig changed since inspection; inspect it again before applying.")
    name = _rs_rg_name(a.get("bone"), "bone")
    head, tail = _rs_rg_vec(a.get("head"), "head"), _rs_rg_vec(a.get("tail"), "tail")
    mirror = _rs_rg_name(a["mirror"], "mirror bone") if "mirror" in a else None
    changes, planned = _rs_rg_batch_plan(_rs_rg_records(ob), name, head, tail, mirror)
    _rs_rg_controls_validate(_rs_rg_controls_json(ob), planned)
    result = {"schema": 1, "armature": ob.name, "bone": name, "snapshot": snapshot,
              "mirror": mirror, "changes": [{"name": n, "head": list(planned[n]["head"]),
                                               "tail": list(planned[n]["tail"])} for n in sorted(changes)],
              "meshPreserved": True}
    return dict(result, digest=_rs_rg_digest(result))


def _rs_joint_apply(a):
    """Recompute a whole validated plan, then apply/rollback it as one native edit."""
    _rs_rg_args(a, ("armature", "bone", "head", "tail", "snapshot", "mirror", "digest"))
    plan = _rs_joint_plan({k: v for k, v in a.items() if k != "digest"})
    if not isinstance(a.get("digest"), str) or a["digest"] != plan["digest"]:
        raise ValueError("The reviewed joint plan is stale or was changed; review it again.")
    ob = _rs_rg_armature(a["armature"], unique=True)
    with _rs_rg_object_context(ob):
        bpy.ops.object.mode_set(mode="EDIT")
        saved = {b.name: {"head": tuple(b.head), "tail": tuple(b.tail), "roll": b.roll,
                          "connected": b.use_connect} for b in ob.data.edit_bones}
        mirrored = ob.data.use_mirror_x
        try:
            ob.data.use_mirror_x = False
            for b in ob.data.edit_bones: b.use_connect = False
            for record in plan["changes"]:
                b = ob.data.edit_bones[record["name"]]; b.head = record["head"]; b.tail = record["tail"]
            for name, record in saved.items():
                b = ob.data.edit_bones[name]; b.roll = record["roll"]; b.use_connect = record["connected"]
            # Re-read native endpoints before committing, so Blender propagation cannot silently win.
            for record in plan["changes"]:
                b = ob.data.edit_bones[record["name"]]
                if any(_rs_rg_length(_rs_rg_sub(getattr(b, k), record[k])) > 1e-5 for k in ("head", "tail")):
                    raise ValueError("Native joint propagation disagreed with the reviewed plan.")
        except BaseException:
            for b in ob.data.edit_bones: b.use_connect = False
            for name, record in saved.items():
                b = ob.data.edit_bones[name]; b.head = record["head"]; b.tail = record["tail"]; b.roll = record["roll"]
            for name, record in saved.items(): ob.data.edit_bones[name].use_connect = record["connected"]
            raise
        finally:
            ob.data.use_mirror_x = mirrored
            bpy.ops.object.mode_set(mode="OBJECT")
            bpy.context.view_layer.update()
    return {"changed": "rig.joint.apply", "changes": plan["changes"], "digest": plan["digest"],
            "mirror": plan["mirror"], "meshPreserved": True, "atomic": True}


def _rs_joint_set(a):
    _rs_rg_args(a, ("armature", "bone", "head", "tail"))
    _rs_rg_context_check()
    ob = _rs_rg_armature(a.get("armature"), unique=True)
    active = getattr(bpy.context, "object", None)
    if active and active.mode == "EDIT" and active != ob:
        raise ValueError("Finish the other object's Edit Mode before changing rest joints.")
    name = _rs_rg_name(a.get("bone"), "bone")
    _rs_rg_no_animation(ob)
    changes, planned = _rs_rg_joint_plan(_rs_rg_records(ob), name, a.get("head"), a.get("tail"))
    # A calibration must not silently invalidate an already saved pole.
    _rs_rg_controls_validate(_rs_rg_controls_json(ob), planned)
    with _rs_rg_object_context(ob):
        bpy.ops.object.mode_set(mode="EDIT")
        for n, endpoints in changes.items():
            for endpoint, value in endpoints.items(): setattr(ob.data.edit_bones[n], endpoint, value)
        bpy.ops.object.mode_set(mode="OBJECT")
        bpy.context.view_layer.update()
    return {"changed": "rig.joint", "bone": name, "head": list(planned[name]["head"]),
            "tail": list(planned[name]["tail"]), "meshPreserved": True}


def _rs_rg_chain_name(value):
    if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{0,63}", value):
        raise ValueError("chain must be a short role identifier, such as front_left_leg.")
    return value


def _rs_rg_controls_json(ob):
    raw = ob.get("riggerset_limb_controls", "{}")
    if not isinstance(raw, str) or len(raw.encode("utf-8")) > 16384:
        raise ValueError("Saved limb controls must be bounded JSON text.")
    try: controls = json.loads(raw)
    except (ValueError, TypeError) as error: raise ValueError("Saved limb controls are invalid JSON.") from error
    if not isinstance(controls, dict) or len(controls) > 12:
        raise ValueError("At most twelve limb chains can be configured.")
    return controls


def _rs_rg_controls_validate(controls, by):
    result = {}
    for chain, c in controls.items():
        _rs_rg_chain_name(chain)
        if not isinstance(c, dict) or set(c) - {"upper", "lower", "end", "pole", "plant", "groundZ"}:
            raise ValueError("Invalid saved limb configuration.")
        names = [_rs_rg_name(c.get(k), k) for k in ("upper", "lower", "end")]
        if len(set(names)) != 3 or any(n not in by for n in names): raise ValueError("A limb needs three separate existing bones.")
        upper, lower, end = (by[n] for n in names)
        if lower["parent"] != names[0] or end["parent"] != names[1]:
            raise ValueError("A limb must be a direct upper → lower → end hierarchy.")
        if min(_rs_rg_length(_rs_rg_sub(lower["head"], upper["head"])), _rs_rg_length(_rs_rg_sub(end["head"], lower["head"]))) < 1e-6:
            raise ValueError("A limb has coincident joints.")
        pole = _rs_rg_unit(_rs_rg_vec(c.get("pole"), "pole direction"))
        _rs_rg_pole(pole, _rs_rg_sub(end["head"], upper["head"]))
        if not isinstance(c.get("plant"), bool): raise ValueError("plant must be a boolean.")
        if c["plant"] and "wing" in chain.lower(): raise ValueError("In-place foot planting is supported on legs, not wings.")
        value = dict(zip(("upper", "lower", "end"), names), pole=list(pole), plant=c["plant"])
        if "groundZ" in c: value["groundZ"] = _rs_rg_number(c["groundZ"], "groundZ")
        result[chain] = value
    return result


def _rs_limb_controls(ob):
    if ob.type != "ARMATURE": raise ValueError("Choose an armature for limb controls.")
    return _rs_rg_controls_validate(_rs_rg_controls_json(ob), {r["name"]: r for r in _rs_rg_records(ob)})


def _rs_limb_configure(a):
    _rs_rg_args(a, ("armature", "chain", "upper", "lower", "end", "pole", "plant", "groundZ"))
    ob = _rs_rg_armature(a.get("armature"))
    chain = _rs_rg_chain_name(a.get("chain"))
    controls = _rs_rg_controls_json(ob)
    controls[chain] = {k: a[k] for k in ("upper", "lower", "end", "pole", "plant", "groundZ") if k in a}
    if len(controls) > 12: raise ValueError("At most twelve limb chains can be configured.")
    controls = _rs_rg_controls_validate(controls, {r["name"]: r for r in _rs_rg_records(ob)})
    encoded = json.dumps(controls, separators=(",", ":"), allow_nan=False)
    if len(encoded.encode("utf-8")) > 16384: raise ValueError("Limb controls exceed their storage bound.")
    ob["riggerset_limb_controls"] = encoded
    return {"changed": "rig.limb", "chain": chain, "controls": controls[chain],
            "plantMode": "in-place-march" if controls[chain]["plant"] else "disabled"}


def _rs_rg_motion_controls(ob, match):
    """Validate explicit role agreement before any action is copied/created."""
    _rs_rg_context_check()
    _rs_rg_editable(ob)
    if ob.mode == "EDIT" or (bpy.context.object and bpy.context.object.mode == "EDIT"):
        raise ValueError("Finish Edit Mode before creating creature motion.")
    controls, by = _rs_limb_controls(ob), {r["name"]: r for r in _rs_rg_records(ob)}
    result = {}
    for chain in match["lengths"]:
        if chain not in controls: continue
        c = controls[chain]
        if any(c[s] != match["roles"][chain + "_" + s] for s in ("upper", "lower", "end")):
            raise ValueError("Saved limb " + chain + " does not match the explicit animation roles.")
        for parent, child in ((c["upper"], c["lower"]), (c["lower"], c["end"])):
            if _rs_rg_length(_rs_rg_sub(by[parent]["tail"], by[child]["head"])) > sum(match["lengths"][chain]) * 1e-5:
                raise ValueError("Configured motion requires coincident upper-tail/lower-head and lower-tail/end-head joints.")
        pole = tuple(ob.matrix_world.to_3x3() @ Vector(c["pole"]))
        _rs_rg_pole(pole, _rs_rg_sub(match["points"][c["end"]], match["points"][c["upper"]]))
        result[chain] = dict(c, pole=pole, groundZ=c.get("groundZ", match["points"][c["end"]][2]))
    return result


def _rs_rg_stance(preset, phase):
    if preset not in ("walk", "trot"): return True
    return phase % 1 < (.65 if preset == "walk" else .5)


def _rs_rg_plant_goal(rest, forward, size, phase, preset, strength, ground):
    """Stationary stance; smooth swing out and back to precisely that anchor."""
    anchor = (rest[0], rest[1], ground)
    if _rs_rg_stance(preset, phase): return anchor
    duty = .65 if preset == "walk" else .5
    u = ((phase % 1) - duty) / (1 - duty)
    bump = math.sin(math.pi * u) ** 2  # zero position/velocity at both boundaries
    return _rs_rg_add(anchor, _rs_rg_add(_rs_rg_mul(forward, .10 * size * strength * bump), (0, 0, .07 * size * strength * bump)))


def _rs_rg_exact_solve(root, goal, lengths, pole):
    """Exact planted endpoint: refuse unreachable or near-singular stances."""
    a, b = lengths; ray = _rs_rg_sub(goal, root); distance = _rs_rg_length(ray)
    margin = (a + b) * 1e-6
    if not abs(a - b) + margin < distance < a + b - margin:
        raise ValueError("A planted stance/swing is unreachable or straight-locked at this groundZ; recalibrate the leg or ground.")
    axis, bend = _rs_rg_unit(ray), _rs_rg_pole(pole, ray)
    along = (a * a - b * b + distance * distance) / (2 * distance)
    knee = _rs_rg_add(root, _rs_rg_add(_rs_rg_mul(axis, along), _rs_rg_mul(bend, math.sqrt(max(0, a * a - along * along)))))
    return knee, tuple(goal)


def _rs_rg_edit_mesh(mesh):
    if mesh.mode != "EDIT": return None
    import bmesh
    live = bmesh.from_edit_mesh(mesh.data)
    if len(live.verts) != len(mesh.data.vertices) or any(v.index < 0 or v.index >= len(mesh.data.vertices) for v in live.verts):
        raise ValueError("Finish the mesh topology edit before assigning rigid weights.")
    return live


def _rs_rg_vertex_ids(mesh, a, edit=None):
    if "vertices" in a and "group" in a: raise ValueError("Choose vertices or a group, not both.")
    if "vertices" in a:
        ids = a["vertices"]
        if not isinstance(ids, list) or not 1 <= len(ids) <= 10000 or any(isinstance(i, bool) or not isinstance(i, int) or not 0 <= i < len(mesh.data.vertices) for i in ids):
            raise ValueError("vertices must contain 1–10000 existing integer vertex indices.")
        if len(set(ids)) != len(ids): raise ValueError("Vertex indices must be unique.")
        return list(ids)
    if "group" in a:
        group = mesh.vertex_groups.get(_rs_rg_name(a["group"], "vertex group"))
        if group is None: raise ValueError("The source vertex group does not exist.")
        ids = []
        deform = edit.verts.layers.deform.active if edit is not None else None
        for v in (edit.verts if edit is not None else mesh.data.vertices):
            chosen = v[deform].get(group.index, 0) > 0 if deform is not None else (False if edit is not None else any(g.group == group.index and g.weight > 0 for g in v.groups))
            if chosen: ids.append(v.index)
            if len(ids) > 10000: raise ValueError("Select at most 10000 vertices.")
    elif mesh.mode == "EDIT":
        edit = edit if edit is not None else _rs_rg_edit_mesh(mesh)
        ids = [v.index for v in edit.verts if v.select]
    else: ids = [v.index for v in mesh.data.vertices if v.select]
    if not 1 <= len(ids) <= 10000: raise ValueError("Choose 1–10000 vertices.")
    return ids


def _rs_rigid_weights(a):
    _rs_rg_args(a, ("object", "armature", "bone", "vertices", "group"))
    _rs_rg_context_check()
    mesh = _rs_obj(_rs_rg_name(a.get("object"), "mesh"))
    if mesh.type != "MESH": raise ValueError("Choose a mesh for rigid weights.")
    active = getattr(bpy.context, "object", None)
    if active and active.mode == "EDIT" and active != mesh:
        raise ValueError("Finish the other object's Edit Mode before assigning rigid weights.")
    _rs_rg_editable(mesh, unique=True)
    ob = _rs_rg_armature(a.get("armature"))
    name = _rs_rg_name(a.get("bone"), "deform bone")
    bone = ob.data.bones.get(name)
    if bone is None or not bone.use_deform: raise ValueError("Choose an existing deform bone.")
    armatures = [m for m in mesh.modifiers if m.type == "ARMATURE" and (m.show_viewport or m.show_render)]
    if len(armatures) != 1 or armatures[0].object != ob or not armatures[0].use_vertex_groups or armatures[0].use_bone_envelopes:
        raise ValueError("Rigid weights need one vertex-group armature modifier targeting this rig, without bone envelopes.")
    edit = _rs_rg_edit_mesh(mesh)
    ids = _rs_rg_vertex_ids(mesh, a, edit)
    groups = {g.index: g for g in mesh.vertex_groups}
    deform_names = {b.name for b in ob.data.bones if b.use_deform}
    remove = {}
    target = mesh.vertex_groups.get(name)
    if target and target.lock_weight: raise ValueError("The target vertex group is locked.")
    if edit is not None:
        chosen = set(ids); deform = edit.verts.layers.deform.active
        memberships = {v.index: dict(v[deform]) if deform is not None else {} for v in edit.verts if v.index in chosen}
    else:
        memberships = {i: {g.group: g.weight for g in mesh.data.vertices[i].groups} for i in ids}
    for index in ids:
        for group_index in memberships[index]:
            group = groups[group_index]
            if group.name in deform_names and group.name != name:
                if group.lock_weight: raise ValueError("A competing deform-bone group is locked: " + group.name)
                remove.setdefault(group.index, []).append(index)
    with _rs_rg_object_context(mesh):
        target = target or mesh.vertex_groups.new(name=name)
        for group_index, vertices in remove.items(): groups[group_index].remove(vertices)
        target.add(ids, 1.0, "REPLACE")
        bpy.context.view_layer.update()
    return {"changed": "rig.weights", "bone": name, "vertices": len(ids), "rigid": True}


# SPDX-License-Identifier: GPL-3.0-or-later
"""Bounded, in-place creature FK starters; inline after automatic-animation.py.

Canonical roles: body, head, and <chain>_{upper,lower,end}. Bird chains are
left_wing, right_wing, left_leg, right_leg; quadruped chains are
front_left_leg, front_right_leg, hind_left_leg, hind_right_leg.
The three mapped heads are shoulder/hip, elbow/knee, wrist/ankle respectively.
Configured foot plants are stationary in-place/march anchors, not root locomotion.
Load creature-rig.py before this module for configured poles and planting.
"""
import math


def _rs_cr_chains(family):
    if family == "bird": return ("left_wing", "right_wing", "left_leg", "right_leg")
    if family == "quadruped": return tuple(a+"_"+b+"_leg" for a in ("front", "hind") for b in ("left", "right"))
    raise ValueError("Choose bird or quadruped.")


def _rs_cr_required(family):
    return ["body", "head"]+[c+"_"+s for c in _rs_cr_chains(family) for s in ("upper", "lower", "end")]


def _rs_cr_add(a, b): return tuple(x+y for x, y in zip(a, b))
def _rs_cr_sub(a, b): return tuple(x-y for x, y in zip(a, b))
def _rs_cr_mul(a, s): return tuple(x*s for x in a)
def _rs_cr_dot(a, b): return sum(x*y for x, y in zip(a, b))
def _rs_cr_len(a): return math.sqrt(_rs_cr_dot(a, a))
def _rs_cr_unit(a):
    size = _rs_cr_len(a)
    if size < 1e-10: raise ValueError("A required limb has coincident joints.")
    return _rs_cr_mul(a, 1/size)


def _rs_cr_rotate(v, axis, angle):
    c, s = math.cos(angle), math.sin(angle)
    cross = (axis[1]*v[2]-axis[2]*v[1], axis[2]*v[0]-axis[0]*v[2], axis[0]*v[1]-axis[1]*v[0])
    return _rs_cr_add(_rs_cr_add(_rs_cr_mul(v, c), _rs_cr_mul(cross, s)), _rs_cr_mul(axis, _rs_cr_dot(axis, v)*(1-c)))


def _rs_cr_map(bones, family, forward_axis="Y", roles=None):
    required = _rs_cr_required(family)
    axes = {"X": (1, 0, 0), "-X": (-1, 0, 0), "Y": (0, 1, 0), "-Y": (0, -1, 0)}
    if not isinstance(forward_axis, str) or forward_axis not in axes: raise ValueError("forwardAxis must be X, -X, Y or -Y.")
    if not isinstance(bones, list) or not 14 <= len(bones) <= 256: raise ValueError("Creature motion needs one skeleton with 14–256 joints.")
    by, points = {}, {}
    for b in bones:
        if not isinstance(b, dict) or not isinstance(b.get("name"), str) or not b["name"] or b["name"] in by: raise ValueError("Joint names must be unique nonempty strings.")
        p = b.get("head")
        if not isinstance(p, (list, tuple)) or len(p) != 3 or any(isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or abs(v) > 1e12 for v in p): raise ValueError("Joint positions must be finite bounded 3D coordinates.")
        by[b["name"]], points[b["name"]] = b, tuple(p)
    children = {n: [] for n in by}
    for n, b in by.items():
        p = b.get("parent")
        if p is not None:
            if not isinstance(p, str) or p not in by: raise ValueError("The skeleton has a missing parent.")
            children[p].append(n)
    for n in by:
        seen = set(); p = n
        while p is not None:
            if p in seen: raise ValueError("The skeleton contains a parent cycle.")
            seen.add(p); p = by[p].get("parent")
    roots = [n for n in by if by[n].get("parent") is None]
    if len(roots) != 1: raise ValueError("Creature motion needs one connected skeleton.")
    forward = axes[forward_axis]; left = (-forward[1], forward[0], 0)
    f = lambda n: _rs_cr_dot(points[n], forward)
    l = lambda n: _rs_cr_dot(points[n], left)
    def ancestors(n):
        result = []
        while n is not None: result.append(n); n = by[n].get("parent")
        return result
    def refuse(): raise ValueError("Ambiguous creature layout. Supply a complete roles map using requiredRoles and check forwardAxis.")
    chains = _rs_cr_chains(family)
    if roles is None:
        named = {r: [n for n in by if n.lower() == r] for r in required}
        if all(len(v) == 1 for v in named.values()): roles = {r: v[0] for r, v in named.items()}
        else:
            legs, wings = [], []
            for n in by:
                p = by[n].get("parent")
                if p is None or len(children[p]) < 2 or len(children[n]) != 1: continue
                mid = children[n][0]
                if len(children[mid]) != 1: continue
                end = children[mid][0]
                if children[end]: continue
                size = _rs_cr_len(_rs_cr_sub(points[mid], points[n]))+_rs_cr_len(_rs_cr_sub(points[end], points[mid]))
                if size < 1e-7: continue
                if points[n][2]-points[end][2] > .45*size: legs.append((n, mid, end))
                if abs(l(end)-l(n)) > .65*size and abs(points[end][2]-points[n][2]) < .35*size: wings.append((n, mid, end))
            if len(legs) != (2 if family == "bird" else 4) or (family == "bird" and len(wings) != 2): refuse()
            if family == "bird": parts = sorted(wings, key=lambda p: l(p[0]), reverse=True)+sorted(legs, key=lambda p: l(p[0]), reverse=True)
            else:
                legs.sort(key=lambda p: f(p[0]), reverse=True)
                parts = sorted(legs[:2], key=lambda p: l(p[0]), reverse=True)+sorted(legs[2:], key=lambda p: l(p[0]), reverse=True)
            roles = {c+"_"+s: n for c, part in zip(chains, parts) for s, n in zip(("upper", "lower", "end"), part)}
            body = next(n for n in ancestors(parts[0][0]) if all(n in ancestors(p[0]) for p in parts))
            occupied = {n for part in parts for n in part}
            reference = sum(_rs_cr_len(_rs_cr_sub(points[p[0]], points[p[2]])) for p in legs)/len(legs)
            heads = [n for n in by if n not in occupied and n != body and not children[n] and body in ancestors(n)
                     and points[n][2] > points[body][2]-.15*reference and
                     (f(n) > max(f(p[0]) for p in legs)+.15*reference if family == "quadruped" else points[n][2] > points[body][2]+.2*reference)]
            if len(heads) != 1: refuse()
            roles.update(body=body, head=heads[0])
    if not isinstance(roles, dict) or set(roles) != set(required): raise ValueError("roles must provide exactly every required role; partial maps are not inferred.")
    if any(not isinstance(n, str) or n not in by for n in roles.values()): raise ValueError("A role refers to a missing joint.")
    if len(set(roles.values())) != len(required): raise ValueError("Role assignments must not reuse joints.")
    body = roles["body"]
    if any(body not in ancestors(n) for n in roles.values()): raise ValueError("body must be an ancestor of every mapped joint.")
    lengths = {}
    for c in chains:
        a, b, e = (roles[c+"_"+s] for s in ("upper", "lower", "end"))
        if by[b].get("parent") != a or by[e].get("parent") != b: raise ValueError("Each mapped limb must be a direct upper → lower → end chain.")
        if roles["head"] in ancestors(a) or a in ancestors(roles["head"]) or any(other in ancestors(a)[1:] for other in roles.values() if other not in (body, a)): raise ValueError("Mapped limb branches must be separate from head and other limbs.")
        v, w = _rs_cr_sub(points[b], points[a]), _rs_cr_sub(points[e], points[b])
        x, y = _rs_cr_len(v), _rs_cr_len(w)
        if min(x, y) < 1e-7 or not .2 <= x/y <= 5 or _rs_cr_len(_rs_cr_add(v, w)) < .25*(x+y): raise ValueError("A limb has implausible lengths or is folded back on itself.")
        lengths[c] = (x, y)
        if c.endswith("leg") and (points[a][2]-points[e][2] < .45*(x+y) or min(points[a][2]-points[b][2], points[b][2]-points[e][2]) < -.05*(x+y)): raise ValueError("Legs must descend from hip/shoulder through knee to ankle.")
        if "wing" in c and (l(e)-l(a))*(1 if c.startswith("left") else -1) < .45*(x+y): raise ValueError("Rest wings must extend outward against the chosen forward axis.")
    pairs = (("left_wing", "right_wing"), ("left_leg", "right_leg")) if family == "bird" else tuple((a+"_left_leg", a+"_right_leg") for a in ("front", "hind"))
    for a, b in pairs:
        size = sum(lengths[a]+lengths[b])/2
        if l(roles[a+"_upper"])-l(roles[b+"_upper"]) < .06*size: raise ValueError("Left/right attachments are ambiguous or reversed for forwardAxis.")
        centre = (l(roles[a+"_upper"])+l(roles[b+"_upper"]))/2
        if l(roles[a+"_end"]) <= centre or l(roles[b+"_end"]) >= centre: raise ValueError("Limb endpoints cross the bilateral centre.")
        if not .5 < sum(lengths[a])/sum(lengths[b]) < 2: raise ValueError("Paired limb lengths are too dissimilar.")
    if family == "quadruped":
        front = [f(roles[c+"_upper"]) for c in chains[:2]]; hind = [f(roles[c+"_upper"]) for c in chains[2:]]
        if min(front)-max(hind) < .12*sum(sum(v) for v in lengths.values())/4: raise ValueError("Front/hind leg attachments are ambiguous or reversed for forwardAxis.")
    return {"roles": dict(roles), "points": points, "lengths": lengths, "forward": forward, "left": left, "family": family, "parents": {n: b.get("parent") for n, b in by.items()}}


def _rs_cr_solve(root, goal, lengths, pole):
    """Two-link positional solve, clamped inside the reachable annulus."""
    a, b = lengths; eps = (a+b)*1e-5
    ray = _rs_cr_sub(goal, root); distance = _rs_cr_len(ray)
    axis = _rs_cr_unit(ray) if distance > eps else (0, 0, -1)
    distance = max(abs(a-b)+eps, min(a+b-eps, distance))
    pole = _rs_cr_sub(pole, _rs_cr_mul(axis, _rs_cr_dot(pole, axis)))
    if _rs_cr_len(pole) < eps:
        fallback = min(((1, 0, 0), (0, 1, 0), (0, 0, 1)), key=lambda v: abs(_rs_cr_dot(v, axis)))
        pole = _rs_cr_sub(fallback, _rs_cr_mul(axis, _rs_cr_dot(fallback, axis)))
    along = (a*a-b*b+distance*distance)/(2*distance)
    knee = _rs_cr_add(root, _rs_cr_add(_rs_cr_mul(axis, along), _rs_cr_mul(_rs_cr_unit(pole), math.sqrt(max(0, a*a-along*along)))))
    return knee, _rs_cr_add(root, _rs_cr_mul(axis, distance))


def _rs_cr_plan(match, preset, t, strength):
    """Pure geometry: desired world directions, body pitch and reachable feet."""
    family = match["family"]
    if preset not in (("flap", "fold", "idle") if family == "bird" else ("walk", "trot", "idle")): raise ValueError("Preset does not belong to this creature family.")
    if not math.isfinite(t) or not math.isfinite(strength) or not .25 <= strength <= 1.25: raise ValueError("Invalid motion phase or strength.")
    phase = 2*math.pi*(t % 1); f, left = match["forward"], match["left"]
    roles, points = match["roles"], match["points"]
    pitch = 0 if preset == "fold" else .012*strength*math.sin(phase)
    origin = points[roles["body"]]; directions, feet = {}, {}
    controls = match.get("limbControls", {})
    for index, c in enumerate(_rs_cr_chains(family)):
        a, b, e = (points[roles[c+"_"+s]] for s in ("upper", "lower", "end"))
        control = controls.get(c)
        if "wing" in c:
            sign = 1 if c.startswith("left") else -1
            for suffix, vector, delay in (("upper", _rs_cr_sub(b, a), 0), ("lower", _rs_cr_sub(e, b), .3)):
                if preset == "fold": vector = _rs_cr_rotate(_rs_cr_rotate(vector, (0, 0, 1), sign*(1 if suffix == "upper" else 1.55)*min(1, strength)), f, -sign*.12*strength)
                else:
                    angle = strength*(.55*math.sin(phase)+(.12*math.sin(phase-delay) if suffix == "lower" else 0)) if preset == "flap" else .025*strength*math.sin(phase)
                    vector = _rs_cr_rotate(vector, f, sign*angle)
                directions[c+"_"+suffix] = _rs_cr_rotate(vector, left, pitch)
            if control:
                root = _rs_cr_add(origin, _rs_cr_rotate(_rs_cr_sub(a, origin), left, pitch))
                goal = _rs_cr_add(root, _rs_cr_add(directions[c+"_upper"], directions[c+"_lower"]))
                _rs_rg_pole(control["pole"], _rs_cr_sub(goal, root))
                knee, foot = _rs_cr_solve(root, goal, match["lengths"][c], control["pole"])
                directions[c+"_upper"], directions[c+"_lower"] = _rs_cr_sub(knee, root), _rs_cr_sub(foot, knee)
        else:
            root = _rs_cr_add(origin, _rs_cr_rotate(_rs_cr_sub(a, origin), left, pitch))
            goal = e
            if control and control["plant"]:
                offset = ((.25, .75, 0, .5) if preset == "walk" else (0, .5, .5, 0))[index] if preset in ("walk", "trot") else 0
                goal = _rs_rg_plant_goal(e, f, sum(match["lengths"][c]), t+offset, preset, strength, control["groundZ"])
            elif preset in ("walk", "trot"):
                offset = ((.25, .75, 0, .5) if preset == "walk" else (0, .5, .5, 0))[index]
                q = (t+offset) % 1; duty = .65 if preset == "walk" else .5
                swing = q >= duty; u = (q-duty)/(1-duty) if swing else q/duty
                size = sum(match["lengths"][c]); stride = .10*size*strength
                goal = _rs_cr_add(e, _rs_cr_add(_rs_cr_mul(f, stride*math.cos(math.pi*u)*(-1 if swing else 1)), (0, 0, .07*size*strength*math.sin(math.pi*u)**2 if swing else 0)))
            rest_axis = _rs_cr_unit(_rs_cr_sub(e, a))
            pole = _rs_cr_sub(_rs_cr_sub(b, a), _rs_cr_mul(rest_axis, _rs_cr_dot(_rs_cr_sub(b, a), rest_axis)))
            if _rs_cr_len(pole) < 1e-7: pole = f
            if control:
                pole = control["pole"]
                _rs_rg_pole(pole, _rs_cr_sub(goal, root))
            knee, foot = (_rs_rg_exact_solve(root, goal, match["lengths"][c], pole)
                          if control and control["plant"] else _rs_cr_solve(root, goal, match["lengths"][c], pole))
            directions[c+"_upper"], directions[c+"_lower"] = _rs_cr_sub(knee, root), _rs_cr_sub(foot, knee)
            feet[c] = foot
    return {"directions": directions, "pitch": pitch, "feet": feet}


def _rs_cr_guard(ob):
    if ob.type != "ARMATURE": raise ValueError("Choose an armature for creature motion.")
    scale, local = tuple(ob.matrix_world.to_scale()), tuple(ob.scale)
    if any(not math.isfinite(v) or v <= 0 for v in scale+local) or max(scale)/min(scale) > 1.001 or max(local)/min(local) > 1.001 or ob.matrix_world.determinant() <= 0: raise ValueError("Apply non-uniform or negative armature scale first.")
    axes = [ob.matrix_world.to_3x3().col[i].normalized() for i in range(3)]
    if any(abs(axes[i].dot(axes[j])) > .001 for i in range(3) for j in range(i)): raise ValueError("Apply armature shear first.")
    if ob.animation_data and (ob.animation_data.drivers or ob.animation_data.nla_tracks): raise ValueError("Creature presets need a rig without drivers or NLA tracks.")
    action = ob.animation_data.action if ob.animation_data else None
    if action and hasattr(action, "layers") and (len(action.layers) > 1 or any(len(layer.strips) > 1 for layer in action.layers)): raise ValueError("Creature presets need at most one action layer and strip.")
    if any(b.constraints for b in ob.pose.bones): raise ValueError("Creature presets need a rig without bone constraints.")
    if ob.constraints: raise ValueError("Creature presets need an armature without object constraints.")


def _rs_creature_info(ob, family, forward_axis="Y"):
    result = {"supported": False, "suggestedRoles": {}, "requiredRoles": [], "presets": []}
    try:
        result["requiredRoles"] = _rs_cr_required(family)
        result["presets"] = ["flap", "fold", "idle"] if family == "bird" else ["walk", "trot", "idle"]
        _rs_cr_guard(ob)
        result["suggestedRoles"] = _rs_cr_map(_rs_motion_bones(ob), family, forward_axis)["roles"]
        result["supported"] = True
    except (ValueError, KeyError, TypeError, OverflowError) as error: result["reason"] = str(error)[:220]
    return result


def _rs_cr_channels(action, slot):
    layers = getattr(action, "layers", [])
    if not layers and hasattr(action, "fcurves"): return [action.fcurves]
    bags = [bag for layer in layers for strip in layer.strips for bag in getattr(strip, "channelbags", [])]
    if slot is None and len(bags) > 1: raise ValueError("An active action slot is required for a multi-slot action.")
    return [bag.fcurves for bag in bags if slot is None or bag.slot_handle == slot.handle]


def _rs_apply_creature_motion(a):
    if not isinstance(a, dict) or set(a)-{"armature", "family", "preset", "duration", "strength", "forwardAxis", "roles"}: raise ValueError("Unknown creature animation parameter.")
    family, preset = a.get("family"), a.get("preset")
    _rs_cr_chains(family)
    if preset not in (("flap", "fold", "idle") if family == "bird" else ("walk", "trot", "idle")): raise ValueError("Choose a preset for the selected creature family.")
    duration = _rs_num(a.get("duration", 3), .75, 6); strength = _rs_num(a.get("strength", 1), .25, 1.25)
    if not math.isfinite(duration) or not math.isfinite(strength): raise ValueError("Motion parameters must be finite.")
    ob = _rs_obj(a.get("armature", "")); _rs_cr_guard(ob)
    match = _rs_cr_map(_rs_motion_bones(ob), family, a.get("forwardAxis", "Y"), a.get("roles"))
    bones, roles = ob.pose.bones, match["roles"]
    controlled = set(roles.values())
    for n in list(controlled):
        p = bones[n].parent
        while p: controlled.add(p.name); p = p.parent
    ordered = []; pending = [b for b in bones if b.parent is None]
    while pending:
        b = pending.pop(); pending.extend(b.children)
        if b.name in controlled: ordered.append(b)
    if any(not b.bone.use_inherit_rotation or b.bone.inherit_scale != "FULL" or not b.bone.use_local_location for b in ordered): raise ValueError("Creature presets need standard bone transform inheritance.")
    rest = {b.name: (ob.matrix_world @ b.bone.matrix_local).to_quaternion() for b in ordered}
    heads = match["points"]; identity = Quaternion((1, 0, 0, 0))
    match["limbControls"] = _rs_rg_motion_controls(ob, match)
    scene = bpy.context.scene; end = 1 if preset == "fold" else round(duration*24)+1
    captured = _rs_control().get("epoch")
    plans = []
    for frame in range(1, end+1):
        if _rs_control().get("epoch") != captured: raise ValueError("Animation stopped before creating an action.")
        # Refuse every unreachable anchor or singular pole before changing state.
        plans.append(_rs_cr_plan(match, preset, 0 if end == 1 else (frame-1)/(end-1), strength))
    data = ob.animation_data; previous = data.action if data else None
    previous_slot = getattr(data, "action_slot", None) if data else None
    if previous: _rs_cr_channels(previous, previous_slot)
    ob.animation_data_create(); data = ob.animation_data
    action = previous.copy() if previous else bpy.data.actions.new("RiggerSet")
    action.name = "RiggerSet · "+family.title()+" "+preset.title(); action.use_fake_user = True
    if previous: previous.use_fake_user = True
    data.action = action
    if previous_slot is not None:
        data.action_slot = next(slot for slot in action.slots if slot.identifier == previous_slot.identifier)
    paths = {b.path_from_id(prop) for b in ordered for prop in ("rotation_quaternion", "rotation_euler", "rotation_axis_angle", "location", "scale")}
    for channels in _rs_cr_channels(action, getattr(data, "action_slot", None)):
        for curve in list(channels):
            if curve.data_path in paths: channels.remove(curve)
    scene.render.fps = 24; scene.frame_start = 1; scene.frame_end = max(2, end)
    last = {}
    for frame in range(1, end+1):
        if _rs_control().get("epoch") != captured: raise ValueError("Animation stopped; restoring the previous checkpoint.")
        plan = plans[frame-1]
        target = {roles["body"]: Quaternion(Vector(match["left"]), plan["pitch"]), roles["head"]: Quaternion(Vector(match["left"]), plan["pitch"]*.35)}
        for role, vector in plan["directions"].items():
            child = role.rsplit("_", 1)[0]+("_lower" if role.endswith("_upper") else "_end")
            target[roles[role]] = Vector(_rs_cr_sub(heads[roles[child]], heads[roles[role]])).rotation_difference(Vector(vector))
        for c in _rs_cr_chains(family):
            if c.endswith("leg"): target[roles[c+"_end"]] = identity
        world = {}
        for b in ordered:
            n = b.name
            inherited = rest[n] if b.parent is None else world[b.parent.name] @ rest[b.parent.name].inverted() @ rest[n]
            quat = inherited.inverted() @ target[n] @ rest[n] if n in target else identity.copy()
            quat.normalize()
            if n in last and last[n].dot(quat) < 0: quat.negate()
            b.rotation_mode = "QUATERNION"; b.rotation_quaternion = quat; b.location = (0, 0, 0); b.scale = (1, 1, 1)
            world[n] = inherited @ quat; last[n] = quat.copy()
            b.keyframe_insert(data_path="rotation_quaternion", frame=frame, group=n)
            if frame == 1:
                for prop in ("location", "scale"): b.keyframe_insert(data_path=prop, frame=1, group=n)
    for channels in _rs_cr_channels(action, getattr(data, "action_slot", None)):
        for curve in channels:
            if curve.data_path in paths:
                for key in curve.keyframe_points: key.interpolation = "LINEAR"
    action["riggerset_preset"] = preset; action["riggerset_family"] = family
    action["riggerset_in_place"] = True; action["riggerset_duration"] = 0 if end == 1 else (end-1)/24
    plants = {roles[c+"_end"]: {"chain": c, "index": i, "groundZ": match["limbControls"][c]["groundZ"]}
              for i, c in enumerate(_rs_cr_chains(family)) if c in match["limbControls"] and match["limbControls"][c]["plant"]}
    action["riggerset_plant_mode"] = "in-place-march" if plants else "disabled"
    action["riggerset_plant_contacts"] = json.dumps(plants, separators=(",", ":"), allow_nan=False)
    action["riggerset_plant_end"] = end
    scene.frame_set(1); bpy.context.view_layer.update()
    return {"changed": "animation.creature", "action": action.name, "frames": end, "kind": "pose" if end == 1 else "clip", "inPlace": True}


# SPDX-License-Identifier: GPL-3.0-or-later
"""Explicit six/eight-leg FK starters. No anatomical guessing or new inference.

Leg end heads are the contact anchors. This is a stationary, in-place gait,
not forward locomotion. Genuine action/slot/scene state remains undoable.
"""
import math
import json
import time


def _rs_ar_chains(family):
    positions = ("front", "middle", "hind") if family in ("insect", "flying-insect") else ("front", "midfront", "midhind", "hind") if family == "arachnid" else None
    if positions is None:
        raise ValueError("Choose insect, flying-insect or arachnid.")
    return tuple(p + "_" + side + "_leg" for p in positions for side in ("left", "right"))


def _rs_ar_required(family):
    return ["body", "head"] + [c + "_" + part for c in _rs_ar_chains(family) for part in ("upper", "lower", "end")]


def _rs_ar_optional(family):
    wings = ["left_wing", "right_wing", "left_hindwing", "right_hindwing"] if family in ("insect", "flying-insect") else []
    return wings + ["tail_1", "tail_2", "tail_3", "tail_4"]


def _rs_ar_presets(family):
    return ["walk", "idle"] + (["flap", "fold"] if family in ("insect", "flying-insect") else [])


def _rs_ar_check(ticket):
    if _rs_control().get("epoch") != ticket[0]:
        raise ValueError("Arthropod animation cancelled; the prior checkpoint is retained.")
    if time.monotonic() - ticket[1] > 30:
        raise ValueError("Arthropod animation exceeded its thirty second work budget.")


def _rs_ar_match(ob, family, roles, forward_axis="Y"):
    required = _rs_ar_required(family)
    allowed = set(required + _rs_ar_optional(family))
    if not isinstance(roles, dict) or set(roles) - allowed or any(not roles.get(r) for r in required):
        raise ValueError("Assign every actual body, head and leg joint before creating this arthropod motion.")
    if len(set(roles.values())) != len(roles):
        raise ValueError("Each arthropod role needs its own joint.")
    if forward_axis not in ("X", "-X", "Y", "-Y"):
        raise ValueError("Choose an actual forward axis.")
    bones = ob.data.bones
    if any(not isinstance(v, str) or v not in bones for v in roles.values()):
        raise ValueError("An assigned arthropod joint is missing.")
    forward = {"X": (1, 0, 0), "-X": (-1, 0, 0), "Y": (0, 1, 0), "-Y": (0, -1, 0)}[forward_axis]
    # Forward axis is world space, as in the existing animal controls.
    points = {b.name: tuple(ob.matrix_world @ b.head_local) for b in bones}
    def ancestors(name):
        result = []
        p = bones[name].parent
        while p is not None:
            result.append(p.name)
            p = p.parent
        return result
    body = roles["body"]
    if body not in ancestors(roles["head"]):
        raise ValueError("The head must descend from the assigned body.")
    lengths, poles = {}, {}
    saved = _rs_limb_controls(ob)
    all_leg_names = {roles[c + "_" + s] for c in _rs_ar_chains(family) for s in ("upper", "lower", "end")}
    for chain in _rs_ar_chains(family):
        upper, lower, end = [roles[chain + "_" + s] for s in ("upper", "lower", "end")]
        if body not in ancestors(upper) or bones[lower].parent != bones[upper] or bones[end].parent != bones[lower]:
            raise ValueError("Each leg needs a separate body-descendant upper -> lower -> end chain.")
        if any(n in all_leg_names for n in ancestors(upper)) or roles["head"] in ancestors(upper):
            raise ValueError("Leg chains cannot descend from the head or another leg.")
        a = _rs_rg_sub(points[lower], points[upper])
        b = _rs_rg_sub(points[end], points[lower])
        size = _rs_rg_length(a) + _rs_rg_length(b)
        if min(_rs_rg_length(a), _rs_rg_length(b)) < 1e-6:
            raise ValueError("A mapped leg has a zero-length segment.")
        for parent, child in ((upper, lower), (lower, end)):
            if (ob.matrix_world @ bones[parent].tail_local - ob.matrix_world @ bones[child].head_local).length > size * 1e-5:
                raise ValueError("Arthropod joint tails and child heads must meet; calibrate this leg first.")
        lengths[chain] = (_rs_rg_length(a), _rs_rg_length(b))
        config = saved.get(chain)
        if config:
            if any(config[s] != roles[chain + "_" + s] for s in ("upper", "lower", "end")):
                raise ValueError("Saved limb controls do not match the selected arthropod joints.")
            poles[chain] = tuple(ob.matrix_world.to_3x3() @ Vector(config["pole"]))
        else:
            poles[chain] = _rs_rg_pole(a, _rs_rg_sub(points[end], points[upper]))
    for left, right in (("left_wing", "right_wing"), ("left_hindwing", "right_hindwing")):
        if bool(roles.get(left)) != bool(roles.get(right)):
            raise ValueError("Map both members of each actual wing pair.")
    for role in set(roles) - set(required):
        if body not in ancestors(roles[role]) or any(n in all_leg_names for n in ancestors(roles[role])):
            raise ValueError("Optional wings/tail must descend from the body independently of the walking legs.")
    tail_roles = [r for r in ("tail_1", "tail_2", "tail_3", "tail_4") if r in roles]
    if tail_roles != ["tail_" + str(i + 1) for i in range(len(tail_roles))]:
        raise ValueError("Map tail segments in order, starting with tail 1.")
    if any(bones[roles[tail_roles[i]]].parent != bones[roles[tail_roles[i-1]]] for i in range(1, len(tail_roles))):
        raise ValueError("Tail segments must be a direct parent-child chain.")
    return {"roles": roles, "points": points, "lengths": lengths, "poles": poles, "forward": forward, "controls": saved, "family": family}


def _rs_ar_phase(index, family):
    pair, side = divmod(index, 2)
    # Alternating tripod (six legs) and staggered wave (eight legs).
    return ((pair + side) % 2) * .5 if family != "arachnid" else (pair * .25 + side * .5) % 1


def _rs_ar_plan(match, preset, phase, strength, ground):
    directions, contacts = {}, {}
    roles = match["roles"]
    for index, chain in enumerate(_rs_ar_chains(match["family"])):
        root, foot = (match["points"][roles[chain + "_" + s]] for s in ("upper", "end"))
        config = match["controls"].get(chain, {})
        z = ground if ground is not None else config.get("groundZ", foot[2])
        p = (phase + _rs_ar_phase(index, match["family"])) % 1
        # The in-place swing returns to the same planted anchor with zero
        # displacement and velocity at each stance boundary.
        goal = _rs_rg_plant_goal(foot, match["forward"], sum(match["lengths"][chain]), p, "walk" if preset == "walk" else "idle", strength, z)
        knee, goal = _rs_rg_exact_solve(root, goal, match["lengths"][chain], match["poles"][chain])
        directions[chain + "_upper"] = _rs_rg_sub(knee, root)
        directions[chain + "_lower"] = _rs_rg_sub(goal, knee)
        contacts[roles[chain + "_end"]] = goal
    return {"directions": directions, "contacts": contacts}


def _rs_arthropod_info(ob, family):
    result = {"supported": False, "manualRequired": True, "suggestedRoles": {}, "requiredRoles": _rs_ar_required(family), "optionalRoles": _rs_ar_optional(family), "presets": _rs_ar_presets(family)}
    try:
        _rs_cr_guard(ob)
        _rs_rg_editable(ob)
        # Exact semantic names are suggestions only. No guessed limb count.
        names = {b.name for b in ob.data.bones}
        result["suggestedRoles"] = {r: r for r in result["requiredRoles"] + result["optionalRoles"] if r in names}
        saved = ob.get("riggerset_arthropod_roles", "")
        if isinstance(saved, str) and len(saved) <= 16384:
            try:
                prior = json.loads(saved)
                if prior.get("family") == family and isinstance(prior.get("roles"), dict):
                    result["suggestedRoles"].update({r: n for r, n in prior["roles"].items() if r in result["requiredRoles"] + result["optionalRoles"] and isinstance(n, str) and n in names})
            except (ValueError, AttributeError):
                pass
        result["supported"] = True
        result["reason"] = "Map the actual joints and inspect this in-place starter before use."
    except (ValueError, TypeError, KeyError) as error:
        result["reason"] = str(error)[:240]
    return result


def _rs_apply_arthropod_motion(a):
    _rs_rg_args(a, ("armature", "family", "preset", "roles", "duration", "strength", "forwardAxis", "groundZ", "wingAmplitude"))
    family, preset = a.get("family"), a.get("preset")
    if preset not in _rs_ar_presets(family):
        raise ValueError("Choose a motion for this arthropod family.")
    duration = _rs_rg_number(a.get("duration", 2), "cycle duration", 6)
    strength = _rs_rg_number(a.get("strength", .65), "motion strength", 1.25)
    amplitude = _rs_rg_number(a.get("wingAmplitude", .65), "wing amplitude", 1.2)
    if not .75 <= duration <= 6 or not .25 <= strength <= 1.25 or not .1 <= amplitude <= 1.2:
        raise ValueError("Choose a bounded cycle, motion amount and wing angle.")
    ground = None if a.get("groundZ") is None else _rs_rg_number(a["groundZ"], "ground height", 10000)
    ob = _rs_rg_armature(a.get("armature"))
    _rs_cr_guard(ob)
    _rs_rg_context_check()
    if ob.mode != "OBJECT":
        raise ValueError("Finish Edit/Pose Mode before generating an arthropod action.")
    match = _rs_ar_match(ob, family, a.get("roles"), a.get("forwardAxis", "Y"))
    roles, bones = match["roles"], ob.pose.bones
    ground_heights = {c: ground if ground is not None else match["controls"].get(c, {}).get("groundZ", match["points"][roles[c + "_end"]][2]) for c in _rs_ar_chains(family)}
    if len(set(match["controls"]) | set(_rs_ar_chains(family))) > 12:
        raise ValueError("At most twelve saved limb chains are supported; remove unused limb controls first.")
    if preset in ("flap", "fold") and not all(r in roles for r in ("left_wing", "right_wing")):
        raise ValueError("Map the actual left and right flight wings; this tool does not invent wings.")
    controlled = set(roles.values())
    for n in list(controlled):
        p = bones[n].parent
        while p:
            controlled.add(p.name)
            p = p.parent
    ordered, pending = [], [b for b in bones if b.parent is None]
    while pending:
        b = pending.pop()
        pending.extend(b.children)
        if b.name in controlled:
            ordered.append(b)
    if any(not b.bone.use_inherit_rotation or b.bone.inherit_scale != "FULL" or not b.bone.use_local_location for b in ordered):
        raise ValueError("Arthropod starters require standard joint inheritance.")
    ticket = (_rs_control().get("epoch"), time.monotonic())
    end = 1 if preset == "fold" else round(duration * 24) + 1
    plans = []
    for frame in range(1, end + 1):
        _rs_ar_check(ticket)
        plans.append(_rs_ar_plan(match, preset, 0 if end == 1 else (frame - 1) / (end - 1), strength, ground))
    rest = {b.name: (ob.matrix_world @ b.bone.matrix_local).to_quaternion() for b in ordered}
    data = ob.animation_data
    previous, previous_slot = (data.action, getattr(data, "action_slot", None)) if data else (None, None)
    if previous:
        _rs_cr_channels(previous, previous_slot)
    ob.animation_data_create()
    action = previous.copy() if previous else bpy.data.actions.new("RiggerSet")
    action.name = "RiggerSet · " + family.title() + " " + preset.title()
    action.use_fake_user = True
    if previous:
        previous.use_fake_user = True
    ob.animation_data.action = action
    if previous_slot is not None:
        ob.animation_data.action_slot = next(s for s in action.slots if s.identifier == previous_slot.identifier)
    paths = {b.path_from_id(p) for b in ordered for p in ("rotation_quaternion", "rotation_euler", "rotation_axis_angle", "location", "scale")}
    for channels in _rs_cr_channels(action, getattr(ob.animation_data, "action_slot", None)):
        for curve in list(channels):
            if curve.data_path in paths:
                channels.remove(curve)
    scene = bpy.context.scene
    scene.render.fps, scene.frame_start, scene.frame_end = 24, 1, max(2, end)
    last, identity = {}, Quaternion((1, 0, 0, 0))
    for frame, plan in enumerate(plans, 1):
        _rs_ar_check(ticket)
        t = 0 if end == 1 else (frame - 1) / (end - 1)
        target = {roles["body"]: identity.copy(), roles["head"]: Quaternion(Vector((0, 0, 1)), math.sin(t * math.tau) * .035 * strength)}
        for role, vector in plan["directions"].items():
            child_role = role.rsplit("_", 1)[0] + ("_lower" if role.endswith("_upper") else "_end")
            rest_direction = Vector(_rs_rg_sub(match["points"][roles[child_role]], match["points"][roles[role]]))
            target[roles[role]] = rest_direction.rotation_difference(Vector(vector))
        for chain in _rs_ar_chains(family):
            target[roles[chain + "_end"]] = identity.copy()
        # Joint-local Z is the explicit wing hinge axis; users control mapping
        # and amplitude. Visual wing motion is slowed, not an aerodynamic model.
        for role in ("left_wing", "right_wing", "left_hindwing", "right_hindwing"):
            if role in roles:
                sign = 1 if role.startswith("left") else -1
                angle = amplitude * sign * (1 if preset == "fold" else math.sin(t * math.tau) if preset == "flap" else .04 * math.sin(t * math.tau))
                n = roles[role]
                axis = rest[n] @ Vector((0, 0, 1))
                target[n] = Quaternion(axis, angle)
        for index in range(1, 5):
            role = "tail_" + str(index)
            if role in roles:
                n = roles[role]
                target[n] = Quaternion(rest[n] @ Vector((0, 1, 0)), math.sin(t * math.tau - index * .45) * .055 * strength)
        world = {}
        for b in ordered:
            n = b.name
            inherited = rest[n] if b.parent is None else world[b.parent.name] @ rest[b.parent.name].inverted() @ rest[n]
            quat = inherited.inverted() @ target[n] @ rest[n] if n in target else identity.copy()
            quat.normalize()
            if n in last and last[n].dot(quat) < 0:
                quat.negate()
            b.rotation_mode, b.rotation_quaternion, b.location, b.scale = "QUATERNION", quat, (0, 0, 0), (1, 1, 1)
            world[n], last[n] = inherited @ quat, quat.copy()
            b.keyframe_insert(data_path="rotation_quaternion", frame=frame, group=n)
            if frame == 1:
                for prop in ("location", "scale"):
                    b.keyframe_insert(data_path=prop, frame=1, group=n)
    for channels in _rs_cr_channels(action, getattr(ob.animation_data, "action_slot", None)):
        for curve in channels:
            if curve.data_path in paths:
                for key in curve.keyframe_points:
                    key.interpolation = "LINEAR"
    action["riggerset_family"], action["riggerset_preset"], action["riggerset_in_place"] = family, preset, True
    action["riggerset_duration"] = 0 if end == 1 else (end - 1) / 24
    action["riggerset_arthropod_roles"] = json.dumps(roles, separators=(",", ":"))
    action["riggerset_plant_mode"] = "in-place-march"
    action["riggerset_plant_contacts"] = json.dumps({roles[c + "_end"]: {"chain": c, "index": i, "groundZ": ground_heights[c], "family": family} for i, c in enumerate(_rs_ar_chains(family))}, separators=(",", ":"))
    action["riggerset_plant_end"] = end
    controls = dict(match["controls"])
    inverse_axes = ob.matrix_world.to_3x3().inverted()
    for chain in _rs_ar_chains(family):
        controls[chain] = {**{part: roles[chain + "_" + part] for part in ("upper", "lower", "end")}, "pole": list(inverse_axes @ Vector(match["poles"][chain])), "plant": True, "groundZ": ground_heights[chain]}
    if len(controls) > 12:
        raise ValueError("At most twelve saved limb chains are supported; remove unused limb controls first.")
    ob["riggerset_limb_controls"] = json.dumps(controls, separators=(",", ":"), allow_nan=False)
    ob["riggerset_arthropod_roles"] = json.dumps({"family": family, "roles": roles}, separators=(",", ":"))
    scene.frame_set(1)
    bpy.context.view_layer.update()
    return {"changed": "animation.arthropod", "action": action.name, "frames": end, "kind": "pose" if end == 1 else "clip", "inPlace": True, "legCount": len(_rs_ar_chains(family)), "mappedRoles": roles, "groundContact": "stationary stance / smooth returning swing", "previousAction": previous.name if previous else None}


# SPDX-License-Identifier: GPL-3.0-or-later
"""Explicit bounded FK retarget. Inline before the named dispatcher; no inference."""
import math as _rsrt_math
import time as _rsrt_time


def _rsrt_check(token):
    if _rs_control().get("epoch") != token[0]:
        raise ValueError("Retarget cancelled; the previous actions and pose were restored.")
    if _RS_REV != token[1]:
        raise ValueError("Stale scene revision during retarget; retry from the current scene.")
    if _rsrt_time.monotonic() - token[2] > 45:
        raise ValueError("Retarget exceeded its 45 second work limit.")


def _rsrt_name(value, label):
    if not isinstance(value, str) or not 1 <= len(value) <= 120 or any(ord(c) < 32 for c in value):
        raise ValueError(label + " must be an existing name of 1..120 characters.")
    return value


def _rsrt_number(value, label, low, high):
    if type(value) not in (int, float) or not _rsrt_math.isfinite(value) or not low <= value <= high:
        raise ValueError(label + " must be a finite number in " + str(low) + ".." + str(high) + ".")
    return float(value)


def _rsrt_args(args):
    required = {"source", "target", "mapping", "frameStart", "frameEnd"}
    allowed = required | {"rootMotion", "rootScale", "maxRootDistance", "actionName"}
    if not isinstance(args, dict) or set(args) - allowed or required - set(args):
        raise ValueError("Retarget requires source, target, mapping, frameStart and frameEnd; unknown parameters are refused.")
    source = _rsrt_name(args["source"], "source")
    target = _rsrt_name(args["target"], "target")
    if source == target:
        raise ValueError("Choose two different existing armatures.")
    start, end = args["frameStart"], args["frameEnd"]
    if (type(start) is not int or type(end) is not int or not -10000 <= start <= end <= 10000 or
            end - start + 1 > 240):
        raise ValueError("Use integer frames -10000..10000 and at most 240 consecutive samples.")
    if type(args.get("rootMotion", False)) is not bool:
        raise ValueError("rootMotion must be a boolean.")
    scale = _rsrt_number(args.get("rootScale", 1), "rootScale", .01, 10)
    maximum = _rsrt_number(args.get("maxRootDistance", 2), "maxRootDistance", .01, 10)
    action_name = _rsrt_name(args.get("actionName", "RiggerSet retarget"), "actionName")
    mapping = args["mapping"]
    if not isinstance(mapping, list) or not 1 <= len(mapping) <= 128 or len(mapping) * (end - start + 1) > 30720:
        raise ValueError("Map 1..128 bones with at most 30720 bone samples.")
    pairs = []
    for pair in mapping:
        if not isinstance(pair, dict) or set(pair) != {"source", "target"}:
            raise ValueError("Each manual bone pair must contain only source and target names.")
        pairs.append((_rsrt_name(pair["source"], "source bone"), _rsrt_name(pair["target"], "target bone")))
    if len({s for s, t in pairs}) != len(pairs) or len({t for s, t in pairs}) != len(pairs):
        raise ValueError("Bone mapping must be one-to-one; duplicate source or target bones are refused.")
    return source, target, dict(pairs), start, end, args.get("rootMotion", False), scale, maximum, action_name


def _rsrt_plain_rig(name):
    ob = _rs_obj(name)
    if (ob.type != "ARMATURE" or ob.mode != "OBJECT" or bpy.context.mode != "OBJECT" or
            ob.name not in bpy.context.view_layer.objects or not ob.visible_get()):
        raise ValueError("Choose visible armatures in Object Mode in the current view layer.")
    if (ob.library or ob.data.library or ob.override_library or getattr(ob.data, "override_library", None) or
            not ob.is_editable or ob.data.users - int(ob.data.use_fake_user) != 1 or ob.parent or ob.constraints or ob.modifiers or
            ob.data.animation_data or ob.data.pose_position != "POSE"):
        raise ValueError("Retarget needs unique local plain FK armatures without parents, modifiers, constraints or animated data.")
    data = ob.animation_data
    if data and (data.drivers or data.nla_tracks or getattr(data, "use_tweak_mode", False) or
                 getattr(data, "action_blend_type", "REPLACE") != "REPLACE" or
                 abs(getattr(data, "action_influence", 1) - 1) > 1e-6):
        raise ValueError("Drivers, NLA and blended/tweaked actions are unsupported for retarget.")
    if not 1 <= len(ob.data.bones) <= 128:
        raise ValueError("Retarget supports 1..128 deform bones.")
    roots = [b for b in ob.data.bones if b.parent is None]
    if len(roots) != 1:
        raise ValueError("Retarget needs one explicit hierarchy root on each armature.")
    for bone in ob.pose.bones:
        rest = bone.bone
        if (bone.constraints or bone.custom_shape or not rest.use_deform or rest.bbone_segments != 1 or
                rest.inherit_scale != "FULL" or not rest.use_inherit_rotation or not rest.use_local_location or
                rest.length < 1e-5 or any(not _rsrt_math.isfinite(c) for row in rest.matrix_local for c in row)):
            raise ValueError("Control/constraint/B-Bone, zero-length or nonstandard inheritance rigs are unsupported.")
    matrix = ob.matrix_world
    axes = matrix.to_3x3()
    lengths = [axes.col[i].length for i in range(3)]
    if (any(not _rsrt_math.isfinite(c) or abs(c) > 1e7 for row in matrix for c in row) or
            min(lengths) < 1e-5 or max(lengths) / min(lengths) > 1.00001 or axes.determinant() <= 0 or
            any(abs(axes.col[i].dot(axes.col[j])) > 1e-5 * lengths[i] * lengths[j]
                for i in range(3) for j in range(i))):
        raise ValueError("Apply non-uniform/reflected/sheared armature transforms before retarget.")
    return ob, roots[0].name


def _rsrt_channels(ob, required=False):
    """Read ONLY the assigned slot. Never flatten other slots into this rig's clip."""
    data = ob.animation_data
    action = data.action if data else None
    slot = getattr(data, "action_slot", None) if data else None
    if action is None:
        if required:
            raise ValueError("Source armature needs a currently assigned action and slot.")
        return None, None, []
    if action.library or action.users - int(action.use_fake_user) > 1:
        raise ValueError("Shared/linked actions are unsupported; make the assigned action single-user first.")
    layers = list(getattr(action, "layers", []))
    if layers:
        if slot is None or not any(s.handle == slot.handle for s in action.slots):
            raise ValueError("Assign the correct action slot explicitly before retarget.")
        if len(layers) != 1 or len(layers[0].strips) != 1:
            raise ValueError("Retarget supports one action layer and one keyframe strip, without layered blending.")
        layer, strip = layers[0], layers[0].strips[0]
        if (getattr(layer, "mute", False) or abs(getattr(layer, "influence", 1) - 1) > 1e-6 or
                getattr(strip, "type", "KEYFRAME") != "KEYFRAME"):
            raise ValueError("Muted/blended layers and non-keyframe strips are unsupported.")
        bags = [bag for bag in strip.channelbags if bag.slot_handle == slot.handle]
        if len(bags) != 1:
            raise ValueError("The assigned action slot needs exactly one channel bag.")
        curves = list(bags[0].fcurves)
    elif hasattr(action, "fcurves"):
        curves = list(action.fcurves)  # Legacy source clips only; output is explicitly layered.
    else:
        raise ValueError("The assigned action has no readable keyframe channels.")
    allowed = {bone.path_from_id(prop): (bone, prop, count)
               for bone in ob.pose.bones for prop, count in (("rotation_quaternion", 4), ("rotation_euler", 3),
                     ("rotation_axis_angle", 4), ("location", 3), ("scale", 3))}
    if not curves or len(curves) > 1664 or sum(len(c.keyframe_points) for c in curves) > 200000:
        raise ValueError("The assigned slot needs a bounded nonempty FK clip (<=200000 keys).")
    seen = set()
    for curve in curves:
        info = allowed.get(curve.data_path)
        if info is None or not 0 <= curve.array_index < info[2] or (curve.data_path, curve.array_index) in seen:
            raise ValueError("Only unambiguous bone transform curves are supported; object/control/custom-property animation is refused.")
        if curve.modifiers or curve.mute or len(curve.sampled_points) or not len(curve.keyframe_points):
            raise ValueError("Use unmuted editable keyframe curves without modifiers or sampled-point strips.")
        if any(not _rsrt_math.isfinite(v) for key in curve.keyframe_points for v in key.co):
            raise ValueError("The active action contains nonfinite keyframes.")
        bone, prop, count = info
        if required and prop.startswith("rotation_"):
            expected = "rotation_quaternion" if bone.rotation_mode == "QUATERNION" else (
                "rotation_axis_angle" if bone.rotation_mode == "AXIS_ANGLE" else "rotation_euler")
            if prop != expected:
                raise ValueError("Source rotation channels do not match the bone's current rotation mode.")
        seen.add((curve.data_path, curve.array_index))
    return action, slot, curves


def _rsrt_snapshot(ob):
    data = ob.animation_data
    return {"hadData": data is not None, "action": data.action if data else None,
            "slot": getattr(data, "action_slot", None) if data else None,
            "lastSlot": getattr(data, "last_slot_identifier", None) if data else None,
            "pose": [(b.name, b.rotation_mode, tuple(b.location), tuple(b.rotation_quaternion),
                      tuple(b.rotation_euler), tuple(b.rotation_axis_angle), tuple(b.scale)) for b in ob.pose.bones]}


def _rsrt_pose_restore(ob, state):
    for name, mode, location, quaternion, euler, axis, scale in state["pose"]:
        bone = ob.pose.bones[name]
        bone.rotation_mode = mode
        bone.location, bone.rotation_quaternion = location, quaternion
        bone.rotation_euler, bone.rotation_axis_angle, bone.scale = euler, axis, scale


def _rsrt_action_restore(ob, state):
    if not state["hadData"]:
        ob.animation_data_clear()
    else:
        data = ob.animation_data_create()
        data.action = state["action"]
        if state["slot"] is not None:
            data.action_slot = state["slot"]
        if state["lastSlot"] is not None and not data.is_property_readonly("last_slot_identifier"):
            data.last_slot_identifier = state["lastSlot"]


def _rsrt_curve(channels, path, index, values, start, token):
    _rsrt_check(token)
    curve = channels.new(data_path=path, index=index)
    curve.keyframe_points.add(len(values))
    curve.keyframe_points.foreach_set("co", [v for i, value in enumerate(values) for v in (start + i, value)])
    for key in curve.keyframe_points:
        key.interpolation = "LINEAR"
    curve.update()


def _rs_animation_retarget(args):
    from mathutils import Quaternion, Vector
    token = (_rs_control().get("epoch"), _RS_REV, _rsrt_time.monotonic())
    source_name, target_name, mapping, start, end, root_motion, root_scale, maximum, name = _rsrt_args(args)
    _rsrt_check(token)
    source, source_root = _rsrt_plain_rig(source_name)
    target, target_root = _rsrt_plain_rig(target_name)
    if (set(mapping) != {b.name for b in source.data.bones} or
            set(mapping.values()) != {b.name for b in target.data.bones} or mapping.get(source_root) != target_root):
        raise ValueError("Manually map every bone on both armatures, including root to root; partial/anatomy guessing is unsupported.")
    for sname, tname in mapping.items():
        sp, tp = source.data.bones[sname].parent, target.data.bones[tname].parent
        if (mapping.get(sp.name) if sp else None) != (tp.name if tp else None):
            raise ValueError("Mapped bones must have the same parent relationships; different control/anatomy hierarchies are unsupported.")
    source_action, source_slot, curves = _rsrt_channels(source, required=True)
    previous, previous_slot, _ = _rsrt_channels(target)
    low = min(c.range()[0] for c in curves)
    high = max(c.range()[1] for c in curves)
    if start < low or end > high:
        raise ValueError("The requested sample range must lie within the source assigned slot's keyframe range.")
    source_state, target_state = _rsrt_snapshot(source), _rsrt_snapshot(target)
    previous_fake = previous.use_fake_user if previous else False
    scene = bpy.context.scene
    frame, subframe = scene.frame_current, scene.frame_subframe
    source_rest = {b.name: b.matrix_local.to_quaternion().normalized() for b in source.data.bones}
    target_rest = {b.name: b.matrix_local.to_quaternion().normalized() for b in target.data.bones}
    # Rest-space corrections are in world axes; object rotations need not match.
    correction = target.matrix_world.to_quaternion().inverted() @ source.matrix_world.to_quaternion()
    source_axes = source.matrix_world.to_3x3()
    target_inverse_axes = target.matrix_world.to_3x3().inverted()
    ordered = []
    def visit(bone):
        ordered.append(bone)
        for child in bone.children:
            visit(child)
    visit(target.data.bones[target_root])
    inverse_map = {t: s for s, t in mapping.items()}
    samples = {b.name: [] for b in ordered}
    root_locations, last, created = [], {}, []
    baseline, measured, success = None, 0., False
    try:
        # First validate and sample the WHOLE clip. No target action is replaced here.
        for at in range(start, end + 1):
            _rsrt_check(token)
            scene.frame_set(at)
            bpy.context.view_layer.update()
            for bone in source.pose.bones:
                if (any(not _rsrt_math.isfinite(v) or abs(v) > 1e6 for row in bone.matrix for v in row) or
                        any(not _rsrt_math.isfinite(v) for v in (*bone.location, *bone.scale)) or
                        any(abs(v - 1) > 1e-5 for v in bone.scale) or
                        (bone.name != source_root and any(abs(v) > 1e-6 for v in bone.location))):
                    raise ValueError("Source clip contains scale, non-root translation or invalid poses; FK rotations only are supported.")
            root_location = source.pose.bones[source_root].location.copy()
            if baseline is None:
                baseline = root_location.copy()
            displacement = target_inverse_axes @ (source_axes @ (source_rest[source_root] @ (root_location - baseline))) * root_scale
            if root_motion and displacement.length > maximum + 1e-6:
                raise ValueError("Root displacement exceeds maxRootDistance; no clipping or unsafe motion was applied.")
            location = target_rest[target_root].inverted() @ displacement if root_motion else Vector((0, 0, 0))
            root_locations.append(tuple(location))
            measured = max(measured, displacement.length if root_motion else 0.)
            posed = {}
            for bone in ordered:
                sname = inverse_map[bone.name]
                sq = source.pose.bones[sname].matrix.to_quaternion().normalized()
                delta = correction @ sq @ source_rest[sname].inverted() @ correction.inverted()
                desired = delta @ target_rest[bone.name]
                inherited = target_rest[bone.name] if bone.parent is None else (
                    posed[bone.parent.name] @ target_rest[bone.parent.name].inverted() @ target_rest[bone.name])
                rotation = (inherited.inverted() @ desired).normalized()
                if bone.name in last and last[bone.name].dot(rotation) < 0:
                    rotation.negate()
                samples[bone.name].append(tuple(rotation))
                last[bone.name], posed[bone.name] = rotation.copy(), desired.normalized()
        _rsrt_check(token)
        action = bpy.data.actions.new(name)
        created.append(action)
        if not hasattr(action, "slots") or not hasattr(action, "layers"):
            raise ValueError("This build lacks explicit layered-action slots required for safe retarget.")
        try:
            slot = action.slots.new(id_type="OBJECT", name=target.name)
            layer = action.layers.new("RiggerSet FK retarget")
            strip = layer.strips.new(type="KEYFRAME")
            bag = strip.channelbag(slot, ensure=True)
        except (AttributeError, TypeError, RuntimeError) as error:
            raise ValueError("This build cannot create explicit layered-action slots safely: " + str(error)) from error
        if bag is None or bag.slot_handle != slot.handle:
            raise ValueError("This build could not create the requested target action slot.")
        for bone in target.pose.bones:
            for index in range(4):
                _rsrt_curve(bag.fcurves, bone.path_from_id("rotation_quaternion"), index,
                            [q[index] for q in samples[bone.name]], start, token)
            for index in range(3):
                values = [v[index] for v in root_locations] if root_motion and bone.name == target_root else [0.]
                _rsrt_curve(bag.fcurves, bone.path_from_id("location"), index, values, start, token)
                _rsrt_curve(bag.fcurves, bone.path_from_id("scale"), index, [1.], start, token)
        backup, backup_slot = None, None
        if previous:
            _rsrt_check(token)
            backup = previous.copy()  # Full duplicate; no NLA strip is introduced.
            created.append(backup)
            backup.name = previous.name + " before retarget"
            backup.use_fake_user = True
            if previous_slot is not None:
                matching = [s for s in backup.slots if s.identifier == previous_slot.identifier]
                if len(matching) != 1:
                    raise ValueError("Cannot preserve the previous action's assigned slot in its backup.")
                backup_slot = matching[0]
                backup["riggerset_retained_slot"] = backup_slot.identifier
        action.use_fake_user = True
        action["riggerset_retarget_source"] = source.name
        action["riggerset_retarget_source_action"] = source_action.name
        action["riggerset_in_place"] = not root_motion
        _rsrt_check(token)
        data = target.animation_data_create()
        if previous:
            previous.use_fake_user = True  # Keep original ID as well as the named duplicate.
        data.action = action
        data.action_slot = slot
        for bone in target.pose.bones:
            bone.rotation_mode = "QUATERNION"
            bone.location, bone.scale = (0, 0, 0), (1, 1, 1)
            bone.rotation_quaternion = Quaternion((1, 0, 0, 0))
        scene.frame_set(frame, subframe=subframe)
        _rsrt_pose_restore(source, source_state)
        bpy.context.view_layer.update()
        _rsrt_check(token)  # Cancellation after assignment must roll back too.
        if data.action != action or data.action_slot != slot:
            raise ValueError("The output action did not bind to its requested slot.")
        result = {"changed": "animation.retarget", "source": source.name, "target": target.name,
                  "action": action.name, "actionSlot": slot.identifier,
                  "previousAction": previous.name if previous else None,
                  "previousActionSlot": previous_slot.identifier if previous_slot else None,
                  "stashedAction": backup.name if backup else None,
                  "stashedActionSlot": backup_slot.identifier if backup_slot else None,
                  "sourceAction": source_action.name, "sourceActionSlot": source_slot.identifier if source_slot else None,
                  "frameStart": start, "frameEnd": end, "frames": end - start + 1, "mappedBones": len(mapping),
                  "rootMotion": root_motion, "measuredRootDistance": measured,
                  "proportionsPreserved": True, "originalActionsPreserved": True,
                  "note": "Explicit FK rest-space bake. Target rest joints and lengths are unchanged; no anatomy was inferred."}
        success = True
        return result
    finally:
        if not success:
            try:
                _rsrt_action_restore(target, target_state)
                if previous:
                    previous.use_fake_user = previous_fake
                scene.frame_set(frame, subframe=subframe)
                _rsrt_pose_restore(source, source_state)
                _rsrt_pose_restore(target, target_state)
                bpy.context.view_layer.update()
            finally:
                for action in reversed(created):
                    # These actions were allocated solely by this call.
                    bpy.data.actions.remove(action, do_unlink=True)


# SPDX-FileCopyrightText: 2026 OddsPrig RiggerSet contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Static pose and RMS mouth envelope on existing shape keys or an explicit jaw bone.
Inline globals: bpy, math, Vector, Quaternion, _rs_obj, _rs_num, _rs_control, _rs_motion_curves.
Not phoneme recognition and not a facial-rig generator. The parent owns undo."""
_RS_FACE_AXIS = {"X": (1.0, 0.0, 0.0), "Y": (0.0, 1.0, 0.0), "Z": (0.0, 0.0, 1.0)}
def _rs_face_info(ob):
    data = getattr(ob, "data", None)
    block = getattr(data, "shape_keys", None) if data is not None else None
    keys = [{"name": kb.name, "value": kb.value} for kb in block.key_blocks if kb != block.reference_key] if block is not None and getattr(block, "use_relative", False) else []
    arms = [ob] if getattr(ob, "type", "") == "ARMATURE" else []
    parent = getattr(ob, "parent", None)
    if getattr(parent, "type", "") == "ARMATURE" and parent not in arms:
        arms.append(parent)
    for mod in getattr(ob, "modifiers", []) or []:
        arm = getattr(mod, "object", None)
        if getattr(mod, "type", "") == "ARMATURE" and arm is not None and arm not in arms:
            arms.append(arm)
    seen, names = set(), []
    for arm in arms:
        pose = getattr(arm, "pose", None)
        for bone in (getattr(pose, "bones", []) if pose is not None else []):
            if bone.name not in seen:
                seen.add(bone.name)
                names.append(bone.name)
    return {"shapeKeys": keys, "jawCandidates": names, "anatomyGuarantee": False,
            "note": "Existing control names only. No anatomy or expression is inferred."}
def _rs_face_esc(name):
    return name.replace("\\", "\\\\").replace('"', '\\"')
def _rs_face_stop(epoch):
    if _rs_control().get("epoch") != epoch:
        raise ValueError("Animation stopped; restoring the previous checkpoint.")
def _rs_face_fps(value):
    if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or float(value) not in (12.0, 24.0):
        raise ValueError("FPS must be 12 or 24")
    return int(value)
def _rs_face_weights(values):
    if not isinstance(values, list) or not 2 <= len(values) <= 7201:
        raise ValueError("Mouth envelope needs 2 to 7201 normalized weights")
    return [_rs_num(weight, 0, 1) for weight in values]
def _rs_face_jaw(spec):
    if not isinstance(spec, dict) or set(spec) - {"armature", "bone", "axis", "angle"}:
        raise ValueError("Invalid jaw control")
    axis = spec.get("axis")
    if axis not in _RS_FACE_AXIS:
        raise ValueError("Jaw axis must be X, Y or Z")
    arm = _rs_obj(spec.get("armature", ""))
    if getattr(arm, "type", "") != "ARMATURE":
        raise ValueError("Jaw control needs an armature")
    bone = arm.pose.bones.get(str(spec.get("bone", "")))
    if bone is None:
        raise ValueError("Jaw bone not found")
    return arm, bone, axis, _rs_num(spec.get("angle"), -35, 35)
def _rs_face_linked(ob, arm):
    mods = getattr(ob, "modifiers", []) or []
    ok = ob == arm or (getattr(ob, "type", "") == "MESH" and (getattr(ob, "parent", None) == arm or any(getattr(mod, "type", "") == "ARMATURE" and getattr(mod, "object", None) == arm for mod in mods)))
    if not ok:
        raise ValueError("Jaw armature is not used by the selected object")
def _rs_face_block(ob):
    if getattr(ob, "type", "") != "MESH" or not getattr(ob, "data", None) or not ob.data.shape_keys:
        raise ValueError("The mesh has no shape keys")
    keys = ob.data.shape_keys
    if not keys.use_relative:
        raise ValueError("Shape keys are in absolute mode")
    return keys
def _rs_face_guard(owner, prefix):
    ad = getattr(owner, "animation_data", None)
    tracks = getattr(ad, "nla_tracks", None) if ad else None
    if tracks is not None and len(tracks):
        raise ValueError("Facial controls cannot change a target that uses NLA tracks")
    action = ad.action if ad else None
    if action and (len(getattr(action, "slots", [])) > 1 or len(getattr(action, "layers", [])) > 1 or any(len(layer.strips)>1 for layer in getattr(action,"layers",[]))):
        raise ValueError("Use the manual editor for a facial target with multiple action slots or layers")
    for driver in (getattr(ad, "drivers", []) if ad else []):
        path = getattr(driver, "data_path", "") or ""
        if path == prefix or path.startswith(prefix):
            raise ValueError("The facial target has a driver")
def _rs_face_base(bone):
    if bone.rotation_mode == "QUATERNION":
        quat = bone.rotation_quaternion.copy()
    elif bone.rotation_mode == "AXIS_ANGLE":
        quat = bone.matrix_basis.to_quaternion()
    else:
        quat = bone.rotation_euler.to_quaternion()
    quat.normalize()
    return quat
def _rs_face_turn(bone, axis, degrees, weight, base):
    quat = base @ Quaternion(_RS_FACE_AXIS[axis], math.radians(degrees) * weight)
    quat.normalize()
    bone.rotation_mode = "QUATERNION"
    bone.rotation_quaternion = quat
    return quat
def _rs_face_bags(action):
    for layer in getattr(action, "layers", []) or []:
        for strip in getattr(layer, "strips", []) or []:
            for bag in getattr(strip, "channelbags", []) or []:
                yield bag
def _rs_face_holds(owner, curve):
    try:
        return any(curve is item for item in owner.fcurves)
    except Exception:
        return False
def _rs_face_iter(action):
    try: found = list(_rs_motion_curves(action))
    except Exception: found = []
    if found:
        for curve in found:
            owner = action if getattr(action, "fcurves", None) is not None and _rs_face_holds(action, curve) else next((bag for bag in _rs_face_bags(action) if _rs_face_holds(bag, curve)), None)
            yield owner, curve
        return
    for bag in _rs_face_bags(action):
        for curve in list(getattr(bag, "fcurves", []) or []): yield bag, curve
def _rs_face_drop(action, match):
    for owner, curve in [(owner, curve) for owner, curve in _rs_face_iter(action) if match(curve)]:
        if owner is None or not hasattr(owner, "fcurves"):
            raise ValueError("The facial channel could not be replaced")
        owner.fcurves.remove(curve)
def _rs_face_bind(owner, action):
    ad = owner.animation_data_create(); ad.action = action
    slots = getattr(action, "slots", None)
    if slots is None or not hasattr(ad, "action_slot"): return action
    slot = slots[0] if len(slots) else None
    if slot is None and hasattr(slots, "new"):
        kind = "KEY" if hasattr(owner, "key_blocks") else "OBJECT"
        try: slot = slots.new(kind, getattr(owner, "name", "Slot"))
        except TypeError:
            try: slot = slots.new(getattr(owner, "name", "Slot"))
            except Exception: slot = None
        except Exception: slot = None
    if slot is not None:
        try: ad.action_slot = slot
        except Exception: pass
    return action
def _rs_face_action(owner, epoch):
    _rs_face_stop(epoch)
    previous = owner.animation_data_create().action
    if previous:
        action = previous.copy()
        previous.use_fake_user = True
        action.use_fake_user = True
        action.name = previous.name + " · Mouth Envelope"
    else:
        action = bpy.data.actions.new("RiggerSet · Mouth Envelope")
        action.use_fake_user = True
    action["riggerset_face"] = "rms-envelope"
    return _rs_face_bind(owner, action)
def _rs_face_linear(action, match):
    for _owner, curve in _rs_face_iter(action):
        if match(curve):
            for key in curve.keyframe_points:
                key.interpolation = "LINEAR"
def _rs_face_finish(action, frames, target, kind, fps):
    scene = bpy.context.scene
    scene.render.fps, scene.frame_start = fps, 1
    if scene.frame_end < frames: scene.frame_end = frames
    scene.frame_set(1)
    update = getattr(getattr(bpy.context, "view_layer", None), "update", None)
    if update: update()
    return {"changed": "animation.lipsync", "action": action.name, "frames": frames, "target": target, "kind": kind}
def _rs_face_baseline(bone):
    stored = bone.get("riggerset_face_base")
    if stored is not None:
        if len(stored) != 4 or any(not math.isfinite(v) for v in stored): raise ValueError("Invalid saved jaw base pose")
        return Quaternion(stored).normalized()
    return _rs_face_base(bone)
def _rs_face_pose(a):
    if not isinstance(a, dict) or set(a)-{"object","values","jaw"}: raise ValueError("Unknown face pose parameter")
    if ("values" in a) == ("jaw" in a): raise ValueError("Choose shape keys or one jaw bone")
    ob = _rs_obj(a.get("object", ""))
    if "jaw" in a:
        arm, bone, axis, angle = _rs_face_jaw(a["jaw"])
        _rs_face_linked(ob, arm)
        if bone.constraints: raise ValueError("The jaw has constraints")
        _rs_face_guard(arm, 'pose.bones["%s"]' % _rs_face_esc(bone.name))
        base = _rs_face_baseline(bone)
        bone["riggerset_face_base"] = list(base)
        _rs_face_turn(bone, axis, angle, 1, base)
        target = [bone.name]
    else:
        values = a["values"]
        if not isinstance(values, dict) or not 1 <= len(values) <= 16: raise ValueError("Choose 1 to 16 facial shape keys")
        keys = _rs_face_block(ob); chosen = []
        for name, weight in values.items():
            key = keys.key_blocks.get(name) if isinstance(name, str) else None
            if key is None or key == keys.reference_key: raise ValueError("Unknown or reference shape key")
            chosen.append((key, _rs_num(weight, 0, 1)))
            _rs_face_guard(keys, key.path_from_id("value"))
        for key, weight in chosen: key.value = weight
        target = [key.name for key, _weight in chosen]
    bpy.context.view_layer.update()
    return {"changed":"face.pose","kind":"pose","target":target}
def _rs_face_lipsync(a):
    if not isinstance(a, dict) or set(a) - {"object", "shapeKey", "jaw", "fps", "values"}:
        raise ValueError("Unknown mouth envelope parameter")
    if ("shapeKey" in a) == ("jaw" in a):
        raise ValueError("Choose one existing shape key or one jaw bone")
    fps = _rs_face_fps(a.get("fps"))
    weights = _rs_face_weights(a.get("values"))
    if (len(weights) - 1) / fps > 300:
        raise ValueError("Mouth envelope is longer than 300 seconds")
    ob = _rs_obj(a.get("object", ""))
    epoch = _rs_control().get("epoch")
    if "shapeKey" in a:
        if not isinstance(a.get("shapeKey"), str) or not a["shapeKey"] or a["shapeKey"] == "Basis":
            raise ValueError("Unknown shape key")
        keys = _rs_face_block(ob)
        block = keys.key_blocks.get(a["shapeKey"])
        if block is None or block == keys.reference_key:
            raise ValueError("Unknown shape key")
        path = 'key_blocks["%s"].value' % _rs_face_esc(block.name)
        _rs_face_guard(keys, path)
        action = _rs_face_action(keys, epoch)
        _rs_face_drop(action, lambda curve: curve.data_path == path)
        for frame, weight in enumerate(weights, start=1):
            _rs_face_stop(epoch)
            block.value = weight
            block.keyframe_insert(data_path="value", frame=frame, group=block.name)
        _rs_face_linear(action, lambda curve: curve.data_path == path)
        return _rs_face_finish(action, len(weights), block.name, "shapeKey", fps)
    arm, bone, axis, angle = _rs_face_jaw(a["jaw"])
    _rs_face_linked(ob, arm)
    if len(getattr(bone, "constraints", []) or []):
        raise ValueError("The facial target has constraints")
    prefix = 'pose.bones["%s"]' % _rs_face_esc(bone.name)
    _rs_face_guard(arm, prefix)
    base = _rs_face_baseline(bone)
    action = _rs_face_action(arm, epoch)
    bone["riggerset_face_base"] = list(base)
    channel = prefix + ".rotation_"
    _rs_face_drop(action, lambda curve: getattr(curve, "data_path", "").startswith(channel))
    previous = None
    for frame, weight in enumerate(weights, start=1):
        _rs_face_stop(epoch)
        quat = _rs_face_turn(bone, axis, angle, weight, base)
        if previous is not None and previous.dot(quat) < 0:
            quat.negate()
            bone.rotation_quaternion = quat
        previous = quat.copy()
        bone.keyframe_insert(data_path="rotation_quaternion", frame=frame, group=bone.name)
    _rs_face_linear(action, lambda curve: getattr(curve, "data_path", "").startswith(channel))
    return _rs_face_finish(action, len(weights), bone.name, "jaw", fps)


"""RiggerSet local cut/cap. Inline before the daemon dispatcher; no bpy ops.

Pure helpers intentionally have no Blender imports. Caps are deterministic ear
triangulations in simple rings' best-fit projections, not inferred anatomy.
Repair requires Object mode and refuses shape keys, library/override objects,
nonmanifold cut neighborhoods, strongly folded/overlapping caps and intersections with
surviving surface. Unrelated open boundaries are retained. Source Mesh IDs are
never edited: a verified BMesh copy is assigned at the final commit.
"""

import collections as _rsr_collections
import hashlib as _rsr_hashlib
import math as _rsr_math
import struct as _rsr_struct


def _rsr_sub(a, b):
    return tuple(a[i] - b[i] for i in range(3))


def _rsr_dot(a, b):
    return sum(a[i] * b[i] for i in range(3))


def _rsr_cross(a, b):
    return (a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0])


def _rsr_len(v):
    return _rsr_math.sqrt(_rsr_dot(v, v))


def _rsr_coord(v, size=3):
    if not isinstance(v, (list, tuple)) or len(v) != size:
        raise ValueError("Expected a finite local-space coordinate")
    if any(isinstance(x, bool) or not isinstance(x, (int, float)) or not _rsr_math.isfinite(x) for x in v):
        raise ValueError("Coordinates must contain finite numbers")
    return tuple(float(x) for x in v)


def _rsr_edges(faces):
    edges = {}
    for fi, face in enumerate(faces):
        for u, v in zip(face, face[1:] + face[:1]):
            edges.setdefault(tuple(sorted((u, v))), []).append((fi, u, v))
    return edges


def _rsr_choose_faces(verts, faces, explicit=None, center=None, radius=None, current=None):
    if not faces or len(faces) > 200000:
        raise ValueError("Mesh must have 1..200000 polygons")
    if explicit is not None:
        if not isinstance(explicit, (list, tuple)) or not 1 <= len(explicit) <= 8192:
            raise ValueError("faces must contain 1..8192 face IDs")
        if any(type(i) is not int or i < 0 or i >= len(faces) for i in explicit):
            raise ValueError("Invalid face ID")
        chosen = sorted(set(explicit))
    elif center is not None or radius is not None:
        center = _rsr_coord(center)
        if isinstance(radius, bool) or not isinstance(radius, (int, float)) or not _rsr_math.isfinite(radius) or radius <= 0:
            raise ValueError("radius must be finite and positive")
        distances = []
        for f in faces:
            p = tuple(sum(verts[i][j] for i in f) / len(f) for j in range(3))
            distances.append(_rsr_dot(_rsr_sub(p, center), _rsr_sub(p, center)))
        candidates = {i for i, d in enumerate(distances) if d <= radius * radius}
        if not candidates:
            raise ValueError("No face centers inside the selection sphere")
        seed = min(candidates, key=lambda i: (distances[i], i))
        adjacency = {i: set() for i in candidates}
        for uses in _rsr_edges(faces).values():
            ids = [t[0] for t in uses if t[0] in candidates]
            for i in ids:
                adjacency[i].update(j for j in ids if j != i)
        found, todo = {seed}, [seed]
        while todo:
            for other in adjacency[todo.pop()]:
                if other not in found:
                    found.add(other)
                    todo.append(other)
                    if len(found) > 8192:
                        raise ValueError("Connected selection exceeds 8192 faces")
        chosen = sorted(found)
    else:
        chosen = sorted(set(current or []))
    if not 1 <= len(chosen) <= 8192:
        raise ValueError("Selection must contain 1..8192 faces")
    return chosen


def _rsr_digest(verts, faces, edges, chosen):
    h = _rsr_hashlib.sha256(b"RiggerSet/local-repair/v1\0")
    for count in (len(verts), len(faces), len(edges), len(chosen)):
        h.update(_rsr_struct.pack("<Q", count))
    for p in verts:
        if any(not _rsr_math.isfinite(x) for x in p):
            raise ValueError("Mesh contains nonfinite vertex coordinates")
        h.update(_rsr_struct.pack("<ddd", *p))
    for f in faces:
        h.update(_rsr_struct.pack("<Q", len(f)))
        for i in f:
            h.update(_rsr_struct.pack("<Q", i))
    for u, v in edges:
        h.update(_rsr_struct.pack("<QQ", u, v))
    for i in sorted(chosen):
        h.update(_rsr_struct.pack("<Q", i))
    return h.hexdigest()


def _rsr_cross2(a, b, c):
    return (b[0]-a[0])*(c[1]-a[1]) - (b[1]-a[1])*(c[0]-a[0])


def _rsr_on2(p, a, b, eps):
    return (abs(_rsr_cross2(a, b, p)) <= eps * max(eps, _rsr_math.dist(a, b))
            and all(min(a[k], b[k])-eps <= p[k] <= max(a[k], b[k])+eps for k in range(2)))


def _rsr_seg2(a, b, c, d, eps):
    """All crossing/touch endpoints, including collinear overlap endpoints."""
    out = []
    for p, u, v in ((a, c, d), (b, c, d), (c, a, b), (d, a, b)):
        if _rsr_on2(p, u, v, eps):
            out.append(p)
    r, s = (b[0]-a[0], b[1]-a[1]), (d[0]-c[0], d[1]-c[1])
    den = r[0]*s[1] - r[1]*s[0]
    if abs(den) > eps * max(eps, _rsr_math.dist(a, b), _rsr_math.dist(c, d)):
        q = (c[0]-a[0], c[1]-a[1])
        t = (q[0]*s[1] - q[1]*s[0]) / den
        u = (q[0]*r[1] - q[1]*r[0]) / den
        if 0 <= t <= 1 and 0 <= u <= 1:
            out.append((a[0]+t*r[0], a[1]+t*r[1]))
    return out


def _rsr_inside2(p, tri, eps):
    orient = 1 if _rsr_cross2(*tri) >= 0 else -1
    return all(orient*_rsr_cross2(a, b, p) >= -eps*max(eps, _rsr_math.dist(a, b))
               for a, b in zip(tri, tri[1:] + tri[:1]))


def _rsr_project(points, normal):
    drop = max(range(3), key=lambda i: abs(normal[i]))
    return [tuple(p[k] for k in range(3) if k != drop) for p in points], drop


def _rsr_fit_loop(verts, loop, eps):
    """Small symmetric PCA, computed near origin; no numpy or flattened verts.

    A mild ring has max plane residual <= 5% of its bbox diagonal. Every cap
    triangle must subsequently stay within 35 degrees of this oriented plane.
    """
    origin = verts[loop[0]]
    local = [_rsr_sub(verts[i], origin) for i in loop]
    center = tuple(_rsr_math.fsum(p[k] for p in local)/len(local) for k in range(3))
    centered = [_rsr_sub(p, center) for p in local]
    extent = _rsr_len(tuple(max(p[k] for p in local)-min(p[k] for p in local) for k in range(3)))
    covariance = [[_rsr_math.fsum(p[i]*p[j] for p in centered) for j in range(3)] for i in range(3)]
    eigenvectors = [[float(i == j) for j in range(3)] for i in range(3)]
    threshold = max(1e-30, sum(covariance[i][i] for i in range(3))*1e-14)
    for _ in range(32):
        p, q = max(((0, 1), (0, 2), (1, 2)), key=lambda ij: abs(covariance[ij[0]][ij[1]]))
        off = covariance[p][q]
        if abs(off) <= threshold:
            break
        tau = (covariance[q][q]-covariance[p][p])/(2*off)
        tangent = (1 if tau >= 0 else -1)/(abs(tau)+_rsr_math.hypot(1, tau))
        cosine = 1/_rsr_math.hypot(1, tangent)
        sine = tangent*cosine
        covariance[p][p] -= tangent*off
        covariance[q][q] += tangent*off
        covariance[p][q] = covariance[q][p] = 0.0
        for r in range(3):
            if r not in (p, q):
                a, b = covariance[r][p], covariance[r][q]
                covariance[r][p] = covariance[p][r] = cosine*a-sine*b
                covariance[r][q] = covariance[q][r] = sine*a+cosine*b
            a, b = eigenvectors[r][p], eigenvectors[r][q]
            eigenvectors[r][p], eigenvectors[r][q] = cosine*a-sine*b, sine*a+cosine*b
    order = sorted(range(3), key=lambda i: covariance[i][i])
    if covariance[order[1]][order[1]] <= eps*eps:
        raise ValueError("Degenerate/collinear cap ring")
    normal = tuple(eigenvectors[k][order[0]] for k in range(3))
    newell = tuple(_rsr_math.fsum(_rsr_cross(a, b)[k] for a, b in zip(centered, centered[1:] + centered[:1])) for k in range(3))
    if _rsr_len(newell) <= eps*max(eps, extent):
        raise ValueError("Degenerate or self-intersecting cap ring")
    if _rsr_dot(normal, newell) < 0:
        normal = tuple(-x for x in normal)
    if max(abs(_rsr_dot(p, normal)) for p in centered) > max(eps, extent*.05):
        raise ValueError("Strongly folded cap ring exceeds the 5% best-fit-plane residual limit")
    axis = tuple(float(k == min(range(3), key=lambda j: abs(normal[j]))) for k in range(3))
    u = _rsr_cross(axis, normal)
    u = tuple(x/_rsr_len(u) for x in u)
    v = _rsr_cross(normal, u)
    flat = [(_rsr_dot(p, u), _rsr_dot(p, v)) for p in centered]
    return flat, normal, extent


def _rsr_triangulate_loop(verts, loop, eps, budget=None):
    if not 3 <= len(loop) <= 512 or len(set(loop)) != len(loop):
        raise ValueError("Each cap ring must have 3..512 distinct vertices")
    flat, normal, _ = _rsr_fit_loop(verts, loop, eps)
    n = len(loop)
    for i in range(n):
        if _rsr_math.dist(flat[i], flat[(i+1) % n]) <= eps:
            raise ValueError("Zero-length cap boundary edge")
        previous, at, following = flat[i-1], flat[i], flat[(i+1) % n]
        if (abs(_rsr_cross2(previous, at, following)) <= eps*max(eps, _rsr_math.dist(previous, following))
                and sum((at[k]-previous[k])*(following[k]-at[k]) for k in range(2)) < 0):
            raise ValueError("Backtracking/self-overlapping boundary edge")
        for j in range(i+1, n):
            if j == i+1 or (i == 0 and j == n-1):
                continue
            if _rsr_seg2(flat[i], flat[(i+1) % n], flat[j], flat[(j+1) % n], eps):
                raise ValueError("Self-intersecting or self-touching cap ring")
    area = sum(a[0]*b[1]-a[1]*b[0] for a, b in zip(flat, flat[1:] + flat[:1]))
    sign = 1 if area > 0 else -1
    remaining, triangles = list(range(n)), []
    budget = budget if budget is not None else [2000000]
    while len(remaining) > 3:
        for k, i in enumerate(remaining):
            prev, nxt = remaining[k-1], remaining[(k+1) % len(remaining)]
            tri = [flat[prev], flat[i], flat[nxt]]
            if sign * _rsr_cross2(*tri) <= eps * max(eps, _rsr_math.dist(tri[0], tri[2])):
                continue
            blocked = False
            for j in remaining:
                budget[0] -= 1
                if budget[0] < 0:
                    raise ValueError("Cap triangulation exceeds bounded work budget")
                if j not in (prev, i, nxt) and _rsr_inside2(flat[j], tri, eps):
                    blocked = True
                    break
            if not blocked:
                triangles.append((loop[prev], loop[i], loop[nxt]))
                remaining.pop(k)
                break
        else:
            raise ValueError("Ambiguous or degenerate cap triangulation")
    tri = [flat[i] for i in remaining]
    if sign*_rsr_cross2(*tri) <= eps * max(eps, _rsr_math.dist(tri[0], tri[2])):
        raise ValueError("Degenerate final cap triangle")
    triangles.append(tuple(loop[i] for i in remaining))
    normals = []
    for tri in triangles:
        a, b, c = (verts[i] for i in tri)
        cross = _rsr_cross(_rsr_sub(b, a), _rsr_sub(c, a))
        length = _rsr_len(cross)
        if length <= eps*max(eps, _rsr_len(_rsr_sub(b, a)), _rsr_len(_rsr_sub(c, a))):
            raise ValueError("Degenerate 3D cap triangle")
        unit = tuple(x/length for x in cross)
        if _rsr_dot(unit, normal) < _rsr_math.cos(_rsr_math.radians(35)):
            raise ValueError("Folded/steep cap triangle exceeds 35 degrees from best-fit plane")
        normals.append(unit)
    adjacent = _rsr_edges(triangles)
    for uses in adjacent.values():
        if len(uses) == 2 and _rsr_dot(normals[uses[0][0]], normals[uses[1][0]]) < _rsr_math.cos(_rsr_math.radians(50)):
            raise ValueError("Strongly folded cap exceeds the 50 degree dihedral limit")
    return triangles


def _rsr_point_on_shared(p, shared, verts, eps):
    if not shared:
        return False
    if len(shared) == 1:
        return _rsr_len(_rsr_sub(p, verts[shared[0]])) <= eps*4
    if len(shared) != 2:
        return False
    a, b = (verts[i] for i in shared)
    ab = _rsr_sub(b, a)
    denom = _rsr_dot(ab, ab)
    if denom <= eps*eps:
        return False
    t = _rsr_dot(_rsr_sub(p, a), ab) / denom
    q = tuple(a[k]+t*ab[k] for k in range(3))
    return -eps/_rsr_math.sqrt(denom) <= t <= 1+eps/_rsr_math.sqrt(denom) and _rsr_len(_rsr_sub(p, q)) <= eps*4


def _rsr_tri_conflict(verts, aa, bb, eps):
    """Intersection beyond the pair's actual shared topological point/edge."""
    origin = verts[aa[0]]
    verts = {i: _rsr_sub(verts[i], origin) for i in set(aa) | set(bb)}
    a, b = [verts[i] for i in aa], [verts[i] for i in bb]
    if any(max(p[k] for p in a)+eps < min(p[k] for p in b) or
           max(p[k] for p in b)+eps < min(p[k] for p in a) for k in range(3)):
        return False
    shared = sorted(set(aa) & set(bb))
    if len(shared) == 3:
        return True
    normals = [_rsr_cross(_rsr_sub(t[1], t[0]), _rsr_sub(t[2], t[0])) for t in (a, b)]
    lengths = [_rsr_len(n) for n in normals]
    if any(x <= eps*eps for x in lengths):
        raise ValueError("Degenerate surviving triangle near the cap")
    normals = [tuple(x/lengths[i] for x in normals[i]) for i in range(2)]
    da = [_rsr_dot(_rsr_sub(p, b[0]), normals[1]) for p in a]
    db = [_rsr_dot(_rsr_sub(p, a[0]), normals[0]) for p in b]
    if any(all(d > eps for d in ds) or all(d < -eps for d in ds) for ds in (da, db)):
        return False
    flat_a, drop = _rsr_project(a, normals[0])
    flat_b = [tuple(p[k] for k in range(3) if k != drop) for p in b]
    if all(abs(d) <= eps for d in da+db):
        # Convex clipping distinguishes positive-area overlap from a legal seam.
        clipped = list(flat_a)
        sign = 1 if _rsr_cross2(*flat_b) > 0 else -1
        for u, v in zip(flat_b, flat_b[1:] + flat_b[:1]):
            old, clipped = clipped, []
            if not old:
                break
            for p, q in zip(old, old[1:] + old[:1]):
                dp, dq = sign*_rsr_cross2(u, v, p), sign*_rsr_cross2(u, v, q)
                if dp >= 0:
                    clipped.append(p)
                if (dp < 0) != (dq < 0):
                    t = dp/(dp-dq)
                    clipped.append(tuple(p[k]+t*(q[k]-p[k]) for k in range(2)))
        area = abs(sum(p[0]*q[1]-p[1]*q[0] for p, q in zip(clipped, clipped[1:] + clipped[:1]))) / 2
        if area > eps*eps:
            return True
        hits = [p for p in flat_a if _rsr_inside2(p, flat_b, eps)]
        hits += [p for p in flat_b if _rsr_inside2(p, flat_a, eps)]
        for p, q in zip(flat_a, flat_a[1:] + flat_a[:1]):
            for u, v in zip(flat_b, flat_b[1:] + flat_b[:1]):
                hits.extend(_rsr_seg2(p, q, u, v, eps))
        kept = [k for k in range(3) if k != drop]
        for p in hits:
            pos = [0.0, 0.0, 0.0]
            for k, value in zip(kept, p):
                pos[k] = value
            pos[drop] = a[0][drop] - sum(normals[0][k]*(pos[k]-a[0][k]) for k in kept)/normals[0][drop]
            if not _rsr_point_on_shared(pos, shared, verts, eps):
                return True
        return False
    hits = []
    for tri, other, distances, normal in ((a, b, da, normals[1]), (b, a, db, normals[0])):
        flat_other, axis = _rsr_project(other, normal)
        kept = [k for k in range(3) if k != axis]
        for i in range(3):
            p, q, d, e = tri[i], tri[(i+1) % 3], distances[i], distances[(i+1) % 3]
            if abs(d) <= eps and _rsr_inside2(tuple(p[k] for k in kept), flat_other, eps):
                hits.append(p)
            if d*e < 0:
                t = d/(d-e)
                pos = tuple(p[k]+t*(q[k]-p[k]) for k in range(3))
                if _rsr_inside2(tuple(pos[k] for k in kept), flat_other, eps):
                    hits.append(pos)
            elif abs(d) <= eps and abs(e) <= eps:
                p2, q2 = tuple(p[k] for k in kept), tuple(q[k] for k in kept)
                for u, v in zip(flat_other, flat_other[1:] + flat_other[:1]):
                    for hit in _rsr_seg2(p2, q2, u, v, eps):
                        delta = tuple(q2[k]-p2[k] for k in range(2))
                        idx = max(range(2), key=lambda k: abs(delta[k]))
                        t = (hit[idx]-p2[idx])/delta[idx] if abs(delta[idx]) > eps else 0
                        hits.append(tuple(p[k]+t*(q[k]-p[k]) for k in range(3)))
    return any(not _rsr_point_on_shared(p, shared, verts, eps) for p in hits)


def _rsr_plan(verts, faces, mesh_edges, chosen, survivor_triangles=None):
    selected = set(chosen)
    if not selected or len(selected) >= len(faces):
        raise ValueError("Empty selection or entire mesh removal")
    edge_uses = _rsr_edges(faces)
    selected_vertices = {v for fi in chosen for v in faces[fi]}
    if any(len(faces[fi]) < 3 or len(set(faces[fi])) != len(faces[fi]) for fi in chosen):
        raise ValueError("Degenerate selected polygon")
    relevant_edges = {e for fi in chosen for e in (tuple(sorted((u, v))) for u, v in zip(faces[fi], faces[fi][1:]+faces[fi][:1]))}
    for e, uses in edge_uses.items():
        if not (set(e) & selected_vertices):
            continue
        if len(uses) != 2 or uses[0][1:] != tuple(reversed(uses[1][1:])):
            raise ValueError("Cut touches an existing boundary, nonmanifold edge or inconsistent winding")
    # A closed vertex fan rejects bowties even when all edges have two users.
    fans = {v: {} for v in selected_vertices}
    for face in faces:
        for k, v in enumerate(face):
            if v in fans:
                x, y = face[k-1], face[(k+1) % len(face)]
                fans[v].setdefault(x, []).append(y)
                fans[v].setdefault(y, []).append(x)
    for fan in fans.values():
        if not fan or any(len(ns) != 2 for ns in fan.values()):
            raise ValueError("Nonmanifold vertex fan at the cut")
        seen, todo = set(), [next(iter(fan))]
        while todo:
            i = todo.pop()
            if i not in seen:
                seen.add(i)
                todo.extend(fan[i])
        if len(seen) != len(fan):
            raise ValueError("Disconnected/bowtie vertex fan at the cut")
    boundary = []
    for e in relevant_edges:
        uses = edge_uses[e]
        selected_uses = [u for u in uses if u[0] in selected]
        if len(selected_uses) == 1:
            boundary.append(selected_uses[0][1:])
    outgoing, incoming = {}, {}
    for u, v in boundary:
        if u in outgoing or v in incoming:
            raise ValueError("Branching or self-touching cap boundary")
        outgoing[u], incoming[v] = v, u
    if set(outgoing) != set(incoming) or not outgoing:
        raise ValueError("No closed cut ring; detached-component removal is unsupported")
    loops, remaining = [], set(outgoing)
    while remaining:
        start, loop = min(remaining), []
        v = start
        while v in remaining:
            remaining.remove(v)
            loop.append(v)
            v = outgoing[v]
        if v != start:
            raise ValueError("Unclosed or intersecting boundary")
        loops.append(loop)
    if not 1 <= len(loops) <= 8 or sum(map(len, loops)) > 2048:
        raise ValueError("Repair supports 1..8 rings and at most 2048 rim vertices")
    extent = max(max(verts[v][k] for v in selected_vertices)-min(verts[v][k] for v in selected_vertices) for k in range(3))
    eps = max(1e-7, extent * 1e-7)
    budget, caps, cap_rings = [2000000], [], []
    for ri, loop in enumerate(loops):
        triangles = _rsr_triangulate_loop(verts, loop, eps, budget)
        caps.extend(triangles)
        cap_rings.extend([ri]*len(triangles))
    # AABB broad phase bounds work on large meshes; no geometry is touched.
    boxes = [(tuple(min(verts[v][k] for v in tri) for k in range(3)), tuple(max(verts[v][k] for v in tri) for k in range(3))) for tri in caps]
    global_min = tuple(min(b[0][k] for b in boxes) for k in range(3))
    global_max = tuple(max(b[1][k] for b in boxes) for k in range(3))
    def near(poly, lo, hi):
        return not any(max(verts[v][k] for v in poly) < lo[k]-eps or min(verts[v][k] for v in poly) > hi[k]+eps for k in range(3))
    if survivor_triangles is None:
        survivors = []
        for fi, face in enumerate(faces):
            if fi not in selected and near(face, global_min, global_max):
                survivors.extend(_rsr_triangulate_loop(verts, list(face), eps, budget))
    else:
        survivors = [tri for fi, tri in survivor_triangles if fi not in selected and near(tri, global_min, global_max)]
    # X sweep avoids an unbounded all-pairs scan while retaining every candidate.
    import bisect
    survivor_boxes = sorted((min(verts[v][0] for v in tri), max(verts[v][0] for v in tri), tri) for tri in survivors)
    starts = [entry[0] for entry in survivor_boxes]
    comparisons, broad_tests = 0, 0
    for ci, cap in enumerate(caps):
        lo, hi = boxes[ci]
        for xmin, xmax, tri in survivor_boxes[:bisect.bisect_right(starts, hi[0]+eps)]:
            broad_tests += 1
            if broad_tests > 4000000:
                raise ValueError("Cap broad phase exceeds bounded work budget")
            if xmax < lo[0]-eps or not near(tri, lo, hi):
                continue
            comparisons += 1
            if comparisons > 250000:
                raise ValueError("Cap collision checks exceed bounded work budget")
            if _rsr_tri_conflict(verts, cap, tri, eps):
                raise ValueError("Cap intersects surviving surface; manual repair required")
        for cj in range(ci):
            if _rsr_tri_conflict(verts, cap, caps[cj], eps):
                raise ValueError("Intersecting/nested caps or ambiguous triangulation")
    kept_vertices = {v for fi, face in enumerate(faces) if fi not in selected for v in face}
    # Loose pre-existing edges are unrelated and keep their endpoint vertices.
    kept_vertices.update(v for e in mesh_edges if tuple(sorted(e)) not in relevant_edges for v in e)
    removed_vertices = sorted(selected_vertices - kept_vertices)
    return {"loops": loops, "caps": caps, "capRings": cap_rings, "removedVertices": removed_vertices, "selectedEdges": relevant_edges, "epsilon": eps}


def _rsr_bpy():
    import bpy
    return bpy


def _rsr_object(a):
    if not isinstance(a, dict) or not isinstance(a.get("object"), str) or not a["object"]:
        raise ValueError("object must name a mesh object")
    obj = _rsr_bpy().data.objects.get(a["object"])
    if obj is None or obj.type != 'MESH':
        raise ValueError("Object is missing or is not a mesh")
    return obj


def _rsr_snapshot(obj, flush=False):
    if flush and obj.mode == 'EDIT':
        if not obj.update_from_editmode():
            raise ValueError("Could not flush Edit mesh selection")
    mesh = obj.data
    if not 1 <= len(mesh.polygons) <= 200000 or len(mesh.vertices) > 1000000 or len(mesh.loops) > 1000000:
        raise ValueError("Mesh exceeds bounded limits (200000 faces / 1000000 vertices or loops)")
    verts = [tuple(v.co) for v in mesh.vertices]
    faces = [tuple(p.vertices) for p in mesh.polygons]
    edges = [tuple(e.vertices) for e in mesh.edges]
    return verts, faces, edges


def _rsr_supported(obj):
    if obj.library is not None or obj.override_library is not None or obj.data.library is not None or not obj.is_editable:
        raise ValueError("Linked/library override meshes are unsupported")
    if obj.data.shape_keys is not None:
        raise ValueError("Shape-key meshes are refused; no morph data will be dropped")
    if obj.data.animation_data is not None:
        raise ValueError("Animated Mesh datablocks are unsupported; object/rig animation is retained")
    if obj.mode != 'OBJECT':
        raise ValueError("Switch the selected mesh to Object mode before repair")
    if obj.data.attributes.get(".rsr_original_vertex_v1") or obj.data.attributes.get(".rsr_original_face_v1"):
        raise ValueError("Reserved repair attribute name already exists")


def _rsr_native_plan(obj, verts, faces, edges, chosen):
    _rsr_supported(obj)
    obj.data.calc_loop_triangles()
    triangles = [(t.polygon_index, tuple(t.vertices)) for t in obj.data.loop_triangles]
    return _rsr_plan(verts, faces, edges, chosen, triangles)


def _rs_mesh_selection(a):
    """Read-only preview. boundaryLoops is a list of original vertex-ID rings."""
    obj = _rsr_object(a)
    verts, faces, edges = _rsr_snapshot(obj, flush=True)
    explicit = a.get("faces")
    if "faces" in a and explicit is None:
        raise ValueError("faces must be a nonempty list when provided")
    chosen = _rsr_choose_faces(verts, faces, explicit, a.get("center"), a.get("radius"), [p.index for p in obj.data.polygons if p.select])
    vertex_ids = sorted({v for fi in chosen for v in faces[fi]})
    digest = _rsr_digest(verts, faces, edges, chosen)
    result = {"object": obj.name, "faces": chosen, "vertices": vertex_ids,
              "bounds": {"min": [min(verts[v][k] for v in vertex_ids) for k in range(3)],
                         "max": [max(verts[v][k] for v in vertex_ids) for k in range(3)]},
              "digest": digest, "faceCount": len(chosen), "vertexCount": len(vertex_ids),
              "boundaryLoops": [], "repairable": False}
    try:
        plan = _rsr_native_plan(obj, verts, faces, edges, chosen)
        result.update(boundaryLoops=plan["loops"], repairable=True)
    except ValueError as exc:
        result["reason"] = str(exc)
    return result


def _rs_mesh_repair(a):
    """Preflight everything, edit/verify a private copy, then swap obj.data."""
    obj = _rsr_object(a)
    if a.get("cap") is not True:
        raise ValueError("cap must be true")
    _rsr_supported(obj)
    verts, faces, edges = _rsr_snapshot(obj)
    if "faces" not in a:
        raise ValueError("Repair requires the explicit preview face IDs")
    chosen = _rsr_choose_faces(verts, faces, a["faces"])
    digest = a.get("digest")
    if not isinstance(digest, str) or digest != _rsr_digest(verts, faces, edges, chosen):
        raise ValueError("Stale or invalid digest; preview this exact mesh and selection again")
    plan = _rsr_native_plan(obj, verts, faces, edges, chosen)
    import bmesh
    bpy = _rsr_bpy()
    source, selected = obj.data, set(chosen)
    uv_names = [layer.name for layer in source.uv_layers]
    original_weights = [tuple(sorted((g.group, g.weight) for g in v.groups)) for v in source.vertices]
    original_uv = {p.index: [tuple(tuple(source.uv_layers[name].data[li].uv) for name in uv_names) for li in p.loop_indices]
                   for p in source.polygons if p.index not in selected}
    stage, bm = None, bmesh.new()
    committed = False
    try:
        stage = source.copy()
        stage.name = source.name + "_localRepair"
        bm.from_mesh(source)
        bm.verts.ensure_lookup_table()
        bm.faces.ensure_lookup_table()
        vmark = bm.verts.layers.int.new(".rsr_original_vertex_v1")
        fmark = bm.faces.layers.int.new(".rsr_original_face_v1")
        original_bm_verts = list(bm.verts)
        original_bm_faces = list(bm.faces)
        for i, v in enumerate(original_bm_verts):
            v[vmark] = i+1
        for i, f in enumerate(original_bm_faces):
            f[fmark] = i+1
        selected_bm_edges = [e for e in bm.edges if tuple(sorted(v[vmark]-1 for v in e.verts)) in plan["selectedEdges"]]
        ring_materials = []
        edge_uses = _rsr_edges(faces)
        for loop in plan["loops"]:
            materials = []
            for u, v in zip(loop, loop[1:] + loop[:1]):
                fi = next(t[0] for t in edge_uses[tuple(sorted((u, v)))] if t[0] in selected)
                materials.append(source.polygons[fi].material_index)
            counts = _rsr_collections.Counter(materials)
            ring_materials.append(min(counts, key=lambda m: (-counts[m], m)))
        for fi in chosen:
            bm.faces.remove(original_bm_faces[fi])
        for edge in selected_bm_edges:
            if edge.is_valid and not edge.link_faces:
                bm.edges.remove(edge)
        for vi in plan["removedVertices"]:
            v = original_bm_verts[vi]
            if v.link_edges or v.link_faces:
                raise ValueError("Unexpected surviving incidence at a removed vertex")
            bm.verts.remove(v)
        for tri, ri in zip(plan["caps"], plan["capRings"]):
            face = bm.faces.new([original_bm_verts[v] for v in tri])
            face[fmark] = 0
            face.material_index = ring_materials[ri]
            ring = plan["loops"][ri]
            points, _, _ = _rsr_fit_loop(verts, ring, plan["epsilon"])
            lo = [min(p[k] for p in points) for k in range(2)]
            span = [max(p[k] for p in points)-lo[k] for k in range(2)]
            cap_uv = {v: tuple((p[k]-lo[k])/max(span[k], plan["epsilon"]) for k in range(2)) for v, p in zip(ring, points)}
            for l in face.loops:
                for name in uv_names:
                    l[bm.loops.layers.uv[name]].uv = cap_uv[l.vert[vmark]-1]
        bm.verts.index_update()
        bm.faces.index_update()
        original_by_new = [v[vmark]-1 for v in bm.verts]
        original_face_by_new = [f[fmark]-1 for f in bm.faces]
        if set(original_by_new) != set(range(len(verts))) - set(plan["removedVertices"]):
            raise ValueError("Staged repair failed surviving vertex preservation")
        bm.verts.layers.int.remove(vmark)
        bm.faces.layers.int.remove(fmark)
        bm.normal_update()
        bm.to_mesh(stage)
        stage.update()
        if len(stage.vertices) != len(original_by_new) or len(stage.polygons) != len(faces)-len(chosen)+len(plan["caps"]):
            raise ValueError("Staged repair produced unexpected topology counts")
        if [l.name for l in stage.uv_layers] != uv_names or list(stage.materials) != list(source.materials):
            raise ValueError("Staged repair changed material or UV layers")
        for i, vertex in enumerate(stage.vertices):
            vi = original_by_new[i]
            if tuple(vertex.co) != verts[vi] or tuple(sorted((g.group, g.weight) for g in vertex.groups)) != original_weights[vi]:
                raise ValueError("Staged repair changed surviving coordinates or weights")
        for i, poly in enumerate(stage.polygons):
            fi = original_face_by_new[i]
            if fi < 0:
                continue
            src = source.polygons[fi]
            old = [(v, original_uv[fi][k]) for k, v in enumerate(faces[fi])]
            new = [(original_by_new[v], tuple(tuple(stage.uv_layers[n].data[li].uv) for n in uv_names)) for v, li in zip(poly.vertices, poly.loop_indices)]
            if len(old) != len(new) or not any(new == old[k:]+old[:k] for k in range(len(old))) or poly.material_index != src.material_index or poly.use_smooth != src.use_smooth:
                raise ValueError("Staged repair changed surviving polygon/UV/material data")
        staged_faces = [tuple(original_by_new[v] for v in p.vertices) for p in stage.polygons]
        staged_edges = _rsr_edges(staged_faces)
        for ring in plan["loops"]:
            for u, v in zip(ring, ring[1:] + ring[:1]):
                uses = staged_edges.get(tuple(sorted((u, v))), [])
                if len(uses) != 2 or uses[0][1:] != tuple(reversed(uses[1][1:])):
                    raise ValueError("Staged cap failed manifold ring closure")
        # Object-level overrides survive a mesh swap; verify rather than reset.
        overrides = [(s.link, s.material) for s in obj.material_slots]
        obj.data = stage
        if [(s.link, s.material) for s in obj.material_slots] != overrides:
            obj.data = source
            raise ValueError("Mesh swap could not preserve object material overrides")
        committed = True
    finally:
        bm.free()
        if stage is not None and not committed and stage.users == 0:
            bpy.data.meshes.remove(stage)
    return {"changed": "mesh.repair", "removedFaces": len(chosen), "removedVertices": len(plan["removedVertices"]),
            "addedFaces": len(plan["caps"]), "closedLoops": len(plan["loops"]), "preservedOutside": True}


"""RiggerSet UV-local raster variants. Inline before the daemon dispatcher.

Only ordinary FILE/GENERATED RGBA images, a direct Principled Base Color image
(reroutes allowed), and ordinary UV/UVMap coordinates are supported. Composite
shader/image graphs and tiled/sequence/movie images are refused before mutation.
spacing is measured in image pixels; points are local UVs in [0,1], clipped at
the image edge without wrapping. Existing pixels are copied explicitly because
Image.copy alone is not a reliable copy of unsaved pixel buffers.
"""

import array as _rslp_array
import json as _rslp_json
import math as _rslp_math
import uuid as _rslp_uuid

_RSLP_META = "_riggerset_locked_variants_v1"
_RSLP_OWNER = "_riggerset_variant_owner_v1"
_RSLP_VARIANT = "_riggerset_variant_id_v1"


def _rslp_number(value, name, lo, hi):
    if isinstance(value, bool) or not isinstance(value, (int, float)) or not _rslp_math.isfinite(value) or not lo <= value <= hi:
        raise ValueError(name + " must be finite and in [" + str(lo) + "," + str(hi) + "]")
    return float(value)


def _rslp_color(value, name):
    if not isinstance(value, (list, tuple)) or len(value) != 4:
        raise ValueError(name + " must be RGBA")
    return tuple(_rslp_number(x, name, 0, 1) for x in value)


def _rslp_request(a):
    if not isinstance(a, dict):
        raise ValueError("Expected texture.variant arguments")
    variant = a.get("variant")
    if not isinstance(variant, str) or not 1 <= len(variant) <= 80 or variant != variant.strip() or any(ord(x) < 32 for x in variant):
        raise ValueError("variant must contain 1..80 printable characters without outer whitespace")
    pattern = a.get("pattern")
    if pattern not in ('solid', 'stripes', 'scales', 'belly'):
        raise ValueError("pattern must be solid, stripes, scales or belly")
    points = a.get("points")
    if not isinstance(points, (list, tuple)) or not 1 <= len(points) <= 128:
        raise ValueError("points must contain 1..128 UV points")
    checked = []
    for p in points:
        if not isinstance(p, (list, tuple)) or len(p) != 2:
            raise ValueError("Each point must be [u,v]")
        checked.append(tuple(_rslp_number(x, "UV", 0, 1) for x in p))
    radius = a.get("radius")
    if type(radius) is not int or not 1 <= radius <= 128:
        raise ValueError("radius must be an integer in [1,128]")
    primary = _rslp_color(a.get("color"), "color")
    secondary = _rslp_color(a["secondaryColor"], "secondaryColor") if "secondaryColor" in a else tuple(primary[i]*0.5 if i < 3 else primary[i] for i in range(4))
    spacing = _rslp_number(a.get("spacing", max(4.0, radius*0.5)), "spacing (pixels)", 0.25, 4096)
    opacity = _rslp_number(a.get("opacity", 1.0), "opacity", 0, 1)
    if "image" in a and (not isinstance(a["image"], str) or not a["image"]):
        raise ValueError("image must name an actually linked Base Color image")
    return {"variant": variant, "pattern": pattern, "points": checked, "color": primary,
            "secondaryColor": secondary, "radius": radius, "spacing": spacing, "opacity": opacity}


def _rslp_smooth(x):
    x = max(0.0, min(1.0, x))
    return x*x*(3-2*x)


def _rslp_pattern(pattern, dx, dy, radius, spacing, primary, secondary):
    distance = _rslp_math.hypot(dx, dy)
    coverage = max(0.0, min(1.0, radius+0.5-distance))
    mix = 1.0
    if pattern == 'stripes':
        wave = 0.5+0.5*_rslp_math.sin(2*_rslp_math.pi*dx/spacing)
        mix = _rslp_smooth((wave-0.3)/0.4)
    elif pattern == 'scales':
        row = _rslp_math.floor((dy+0.5*spacing)/spacing)
        y = dy-row*spacing
        x = ((dx+(row % 2)*spacing*0.5+spacing*0.5) % spacing)-spacing*0.5
        arc = y+0.35*spacing-_rslp_math.sqrt(max(0.0, (0.6*spacing)**2-x*x))
        line = _rslp_math.exp(-2*(arc/max(0.75, 0.12*spacing))**2)
        mix = 1-line
    elif pattern == 'belly':
        t = min(1.0, distance/radius)
        coverage *= (1-t*t)**2
        mix = 1-t
    color = tuple(secondary[i]+mix*(primary[i]-secondary[i]) for i in range(4))
    return color, coverage


def _rslp_paint_pixels(pixels, width, height, request):
    """Mutate a private RGBA buffer; return distinct pixels actually changed."""
    if type(width) is not int or type(height) is not int or not (1 <= width <= 4096 and 1 <= height <= 4096) or len(pixels) != width*height*4:
        raise ValueError("Expected a 1..4096 by 1..4096 RGBA image buffer")
    if request["opacity"] == 0 or (request["color"][3] == 0 and request["secondaryColor"][3] == 0):
        return 0
    seen = bytearray(width*height)
    painted = 0
    radius = request["radius"]
    for u, v in request["points"]:
        cx, cy = u*(width-1), v*(height-1)
        x0, x1 = max(0, _rslp_math.ceil(cx-radius-0.5)), min(width-1, _rslp_math.floor(cx+radius+0.5))
        y0, y1 = max(0, _rslp_math.ceil(cy-radius-0.5)), min(height-1, _rslp_math.floor(cy+radius+0.5))
        for y in range(y0, y1+1):
            for x in range(x0, x1+1):
                target, coverage = _rslp_pattern(request["pattern"], x-cx, y-cy, radius, request["spacing"], request["color"], request["secondaryColor"])
                alpha = target[3]*request["opacity"]*coverage
                if alpha <= 0:
                    continue
                pi, offset = y*width+x, (y*width+x)*4
                old = tuple(pixels[offset+k] for k in range(4))
                if any(not _rslp_math.isfinite(value) for value in old) or not 0 <= old[3] <= 1:
                    raise ValueError("Painted source pixels must be finite with alpha in [0,1]")
                out_alpha = alpha+old[3]*(1-alpha)
                rgb = tuple((target[k]*alpha+old[k]*old[3]*(1-alpha))/out_alpha for k in range(3)) if out_alpha > 0 else (0.0, 0.0, 0.0)
                for k, value in enumerate(rgb+(out_alpha,)):
                    pixels[offset+k] = value
                if not seen[pi] and any(pixels[offset+k] != old[k] for k in range(4)):
                    seen[pi] = 1
                    painted += 1
    return painted


def _rslp_metadata(raw):
    if raw is None:
        return {"schema": 1, "owner": _rslp_uuid.uuid4().hex, "variants": []}
    if not isinstance(raw, str) or len(raw) > 131072:
        raise ValueError("Invalid or oversized variant metadata")
    try:
        meta = _rslp_json.loads(raw)
    except (ValueError, TypeError) as exc:
        raise ValueError("Invalid variant metadata JSON") from exc
    if not isinstance(meta, dict) or type(meta.get("schema")) is not int or meta["schema"] != 1 or not isinstance(meta.get("owner"), str) or len(meta["owner"]) != 32 or any(c not in '0123456789abcdef' for c in meta['owner']):
        raise ValueError("Unsupported variant metadata")
    entries = meta.get("variants")
    if not isinstance(entries, list) or len(entries) > 32:
        raise ValueError("At most 32 variants per object are supported")
    ids = set()
    for entry in entries:
        if not isinstance(entry, dict) or not isinstance(entry.get("variant"), str) or not 1 <= len(entry["variant"]) <= 80 or entry["variant"] in ids:
            raise ValueError("Invalid or duplicate variant IDs in metadata")
        ids.add(entry["variant"])
        if any(not isinstance(entry.get(k), str) or not entry[k] or len(entry[k]) > 256 for k in ("image", "sourceImage")):
            raise ValueError("Invalid variant image record")
        slots = entry.get("slots")
        if not isinstance(slots, list) or not 1 <= len(slots) <= 1024:
            raise ValueError("Invalid variant material slot records")
        seen = set()
        for slot in slots:
            if not isinstance(slot, dict) or type(slot.get("index")) is not int or slot["index"] < 0 or slot["index"] in seen:
                raise ValueError("Invalid or duplicate variant material slot")
            seen.add(slot["index"])
            if any(not isinstance(slot.get(k), str) or not slot[k] or len(slot[k]) > 256 for k in ("material", "baseMaterial")):
                raise ValueError("Invalid variant material reference")
    return meta


def _rslp_bpy():
    import bpy
    return bpy


def _rslp_follow(socket):
    seen = set()
    while socket.is_linked:
        links = list(socket.links)
        if len(links) != 1:
            raise ValueError("Ambiguous material input links")
        source = links[0].from_socket
        node = source.node
        if node.type != 'REROUTE':
            return node, source
        if node.as_pointer() in seen or len(seen) >= 64:
            raise ValueError("Cyclic or excessive material reroutes")
        seen.add(node.as_pointer())
        socket = node.inputs[0]
    return None, None


def _rslp_binding(material):
    if material is None or not material.use_nodes or material.node_tree is None:
        return None
    outputs = [n for n in material.node_tree.nodes if n.type == 'OUTPUT_MATERIAL' and n.is_active_output]
    if len(outputs) != 1:
        raise ValueError("Material needs one active Material Output")
    shader, _ = _rslp_follow(outputs[0].inputs['Surface'])
    if shader is None:
        return None
    if shader.type != 'BSDF_PRINCIPLED':
        raise ValueError("Only a direct Principled BSDF surface is supported")
    base = shader.inputs['Base Color']
    image_node, source = _rslp_follow(base)
    if image_node is None:
        return None
    if image_node.type != 'TEX_IMAGE' or source.name != 'Color' or image_node.image is None:
        raise ValueError("Base Color must be a directly linked Image Texture Color (reroutes allowed)")
    # Replacing the node's image must not also change roughness, alpha, etc.
    socket = base
    while True:
        link = list(socket.links)[0]
        output = link.from_socket
        node = output.node
        if sum(len(s.links) for s in node.outputs) != 1:
            raise ValueError("Base Color image/reroutes with shared consumers are unsupported")
        if node.type != 'REROUTE':
            break
        socket = node.inputs[0]
    return {"material": material, "node": image_node, "image": image_node.image}


def _rslp_uv(obj, node):
    if node.projection != 'FLAT':
        raise ValueError("Texture variants require FLAT UV image projection")
    source, socket = _rslp_follow(node.inputs['Vector'])
    if source is None:
        if obj.data.uv_layers.active is None:
            raise ValueError("The mesh has no active UV map")
        return
    if source.type == 'UVMAP':
        name = source.uv_map
        if (name and obj.data.uv_layers.get(name) is None) or (not name and obj.data.uv_layers.active is None):
            raise ValueError("Image refers to a missing UV map")
        return
    if source.type == 'TEX_COORD' and socket.name == 'UV' and obj.data.uv_layers.active is not None:
        return
    raise ValueError("Only untransformed UV or UVMap image coordinates are supported")


def _rslp_object_bindings(obj):
    if len(obj.material_slots) > 1024:
        raise ValueError("At most 1024 material slots are supported")
    used = sorted({p.material_index for p in obj.data.polygons})
    bindings = []
    for index in used:
        if index >= len(obj.material_slots):
            continue
        binding = _rslp_binding(obj.material_slots[index].material)
        if binding:
            _rslp_uv(obj, binding["node"])
            bindings.append(dict(binding, index=index))
    return bindings


def _rslp_image_buffer(image):
    if image.source not in ('FILE', 'GENERATED') or image.type not in ('IMAGE', 'UV_TEST') or image.is_multiview or getattr(image, "use_multiview", False):
        raise ValueError("Only ordinary single-view FILE/GENERATED images are supported")
    width, height = tuple(image.size)
    if not 1 <= width <= 4096 or not 1 <= height <= 4096 or len(image.pixels) != width*height*4:
        raise ValueError("Image must have loaded RGBA pixels and dimensions at most 4096x4096")
    pixels = _rslp_array.array('f', [0.0]) * (width*height*4)
    image.pixels.foreach_get(pixels)
    if any(not _rslp_math.isfinite(value) for value in pixels):
        raise ValueError("Image pixels must all be finite")
    # RGB can be HDR; alpha remains a coverage value.
    if any(not 0 <= pixels[i] <= 1 for i in range(3, len(pixels), 4)):
        raise ValueError("Image alpha must lie in [0,1]")
    return pixels, width, height


def _rslp_private(obj, image, materials, owner, variant):
    bpy = _rslp_bpy()
    if image.library is not None or image.override_library is not None or image.get(_RSLP_OWNER) != owner or image.get(_RSLP_VARIANT) != variant:
        raise ValueError("Variant image ownership changed; create a fresh variant")
    for other in bpy.data.objects:
        if other == obj:
            continue
        if any(slot.material in materials for slot in other.material_slots):
            raise ValueError("Variant material is shared with another object; create a fresh variant")
    references = 0
    for mat in bpy.data.materials:
        if mat.node_tree:
            for node in mat.node_tree.nodes:
                if getattr(node, "image", None) == image:
                    if mat not in materials:
                        raise ValueError("Variant image is referenced by another material")
                    references += 1
    # Includes nonmaterial node trees, texture IDs, brushes and other consumers.
    if image.users > references + int(image.use_fake_user):
        raise ValueError("Variant image has additional consumers; create a fresh variant")


def _rs_texture_variant(a):
    request = _rslp_request(a)
    bpy = _rslp_bpy()
    if not isinstance(a.get("object"), str) or not a["object"]:
        raise ValueError("object must name a mesh object")
    obj = bpy.data.objects.get(a["object"])
    if obj is None or obj.type != 'MESH':
        raise ValueError("Object is missing or is not a mesh")
    if obj.mode != 'OBJECT' or obj.library is not None or obj.override_library is not None or obj.data.library is not None or not obj.is_editable:
        raise ValueError("Texture painting requires an editable local mesh in Object mode")
    meta = _rslp_metadata(obj.get(_RSLP_META))
    for other in bpy.data.objects:
        if other != obj and isinstance(other.get(_RSLP_META), str):
            try:
                other_owner = _rslp_json.loads(other[_RSLP_META]).get("owner")
            except (ValueError, AttributeError):
                other_owner = None
            if other_owner == meta["owner"]:
                raise ValueError("Variant metadata was duplicated onto another object; ownership is ambiguous")
    bindings = _rslp_object_bindings(obj)
    images = {b["image"] for b in bindings}
    if not images:
        raise ValueError("No existing linked Base Color image was found; no blank substitute will be created")
    if "image" in a:
        current_image = bpy.data.images.get(a["image"])
        if current_image not in images:
            raise ValueError("Requested image is not linked to this mesh's used Base Color materials")
    else:
        if len(images) != 1:
            raise ValueError("Multiple Base Color images are linked; specify image explicitly")
        current_image = next(iter(images))
    record = next((e for e in meta["variants"] if e["variant"] == request["variant"]), None)
    if record is not None:
        image = bpy.data.images.get(record["image"])
        if image is None:
            raise ValueError("Saved variant image is missing")
        if "image" in a and current_image != image:
            raise ValueError("Explicit image must match this variant; omit image to reactivate a stored variant")
        slots, materials = [], set()
        for saved in record["slots"]:
            index = saved["index"]
            material = bpy.data.materials.get(saved["material"])
            if index >= len(obj.material_slots) or material is None or material.get(_RSLP_OWNER) != meta["owner"] or material.get(_RSLP_VARIANT) != request["variant"]:
                raise ValueError("Saved variant material/slot ownership changed")
            binding = _rslp_binding(material)
            if not binding or binding["image"] != image:
                raise ValueError("Saved variant Base Color connection changed")
            _rslp_uv(obj, binding["node"])
            allowed = {saved["baseMaterial"], saved["material"]}
            for entry in meta["variants"]:
                allowed.update(s["material"] for s in entry["slots"] if s["index"] == index)
            current = obj.material_slots[index].material
            if current is None or current.name not in allowed:
                raise ValueError("Material slot was reassigned outside the variant family")
            slots.append((index, material))
            materials.add(material)
        _rslp_private(obj, image, materials, meta["owner"], request["variant"])
    else:
        if len(meta["variants"]) >= 32:
            raise ValueError("At most 32 variant IDs per object are supported")
        image = current_image
        relevant = [b for b in bindings if b["image"] == image]
        # Existing source materials are copied, never edited or re-used as copies.
        for binding in relevant:
            material = binding["material"]
            if material.node_tree is None:
                raise ValueError("Missing material node tree")
        # Bound the prospective metadata before creating any Blender IDs. Names
        # include slack for Blender's collision suffix; truncation only shrinks.
        estimate = {"variant": request["variant"], "image": image.name + " / " + request["variant"] + "x"*64,
                    "sourceImage": image.name, "slots": [
                        {"index": b["index"], "material": b["material"].name + " / " + request["variant"] + "x"*64,
                         "baseMaterial": b["material"].name} for b in relevant]}
        if len(_rslp_json.dumps(dict(meta, variants=meta["variants"]+[estimate]), ensure_ascii=True)) > 131072:
            raise ValueError("Variant metadata would exceed the bounded size")
    pixels, width, height = _rslp_image_buffer(image)
    painted = _rslp_paint_pixels(pixels, width, height, request)
    previous_slots = [(s.link, s.material) for s in obj.material_slots]
    previous_meta = obj.get(_RSLP_META)
    created_image, created_materials, committed = None, [], False
    try:
        if record is None:
            source_image = image
            created_image = source_image.copy()
            image = created_image
            image.use_fake_user = False
            image.name = source_image.name + " / " + request["variant"]
            image[_RSLP_OWNER], image[_RSLP_VARIANT] = meta["owner"], request["variant"]
            copies, slots, saved_slots = {}, [], []
            for binding in relevant:
                source_mat = binding["material"]
                if source_mat not in copies:
                    material = source_mat.copy()
                    created_materials.append(material)
                    material.use_fake_user = False
                    material.name = source_mat.name + " / " + request["variant"]
                    if material.node_tree is source_mat.node_tree:
                        raise ValueError("Material copy did not isolate its node tree")
                    material[_RSLP_OWNER], material[_RSLP_VARIANT] = meta["owner"], request["variant"]
                    new_binding = _rslp_binding(material)
                    if not new_binding or new_binding["image"] != source_image:
                        raise ValueError("Material copy changed the Base Color connection")
                    new_binding["node"].image = image
                    copies[source_mat] = material
                material = copies[source_mat]
                slots.append((binding["index"], material))
                saved_slots.append({"index": binding["index"], "material": material.name, "baseMaterial": source_mat.name})
            meta["variants"].append({"variant": request["variant"], "image": image.name,
                                     "sourceImage": source_image.name, "slots": saved_slots})
        packed_meta = _rslp_json.dumps(meta, separators=(',', ':'), ensure_ascii=True)
        if len(packed_meta) > 131072:
            raise ValueError("Variant metadata exceeds the bounded size")
        # Resolve the copy's lazy backing buffer while its original path/packed
        # data is still available, then replace ALL pixels with our source copy.
        if tuple(image.size) != (width, height) or len(image.pixels) != len(pixels):
            raise ValueError("Image copy has no matching pixel buffer; source is left unchanged")
        image.pixels.foreach_set(pixels)
        if created_image is not None:
            image.filepath_raw = ""
        image.update()
        image.pack()
        if image.packed_file is None:
            raise ValueError("Variant image could not be packed")
        for index, material in slots:
            # DATA-link assignment would alter a mesh shared by another object.
            obj.material_slots[index].link = 'OBJECT'
            obj.material_slots[index].material = material
        obj[_RSLP_META] = packed_meta
        committed = True
    except Exception:
        for slot, (link, material) in zip(obj.material_slots, previous_slots):
            # Restore through an OBJECT override, then restore link mode. This
            # drops references to staged materials without writing shared data.
            slot.link = 'OBJECT'
            slot.material = material
            slot.link = link
        if previous_meta is None:
            if _RSLP_META in obj:
                del obj[_RSLP_META]
        else:
            obj[_RSLP_META] = previous_meta
        raise
    finally:
        if not committed:
            for material in created_materials:
                if material.users == 0:
                    bpy.data.materials.remove(material)
            if created_image is not None and created_image.users == 0:
                bpy.data.images.remove(created_image)
    return {"changed": "texture.variant", "image": image.name, "variant": request["variant"],
            "pattern": request["pattern"], "shapeLocked": True, "paintedPixels": painted}


# SPDX-License-Identifier: GPL-3.0-or-later
"""Read-only, cooperative <=45 s motion probes; inline after creature-rig.py.

Evaluated mesh.data is read directly, never baked/applied or copied into base
data. Individual Blender dependency-graph evaluations cannot be preempted by
Python; the parent's native job watchdog remains the hard wall-clock bound.
"""
import math
import json
import time

# The parent dispatcher supplies its trusted saved-scene/revision token, including
# manual edits. Timeline seeks/inspection/export must retain that same token.
_rs_mv_checkpoint = None
_rs_mv_reports = {}


def _rs_motion_checkpoint(token):
    global _rs_mv_checkpoint
    if not isinstance(token, str) or not 1 <= len(token) <= 512:
        raise ValueError("A bounded trusted scene checkpoint token is required.")
    if token != _rs_mv_checkpoint:
        _rs_mv_reports.clear()
        _rs_mv_checkpoint = token


def _rs_mv_action_snapshot(ob):
    action = ob.animation_data.action if ob.animation_data else None
    if not action: raise ValueError("The validated action is no longer active.")
    curves = _rs_mv_curves(action, getattr(ob.animation_data, "action_slot", None))
    if len(curves) > 4096 or sum(len(c.keyframe_points) for c in curves) > 100000:
        raise ValueError("This action exceeds the bounded warning-preview fingerprint limit.")
    records = [{"path": c.data_path, "index": c.array_index, "mute": c.mute,
                "keys": [[*p.co, *p.handle_left, *p.handle_right, p.interpolation,
                          p.handle_left_type, p.handle_right_type] for p in c.keyframe_points]}
               for c in curves]
    return _rs_rg_digest({"armature": ob.name, "rest": _rs_rg_records(ob), "action": action.name,
                          "curves": records, "limbs": _rs_rg_controls_json(ob)})


class _rs_mv_Interrupted(Exception):
    pass


def _rs_mv_check(started, budget, epoch):
    if _rs_control().get("epoch") != epoch: raise _rs_mv_Interrupted("cancelled")
    if time.perf_counter() - started >= budget: raise _rs_mv_Interrupted("time-budget")


def _rs_mv_indices(size, limit):
    n = min(size, limit)
    if n <= 1: return [0] if n else []
    return [round(i * (size - 1) / (n - 1)) for i in range(n)]


def _rs_mv_probes(mesh):
    """<=512 UNIQUE evaluated vertices total, including edge endpoints."""
    nv, ne = len(mesh.vertices), len(mesh.edges)
    vertices = set(_rs_mv_indices(nv, 512)) if nv <= 512 else set()
    edges = set()
    # Dispersed edge seeds use at most 512 endpoints; retain all seed edges.
    for i in _rs_mv_indices(ne, 256):
        endpoints = set(mesh.edges[i].vertices)
        if len(vertices | endpoints) <= 512: vertices.update(endpoints); edges.add(i)
    for i in _rs_mv_indices(nv, 512):
        if len(vertices) == 512: break
        vertices.add(i)
    for i in _rs_mv_indices(ne, 8192):
        if len(edges) == 2048: break
        if all(v in vertices for v in mesh.edges[i].vertices): edges.add(i)
    return sorted(vertices), sorted(edges)


def _rs_mv_thresholds(height):
    if not math.isfinite(height) or height < 1e-8: raise ValueError("The visible model has no measurable height.")
    return {"height": height, "quaternionJumpDegrees": 150.0, "bendPlaneDegrees": 120.0,
            "minimumBend": .01 * height, "footSlide": .02 * height,
            "contactBand": .015 * height, "groundPenetration": .005 * height,
            "edgeStrainRatio": .35, "minimumEdge": 1e-6 * height}


def _rs_mv_cross(a, b):
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def _rs_mv_quat_angle(a, b):
    sizes = (_rs_rg_length(a), _rs_rg_length(b))
    if min(sizes) < 1e-10: raise ValueError("Evaluated rotation has zero quaternion length.")
    cosine = min(1, abs(_rs_rg_dot(a, b)) / (sizes[0] * sizes[1]))
    return math.degrees(2 * math.acos(cosine))


def _rs_mv_bend(frame, c):
    a, b, e = (frame["bones"][c[k]]["head"] for k in ("upper", "lower", "end"))
    ray = _rs_rg_sub(e, a)
    if _rs_rg_length(ray) < 1e-9: return None
    axis = _rs_rg_unit(ray); arm = _rs_rg_sub(b, a)
    bend = _rs_rg_sub(arm, _rs_rg_mul(axis, _rs_rg_dot(arm, axis)))
    return axis, bend


def _rs_mv_plane_jump(previous, current, chain, c, thresholds):
    old, new = _rs_mv_bend(previous, c), _rs_mv_bend(current, c)
    if old is None or new is None: return None
    old_axis, old_bend = old; axis, bend = new
    if min(_rs_rg_length(old_bend), _rs_rg_length(bend)) < thresholds["minimumBend"]: return None
    cosine = _rs_rg_dot(old_axis, axis)
    if cosine < .5: return None  # large endpoint turns are ambiguous, not proven knee flips
    k = _rs_mv_cross(old_axis, axis)
    transported = _rs_rg_add(old_bend, _rs_rg_add(_rs_mv_cross(k, old_bend),
                              _rs_rg_mul(_rs_mv_cross(k, _rs_mv_cross(k, old_bend)), 1 / (1 + cosine))))
    old_pole, pole = previous["poles"][chain], current["poles"][chain]
    try:
        old_sign = _rs_rg_dot(_rs_rg_unit(old_bend), _rs_rg_pole(old_pole, old_axis))
        sign = _rs_rg_dot(_rs_rg_unit(bend), _rs_rg_pole(pole, axis))
    except ValueError: return None
    # A sign alone is not a flip: require a substantial, abrupt plane reversal.
    if old_sign * sign >= -.04: return None
    angle = math.degrees(math.acos(max(-1, min(1, _rs_rg_dot(_rs_rg_unit(transported), _rs_rg_unit(bend))))))
    return angle if angle > thresholds["bendPlaneDegrees"] else None


def _rs_mv_issue(state, kind, frame, obj, value, threshold, bone=None, **detail):
    state["counts"][kind] = state["counts"].get(kind, 0) + 1
    if len(state["issues"]) >= 1024:
        state["issuesTruncated"] = True
        return
    issue = {"kind": kind, "frame": frame, "object": obj, "value": float(value), "threshold": float(threshold)}
    if bone is not None: issue["bone"] = bone
    issue.update(detail); state["issues"].append(issue)


def _rs_mv_state():
    return {"issues": [], "counts": {}, "issuesTruncated": False, "anchors": {}}


def _rs_mv_inspect(previous, current, chains, thresholds, state):
    """Pure numeric diagnostics, also used by the CPU/native fixture checks."""
    frame, obj = current["frame"], current["object"]
    if previous:
        for name, bone in current["bones"].items():
            angle = _rs_mv_quat_angle(previous["bones"][name]["quaternion"], bone["quaternion"])
            if angle > thresholds["quaternionJumpDegrees"]:
                _rs_mv_issue(state, "joint-flip", frame, obj, angle, thresholds["quaternionJumpDegrees"], name, measure="quaternion-jump-degrees")
        for chain, c in chains.items():
            angle = _rs_mv_plane_jump(previous, current, chain, c, thresholds)
            if angle is not None:
                _rs_mv_issue(state, "joint-flip", frame, obj, angle, thresholds["bendPlaneDegrees"], c["lower"], measure="signed-bend-plane-degrees", chain=chain)
    for name, contact in current["contacts"].items():
        position, ground = contact["position"], contact["groundZ"]
        depth = ground - position[2]
        if depth > thresholds["groundPenetration"]:
            _rs_mv_issue(state, "ground-penetration", frame, obj, depth, thresholds["groundPenetration"], name, measure="contact-joint-world-distance")
        grounded = contact["active"] and (contact["exactStance"] or abs(position[2] - ground) <= thresholds["contactBand"])
        if not grounded:
            state["anchors"].pop(name, None)
            continue
        anchor = state["anchors"].setdefault(name, position)
        slide = math.hypot(position[0] - anchor[0], position[1] - anchor[1])
        if slide > thresholds["footSlide"]:
            _rs_mv_issue(state, "foot-slide", frame, obj, slide, thresholds["footSlide"], name, measure="world-XY-drift-in-sampled-stance")
    for name, mesh in current["meshes"].items():
        for index, base, evaluated in mesh["edges"]:
            if base <= thresholds["minimumEdge"]: continue
            strain = abs(evaluated / base - 1)
            if strain > thresholds["edgeStrainRatio"]:
                _rs_mv_issue(state, "skin-stretch", frame, name, strain, thresholds["edgeStrainRatio"], edge=index, measure="absolute-evaluated-base-length-ratio-minus-one")
        for index, point in mesh["vertices"].items():
            depth = current["groundZ"] - point[2]
            if depth > thresholds["groundPenetration"]:
                _rs_mv_issue(state, "ground-penetration", frame, name, depth, thresholds["groundPenetration"], vertex=index, measure="sampled-vertex-world-distance")


def _rs_mv_int(value, label, low, high):
    if isinstance(value, bool) or not isinstance(value, int) or not low <= value <= high:
        raise ValueError(label + " must be an integer in the supported range.")
    return value


def _rs_mv_curves(action, slot):
    # Same action/slot compatibility as the starter's helper, without mutation.
    if not getattr(action, "layers", []) and hasattr(action, "fcurves"): return list(action.fcurves)
    bags = [bag for layer in action.layers for strip in layer.strips for bag in getattr(strip, "channelbags", [])]
    if slot is None and len(bags) > 1: raise ValueError("Motion validation needs the active action slot for a multi-slot action.")
    return [curve for bag in bags if slot is None or bag.slot_handle == slot.handle for curve in bag.fcurves]


def _rs_mv_meshes(ob, names):
    if names is not None:
        if not isinstance(names, list) or not 1 <= len(names) <= 8 or any(not isinstance(n, str) for n in names) or len(set(names)) != len(names):
            raise ValueError("objects must list 1–8 separate mesh names.")
        meshes = [_rs_obj(_rs_rg_name(n, "mesh name")) for n in names]
    else:
        meshes = [m for m in bpy.context.scene.objects if m.type == "MESH" and m.visible_get()
                  and any(mod.type == "ARMATURE" and mod.object == ob and mod.show_viewport for mod in m.modifiers)]
        if len(meshes) > 8: raise ValueError("Choose at most eight bound meshes explicitly.")
    supported = {"ARMATURE", "CORRECTIVE_SMOOTH", "SMOOTH", "LAPLACIANSMOOTH", "SIMPLE_DEFORM",
                 "LATTICE", "DISPLACE", "SHRINKWRAP", "HOOK", "MESH_DEFORM", "SURFACE_DEFORM", "CAST", "WAVE", "WARP"}
    for mesh in meshes:
        if mesh.type != "MESH" or not mesh.visible_get() or not any(m.type == "ARMATURE" and m.object == ob and m.show_viewport for m in mesh.modifiers):
            raise ValueError("Validation objects must be visible meshes bound to this armature.")
        if any(m.show_viewport and m.type not in supported for m in mesh.modifiers):
            raise ValueError("Topology-changing or unrecognized modifiers are unsupported for sampled strain: " + mesh.name)
        if not len(mesh.data.vertices): raise ValueError("A selected mesh has no vertices: " + mesh.name)
    return meshes


def _rs_mv_height(ob, meshes):
    points = [tuple(m.matrix_world @ Vector(corner)) for m in meshes for corner in m.bound_box]
    if not points:
        points = [tuple(ob.matrix_world @ p) for b in ob.data.bones for p in (b.head_local, b.tail_local)]
    if any(not all(math.isfinite(v) for v in p) for p in points): raise ValueError("Non-finite visible model bounds.")
    return max(p[2] for p in points) - min(p[2] for p in points)


def _rs_mv_arthropod_chain(index, family):
    if family not in ("insect", "flying-insect", "arachnid"): raise ValueError("Unknown arthropod contact family.")
    count = 8 if family == "arachnid" else 6
    index = _rs_mv_int(index, "plant chain index", 0, count - 1)
    stations = ("front", "midfront", "midhind", "hind") if count == 8 else ("front", "middle", "hind")
    return stations[index // 2] + ("_left_leg" if index % 2 == 0 else "_right_leg")


def _rs_mv_arthropod_phase(index, family):
    _rs_mv_arthropod_chain(index, family)  # Validate before phase lookup.
    if family == "arachnid": return (index // 2 * .25 + index % 2 * .5) % 1
    return ((index // 2 + index % 2) % 2) * .5


def _rs_mv_contacts(ob, action, controls, names, default_ground):
    if names is not None and (not isinstance(names, list) or len(names) > 32 or any(not isinstance(n, str) for n in names) or len(set(names)) != len(names)):
        raise ValueError("contacts must list at most 32 separate bone names.")
    contacts = {}
    for name in names or []:
        _rs_rg_name(name, "contact bone")
        if name not in ob.pose.bones: raise ValueError("An identified contact bone is missing: " + name)
        contacts[name] = {"groundZ": default_ground, "source": "explicit-near-ground"}
    for chain, c in controls.items():
        if c["plant"]:
            ground = c["groundZ"] if "groundZ" in c else (ob.matrix_world @ ob.data.bones[c["end"]].head_local).z
            contacts[c["end"]] = {"groundZ": ground, "source": "configured-near-ground", "chain": chain}
    raw = action.get("riggerset_plant_contacts", "{}")
    if action.get("riggerset_plant_mode") == "in-place-march":
        if not isinstance(raw, str) or len(raw) > 16384: raise ValueError("Invalid action contact metadata.")
        try: metadata = json.loads(raw)
        except ValueError as error: raise ValueError("Invalid action contact JSON.") from error
        if not isinstance(metadata, dict) or len(metadata) > 12: raise ValueError("Invalid action contact map.")
        end = _rs_mv_int(action.get("riggerset_plant_end"), "plant clip end", 1, 10000)
        preset = action.get("riggerset_preset")
        family = action.get("riggerset_family", "legacy")
        arthropod = family in ("insect", "flying-insect", "arachnid")
        legs = (8 if family == "arachnid" else 6) if arthropod else 4
        if preset not in (("walk", "idle", "flap", "fold") if arthropod else ("walk", "trot", "idle", "flap", "fold")):
            raise ValueError("Unrecognized plant clip preset.")
        seen_indices = set()
        for name, c in metadata.items():
            fields = {"chain", "index", "groundZ", "family"} if arthropod else {"chain", "index", "groundZ"}
            if not isinstance(c, dict) or set(c) != fields: raise ValueError("Invalid action contact record.")
            chain = c["chain"]
            if not isinstance(chain, str) or chain not in controls or controls[chain]["end"] != name or not controls[chain]["plant"]:
                raise ValueError("Plant action metadata disagrees with the current limb controls; regenerate the clip.")
            index = _rs_mv_int(c["index"], "plant chain index", 0, legs - 1)
            if arthropod and index in seen_indices: raise ValueError("Arthropod contact indices must be unique.")
            seen_indices.add(index)
            if arthropod and (c["family"] != family or chain != _rs_mv_arthropod_chain(index, family)):
                raise ValueError("Arthropod contact family/index disagrees with the saved named chain.")
            ground = _rs_rg_number(c["groundZ"], "plant groundZ")
            if abs(contacts[name]["groundZ"] - ground) > 1e-6:
                raise ValueError("Plant groundZ changed since this action was made; regenerate the clip.")
            contacts[name] = {"groundZ": ground, "source": "configured-clip-stance", "chain": chain,
                              "preset": preset, "index": index, "end": end, "family": family}
    return contacts


def _rs_mv_frame_contacts(frame, specs, bones):
    result = {}
    for name, c in specs.items():
        exact = c["source"] == "configured-clip-stance"
        active = True
        if exact:
            t = max(0, min(1, (frame - 1) / max(1, c["end"] - 1)))
            if c.get("family") in ("insect", "flying-insect", "arachnid"):
                active = _rs_rg_stance(c["preset"], t + _rs_mv_arthropod_phase(c["index"], c["family"]))
            else:
                offset = ((.25, .75, 0, .5) if c["preset"] == "walk" else (0, .5, .5, 0))[c["index"]] if c["preset"] in ("walk", "trot") else 0
                active = _rs_rg_stance(c["preset"], t + offset)
        result[name] = {"position": bones[name]["head"], "groundZ": c["groundZ"], "active": active, "exactStance": exact}
    return result


def _rs_mv_finite(point, label):
    point = tuple(point)
    if any(not math.isfinite(v) for v in point): raise ValueError("Non-finite evaluated " + label + ".")
    return point


def _rs_motion_validate(a):
    started = time.perf_counter()
    _rs_rg_args(a, ("armature", "objects", "start", "end", "samples", "groundZ", "contacts", "maxSeconds"))
    budget = _rs_rg_number(a.get("maxSeconds", 45), "maxSeconds", 45)
    if not .001 <= budget <= 45: raise ValueError("maxSeconds must be in .001–45 seconds.")
    _rs_rg_context_check()
    if bpy.context.object and bpy.context.object.mode == "EDIT":
        raise ValueError("Finish Edit Mode before read-only evaluated motion validation.")
    ob = _rs_obj(_rs_rg_name(a.get("armature"), "armature"))
    if ob.type != "ARMATURE" or not 1 <= len(ob.data.bones) <= 256:
        raise ValueError("Motion validation supports an armature with 1–256 bones.")
    if ob.data.pose_position != "POSE": raise ValueError("Use Pose Position to validate evaluated animation.")
    data = ob.animation_data
    if not data or not data.action: raise ValueError("Animation is not present on this armature.")
    if data.drivers or _rs_rg_active_nla(data) or ob.constraints or any(b.constraints for b in ob.pose.bones):
        raise ValueError("This validator supports an active action without rig drivers, NLA or constraints.")
    action = data.action
    checkpoint_token = _rs_mv_checkpoint
    source_snapshot = _rs_mv_action_snapshot(ob) if checkpoint_token else None
    curves = _rs_mv_curves(action, getattr(data, "action_slot", None))
    if not any(len(c.keyframe_points) and (c.data_path.startswith("pose.bones[") or c.data_path in ("location", "rotation_quaternion", "rotation_euler", "rotation_axis_angle", "scale")) for c in curves):
        raise ValueError("Animation is not present in the armature's active action slot.")
    scene = bpy.context.scene
    start = _rs_mv_int(a.get("start", scene.frame_start), "start", -1000000, 1000000)
    end = _rs_mv_int(a.get("end", scene.frame_end), "end", -1000000, 1000000)
    if end < start: raise ValueError("end precedes start.")
    count = _rs_mv_int(a.get("samples", 32), "samples", 1, 60)
    frames = [start + i for i in _rs_mv_indices(end - start + 1, count)]
    ground = _rs_rg_number(a.get("groundZ", 0), "groundZ")
    meshes = _rs_mv_meshes(ob, a.get("objects"))
    controls = _rs_limb_controls(ob)
    specs = _rs_mv_contacts(ob, action, controls, a.get("contacts"), ground)
    thresholds = _rs_mv_thresholds(_rs_mv_height(ob, meshes))
    epoch = _rs_control().get("epoch")
    state = _rs_mv_state(); inspected = []; coverage = {}; interrupted = None; previous = None
    selection = _rs_rg_selection_state(); original_frame = scene.frame_current; original_subframe = scene.frame_subframe
    assumptions = ["Sampled diagnostics, not exhaustive validation; unsampled frames, vertices and edges can contain defects.",
                   "Quaternion jumps >150 degrees and abrupt signed bend reversals >120 degrees are warnings, not proof of an unintended pose.",
                   "Near-straight knees and large endpoint-axis turns are excluded from the bend-plane test.",
                   "Edge strain compares evaluated and base edges in the same current world transform; intentional squash/stretch can warn.",
                   "Ground is a horizontal world-Z plane; no terrain or sole-volume inference.",
                   "The time limit is cooperative between native evaluations; the parent watchdog must bound a single stalled native call."]
    if any(c["source"] != "configured-clip-stance" for c in specs.values()):
        assumptions.append("Explicit/configured contacts without generated stance metadata use a near-ground heuristic: XY drift is measured from the first consecutive grounded sample.")
    if not specs: assumptions.append("No contacts were identified; foot sliding and joint ground penetration were not checked.")
    if not meshes: assumptions.append("No bound meshes were found; skin strain and surface penetration were not checked.")
    if len(frames) < 2: assumptions.append("One frame was requested; temporal jumps and sliding cannot be assessed.")
    try:
        _rs_mv_check(started, budget, epoch)
        probes = {}
        for mesh in meshes:
            _rs_mv_check(started, budget, epoch)
            vertices, edges = _rs_mv_probes(mesh.data)
            records = []
            for i in edges:
                x, y = mesh.data.edges[i].vertices
                delta = tuple(mesh.data.vertices[y].co - mesh.data.vertices[x].co)
                records.append((i, x, y, delta))
            probes[mesh.name] = (vertices, records, len(mesh.data.vertices), len(mesh.data.edges))
            coverage[mesh.name] = {"vertexSamplesPerFrame": len(vertices), "edgeSamplesPerFrame": len(edges),
                                   "baseVertices": len(mesh.data.vertices), "baseEdges": len(mesh.data.edges)}
        for frame in frames:
            _rs_mv_check(started, budget, epoch)  # Check cancellation on every sample.
            scene.frame_set(frame)
            depsgraph = bpy.context.evaluated_depsgraph_get()
            _rs_mv_check(started, budget, epoch)
            evaluated_rig = ob.evaluated_get(depsgraph)
            bones = {}
            for b in evaluated_rig.pose.bones:
                if b.parent and abs(b.parent.matrix.determinant()) < 1e-12:
                    raise ValueError("A zero-scale parent transform is unsupported for rotation validation.")
                matrix = b.parent.matrix.inverted_safe() @ b.matrix if b.parent else b.matrix
                bones[b.name] = {"head": _rs_mv_finite(evaluated_rig.matrix_world @ b.head, "joint"),
                                 "quaternion": _rs_mv_finite(matrix.to_quaternion(), "quaternion")}
            poles = {chain: tuple(evaluated_rig.matrix_world.to_3x3() @ Vector(c["pole"])) for chain, c in controls.items()}
            sampled_meshes = {}
            for mesh in meshes:
                _rs_mv_check(started, budget, epoch)
                evaluated = mesh.evaluated_get(depsgraph); final_mesh = evaluated.data
                vertices, edges, nv, ne = probes[mesh.name]
                if len(final_mesh.vertices) != nv or len(final_mesh.edges) != ne:
                    raise ValueError("Evaluated mesh topology changed; strain sampling is unsupported: " + mesh.name)
                points = {i: _rs_mv_finite(evaluated.matrix_world @ final_mesh.vertices[i].co, "vertex") for i in vertices}
                edge_values = []
                for i, x, y, delta in edges:
                    if tuple(final_mesh.edges[i].vertices) != (x, y):
                        raise ValueError("Evaluated edge correspondence changed: " + mesh.name)
                    base = (evaluated.matrix_world.to_3x3() @ Vector(delta)).length
                    actual = _rs_rg_length(_rs_rg_sub(points[y], points[x]))
                    edge_values.append((i, base, actual))
                sampled_meshes[mesh.name] = {"vertices": points, "edges": edge_values}
                _rs_mv_check(started, budget, epoch)
            sample = {"frame": frame, "object": ob.name, "groundZ": ground, "bones": bones, "poles": poles,
                      "meshes": sampled_meshes, "contacts": _rs_mv_frame_contacts(frame, specs, bones)}
            _rs_mv_inspect(previous, sample, controls, thresholds, state)
            inspected.append(frame); previous = sample
            _rs_mv_check(started, budget, epoch)
    except _rs_mv_Interrupted as error:
        interrupted = str(error)
    finally:
        try:
            scene.frame_set(original_frame, subframe=original_subframe)
        finally:
            # Normally untouched; also restore if a frame callback changed context.
            current = _rs_rg_selection_state()
            if current != selection: _rs_rg_restore_selection(selection)
    elapsed = time.perf_counter() - started
    if _rs_control().get("epoch") != epoch and interrupted is None: interrupted = "cancelled"
    if elapsed >= budget and interrupted is None: interrupted = "time-budget"
    partial = interrupted is not None or len(frames) < 2 or not meshes
    report = {"status": "partial" if partial else ("warnings" if state["issues"] else "passed"),
            "issues": state["issues"], "issueCounts": state["counts"], "issuesTruncated": state["issuesTruncated"],
            "sampled": True, "truncated": interrupted is not None, "elapsedSeconds": elapsed,
            "samplesInspected": len(inspected), "samplesRequested": len(frames), "frames": inspected,
            "thresholds": thresholds, "assumptions": assumptions, "interruption": interrupted,
            "coverage": {"bonesPerFrame": len(ob.data.bones), "meshes": coverage,
                         "contacts": {n: c["source"] for n, c in specs.items()}},
            "limits": {"seconds": budget, "samples": 60, "meshes": 8, "bones": 256,
                       "evaluatedVerticesPerMesh": 512, "edgesPerMesh": 2048}}
    actionable = bool(checkpoint_token and checkpoint_token == _rs_mv_checkpoint and interrupted != "cancelled")
    report_id = _rs_rg_digest({"checkpoint": checkpoint_token, "source": source_snapshot, "armature": ob.name,
                               "frames": inspected, "issues": state["issues"]})
    report.update(reportId=report_id, sceneCheckpoint=checkpoint_token, actionable=actionable)
    if actionable:
        if len(_rs_mv_reports) >= 4: _rs_mv_reports.pop(next(iter(_rs_mv_reports)))
        _rs_mv_reports[report_id] = {"armature": ob.name, "objects": [m.name for m in meshes],
                                      "checkpoint": checkpoint_token, "source": source_snapshot,
                                      "issues": [dict(i) for i in state["issues"]]}
    return report


def _rs_motion_frame_preview(a, export_static):
    """Exact native frame + a static, evaluated GLB. Parent supplies bounded exporter.

    export_static(temp_objects) must export only these objects, Y-up, no animation,
    and return GLB bytes. The parent's existing epoch/watchdog surrounds the call.
    No viewport renderer, animation playback, base mesh or action edits occur here.
    """
    _rs_rg_args(a, ("reportId", "issueIndex"))
    report_id = a.get("reportId")
    if not isinstance(report_id, str) or len(report_id) != 64 or report_id not in _rs_mv_reports:
        raise ValueError("The warning report is unavailable or stale; run the motion check again.")
    report = _rs_mv_reports[report_id]
    if not _rs_mv_checkpoint or report["checkpoint"] != _rs_mv_checkpoint:
        raise ValueError("The scene checkpoint changed; run the motion check again.")
    index = _rs_mv_int(a.get("issueIndex"), "issueIndex", 0, len(report["issues"]) - 1)
    issue = report["issues"][index]
    ob = _rs_obj(report["armature"])
    if _rs_mv_action_snapshot(ob) != report["source"]:
        raise ValueError("The rig/action changed; run the motion check again.")
    _rs_rg_context_check()
    if bpy.context.object and bpy.context.object.mode == "EDIT": raise ValueError("Finish Edit Mode before frame preview.")
    if not callable(export_static): raise ValueError("The static GLB exporter hook is not installed.")
    if not report["objects"]: raise ValueError("No bound surface is available; open the native bone editor at this frame.")
    meshes = _rs_mv_meshes(ob, report["objects"])
    scene = bpy.context.scene; selection = _rs_rg_selection_state()
    old_frame, old_subframe = scene.frame_current, scene.frame_subframe
    epoch = _rs_control().get("epoch"); token = _rs_mv_checkpoint
    temporary = []; temporary_meshes = []; succeeded = False
    try:
        scene.frame_set(issue["frame"], subframe=0)
        depsgraph = bpy.context.evaluated_depsgraph_get(); evaluated_rig = ob.evaluated_get(depsgraph)
        bone = evaluated_rig.pose.bones.get(issue.get("bone", ""))
        if bone:
            highlight = {"label": bone.name + " · frame " + str(issue["frame"]),
                         "head": list(evaluated_rig.matrix_world @ bone.head),
                         "tail": list(evaluated_rig.matrix_world @ bone.tail)}
        else:
            target = _rs_obj(issue["object"]).evaluated_get(depsgraph)
            if target.type != "MESH": raise ValueError("The warning object no longer exists as a mesh.")
            evaluated_vertices = target.data.vertices
            if "vertex" in issue and issue["vertex"] < len(evaluated_vertices):
                point = target.matrix_world @ evaluated_vertices[issue["vertex"]].co
            elif "edge" in issue and issue["edge"] < len(target.data.edges):
                edge = target.data.edges[issue["edge"]]
                point = target.matrix_world @ ((evaluated_vertices[edge.vertices[0]].co + evaluated_vertices[edge.vertices[1]].co) * .5)
            else:
                point = target.matrix_world @ (sum((Vector(c) for c in target.bound_box), Vector()) / 8)
            highlight = {"label": target.name + " · frame " + str(issue["frame"]), "head": list(point)}
        evaluated_meshes = [m.evaluated_get(depsgraph) for m in meshes]
        if sum(len(m.data.vertices) for m in evaluated_meshes) > 500000:
            raise ValueError("Fixed-frame preview is limited to 500,000 evaluated vertices; open the native editor.")
        for original, evaluated in zip(meshes, evaluated_meshes):
            if epoch != _rs_control().get("epoch") or token != _rs_mv_checkpoint:
                raise ValueError("Frame preview cancelled or its scene checkpoint changed.")
            data = bpy.data.meshes.new_from_object(evaluated, preserve_all_data_layers=True, depsgraph=depsgraph)
            temporary_meshes.append(data)
            static = bpy.data.objects.new("__rs_frame_" + original.name, data)
            temporary.append(static); scene.collection.objects.link(static)
            static.matrix_world = evaluated.matrix_world.copy()
            # new_from_object bakes deformation; there is no armature, animation or
            # modifier on this owned copy. Source materials are only referenced.
        value = export_static(temporary)
        if epoch != _rs_control().get("epoch") or token != _rs_mv_checkpoint:
            raise ValueError("Frame preview cancelled or its scene checkpoint changed.")
        if not isinstance(value, (bytes, bytearray, memoryview)) or len(value) < 12 or bytes(value[:4]) != b"glTF":
            raise ValueError("The fixed-frame exporter did not return a binary GLB.")
        succeeded = True
        return {"bytes": value, "frame": issue["frame"], "highlight": highlight,
                "reportId": report_id, "sceneCheckpoint": token, "animated": False}
    finally:
        try:
            for static in temporary: bpy.data.objects.remove(static, do_unlink=True)
            for data in temporary_meshes:
                if data.users == 0: bpy.data.meshes.remove(data)
        finally:
            try: _rs_rg_restore_selection(selection)
            finally:
                if not succeeded: scene.frame_set(old_frame, subframe=old_subframe)


# SPDX-License-Identifier: GPL-3.0-or-later
"""Owning-frame static exporter for checkpoint-bound warning inspection."""
def _rs_motion_preview_export(a, destination):
    token = a.get("sceneCheckpoint")
    if not isinstance(token, str) or not 1 <= len(token) <= 180:
        raise ValueError("Use the current saved scene checkpoint.")
    _rs_motion_checkpoint(token)
    def export_static(objects):
        if not objects or len(objects) > 8:
            raise ValueError("A frame preview needs one to eight actual evaluated surfaces.")
        active = bpy.context.view_layer.objects.active
        if active is not None and active.mode != "OBJECT":
            bpy.ops.object.mode_set(mode="OBJECT")
        for ob in list(bpy.context.selected_objects):
            ob.select_set(False)
        for ob in objects:
            ob.select_set(True)
        bpy.context.view_layer.objects.active = objects[0]
        bpy.ops.export_scene.gltf(filepath=destination, export_format="GLB", use_selection=True,
                                  export_animations=False, export_extras=True, export_yup=True)
        if os.path.getsize(destination) > 128 * 1024 * 1024:
            raise ValueError("The evaluated frame exceeds the 128 MB preview limit.")
        with open(destination, "rb") as file:
            return file.read()
    try:
        result = _rs_motion_frame_preview({"reportId": a.get("reportId"), "issueIndex": a.get("issueIndex")}, export_static)
        result.pop("bytes", None)
        result.update(file=destination, bytes=os.path.getsize(destination), revision=_RS_REV)
        return result
    except Exception:
        _rs_unlink(destination)
        raise


# SPDX-License-Identifier: GPL-3.0-or-later
"""Named simulation anchors and explicit, uniform physical-scale calibration.

Blender tool inputs use Z-up world coordinates. Export metadata uses glTF Y-up
metres. Actual size is confirmed only when the visitor supplies a height.
"""
import re
from mathutils import Matrix


def _rs_contact_json(ob):
    raw = ob.get("riggerset_contact_v1")
    if not raw:
        return None
    try:
        value = json.loads(raw)
    except (TypeError, ValueError):
        return None
    return value if isinstance(value, dict) and value.get("schema") == 1 else None


def _rs_contacts():
    return [(ob, value) for ob in bpy.context.scene.objects
            if ob.type == "EMPTY" and (value := _rs_contact_json(ob))]


def _rs_contact_armature(ob):
    if ob.type == "ARMATURE":
        return ob
    if ob.parent and ob.parent.type == "ARMATURE":
        return ob.parent
    return next((m.object for m in ob.modifiers
                 if m.type == "ARMATURE" and m.object), None)


def _rs_contact_set(a):
    source = _rs_obj(a.get("object", ""))
    if source.type not in ("MESH", "ARMATURE"):
        raise ValueError("Choose an asset mesh or armature for the contact.")
    name = a.get("name")
    if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z][A-Za-z0-9_.-]{0,79}", name):
        raise ValueError("Contact names use letters, numbers, dots, dashes or underscores.")
    kind = a.get("kind", "body")
    if kind not in ("mouth", "horn", "claw", "foot", "body", "custom"):
        raise ValueError("Choose a contact category.")
    point = Vector(_rs_vec(a.get("position"), 3, -10000, 10000))
    radius = _rs_num(a.get("radius", 0), 0, 100)
    bone = a.get("bone")
    arm = _rs_contact_armature(source)
    if bone is not None and (not isinstance(bone, str) or not arm or bone not in arm.pose.bones):
        raise ValueError("Choose an existing joint linked to this mesh.")
    existing = next(((ob, data) for ob, data in _rs_contacts() if data["name"] == name), None)
    if existing and existing[1]["object"] != source.name:
        raise ValueError("That contact name belongs to another mesh. Choose a unique name.")
    if not existing and len(_rs_contacts()) >= 64:
        raise ValueError("This asset supports up to 64 named contact points.")
    marker = existing[0] if existing else bpy.data.objects.new("RSContact::" + name, None)
    if not existing:
        bpy.context.scene.collection.objects.link(marker)
    marker.parent = arm if bone else source
    marker.parent_type = "BONE" if bone else "OBJECT"
    marker.parent_bone = bone or ""
    marker.matrix_parent_inverse = Matrix.Identity(4)
    bpy.context.view_layer.update()
    marker.matrix_world = Matrix.Translation(point)
    marker.empty_display_type = "SPHERE"
    marker.empty_display_size = max(.015, radius)
    marker["riggerset_contact_v1"] = json.dumps({"schema": 1, "name": name, "kind": kind,
        "object": source.name, "bone": bone, "armature": arm.name if bone else None,
        "binding": "bone" if bone else "object", "radius": radius}, separators=(",", ":"))
    bpy.context.view_layer.update()
    return {"changed": "contact.set", "name": name, "binding": "bone" if bone else "object",
            "object": source.name, "position": list(marker.matrix_world.translation)}


def _rs_contact_remove(a):
    found = next(((ob, data) for ob, data in _rs_contacts()
                  if data["name"] == a.get("name") and data["object"] == a.get("object")), None)
    if not found:
        raise ValueError("That named contact was not found on this mesh.")
    bpy.data.objects.remove(found[0], do_unlink=True)
    return {"changed": "contact.remove", "name": a["name"]}


def _rs_asset_members(source):
    arm = _rs_contact_armature(source)
    members = {arm or source}
    for ob in bpy.context.scene.objects:
        if arm and ob.type == "MESH" and _rs_contact_armature(ob) == arm:
            members.add(ob)
    changed = True
    while changed:
        changed = False
        for ob in bpy.context.scene.objects:
            if ob.parent in members and ob not in members and ob.type in ("MESH", "ARMATURE", "EMPTY"):
                members.add(ob)
                changed = True
    return members


def _rs_asset_bounds(members):
    points = [ob.matrix_world @ Vector(v) for ob in members if ob.type == "MESH"
              and not ob.hide_render for v in ob.bound_box]
    if not points:
        raise ValueError("This asset has no measurable mesh bounds.")
    low = Vector([min(p[i] for p in points) for i in range(3)])
    high = Vector([max(p[i] for p in points) for i in range(3)])
    if any(not math.isfinite(v) for v in (*low, *high)):
        raise ValueError("The asset bounds are not finite.")
    return low, high


def _rs_asset_scale(a):
    source = _rs_obj(a.get("object", ""))
    if source.type not in ("MESH", "ARMATURE"):
        raise ValueError("Choose the asset mesh or armature.")
    target = _rs_num(a.get("heightMeters"), .01, 1000)
    members = _rs_asset_members(source)
    if len(members) > 512 or any(ob.constraints for ob in members):
        raise ValueError("Scale calibration needs a bounded asset without object constraints.")
    low, high = _rs_asset_bounds(members)
    height = high.z - low.z
    if height < 1e-7:
        raise ValueError("The asset needs a nonzero height.")
    factor = target / height
    if not 1e-6 <= factor <= 1e6:
        raise ValueError("The requested scale change is outside the supported range.")
    anchor = Vector(((low.x + high.x) / 2, (low.y + high.y) / 2, low.z))
    transform = Matrix.Translation(anchor) @ Matrix.Scale(factor, 4) @ Matrix.Translation(-anchor)
    if a.get("ground", True):
        transform = Matrix.Translation((0, 0, -low.z)) @ transform
    roots = [ob for ob in members if ob.parent not in members]
    # Animated root-object transforms would overwrite calibration on the next frame.
    if any(ob.animation_data and (ob.animation_data.drivers or _rs_rg_active_nla(ob.animation_data) or (ob.animation_data.action and any(curve.data_path in ("location", "scale", "rotation_euler", "rotation_quaternion", "rotation_axis_angle") for curve in _rs_motion_curves(ob.animation_data.action)))) for ob in roots):
        raise ValueError("Bake or clear animated root-object transforms before scale calibration.")
    controls_by_arm = {ob: _rs_limb_controls(ob) for ob in members if ob.type == "ARMATURE" and ob.get("riggerset_limb_controls")}
    original = {ob: ob.matrix_world.copy() for ob in roots}
    for ob in roots:
        ob.matrix_world = transform @ original[ob]
    for ob, data in _rs_contacts():
        if ob in members:
            data["radius"] *= factor
            ob["riggerset_contact_v1"] = json.dumps(data, separators=(",", ":"))
    # Calibration changes world units only; local joint positions and vertex data stay intact.
    for ob, controls in controls_by_arm.items():
        for control in controls.values():
            if "groundZ" in control:
                control["groundZ"] = (transform @ Vector((0, 0, control["groundZ"]))).z
        ob["riggerset_limb_controls"] = json.dumps(controls, separators=(",", ":"))
    scene = bpy.context.scene
    scene.unit_settings.system = "METRIC"
    scene.unit_settings.scale_length = 1
    scene["riggerset_scale_v1"] = json.dumps({"schema": 1, "object": source.name,
        "heightMeters": target, "confirmed": True, "rootObjects": sorted(ob.name for ob in roots)}, separators=(",", ":"))
    bpy.context.view_layer.update()
    return {"changed": "asset.scale", "heightMeters": target, "factor": factor,
            "shapePreserved": True, "units": "meters", "grounded": a.get("ground", True)}


def _rs_contacts_report(a=None):
    scene = bpy.context.scene
    unit = float(scene.unit_settings.scale_length)
    axis = Quaternion((1, 0, 0), -math.pi / 2)
    contacts = []
    for ob, value in _rs_contacts():
        point = ob.matrix_world.translation * unit
        rotation = axis @ ob.matrix_world.to_quaternion() @ axis.inverted()
        contacts.append({"name": value["name"], "kind": value["kind"], "object": value["object"],
            "binding": value["binding"], "bone": value.get("bone"), "armature": value.get("armature"),
            "positionMeters": [point.x, point.z, -point.y],
            "rotationQuaternionXYZW": [rotation.x, rotation.y, rotation.z, rotation.w],
            "radiusMeters": value.get("radius", 0) * unit, "node": ob.name})
    try:
        scale = json.loads(scene.get("riggerset_scale_v1", "{}"))
    except (TypeError, ValueError):
        scale = {}
    meshes = [ob for ob in scene.objects if ob.type == "MESH" and not ob.hide_render]
    bounds = None
    if meshes:
        low, high = _rs_asset_bounds(meshes)
        bounds = {"min": [low.x * unit, low.z * unit, -high.y * unit],
                  "max": [high.x * unit, high.z * unit, -low.y * unit]}
    return {"schema": "riggerset-simulation-contacts-v1", "units": "meters",
            "coordinateSystem": "right-handed glTF: +Y up, +Z backward", "frame": scene.frame_current,
            "scaleConfirmed": bool(scale.get("confirmed")), "scale": scale, "exportCompatible": abs(unit - 1) < 1e-8,
            "boundsMeters": bounds, "contacts": sorted(contacts, key=lambda v: v["name"])}


def _rs_rig_rest(a):
    arm = _rs_obj(a.get("armature", ""))
    if arm.type != "ARMATURE":
        raise ValueError("Choose an armature.")
    if arm.constraints or any(b.constraints for b in arm.pose.bones):
        raise ValueError("Prepare rest joints needs a rig without constraints.")
    data = arm.animation_data
    if data and (data.drivers or _rs_rg_active_nla(data)):
        raise ValueError("Prepare rest joints needs a rig without drivers or NLA tracks.")
    previous = data.action if data else None
    retained = []
    if data:
        # glTF imports stash alternative clips in muted tracks. Keep those actual
        # Action IDs before explicitly preparing this rig's rest joints.
        for track in list(data.nla_tracks):
            for strip in track.strips:
                if strip.action:
                    strip.action.use_fake_user=True;retained.append(strip.action.name)
            data.nla_tracks.remove(track)
    if previous:
        previous.use_fake_user = True
        data.action = None
    for bone in arm.pose.bones:
        bone.matrix_basis = Matrix.Identity(4)
    bpy.context.view_layer.update()
    return {"changed": "rig.rest", "retainedAction": previous.name if previous else None,"retainedStashedActions":sorted(set(retained))}


# SPDX-License-Identifier: GPL-3.0-or-later
"""Bounded opaque selections and a temporary, read-only highlighted GLB view."""
import hashlib

_RS_SELECTIONS = {}
_RS_SELECTION_SEQ = 0


def _rs_selection_create(a):
    global _RS_SELECTION_SEQ
    args = dict(a)
    space = args.pop("space", "local")
    if space not in ("local", "world"):
        raise ValueError("Selection coordinates must be local or world.")
    if space == "world" and "center" in args:
        ob = _rs_obj(args["object"])
        args["center"] = list(ob.matrix_world.inverted() @ Vector(args["center"]))
    result = _rs_mesh_selection(args)
    _RS_SELECTION_SEQ += 1
    key = hashlib.sha256((str(_RS_SELECTION_SEQ) + result["digest"]).encode()).hexdigest()[:24]
    _RS_SELECTIONS[key] = {**result, "revision": _RS_REV}
    while len(_RS_SELECTIONS) > 8:
        _RS_SELECTIONS.pop(next(iter(_RS_SELECTIONS)))
    public = {k: v for k, v in result.items() if k not in ("faces", "vertices")}
    public["selectionId"] = key
    return public


def _rs_selection_get(key, object_name=None):
    value = _RS_SELECTIONS.get(key)
    if not value or value["revision"] != _RS_REV:
        raise ValueError("Selection expired. Preview the region again after changing the model.")
    if object_name and value["object"] != object_name:
        raise ValueError("This selection belongs to another mesh.")
    fresh = _rs_mesh_selection({"object": value["object"], "faces": value["faces"]})
    if fresh["digest"] != value["digest"]:
        raise ValueError("The mesh changed. Preview the selection again.")
    return value


def _rs_selection_repair(a):
    selected = _rs_selection_get(a.get("selectionId"), a.get("object"))
    if selected["digest"] != a.get("digest"):
        raise ValueError("The repair preview does not match this request.")
    return _rs_mesh_repair({"object": selected["object"], "faces": selected["faces"],
                            "digest": selected["digest"], "cap": True})


def _rs_selection_weights(a):
    args = dict(a)
    key = args.pop("selectionId", None)
    if key:
        selected = _rs_selection_get(key, args.get("object"))
        args["vertices"] = selected["vertices"]
    return _rs_rigid_weights(args)


def _rs_selection_preview_file(key, target):
    selected = _rs_selection_get(key)
    source = _rs_obj(selected["object"])
    old_active = bpy.context.view_layer.objects.active
    old_selected = list(bpy.context.selected_objects)
    old_mode = old_active.mode if old_active else "OBJECT"
    duplicate = mesh = material = None
    try:
        _rs_mode_object()
        mesh = source.data.copy()
        duplicate = source.copy()
        duplicate.data = mesh
        duplicate.name = "RiggerSet selection preview"
        duplicate["riggerset_source_object"] = source.name
        bpy.context.scene.collection.objects.link(duplicate)
        material = bpy.data.materials.new("RiggerSet selected patch")
        material.diffuse_color = (1, .29, .035, 1)
        material.use_nodes = True
        shader = next(n for n in material.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
        shader.inputs["Base Color"].default_value = (1, .29, .035, 1)
        mesh.materials.append(material)
        index = len(mesh.materials) - 1
        for face in selected["faces"]:
            mesh.polygons[face].material_index = index
        for ob in bpy.context.scene.objects:
            ob.select_set(False)
        for ob in bpy.context.scene.objects:
            if ob != source and ob.type in ("MESH", "ARMATURE", "EMPTY") and not ob.hide_render and not ob.hide_get():
                ob.select_set(True)
        duplicate.select_set(True)
        bpy.context.view_layer.objects.active = duplicate
        bpy.ops.export_scene.gltf(filepath=target, export_format="GLB", use_selection=True,
                                  export_animations=False, export_extras=True)
        return {"file": target, "selectionId": key, "revision": _RS_REV}
    finally:
        if duplicate:
            bpy.data.objects.remove(duplicate, do_unlink=True)
        if mesh and mesh.users == 0:
            bpy.data.meshes.remove(mesh)
        if material and material.users == 0:
            bpy.data.materials.remove(material)
        for ob in bpy.context.scene.objects:
            ob.select_set(ob in old_selected)
        if old_active and old_active.name in bpy.data.objects:
            bpy.context.view_layer.objects.active = old_active
            if old_mode == "EDIT" and bpy.ops.object.mode_set.poll():
                bpy.ops.object.mode_set(mode="EDIT")


# SPDX-License-Identifier: GPL-3.0-or-later
"""Private, bounded plane-cut plans. Inline before the RiggerSet dispatcher.

No Blender imports or scene work at import time. Geometry helpers are pure.
All topology work is on a private Mesh ID. Only apply assigns object.data.
"""
import array as _rs_cut_array
import hashlib as _rs_cut_hashlib
import json as _rs_cut_json
import math as _rs_cut_math
import secrets as _rs_cut_secrets
import struct as _rs_cut_struct
import time as _rs_cut_time

_rs_cut_plans = {}


class _rs_cut_Interrupted(ValueError):
    pass


def _rs_cut_check_context():
    epoch = _rs_control().get("epoch")
    deadline = _rs_cut_time.monotonic() + 45.0

    def check():
        if _rs_control().get("epoch") != epoch:
            raise _rs_cut_Interrupted("Plane cut cancelled; source mesh was not changed")
        if _rs_cut_time.monotonic() > deadline:
            raise _rs_cut_Interrupted("Plane cut stopped at its 45 second work limit")
    return check


def _rs_cut_pulse(check):
    if check is not None:
        check()


def _rs_cut_vec(value):
    if (not isinstance(value, (list, tuple)) or len(value) != 3 or
            any(isinstance(x, bool) or not isinstance(x, (int, float)) or
                not _rs_cut_math.isfinite(x) for x in value)):
        raise ValueError("Plane coordinates must contain three finite numbers")
    return tuple(float(x) for x in value)


def _rs_cut_sub(a, b):
    return tuple(a[k] - b[k] for k in range(3))


def _rs_cut_dot(a, b):
    return _rs_cut_math.fsum(x*y for x, y in zip(a, b))


def _rs_cut_cross(a, b):
    return (a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0])


def _rs_cut_unit(v):
    length = _rs_cut_math.hypot(*v)
    if not _rs_cut_math.isfinite(length) or length < 1e-20:
        raise ValueError("Plane normal or transform is degenerate")
    return tuple(x/length for x in v)


def _rs_cut_args(a):
    if not isinstance(a, dict) or set(a) - {"object", "planePoint", "planeNormal", "keep", "cap", "bakeMorphs"}:
        raise ValueError("Unknown or invalid plane-cut arguments")
    if not isinstance(a.get("object"), str) or not a["object"]:
        raise ValueError("object must name a mesh")
    if a.get("cap") is not True or a.get("keep") not in ("front", "back"):
        raise ValueError("Use cap:true and keep:'front' or keep:'back'")
    if type(a.get("bakeMorphs", False)) is not bool:
        raise ValueError("bakeMorphs must be a boolean")
    return {"object": a["object"], "planePoint": _rs_cut_vec(a.get("planePoint")),
            "planeNormal": _rs_cut_unit(_rs_cut_vec(a.get("planeNormal"))),
            "keep": a["keep"], "cap": True, "bakeMorphs": a.get("bakeMorphs", False)}


def _rs_cut_local_plane(matrix, point, normal):
    """Pull back a world covector: n_local=A^T*n_world, p_local=A^-1*(p-t)."""
    rows = [tuple(float(x) for x in row) for row in matrix]
    if (len(rows) != 4 or any(len(r) != 4 for r in rows) or
            any(not _rs_cut_math.isfinite(x) for r in rows for x in r) or
            any(abs(rows[3][k] - (1 if k == 3 else 0)) > 1e-10 for k in range(4))):
        raise ValueError("Object needs a finite affine transform")
    a = [r[:3] for r in rows[:3]]
    cof = [_rs_cut_cross(a[1], a[2]), _rs_cut_cross(a[2], a[0]), _rs_cut_cross(a[0], a[1])]
    det = _rs_cut_dot(a[0], cof[0])
    scale = max(abs(x) for r in a for x in r)
    if not scale or abs(det) < scale**3 * 1e-12:
        raise ValueError("Singular or ill-conditioned object transform")
    inv = [tuple(cof[j][i]/det for j in range(3)) for i in range(3)]
    if max(sum(abs(x) for x in r) for r in a) * max(sum(abs(x) for x in r) for r in inv) > 1e10:
        raise ValueError("Object transform exceeds the condition limit")
    delta = tuple(point[k]-rows[k][3] for k in range(3))
    local_point = tuple(_rs_cut_dot(r, delta) for r in inv)
    local_normal = _rs_cut_unit(tuple(sum(a[j][i]*normal[j] for j in range(3)) for i in range(3)))
    if any(not _rs_cut_math.isfinite(x) for x in local_point):
        raise ValueError("Plane is outside finite object coordinates")
    return local_point, local_normal


def _rs_cut_cross2(a, b, c):
    return (b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0])


def _rs_cut_on2(p, a, b, eps):
    return (abs(_rs_cut_cross2(a, b, p)) <= eps*max(eps, _rs_cut_math.dist(a, b)) and
            all(min(a[k], b[k])-eps <= p[k] <= max(a[k], b[k])+eps for k in range(2)))


def _rs_cut_hit2(a, b, c, d, eps):
    if any(_rs_cut_on2(p, u, v, eps) for p, u, v in ((a, c, d), (b, c, d), (c, a, b), (d, a, b))):
        return True
    x, y = _rs_cut_cross2(a, b, c), _rs_cut_cross2(a, b, d)
    z, w = _rs_cut_cross2(c, d, a), _rs_cut_cross2(c, d, b)
    return (x > 0) != (y > 0) and (z > 0) != (w > 0)


def _rs_cut_inside2(p, ring):
    inside = False
    for a, b in zip(ring, ring[1:]+ring[:1]):
        if (a[1] > p[1]) != (b[1] > p[1]):
            if p[0] < a[0]+(p[1]-a[1])*(b[0]-a[0])/(b[1]-a[1]):
                inside = not inside
    return inside


def _rs_cut_loops(edges):
    adjacency = {}
    for u, v in edges:
        if u == v or v in adjacency.get(u, ()):
            raise ValueError("Degenerate or duplicated cut edge")
        adjacency.setdefault(u, []).append(v)
        adjacency.setdefault(v, []).append(u)
    if not adjacency or any(len(v) != 2 for v in adjacency.values()):
        raise ValueError("New cut must form simple closed loops without branches")
    remaining, loops = set(adjacency), []
    while remaining:
        start, previous, loop = min(remaining), None, []
        at = start
        while at in remaining:
            remaining.remove(at)
            loop.append(at)
            other = next(v for v in adjacency[at] if v != previous)
            previous, at = at, other
        if at != start or not 3 <= len(loop) <= 512:
            raise ValueError("Each new cap must be a simple 3..512 vertex ring")
        loops.append(loop)
    if len(loops) > 8 or sum(map(len, loops)) > 1024:
        raise ValueError("Cut exceeds 8 loops or 1024 total rim vertices")
    return loops


def _rs_cut_caps(points, loops, normal, eps, check=None):
    """Validate nonnested plane rings and ear-clip them with outward winding."""
    axis = tuple(float(k == min(range(3), key=lambda i: abs(normal[i]))) for k in range(3))
    u = _rs_cut_unit(_rs_cut_cross(axis, normal))
    v = _rs_cut_cross(normal, u)
    origin = points[loops[0][0]]
    flat = {i: (_rs_cut_dot(_rs_cut_sub(p, origin), u), _rs_cut_dot(_rs_cut_sub(p, origin), v))
            for ring in loops for i in ring for p in (points[i],)}
    rings, triangles, work = [], [], 0

    def budget():
        nonlocal work
        work += 1
        if work > 2000000:
            raise ValueError("Cap validation exceeds bounded work budget")
        if work % 2048 == 0:
            _rs_cut_pulse(check)

    for ring in loops:
        ring = list(ring)
        if len(set(ring)) != len(ring):
            raise ValueError("Self-touching cap ring")
        coords = [flat[i] for i in ring]
        for i, a in enumerate(coords):
            b = coords[(i+1) % len(coords)]
            if _rs_cut_math.dist(a, b) <= eps:
                raise ValueError("Zero-length cap edge")
            prev = coords[i-1]
            if (_rs_cut_on2(b, prev, a, eps) or _rs_cut_on2(prev, a, b, eps)):
                raise ValueError("Backtracking or overlapping cap edges")
            for j in range(i+1, len(coords)):
                budget()
                if j != i+1 and not (i == 0 and j == len(coords)-1):
                    if _rs_cut_hit2(a, b, coords[j], coords[(j+1) % len(coords)], eps):
                        raise ValueError("Self-crossing or self-touching cap")
        area = sum(a[0]*b[1]-a[1]*b[0] for a, b in zip(coords, coords[1:]+coords[:1]))
        perimeter = sum(_rs_cut_math.dist(a, b) for a, b in zip(coords, coords[1:]+coords[:1]))
        if abs(area) <= eps*perimeter:
            raise ValueError("Degenerate cap area")
        if area < 0:
            ring.reverse()
        rings.append(ring)
    for ri, ring in enumerate(rings):
        coords = [flat[i] for i in ring]
        for other in rings[ri+1:]:
            other_coords = [flat[i] for i in other]
            for a, b in zip(coords, coords[1:]+coords[:1]):
                for c, d in zip(other_coords, other_coords[1:]+other_coords[:1]):
                    budget()
                    if _rs_cut_hit2(a, b, c, d, eps):
                        raise ValueError("Crossing or touching caps are ambiguous")
            if _rs_cut_inside2(coords[0], other_coords) or _rs_cut_inside2(other_coords[0], coords):
                raise ValueError("Nested caps/holes are unsupported")
        left, added = list(ring), []
        while len(left) > 3:
            for k, at in enumerate(left):
                before, after = left[k-1], left[(k+1) % len(left)]
                tri = (flat[before], flat[at], flat[after])
                tol = eps*max(eps, *(_rs_cut_math.dist(x, y) for x, y in zip(tri, tri[1:]+tri[:1])))
                if _rs_cut_cross2(*tri) <= tol:
                    continue
                blocked = False
                for test in left:
                    budget()
                    if test not in (before, at, after) and all(
                            _rs_cut_cross2(x, y, flat[test]) >= -tol for x, y in zip(tri, tri[1:]+tri[:1])):
                        blocked = True
                        break
                if not blocked:
                    added.append((before, at, after))
                    left.pop(k)
                    break
            else:
                raise ValueError("Ambiguous cap triangulation")
        final = [flat[i] for i in left]
        if _rs_cut_cross2(*final) <= eps*max(eps, *(_rs_cut_math.dist(x, y) for x, y in zip(final, final[1:]+final[:1]))):
            raise ValueError("Degenerate final cap triangle")
        added.append(tuple(left))
        triangles.extend((tri, ri) for tri in added)
    return {"rings": rings, "triangles": triangles, "flat": flat}


def _rs_cut_preflight(points, faces, edges, point, normal, keep, check=None):
    if not 1 <= len(faces) <= 200000 or len(points) > 1000000 or sum(map(len, faces)) > 1000000 or len(edges) > 1000000:
        raise ValueError("Mesh exceeds 200000 faces / 1000000 vertices, edges or corners")
    if any(len(p) != 3 or any(not _rs_cut_math.isfinite(x) for x in p) for p in points):
        raise ValueError("Mesh has nonfinite coordinates")
    extent = max(max(p[k] for p in points)-min(p[k] for p in points) for k in range(3))
    eps = max(1e-8, extent*1e-7, max(abs(x) for p in points for x in p)*1e-7)
    distances = [_rs_cut_dot(_rs_cut_sub(p, point), normal) for p in points]
    if any(abs(d) <= eps for d in distances):
        raise ValueError("Plane touches existing vertices/edges; move the plane slightly")
    sign = 1 if keep == "front" else -1
    retained = [d*sign > eps for d in distances]
    if all(retained):
        raise ValueError("No-op cut: the entire mesh is already on the kept side")
    if not any(retained):
        raise ValueError("Cut would remove the entire mesh")
    crossing, removed, incidence, touched = [], [], {}, set()
    cut_edges, links = {}, []
    for fi, face in enumerate(faces):
        if fi % 2048 == 0:
            _rs_cut_pulse(check)
        if len(face) < 3 or len(set(face)) != len(face) or any(type(i) is not int or not 0 <= i < len(points) for i in face):
            raise ValueError("Degenerate or invalid source face")
        uses = [(a, b) for a, b in zip(face, face[1:]+face[:1])]
        for a, b in uses:
            incidence.setdefault(tuple(sorted((a, b))), []).append((fi, a, b))
        sides = [retained[i] for i in face]
        if not all(sides):
            removed.append(fi)
        if not any(sides) or all(sides):
            continue
        if len(face) > 256:
            raise ValueError("Crossed polygon exceeds 256 corners; triangulate it first")
        crossing.append(fi)
        touched.update(face)
        hits = []
        for a, b in uses:
            if retained[a] != retained[b]:
                edge = tuple(sorted((a, b)))
                cut_edges.setdefault(edge, len(cut_edges))
                hits.append(cut_edges[edge])
        if len(hits) != 2:
            raise ValueError("A crossed polygon has ambiguous multiple plane crossings")
        # BMesh can split convex planar polygons without guessing a folded fill.
        polygon = [points[i] for i in face]
        base = polygon[0]
        n = _rs_cut_unit(tuple(sum(_rs_cut_cross(_rs_cut_sub(a, base), _rs_cut_sub(b, base))[k]
                                     for a, b in zip(polygon, polygon[1:]+polygon[:1])) for k in range(3)))
        if any(abs(_rs_cut_dot(_rs_cut_sub(p, base), n)) > eps*4 for p in polygon):
            raise ValueError("Crossed nonplanar polygon; triangulate it first")
        if any(_rs_cut_dot(_rs_cut_cross(_rs_cut_sub(b, a), _rs_cut_sub(c, b)), n) < -eps*extent
               for a, b, c in zip(polygon, polygon[1:]+polygon[:1], polygon[2:]+polygon[:2])):
            raise ValueError("Crossed concave polygon; triangulate it first")
        links.append(tuple(hits))
        if len(cut_edges)*6+len(crossing)*3 > 8192:
            raise ValueError("Cut exceeds the 8192 new-geometry preflight budget")
    if not crossing:
        raise ValueError("No actual plane intersection; detached-component removal is unsupported")
    for edge in edges:
        if len(edge) != 2 or any(type(i) is not int or not 0 <= i < len(points) for i in edge):
            raise ValueError("Invalid source edge")
        key = tuple(sorted(edge))
        if set(edge) & touched:
            uses = incidence.get(key, [])
            if len(uses) != 2 or uses[0][1:] != tuple(reversed(uses[1][1:])):
                raise ValueError("Cut region touches an open/nonmanifold or inconsistently wound edge")
    fans = {i: {} for i in touched}
    for fi, face in enumerate(faces):
        if fi % 4096 == 0:
            _rs_cut_pulse(check)
        for k, at in enumerate(face):
            if at in fans:
                a, b = face[k-1], face[(k+1) % len(face)]
                fans[at].setdefault(a, []).append(b)
                fans[at].setdefault(b, []).append(a)
    for fan in fans.values():
        if not fan or any(len(ns) != 2 for ns in fan.values()):
            raise ValueError("Nonmanifold vertex fan near the cut")
        seen, todo = set(), [next(iter(fan))]
        while todo:
            at = todo.pop()
            if at not in seen:
                seen.add(at)
                todo.extend(fan[at])
        if len(seen) != len(fan):
            raise ValueError("Disconnected/bowtie vertex fan near the cut")
    intersection = [None]*len(cut_edges)
    for (a, b), i in cut_edges.items():
        t = distances[a]/(distances[a]-distances[b])
        intersection[i] = tuple(points[a][k]+t*(points[b][k]-points[a][k]) for k in range(3))
    loops = _rs_cut_loops(links)
    outward = tuple(-sign*x for x in normal)
    _rs_cut_caps(intersection, loops, outward, eps, check)
    return {"epsilon": eps, "distances": distances, "retained": retained, "crossing": crossing,
            "removed": removed, "cutEdges": cut_edges, "loopCount": len(loops), "outward": outward}


def _rs_cut_active(owner):
    data = getattr(owner, "animation_data", None)
    return bool(data and (data.action or data.drivers or (getattr(data, "use_nla", True) and any(
        not t.mute and len(t.strips) for t in data.nla_tracks))))


def _rs_cut_guard(ob, bake=False):
    import bpy
    if ob.type != "MESH" or ob.mode != "OBJECT" or bpy.context.mode != "OBJECT":
        raise ValueError("Plane cutting needs a mesh and an Object-mode scene")
    for owner in (ob, ob.data):
        if owner.library or owner.override_library or not owner.is_editable:
            raise ValueError("Linked/library override data is unsupported")
        if _rs_cut_active(owner):
            raise ValueError("Actively animated meshes are unsupported for plane cutting")
    if ob.constraints or ob.parent_type == "BONE":
        raise ValueError("Constrained or bone-parented meshes are unsupported; use a rest copy")
    rigs = set()
    parent = ob.parent
    while parent is not None:
        if _rs_cut_active(parent) or parent.constraints:
            raise ValueError("An animated/constrained parent makes the world plane unsafe")
        if parent.type == "ARMATURE":
            rigs.add(parent)
        parent = parent.parent
    keys = ob.data.shape_keys
    if keys is not None:
        if not bake:
            raise ValueError("Shape keys require explicit bakeMorphs:true on the private cut copy")
        if keys.library or keys.override_library or _rs_cut_active(keys):
            raise ValueError("Linked or actively animated shape keys are unsupported")
        if sum(len(k.data) for k in keys.key_blocks) > 4000000:
            raise ValueError("Shape-key baking exceeds 4000000 coordinates")
    if ob.data.attributes.get(".rs_cut_normals_v1") is not None:
        raise ValueError("Reserved private cut-normal attribute already exists")
    if len(ob.data.materials) >= 32767:
        raise ValueError("No material slot remains for the cut cap")
    for mod in ob.modifiers:
        if mod.type != "ARMATURE":
            raise ValueError("Unsupported modifier for an exact cut preview: " + mod.type)
        arm = mod.object
        if arm is None or arm.type != "ARMATURE":
            raise ValueError("Armature modifier has no valid rest rig")
        rigs.add(arm)
    for arm in rigs:
        if arm.library or arm.override_library or arm.data.library or arm.data.override_library:
            raise ValueError("Linked/library override rigs are unsupported")
        if arm.mode != "OBJECT" or arm.constraints or _rs_cut_active(arm) or _rs_cut_active(arm.data):
            raise ValueError("Actively animated/constrained rigs are unsupported; prepare rest first")
        parent = arm.parent
        while parent is not None:
            if _rs_cut_active(parent) or parent.constraints:
                raise ValueError("Rig has an animated/constrained parent")
            parent = parent.parent
        for bone in arm.pose.bones:
            if bone.constraints or any(abs(bone.matrix_basis[i][j]-(1 if i == j else 0)) > 1e-6
                                       for i in range(4) for j in range(4)):
                raise ValueError("Posed rigs are unsupported; prepare rest first")
            if any(abs(bone.matrix[i][j]-bone.bone.matrix_local[i][j]) > 1e-5 for i in range(4) for j in range(4)):
                raise ValueError("Evaluated rig is not at rest")
    mesh = ob.data
    if not 1 <= len(mesh.polygons) <= 200000 or max(len(mesh.vertices), len(mesh.edges), len(mesh.loops)) > 1000000:
        raise ValueError("Mesh exceeds bounded plane-cut limits")


def _rs_cut_feed(h, value):
    payload = _rs_cut_json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf8")
    h.update(_rs_cut_struct.pack("<Q", len(payload)))
    h.update(payload)


def _rs_cut_id(value):
    return None if value is None else [value.name_full, int(value.as_pointer())]


def _rs_cut_custom(owner):
    def plain(value, depth=0):
        if depth > 16:
            raise ValueError("Custom properties exceed the digest nesting limit")
        if value is None or isinstance(value, (str, bool, int, float)):
            return value
        if hasattr(value, "to_dict"):
            value = value.to_dict()
        elif hasattr(value, "to_list"):
            value = value.to_list()
        if isinstance(value, dict):
            return {str(k): plain(v, depth+1) for k, v in value.items()}
        if isinstance(value, (tuple, list, bytes)):
            return [plain(v, depth+1) for v in value]
        if hasattr(value, "as_pointer") and hasattr(value, "name_full"):
            return {"ID": _rs_cut_id(value)}
        raise ValueError("Unsupported custom property in the source digest")
    return {str(k): plain(owner[k]) for k in owner.keys()}


def _rs_cut_props(owner):
    out = {}
    for prop in owner.bl_rna.properties:
        name = prop.identifier
        if name in {"rna_type", "users", "is_updated", "is_updated_data", "is_evaluated",
                    "is_runtime_data", "is_missing", "is_library_indirect", "session_uid", "tag"} or prop.type in ("COLLECTION", "POINTER"):
            continue
        if prop.type in ("BOOLEAN", "INT", "FLOAT", "STRING", "ENUM"):
            value = getattr(owner, name)
            if getattr(prop, "is_array", False):
                value = list(value)
            elif isinstance(value, set):
                value = sorted(value)
            out[name] = value
    return out


def _rs_cut_bulk(h, collection, name, kind, width, check):
    _rs_cut_pulse(check)
    values = _rs_cut_array.array(kind, [0])*(len(collection)*width)
    collection.foreach_get(name, values)
    _rs_cut_feed(h, [name, kind, width, len(collection)])
    h.update(values.tobytes())


def _rs_cut_mesh_hash(mesh, check):
    """All stored geometry, custom attribute values, UVs, weights and morph data."""
    h = _rs_cut_hashlib.sha256(b"RiggerSet/plane-cut/mesh/v1\0")
    _rs_cut_feed(h, _rs_cut_props(mesh))
    _rs_cut_feed(h, _rs_cut_custom(mesh))
    for coll, spec in ((mesh.vertices, (("co", "f", 3), ("select", "b", 1), ("hide", "b", 1))),
                       (mesh.edges, (("vertices", "i", 2), ("use_seam", "b", 1), ("use_edge_sharp", "b", 1),
                                     ("select", "b", 1), ("hide", "b", 1))),
                       (mesh.loops, (("vertex_index", "i", 1), ("edge_index", "i", 1))),
                       (mesh.polygons, (("loop_start", "i", 1), ("loop_total", "i", 1),
                                        ("material_index", "i", 1), ("use_smooth", "b", 1),
                                        ("select", "b", 1), ("hide", "b", 1)))):
        for name, kind, width in spec:
            _rs_cut_bulk(h, coll, name, kind, width, check)
    total_values = 0
    for attr in mesh.attributes:
        _rs_cut_feed(h, [attr.name, attr.domain, attr.data_type, len(attr.data)])
        if not attr.data:
            continue
        for prop in attr.data[0].bl_rna.properties:
            if prop.identifier == "rna_type":
                continue
            width = prop.array_length if getattr(prop, "is_array", False) else 1
            total_values += len(attr.data)*width
            if total_values > 32000000:
                raise ValueError("Mesh attributes exceed the 32000000-value digest budget")
            if prop.type in ("FLOAT", "INT", "BOOLEAN"):
                _rs_cut_bulk(h, attr.data, prop.identifier, {"FLOAT": "f", "INT": "i", "BOOLEAN": "b"}[prop.type], width, check)
            elif prop.type == "STRING":
                for i, item in enumerate(attr.data):
                    if i % 2048 == 0:
                        _rs_cut_pulse(check)
                    value = getattr(item, prop.identifier)
                    _rs_cut_feed(h, list(value) if isinstance(value, bytes) else value)
            else:
                raise ValueError("Unsupported attribute for a complete source digest: " + attr.name)
    for uv in mesh.uv_layers:
        _rs_cut_feed(h, _rs_cut_props(uv))
        for name, width, kind in (("uv", 2, "f"), ("pin_uv", 1, "b"), ("select", 1, "b"), ("select_edge", 1, "b")):
            if len(uv.data) and hasattr(uv.data[0], name):
                _rs_cut_bulk(h, uv.data, name, kind, width, check)
    if getattr(mesh, "has_custom_normals", False):
        if hasattr(mesh, "corner_normals"):
            _rs_cut_bulk(h, mesh.corner_normals, "vector", "f", 3, check)
        else:
            mesh.calc_normals_split()
            _rs_cut_bulk(h, mesh.loops, "normal", "f", 3, check)
    for i, vertex in enumerate(mesh.vertices):
        if i % 2048 == 0:
            _rs_cut_pulse(check)
        _rs_cut_feed(h, [(g.group, g.weight) for g in vertex.groups])
    _rs_cut_feed(h, [_rs_cut_id(m) for m in mesh.materials])
    keys = mesh.shape_keys
    _rs_cut_feed(h, _rs_cut_id(keys))
    if keys is not None:
        _rs_cut_feed(h, _rs_cut_props(keys))
        _rs_cut_feed(h, _rs_cut_custom(keys))
        for key in keys.key_blocks:
            _rs_cut_feed(h, [_rs_cut_props(key), key.relative_key.name if key.relative_key else None])
            _rs_cut_bulk(h, key.data, "co", "f", 3, check)
    return h.hexdigest()


def _rs_cut_source_hash(ob, check):
    h = _rs_cut_hashlib.sha256(b"RiggerSet/plane-cut/source/v1\0")
    _rs_cut_feed(h, [_rs_cut_id(ob), _rs_cut_id(ob.data), _rs_cut_mesh_hash(ob.data, check),
                     [list(r) for r in ob.matrix_world], ob.active_shape_key_index, ob.show_only_shape_key,
                     _rs_cut_custom(ob),
                     [_rs_cut_props(g) for g in ob.vertex_groups],
                     [(s.link, _rs_cut_id(s.material)) for s in ob.material_slots]])
    parent = ob.parent
    while parent is not None:
        _rs_cut_feed(h, [_rs_cut_id(parent), [list(r) for r in parent.matrix_world]])
        if parent.type == "ARMATURE":
            _rs_cut_feed(h, [parent.data.pose_position,
                [(b.name, [list(r) for r in b.matrix], [list(r) for r in b.bone.matrix_local]) for b in parent.pose.bones]])
        parent = parent.parent
    for mod in ob.modifiers:
        _rs_cut_feed(h, [_rs_cut_props(mod), _rs_cut_id(mod.object)])
        arm = mod.object
        _rs_cut_feed(h, [[list(r) for r in arm.matrix_world], arm.data.pose_position,
                        [(b.name, [list(r) for r in b.matrix], [list(r) for r in b.bone.matrix_local]) for b in arm.pose.bones]])
    return h.hexdigest()


def _rs_cut_forget(key):
    import bpy
    item = _rs_cut_plans.pop(key, None)
    if not item:
        return
    try:
        if item["mesh"].users == 0:
            bpy.data.meshes.remove(item["mesh"])
        if item["material"].users == 0:
            bpy.data.materials.remove(item["material"])
    except ReferenceError:
        pass  # A checkpoint reload has already disposed of the private IDs.


def _rs_cut_prune():
    for key, value in list(_rs_cut_plans.items()):
        if value["revision"] != _RS_REV:
            _rs_cut_forget(key)


def _rs_cut_bake_copy(ob, check):
    """Bake Blender's evaluated current mix, including masks/absolute keys."""
    import bpy
    stage = ob.data.copy()
    duplicate = None
    try:
        if ob.data.shape_keys is not None:
            _rs_cut_pulse(check)
            graph = bpy.context.evaluated_depsgraph_get()
            evaluated = ob.evaluated_get(graph)
            mixed = evaluated.to_mesh(preserve_all_data_layers=True, depsgraph=graph)
            try:
                if mixed is None or (len(mixed.vertices), len(mixed.edges), len(mixed.loops), len(mixed.polygons)) != (
                        len(stage.vertices), len(stage.edges), len(stage.loops), len(stage.polygons)):
                    raise ValueError("Current shape mix changed topology")
                if any(tuple(p.vertices) != tuple(q.vertices) for p, q in zip(mixed.polygons, stage.polygons)):
                    raise ValueError("Current shape mix changed face connectivity")
                positions = _rs_cut_array.array("f", [0])*(len(mixed.vertices)*3)
                mixed.vertices.foreach_get("co", positions)
            finally:
                evaluated.to_mesh_clear()
            if stage.shape_keys is ob.data.shape_keys or (stage.shape_keys and stage.shape_keys.as_pointer() == ob.data.shape_keys.as_pointer()):
                raise ValueError("Cannot safely isolate the original shape-key datablock")
            duplicate = bpy.data.objects.new("RiggerSet private morph bake", stage)
            duplicate.shape_key_clear()
            stage.vertices.foreach_set("co", positions)
            stage.update()
            _rs_cut_pulse(check)
        return stage
    except Exception:
        if duplicate is not None:
            bpy.data.objects.remove(duplicate, do_unlink=True)
            duplicate = None
        if stage.users == 0:
            bpy.data.meshes.remove(stage)
        raise
    finally:
        if duplicate is not None:
            bpy.data.objects.remove(duplicate, do_unlink=True)


def _rs_cut_build(ob, args, check):
    import bpy
    import bmesh
    stage = _rs_cut_bake_copy(ob, check)
    bm, material, success = bmesh.new(), None, False
    try:
        points = [tuple(v.co) for v in stage.vertices]
        faces = [tuple(p.vertices) for p in stage.polygons]
        edges = [tuple(e.vertices) for e in stage.edges]
        point, normal = _rs_cut_local_plane(ob.matrix_world, args["planePoint"], args["planeNormal"])
        pre = _rs_cut_preflight(points, faces, edges, point, normal, args["keep"], check)
        uv_names = [uv.name for uv in stage.uv_layers]
        old_weights = [tuple((g.group, g.weight) for g in v.groups) for v in stage.vertices]
        unchanged = set(range(len(faces))) - set(pre["removed"])
        old_uv = {fi: [[tuple(stage.uv_layers[name].data[li].uv) for name in uv_names]
                       for li in stage.polygons[fi].loop_indices] for fi in unchanged}
        old_faces = {fi: (stage.polygons[fi].material_index, stage.polygons[fi].use_smooth) for fi in unchanged}
        bm.from_mesh(stage)
        bm.verts.ensure_lookup_table()
        bm.faces.ensure_lookup_table()
        originals = {v: i for i, v in enumerate(bm.verts)}
        original_edges = set(bm.edges)
        original_faces = {f: i for i, f in enumerate(bm.faces) if i in unchanged}
        normal_layer = None
        if getattr(stage, "has_custom_normals", False):
            if hasattr(stage, "corner_normals"):
                normals = [tuple(n.vector) for n in stage.corner_normals]
            else:
                stage.calc_normals_split()
                normals = [tuple(loop.normal) for loop in stage.loops]
            normal_layer = bm.loops.layers.float_vector.new(".rs_cut_normals_v1")
            for fi, face in enumerate(bm.faces):
                by_vertex = {vi: normals[li] for vi, li in zip(stage.polygons[fi].vertices, stage.polygons[fi].loop_indices)}
                for loop in face.loops:
                    loop[normal_layer] = by_vertex[originals[loop.vert]]
        _rs_cut_pulse(check)
        result = bmesh.ops.bisect_plane(bm, geom=list(bm.verts)+list(bm.edges)+list(bm.faces),
                    dist=pre["epsilon"], plane_co=point, plane_no=normal,
                    clear_inner=args["keep"] == "front", clear_outer=args["keep"] == "back")
        _rs_cut_pulse(check)
        bm.verts.index_update()
        bm.verts.ensure_lookup_table()
        rim = [e for e in result["geom_cut"] if isinstance(e, bmesh.types.BMEdge) and e.is_valid and e.is_boundary]
        all_plane_edges = {e for e in bm.edges if e.is_boundary and all(
            abs(_rs_cut_dot(_rs_cut_sub(v.co, point), normal)) <= pre["epsilon"]*4 for v in e.verts)}
        if set(rim) != all_plane_edges or any(v in originals for e in rim for v in e.verts):
            raise ValueError("Bisect did not isolate only new cut boundary edges")
        if len({v for v in bm.verts if v not in originals}) != len(pre["cutEdges"]):
            raise ValueError("Bisect produced unexpected intersection vertices")
        loops = _rs_cut_loops([tuple(v.index for v in e.verts) for e in rim])
        if len(loops) != pre["loopCount"]:
            raise ValueError("Bisect changed the planned number of cut loops")
        cap = _rs_cut_caps([tuple(v.co) for v in bm.verts], loops, pre["outward"], pre["epsilon"], check)
        material = bpy.data.materials.new("RiggerSet cut cap")
        material.diffuse_color = (.32, .38, .44, 1)
        stage.materials.append(material)
        cap_slot = len(stage.materials)-1
        if not uv_names:
            bm.loops.layers.uv.new("RiggerSet cut UV")
        uv_layers = list(bm.loops.layers.uv.values())
        caps = []
        for number, (tri, ri) in enumerate(cap["triangles"]):
            if number % 64 == 0:
                _rs_cut_pulse(check)
            face = bm.faces.new([bm.verts[i] for i in tri])
            face.material_index, face.smooth = cap_slot, False
            coords = [cap["flat"][i] for i in cap["rings"][ri]]
            low = tuple(min(p[k] for p in coords) for k in range(2))
            span = max(max(p[k] for p in coords)-low[k] for k in range(2))
            for loop in face.loops:
                flat = cap["flat"][loop.vert.index]
                for layer in uv_layers:
                    loop[layer].uv = tuple((flat[k]-low[k])/span for k in range(2))
            caps.append(face)
        bm.normal_update()
        if any(not e.is_manifold or not e.is_contiguous for e in rim):
            raise ValueError("Cap failed exact manifold closure/opposite edge winding")
        if any(_rs_cut_dot(f.normal, pre["outward"]) < .999 for f in caps):
            raise ValueError("Cap winding does not face the removed half-space")
        if (sum(v not in originals for v in bm.verts)+sum(e not in original_edges for e in bm.edges)+
                sum(f not in original_faces for f in bm.faces)) > 8192:
            raise ValueError("Result exceeds 8192 new/changed geometry elements")
        if any(_rs_cut_dot(_rs_cut_sub(v.co, point), normal)*(1 if args["keep"] == "front" else -1) < -pre["epsilon"]*4 for v in bm.verts):
            raise ValueError("Bisect retained geometry on the wrong side")
        bm.verts.index_update()
        bm.faces.index_update()
        original_by_new = [originals.get(v, -1) for v in bm.verts]
        face_by_new = [original_faces.get(f, -1) for f in bm.faces]
        if {i for i in original_by_new if i >= 0} != {i for i, kept in enumerate(pre["retained"]) if kept}:
            raise ValueError("Bisect changed unrelated surviving vertex incidence")
        output_normals = None
        if normal_layer is not None:
            cap_set = set(caps)
            output_normals = []
            for face in bm.faces:
                for loop in face.loops:
                    value = tuple(face.normal) if face in cap_set else tuple(loop[normal_layer])
                    output_normals.append(_rs_cut_unit(value) if _rs_cut_math.hypot(*value) > 1e-20 else tuple(face.normal))
            bm.loops.layers.float_vector.remove(normal_layer)
        bm.to_mesh(stage)
        stage.update()
        if output_normals is not None:
            stage.normals_split_custom_set(output_normals)
            stage.update()
        if not stage.polygons or not len(caps):
            raise ValueError("Empty or uncapped plane-cut result")
        if [layer.name for layer in stage.uv_layers][:len(uv_names)] != uv_names:
            raise ValueError("Bisect changed source UV layer order")
        if list(stage.materials)[:-1] != list(ob.data.materials):
            raise ValueError("Bisect changed source material slots")
        for i, vertex in enumerate(stage.vertices):
            vi = original_by_new[i]
            if vi >= 0 and (tuple(vertex.co) != points[vi] or tuple((g.group, g.weight) for g in vertex.groups) != old_weights[vi]):
                raise ValueError("Bisect changed a surviving coordinate or skin weight")
        seen = set()
        for i, poly in enumerate(stage.polygons):
            fi = face_by_new[i]
            if fi < 0:
                continue
            seen.add(fi)
            before = [(vi, old_uv[fi][k]) for k, vi in enumerate(faces[fi])]
            after = [(original_by_new[vi], [tuple(stage.uv_layers[name].data[li].uv) for name in uv_names])
                     for vi, li in zip(poly.vertices, poly.loop_indices)]
            if (len(before) != len(after) or not any(after == before[k:]+before[:k] for k in range(len(before))) or
                    (poly.material_index, poly.use_smooth) != old_faces[fi]):
                raise ValueError("Bisect changed an untouched polygon, UV or material")
        if seen != unchanged:
            raise ValueError("Bisect removed an unrelated retained face")
        _rs_cut_pulse(check)
        success = True
        return stage, material, {"removedFaces": len(pre["removed"]),
            "addedFaces": len(stage.polygons)-len(unchanged), "cutLoops": len(loops),
            "morphsBaked": ob.data.shape_keys is not None}
    finally:
        bm.free()
        if not success:
            if stage.users == 0:
                bpy.data.meshes.remove(stage)
            if material is not None and material.users == 0:
                bpy.data.materials.remove(material)


def _rs_cut_plan(a):
    import bpy
    _rs_cut_prune()
    key = _rs_cut_secrets.token_hex(12)
    public = {"object": a.get("object", "") if isinstance(a, dict) else "", "previewId": key,
              "digest": _rs_cut_hashlib.sha256(b"refused-plane-cut").hexdigest(), "canApply": False,
              "removedFaces": 0, "addedFaces": 0, "cutLoops": 0, "morphsBaked": False}
    check, stage, material, cached = _rs_cut_check_context(), None, None, False
    revision = _RS_REV
    try:
        args = _rs_cut_args(a)
        ob = _rs_obj(args["object"])
        _rs_cut_guard(ob, args["bakeMorphs"])
        source_hash = _rs_cut_source_hash(ob, check)
        public["digest"] = source_hash
        stage, material, summary = _rs_cut_build(ob, args, check)
        stage_hash = _rs_cut_mesh_hash(stage, check)
        digest = _rs_cut_hashlib.sha256((source_hash+stage_hash+
            _rs_cut_json.dumps(args, sort_keys=True, separators=(",", ":"))).encode()).hexdigest()
        if revision != _RS_REV or source_hash != _rs_cut_source_hash(ob, check):
            raise ValueError("Scene changed during plane-cut preview; preview again")
        public.update(summary, digest=digest, canApply=True)
        _rs_cut_plans[key] = {"object": ob, "source": ob.data, "sourceHash": source_hash,
            "mesh": stage, "material": material, "stageHash": stage_hash, "revision": revision,
            "args": args, "public": dict(public)}
        cached = True
        while len(_rs_cut_plans) > 4:
            _rs_cut_forget(next(iter(_rs_cut_plans)))
        return public
    except _rs_cut_Interrupted:
        raise
    except ValueError as error:
        public["reason"] = str(error)[:400]
        return public
    finally:
        if not cached:
            if stage is not None and stage.users == 0:
                bpy.data.meshes.remove(stage)
            if material is not None and material.users == 0:
                bpy.data.materials.remove(material)


def _rs_cut_get(key, object_name, check):
    _rs_cut_prune()
    if not isinstance(key, str) or key not in _rs_cut_plans:
        raise ValueError("Plane-cut preview expired; preview again")
    item = _rs_cut_plans[key]
    try:
        ob = item["object"]
        if object_name is not None and object_name != item["public"]["object"]:
            raise ValueError("Plane-cut preview belongs to another mesh")
        if _rs_obj(item["public"]["object"]) != ob or ob.data != item["source"]:
            raise ValueError("Plane-cut source changed; preview again")
        _rs_cut_guard(ob, item["args"]["bakeMorphs"])
        if _rs_cut_source_hash(ob, check) != item["sourceHash"]:
            raise ValueError("Stale source digest; preview the plane cut again")
        if _rs_cut_mesh_hash(item["mesh"], check) != item["stageHash"]:
            raise ValueError("Staged mesh digest changed; preview again")
        if item["revision"] != _RS_REV:
            raise ValueError("Scene revision changed; preview again")
        return item
    except (ValueError, ReferenceError):
        _rs_cut_forget(key)
        raise


def _rs_cut_apply(a):
    if not isinstance(a, dict) or set(a) != {"object", "previewId", "digest"}:
        raise ValueError("Apply requires object, previewId and digest")
    if (not isinstance(a["object"], str) or not a["object"] or
            not isinstance(a["digest"], str) or len(a["digest"]) != 64 or
            any(c not in "0123456789abcdef" for c in a["digest"])):
        raise ValueError("Apply requires a mesh name and a 64-character preview digest")
    check = _rs_cut_check_context()
    item = _rs_cut_get(a["previewId"], a["object"], check)
    if a["digest"] != item["public"]["digest"]:
        _rs_cut_forget(a["previewId"])
        raise ValueError("Plane-cut digest does not match this exact preview")
    ob, source = item["object"], item["source"]
    slots = [(slot.link, slot.material) for slot in ob.material_slots]
    _rs_cut_pulse(check)
    try:
        ob.data = item["mesh"]
        if [(s.link, s.material) for s in ob.material_slots][:len(slots)] != slots:
            raise ValueError("Mesh cut could not retain object material overrides")
        _rs_cut_pulse(check)
    except Exception:
        ob.data = source
        _rs_cut_forget(a["previewId"])
        raise
    result = {k: v for k, v in item["public"].items() if k not in ("canApply", "previewId", "digest")}
    result.update(changed="mesh.cut", preservedOutside=True)
    _rs_cut_forget(a["previewId"])
    return result


def _rs_cut_preview_file(previewId, target):
    import bpy
    check = _rs_cut_check_context()
    item = _rs_cut_get(previewId, None, check)
    source = item["object"]
    old_active = bpy.context.view_layer.objects.active
    old_selected = set(bpy.context.selected_objects)
    duplicate = mesh = None
    try:
        mesh = item["mesh"].copy()
        duplicate = source.copy()
        duplicate.data = mesh
        duplicate.name = "RiggerSet plane cut preview"
        duplicate["riggerset_source_object"] = source.name
        duplicate["riggerset_cut_preview"] = previewId
        duplicate.hide_render = duplicate.hide_viewport = False
        bpy.context.scene.collection.objects.link(duplicate)
        duplicate.hide_set(False)
        for ob in bpy.context.scene.objects:
            ob.select_set(False)
        for ob in bpy.context.scene.objects:
            if ob not in (source, duplicate) and ob.type in ("MESH", "ARMATURE", "EMPTY") and not ob.hide_render and not ob.hide_get():
                ob.select_set(True)
        duplicate.select_set(True)
        bpy.context.view_layer.objects.active = duplicate
        _rs_cut_pulse(check)
        status = bpy.ops.export_scene.gltf(filepath=target, export_format="GLB", use_selection=True,
                           export_animations=False, export_extras=True)
        if "FINISHED" not in status:
            raise ValueError("Plane-cut preview export did not finish")
        _rs_cut_pulse(check)
        return {"file": target, "previewId": previewId, "digest": item["public"]["digest"], "revision": _RS_REV}
    finally:
        if duplicate is not None:
            bpy.data.objects.remove(duplicate, do_unlink=True)
        if mesh is not None and mesh.users == 0:
            bpy.data.meshes.remove(mesh)
        for ob in bpy.context.scene.objects:
            ob.select_set(ob in old_selected)
        bpy.context.view_layer.objects.active = old_active


# SPDX-License-Identifier: GPL-3.0-or-later
"""Inline before the RiggerSet dispatcher. No registration, handlers or bpy ops.

Daemon dependencies: bpy, Vector, Matrix, _RS_REV, _rs_control, _rs_obj.
Only _rs_build and _rs_sculpt are public entry points. The dispatcher retains
admission/undo/revision authority. Tuple geometry helpers also run without bpy.
"""
import math as _rsb_math
import json as _rsb_json
import struct as _rsb_struct

_RSB_SHAPES = "riggerset_beginner_shapes_v1"
_RSB_MAX_VERTS = 250000
_RSB_MAX_AFFECTED = 10000
_RSB_SIDES = 12


def _rsb_add(a, b): return tuple(a[k] + b[k] for k in range(3))
def _rsb_sub(a, b): return tuple(a[k] - b[k] for k in range(3))
def _rsb_mul(a, s): return tuple(x * s for x in a)
def _rsb_dot(a, b): return sum(a[k] * b[k] for k in range(3))
def _rsb_cross(a, b):
    return (a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0])
def _rsb_length(a): return _rsb_math.sqrt(_rsb_dot(a, a))


def _rsb_unit(a):
    size = _rsb_length(a)
    if not _rsb_math.isfinite(size) or size < 1e-12:
        raise ValueError("Brush direction has zero or invalid length.")
    return _rsb_mul(a, 1.0 / size)


def _rsb_number(v, lo, hi, label):
    if isinstance(v, bool) or not isinstance(v, (int, float)) or not _rsb_math.isfinite(v) or not lo <= v <= hi:
        raise ValueError(label + " must be a finite number in " + str(lo) + ".." + str(hi) + ".")
    return float(v)


def _rsb_vec(v, label="Brush coordinate"):
    if not isinstance(v, (list, tuple)) or len(v) != 3:
        raise ValueError(label + " needs three finite world coordinates.")
    return tuple(_rsb_number(x, -1e7, 1e7, label) for x in v)


def _rsb_name(v, label):
    if not isinstance(v, str) or not 1 <= len(v) <= 120 or any(ord(c) < 32 for c in v):
        raise ValueError("Invalid " + label + ".")
    return v


def _rsb_args(a, sculpt=False):
    allowed = {"object", "points", "radiusWorld"} | ({"strength", "mode", "shapeName"} if sculpt else {"color", "attachToRig"})
    if not isinstance(a, dict) or set(a) - allowed:
        raise ValueError("Unknown brush parameter.")
    name = _rsb_name(a.get("object"), "object")
    radius = _rsb_number(a.get("radiusWorld"), 0.0001, 100, "radiusWorld")
    samples = a.get("points")
    if not isinstance(samples, list) or not 1 <= len(samples) <= 64:
        raise ValueError("A brush stroke needs 1..64 points.")
    points, normals = [], []
    for sample in samples:
        if not isinstance(sample, dict) or set(sample) != {"position", "normal"}:
            raise ValueError("Each point needs only position and normal in world space.")
        points.append(_rsb_vec(sample["position"]))
        normals.append(_rsb_unit(_rsb_vec(sample["normal"], "World normal")))
    if sculpt:
        _rsb_number(a.get("strength"), 0.01, 1, "strength")
        if a.get("mode") not in ("raise", "lower", "smooth"):
            raise ValueError("Shape mode must be raise, lower or smooth.")
        shape = _rsb_name(a.get("shapeName", "Shape edit"), "shape name")
        if len(shape.encode("utf-8")) > 48:
            raise ValueError("Use a shape name of at most 48 UTF-8 bytes to avoid Blender name truncation.")
    else:
        color = a.get("color")
        if not isinstance(color, (list, tuple)) or len(color) != 4:
            raise ValueError("Build color needs four RGBA values in 0..1.")
        for value in color: _rsb_number(value, 0, 1, "Color")
        if type(a.get("attachToRig", False)) is not bool:
            raise ValueError("attachToRig must be a boolean.")
    return name, points, normals, radius


def _rsb_ticket():
    return (_rs_control().get("epoch"), _RS_REV)


def _rsb_check(ticket):
    if _rs_control().get("epoch") != ticket[0]:
        raise ValueError("Brush command cancelled; partial brush changes were discarded.")
    if _RS_REV != ticket[1]:
        raise ValueError("Stale scene revision during brush work; retry against the current scene.")


def _rsb_no_animation(owner):
    data = getattr(owner, "animation_data", None)
    if data and (data.action or len(data.drivers) or (getattr(data, "use_nla", True) and any(not t.mute and len(t.strips) for t in data.nla_tracks))):
        raise ValueError("Brushes need a neutral, nonanimated object and rig. Use rig.rest for the rig; clear object/shape actions, drivers or active NLA on a working copy.")


def _rsb_chain(ob):
    seen, chain = set(), []
    while ob is not None:
        if ob in seen:
            raise ValueError("Unsupported cyclic parent hierarchy.")
        seen.add(ob); chain.append(ob)
        if len(chain) > 64:
            raise ValueError("Unsupported parent hierarchy deeper than 64 objects.")
        if ob.mode != "OBJECT":
            raise ValueError("Switch to Object Mode before brushing. Prepare a posed rig with rig.rest.")
        if ob.constraints or getattr(ob, "rigid_body", None):
            raise ValueError("Object constraints/physics are unsupported for brushes; use a neutral working copy.")
        if ob.parent and ob.parent_type != "OBJECT":
            raise ValueError("Bone/vertex parenting is unsupported for brushes; use ordinary object parenting and an Armature modifier.")
        _rsb_no_animation(ob)
        if getattr(ob, "data", None) is not None: _rsb_no_animation(ob.data)
        ob = ob.parent
    return chain


def _rsb_transform(ob):
    world = ob.matrix_world.copy()
    if any(not _rsb_math.isfinite(x) or abs(x) > 1e7 for row in world for x in row):
        raise ValueError("Move/scale the object into finite, bounded world coordinates before brushing.")
    linear = world.to_3x3()
    try: inverse = linear.inverted()
    except (ValueError, ZeroDivisionError):
        raise ValueError("Zero object scale is unsupported; restore nonzero scale before brushing.")
    norm = _rsb_math.sqrt(sum(x*x for row in linear for x in row))
    invnorm = _rsb_math.sqrt(sum(x*x for row in inverse for x in row))
    if not _rsb_math.isfinite(norm * invnorm) or norm * invnorm > 1e6 or norm > 1e6 or invnorm > 1e6:
        raise ValueError("Extreme or ill-conditioned object scale is unsupported; normalize scale on a working copy.")
    return world, linear, inverse


def _rsb_source(name, sculpt=False):
    ob = _rs_obj(name)
    if bpy.context.mode != "OBJECT" or ob.mode != "OBJECT":
        raise ValueError("Switch to Object Mode before brushing. Prepare a posed rig with rig.rest.")
    if ob.type != "MESH": raise ValueError("Choose an editable mesh for the brush.")
    mesh = ob.data
    if ob.library or mesh.library or getattr(ob, "override_library", None) or not getattr(ob, "is_editable", True) or not getattr(mesh, "is_editable", True):
        raise ValueError("Linked/overridden mesh data is unsupported; make a local working copy.")
    if ob.name not in bpy.context.view_layer.objects or not ob.visible_get():
        raise ValueError("Choose a visible mesh in the current view layer.")
    if not 1 <= len(mesh.vertices) <= _RSB_MAX_VERTS or len(mesh.edges) > 1000000 or len(mesh.loops) > 1500000:
        raise ValueError("Brush mesh must have 1..250000 vertices, at most 1000000 edges and 1500000 loops.")
    if sculpt and mesh.users != 1:
        raise ValueError("Shape brush needs single-user mesh data; make a single-user working copy.")
    if sculpt and ob.show_only_shape_key:
        raise ValueError("Disable Show Only Shape Key so the brush can use the current mixed shape.")
    chain = _rsb_chain(ob)
    arms = {p for p in chain if p.type == "ARMATURE"}
    mods = [m for m in ob.modifiers if m.show_viewport or m.show_render]
    if any(m.type != "ARMATURE" for m in mods):
        raise ValueError("Unsupported topology/deformation modifier. Apply or remove non-Armature modifiers on a working copy before brushing.")
    arm_mods = [m for m in ob.modifiers if m.type == "ARMATURE"]
    if len(arm_mods) > 1:
        raise ValueError("Multiple Armature modifiers are unsupported; use a single neutral rig.")
    for mod in arm_mods:
        if not mod.object or not mod.show_viewport or not mod.show_render or getattr(mod, "use_multi_modifier", False):
            raise ValueError("Enable one valid Armature modifier in viewport and render before brushing.")
        arms.add(mod.object)
    if len(arms) > 1: raise ValueError("Ambiguous multiple rigs; choose a mesh with one neutral rig.")
    arm = next(iter(arms), None)
    if arm is not None:
        _rsb_chain(arm)
        _rsb_transform(arm)
        if arm.type != "ARMATURE" or not 1 <= len(arm.data.bones) <= 256:
            raise ValueError("Brush binding supports a single armature with 1..256 bones.")
        for bone in arm.pose.bones:
            if bone.constraints:
                raise ValueError("Bone constraints are unsupported for brushes; use an unconstrained neutral rig copy.")
            if any(not _rsb_math.isfinite(bone.matrix_basis[i][j]) or abs(bone.matrix_basis[i][j] - float(i == j)) > 1e-6 for i in range(4) for j in range(4)) or any(not _rsb_math.isfinite(bone.matrix[i][j]) or abs(bone.matrix[i][j] - bone.bone.matrix_local[i][j]) > 1e-5 for i in range(4) for j in range(4)):
                raise ValueError("The rig is posed. Use rig.rest before starting a brush stroke.")
    keys = mesh.shape_keys
    if keys:
        _rsb_no_animation(keys)
        if not keys.use_relative: raise ValueError("Absolute shape keys are unsupported; use relative keys on a working copy.")
    world, linear, inverse = _rsb_transform(ob)
    return ob, arm, world, linear, inverse


def _rsb_mixed(ob, ticket):
    """Exact relative-key sum, including masks, without changing any key values.

    Non-Armature modifiers are refused and every rig is neutral, so this is the
    current pre-skin mesh. Relative-key dependencies use their stored coords,
    as Blender does; muted keys and masked zero weights do not contribute.
    """
    mesh, keys = ob.data, ob.data.shape_keys
    basis = keys.reference_key.data if keys else mesh.vertices
    positions = [tuple(v.co) for v in basis]
    active = [k for k in keys.key_blocks if k != keys.reference_key and not k.mute and k.value != 0] if keys else []
    if len(active) > 64:
        raise ValueError("More than 64 active shape keys is unsupported; simplify the mixed shape on a working copy.")
    masks = {}
    for key in active:
        if len(key.data) != len(positions) or not key.relative_key or len(key.relative_key.data) != len(positions) or not _rsb_math.isfinite(key.value):
            raise ValueError("Invalid relative shape-key topology/value.")
        group = ob.vertex_groups.get(key.vertex_group) if key.vertex_group else None
        mask = None
        if group:
            if group.index not in masks:
                masks[group.index] = [next((g.weight for g in v.groups if g.group == group.index), 0.0) for v in mesh.vertices]
            mask = masks[group.index]
        for i, point in enumerate(key.data):
            if i % 2048 == 0: _rsb_check(ticket)
            weight = key.value * (mask[i] if mask is not None else 1.0)
            ref = key.relative_key.data[i].co
            positions[i] = tuple(positions[i][k] + weight*(point.co[k]-ref[k]) for k in range(3))
    for i, p in enumerate(positions):
        if i % 2048 == 0: _rsb_check(ticket)
        if any(not _rsb_math.isfinite(x) or abs(x) > 1e7 for x in p):
            raise ValueError("Mesh/shape coordinates are nonfinite or outside the supported range.")
    return positions


def _rsb_world_offsets(local, linear, ticket):
    out = []
    for i, p in enumerate(local):
        if i % 1024 == 0: _rsb_check(ticket)
        q = tuple(linear @ Vector(p))
        if any(not _rsb_math.isfinite(x) or abs(x) > 1e7 for x in q):
            raise ValueError("World mesh extent is nonfinite or exceeds supported brush coordinates.")
        out.append(q)
    return out


def _rsb_bounds(points, samples, radius, build=False):
    low = tuple(min(p[k] for p in points) for k in range(3))
    high = tuple(max(p[k] for p in points) for k in range(3))
    extent = _rsb_length(_rsb_sub(high, low))
    if extent < 1e-8:
        raise ValueError("The source has no usable bounding extent.")
    if radius > max(0.0001, extent * 2):
        raise ValueError("Brush radius exceeds twice the source bounding diagonal; reduce the radius.")
    def distance(p):
        return _rsb_math.sqrt(sum(max(low[k]-p[k], 0, p[k]-high[k])**2 for k in range(3)))
    if distance(samples[0]) > max(radius*2, extent*.05):
        raise ValueError("Start the brush on or near the source bounds.")
    margin = max(extent*1.5, radius*4) if build else radius
    if any(distance(p) > margin for p in samples):
        raise ValueError("Brush points extend too far from the source bounding extent.")
    length = sum(_rsb_length(_rsb_sub(b, a)) for a, b in zip(samples, samples[1:]))
    if length > min(10000, max(extent*8, radius*32)):
        raise ValueError("Stroke length exceeds the bounded source-relative brush budget; split the stroke.")
    return extent


def _rsb_resample(points, radius):
    kept = [points[0]]
    for p in points[1:]:
        if _rsb_length(_rsb_sub(p, kept[-1])) > max(1e-10, radius*1e-5): kept.append(p)
    if len(kept) == 1: return kept
    lengths = [_rsb_length(_rsb_sub(b, a)) for a, b in zip(kept, kept[1:])]
    steps = [max(1, int(_rsb_math.ceil(d / (radius*.5)))) for d in lengths]
    if sum(steps) > 127:
        spare, total = 127 - len(lengths), sum(lengths)
        shares = [spare*d/total for d in lengths]
        steps = [1 + int(s) for s in shares]
        for i in sorted(range(len(steps)), key=lambda j: (-(shares[j] % 1), j))[:127-sum(steps)]: steps[i] += 1
    out = [kept[0]]
    for a, b, count in zip(kept, kept[1:], steps):
        for j in range(1, count+1): out.append(_rsb_add(a, _rsb_mul(_rsb_sub(b, a), j/count)))
    return out


def _rsb_frames(path, normal):
    directions = [_rsb_unit(_rsb_sub(b, a)) for a, b in zip(path, path[1:])]
    tangents = [directions[0]]
    for a, b in zip(directions, directions[1:]):
        if _rsb_dot(a, b) < -.98:
            raise ValueError("Tube stroke reverses too sharply; use separate strokes around a tight turn.")
        tangents.append(_rsb_unit(_rsb_add(a, b)))
    tangents.append(directions[-1])
    u = _rsb_sub(normal, _rsb_mul(tangents[0], _rsb_dot(normal, tangents[0])))
    if _rsb_length(u) < 1e-5:
        axis = tuple(float(k == min(range(3), key=lambda j: abs(tangents[0][j]))) for k in range(3))
        u = _rsb_cross(tangents[0], axis)
    u = _rsb_unit(u)
    frames = [(tangents[0], u, _rsb_cross(tangents[0], u))]
    for prev, tangent in zip(tangents, tangents[1:]):
        axis = _rsb_cross(prev, tangent)
        sine, cosine = _rsb_length(axis), max(-1.0, min(1.0, _rsb_dot(prev, tangent)))
        if sine > 1e-10:
            axis = _rsb_mul(axis, 1/sine)
            u = _rsb_add(_rsb_add(_rsb_mul(u, cosine), _rsb_mul(_rsb_cross(axis, u), sine)), _rsb_mul(axis, _rsb_dot(axis, u)*(1-cosine)))
        u = _rsb_unit(_rsb_sub(u, _rsb_mul(tangent, _rsb_dot(u, tangent))))
        frames.append((tangent, u, _rsb_cross(tangent, u)))
    return frames


def _rsb_geometry(points, normals, radius):
    """World-offset capsule sweep: <=128 path rings, 12 sides, round endcaps.

    Returns local coordinates around first sample, faces and per-loop UVs.
    Source intersections/self-overlap remain separate editable geometry.
    """
    anchor = points[0]
    path = _rsb_resample([_rsb_sub(p, anchor) for p in points], radius)
    rings = []
    if len(path) == 1:
        tangent = _rsb_unit(normals[0])
        axis = tuple(float(k == min(range(3), key=lambda j: abs(tangent[j]))) for k in range(3))
        u = _rsb_unit(_rsb_cross(tangent, axis)); v = _rsb_cross(tangent, u)
        start, end = _rsb_mul(tangent, -radius), _rsb_mul(tangent, radius)
        for j in range(1, 8):
            angle = j*_rsb_math.pi/8
            rings.append((_rsb_mul(tangent, -radius*_rsb_math.cos(angle)), radius*_rsb_math.sin(angle), u, v, j/8))
    else:
        frames = _rsb_frames(path, normals[0])
        distances = [0.0]
        for a, b in zip(path, path[1:]): distances.append(distances[-1] + _rsb_length(_rsb_sub(b, a)))
        total = distances[-1] + _rsb_math.pi*radius
        t0, u0, v0 = frames[0]; tn, un, vn = frames[-1]
        start = _rsb_sub(path[0], _rsb_mul(t0, radius)); end = _rsb_add(path[-1], _rsb_mul(tn, radius))
        for j in range(1, 4):
            angle = j*_rsb_math.pi/8
            rings.append((_rsb_sub(path[0], _rsb_mul(t0, radius*_rsb_math.cos(angle))), radius*_rsb_math.sin(angle), u0, v0, radius*angle/total))
        for p, (_t, u, v), d in zip(path, frames, distances): rings.append((p, radius, u, v, (radius*_rsb_math.pi/2+d)/total))
        for j in (3, 2, 1):
            angle = j*_rsb_math.pi/8
            rings.append((_rsb_add(path[-1], _rsb_mul(tn, radius*_rsb_math.cos(angle))), radius*_rsb_math.sin(angle), un, vn, (distances[-1]+radius*(_rsb_math.pi-angle))/total))
    vertices, faces, uv = [start], [], []
    for center, r, u, v, _vv in rings:
        for j in range(_RSB_SIDES):
            angle = 2*_rsb_math.pi*j/_RSB_SIDES
            vertices.append(_rsb_add(center, _rsb_add(_rsb_mul(u, r*_rsb_math.cos(angle)), _rsb_mul(v, r*_rsb_math.sin(angle)))))
    pole = len(vertices); vertices.append(end)
    for j in range(_RSB_SIDES):
        nxt = (j+1) % _RSB_SIDES
        faces.append((0, 1+nxt, 1+j))
        uv.append((((j+.5)/_RSB_SIDES, 0), ((j+1)/_RSB_SIDES, rings[0][4]), (j/_RSB_SIDES, rings[0][4])))
        for i in range(len(rings)-1):
            lo, hi = 1+i*_RSB_SIDES, 1+(i+1)*_RSB_SIDES
            faces.append((lo+j, lo+nxt, hi+nxt, hi+j))
            uv.append(((j/_RSB_SIDES, rings[i][4]), ((j+1)/_RSB_SIDES, rings[i][4]), ((j+1)/_RSB_SIDES, rings[i+1][4]), (j/_RSB_SIDES, rings[i+1][4])))
        lo = 1+(len(rings)-1)*_RSB_SIDES
        faces.append((lo+j, lo+nxt, pole))
        uv.append(((j/_RSB_SIDES, rings[-1][4]), ((j+1)/_RSB_SIDES, rings[-1][4]), ((j+.5)/_RSB_SIDES, 1)))
    return vertices, faces, uv, len(path)


def _rsb_segment_distance2(a, b, c, d):
    """Squared distance between finite segments (including a point segment)."""
    u, v, w = _rsb_sub(b, a), _rsb_sub(d, c), _rsb_sub(a, c)
    aa, bb, cc, dd, ee = _rsb_dot(u, u), _rsb_dot(u, v), _rsb_dot(v, v), _rsb_dot(u, w), _rsb_dot(v, w)
    if aa < 1e-24:
        s, t = 0.0, max(0.0, min(1.0, ee/cc)) if cc > 1e-24 else 0.0
    elif cc < 1e-24:
        s, t = max(0.0, min(1.0, -dd/aa)), 0.0
    else:
        den = aa*cc-bb*bb
        s = max(0.0, min(1.0, (bb*ee-cc*dd)/den)) if den > aa*cc*1e-12 else 0.0
        t = (bb*s+ee)/cc
        if t < 0: t, s = 0.0, max(0.0, min(1.0, -dd/aa))
        elif t > 1: t, s = 1.0, max(0.0, min(1.0, (bb-dd)/aa))
    delta = _rsb_sub(_rsb_add(w, _rsb_mul(u, s)), _rsb_mul(v, t))
    return _rsb_dot(delta, delta)


def _rsb_bone(arm, points, origin, ticket):
    segments = list(zip(points, points[1:])) or [(points[0], points[0])]
    linear, translation = arm.matrix_world.to_3x3(), _rsb_sub(tuple(arm.matrix_world.translation), origin)
    found = []
    for bone in arm.data.bones:
        _rsb_check(ticket)
        if not bone.use_deform: continue
        head = _rsb_add(tuple(linear @ bone.head_local), translation)
        tail = _rsb_add(tuple(linear @ bone.tail_local), translation)
        if _rsb_length(_rsb_sub(tail, head)) < 1e-8: continue
        distance = min(_rsb_segment_distance2(a, b, head, tail) for a, b in segments)
        found.append((distance, bone.name))
    if not found: raise ValueError("The rig has no usable deform bone segment for rigid brush binding.")
    return min(found)[1]


def _rs_build(a):
    ticket = _rsb_ticket()
    name, points, normals, radius = _rsb_args(a)
    ob, arm, world, linear, _inverse = _rsb_source(name)
    origin = tuple(world.translation)
    offsets = _rsb_world_offsets(_rsb_mixed(ob, ticket), linear, ticket)
    samples = [_rsb_sub(p, origin) for p in points]
    _rsb_bounds(offsets, samples, radius, build=True)
    bone = None
    if a.get("attachToRig", False):
        if arm is None: raise ValueError("attachToRig needs an existing neutral armature; choose a rigged source or disable attachment.")
        bone = _rsb_bone(arm, samples, origin, ticket)
    vertices, faces, uvs, steps = _rsb_geometry(points, normals, radius)
    _rsb_check(ticket)
    mesh = part = material = image = None
    try:
        mesh = bpy.data.meshes.new("Build part")
        mesh.from_pydata(vertices, [], faces)
        if mesh.validate(verbose=False): raise ValueError("Generated brush geometry was degenerate; shorten or simplify the stroke.")
        mesh.update()
        layer = mesh.uv_layers.new(name="UVMap")
        for poly, coords in zip(mesh.polygons, uvs):
            poly.use_smooth = True
            for loop, uv in zip(poly.loop_indices, coords): layer.data[loop].uv = uv
        material = bpy.data.materials.new("Build color")
        material["riggerset_beginner_build_v1"] = ob.name
        material.diffuse_color = tuple(a["color"])
        material.use_nodes = True
        shader = next((n for n in material.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None)
        if shader is None: raise ValueError("A simple Build material could not be created.")
        image = bpy.data.images.new("Build color", width=256, height=256, alpha=True, float_buffer=False)
        image["riggerset_beginner_build_v1"] = ob.name
        image.colorspace_settings.name = "sRGB"
        image.file_format = "PNG"
        image.pixels.foreach_set(list(a["color"])*65536)
        image.update()
        image.pack()
        if image.packed_file is None:
            raise ValueError("The new Build color image could not be packed; the new part was discarded.")
        texture = material.node_tree.nodes.new("ShaderNodeTexImage")
        texture.image = image
        uv_node = material.node_tree.nodes.new("ShaderNodeUVMap")
        uv_node.uv_map = "UVMap"
        material.node_tree.links.new(uv_node.outputs["UV"], texture.inputs["Vector"])
        material.node_tree.links.new(texture.outputs["Color"], shader.inputs["Base Color"])
        shader.inputs["Base Color"].default_value = (1, 1, 1, 1)
        shader.inputs["Alpha"].default_value = 1
        # texture.variant requires the Base Color image NODE to have only one
        # consumer. A separate node reading the same owned image preserves
        # alpha when Color later replaces only the Base Color node's image.
        if a["color"][3] < 1:
            alpha_node = material.node_tree.nodes.new("ShaderNodeTexImage")
            alpha_node.image = image
            alpha_node.label = "Original Build alpha"
            material.node_tree.links.new(uv_node.outputs["UV"], alpha_node.inputs["Vector"])
            material.node_tree.links.new(alpha_node.outputs["Alpha"], shader.inputs["Alpha"])
        shader.inputs["Roughness"].default_value = .65
        if a["color"][3] < 1:
            if hasattr(material, "surface_render_method"): material.surface_render_method = "DITHERED"
            elif hasattr(material, "blend_method"): material.blend_method = "BLEND"
        mesh.materials.append(material)
        part = bpy.data.objects.new("Build part", mesh)
        part["riggerset_beginner_build_v1"] = ob.name
        # users_collection can be nested; linking to the source's collection
        # itself does not need a selection/context or an operator override.
        collection = ob.users_collection[0] if ob.users_collection else bpy.context.scene.collection
        collection.objects.link(part)
        part.parent = ob
        part.matrix_parent_inverse = world.inverted()
        part.matrix_world = Matrix.Translation(points[0])
        if bone:
            group = part.vertex_groups.new(name=bone)
            group.add(list(range(len(vertices))), 1.0, "REPLACE")
            mod = part.modifiers.new(name="Rigid brush binding", type="ARMATURE")
            mod.object = arm; mod.use_vertex_groups = True; mod.use_bone_envelopes = False
        bpy.context.view_layer.update()
        _rsb_check(ticket)
        result = {"changed": "mesh.build", "object": part.name, "source": ob.name, "geometryAdded": True,
                  "vertices": len(mesh.vertices), "faces": len(mesh.polygons), "pathSteps": steps,
                  "radialSides": _RSB_SIDES, "binding": "rigid-bone" if bone else "object-parent",
                  "image": image.name, "material": material.name, "paintable": True}
        if bone: result.update(bone=bone, armature=arm.name)
        return result
    except Exception:
        if part is not None: bpy.data.objects.remove(part, do_unlink=True)
        if mesh is not None and mesh.users == 0: bpy.data.meshes.remove(mesh)
        if material is not None and material.users == 0: bpy.data.materials.remove(material)
        if image is not None and image.users == 0: bpy.data.images.remove(image)
        raise


def _rsb_owned(ob, name):
    keys = ob.data.shape_keys
    owned, target = [], None
    if keys:
        raw = keys.get(_RSB_SHAPES)
        if raw is not None:
            try:
                if not isinstance(raw, str) or len(raw) > 8192: raise ValueError()
                data = _rsb_json.loads(raw)
                owned = data["keys"]
                if type(data.get("schema")) is not int or data["schema"] != 1 or set(data) != {"schema", "keys"} or not isinstance(owned, list) or any(not isinstance(n, str) for n in owned) or len(set(owned)) != len(owned): raise ValueError()
            except (TypeError, KeyError, ValueError):
                raise ValueError("Shape ownership metadata is invalid; use a fresh working copy or restore its metadata.")
            if any(n == keys.reference_key.name or keys.key_blocks.get(n) is None for n in owned):
                raise ValueError("Stale shape ownership after a rename/removal; restore the original owned key names before brushing.")
        target = keys.key_blocks.get(name)
        if target is not None:
            if name not in owned or target == keys.reference_key:
                raise ValueError("That shape name belongs to an unowned shape key; choose a new shapeName.")
            if target.relative_key != keys.reference_key or target.vertex_group or target.mute or target.value != 1.0 or target.slider_max < 1:
                raise ValueError("Restore the owned shape to unmuted, unmasked, relative to Basis and value 1 before brushing it.")
            if any(k != target and k.relative_key == target for k in keys.key_blocks):
                raise ValueError("Another key uses this shape as its relative key; choose an independent shapeName.")
    if len(owned) > 16 or (target is None and len(owned) >= 16):
        raise ValueError("The 16 owned shape variants limit was reached; reuse an owned shapeName.")
    return keys, target, owned


def _rsb_influences(offsets, samples, normals, radius, ticket):
    from mathutils.kdtree import KDTree
    tree = KDTree(len(offsets))
    for i, p in enumerate(offsets):
        if i % 1024 == 0: _rsb_check(ticket)
        tree.insert(p, i)
    tree.balance()
    found = {}
    for p, normal in zip(samples, normals):
        _rsb_check(ticket)
        for j, (_co, i, distance) in enumerate(tree.find_range(p, radius)):
            if j % 512 == 0: _rsb_check(ticket)
            weight = max(0.0, 1 - (distance/radius)**2)**2
            if weight <= 1e-12: continue
            if i not in found or weight > found[i][0]: found[i] = (weight, normal)
            if len(found) > _RSB_MAX_AFFECTED:
                raise ValueError("Stroke affects more than 10000 vertices; reduce the radius or split the stroke.")
    if not found: raise ValueError("No vertices inside the brush; move onto the visible mesh or increase the radius.")
    return found


def _rsb_deltas(ob, offsets, influence, radius, strength, mode, ticket):
    neighbors = {i: [0.0, 0.0, 0.0, 0] for i in influence} if mode == "smooth" else None
    if neighbors is not None:
        for j, edge in enumerate(ob.data.edges):
            if j % 2048 == 0: _rsb_check(ticket)
            a, b = edge.vertices
            for i, other in ((a, b), (b, a)):
                if i in neighbors:
                    sums = neighbors[i]
                    for k in range(3): sums[k] += offsets[other][k]
                    sums[3] += 1
    deltas = {}
    for j, (i, (weight, normal)) in enumerate(influence.items()):
        if j % 512 == 0: _rsb_check(ticket)
        limit = radius * strength * weight
        if mode == "smooth":
            sums = neighbors[i]
            if not sums[3]: continue
            lap = tuple(sums[k]/sums[3] - offsets[i][k] for k in range(3))
            delta = _rsb_mul(lap, strength*weight)
            length = _rsb_length(delta)
            if length > limit: delta = _rsb_mul(delta, limit/length)
        else: delta = _rsb_mul(normal, limit * (1 if mode == "raise" else -1))
        if _rsb_length(delta) > max(1e-12, radius*1e-9): deltas[i] = delta
    if not deltas: raise ValueError("This stroke moves no vertices; choose a nonflat neighborhood or a different shape mode.")
    return deltas


def _rs_sculpt(a):
    ticket = _rsb_ticket()
    name, points, normals, radius = _rsb_args(a, sculpt=True)
    ob, _arm, world, linear, inverse = _rsb_source(name, sculpt=True)
    shape_name = a.get("shapeName", "Shape edit")
    keys, target, owned = _rsb_owned(ob, shape_name)
    offsets = _rsb_world_offsets(_rsb_mixed(ob, ticket), linear, ticket)
    samples = [_rsb_sub(p, tuple(world.translation)) for p in points]
    _rsb_bounds(offsets, samples, radius)
    influence = _rsb_influences(offsets, samples, normals, radius, ticket)
    deltas = _rsb_deltas(ob, offsets, influence, radius, float(a["strength"]), a["mode"], ticket)
    basis_data = keys.reference_key.data if keys else ob.data.vertices
    old = {i: tuple((target.data if target else basis_data)[i].co) for i in deltas}
    planned, max_displacement = {}, 0.0
    max_step = radius*float(a["strength"])
    for i, delta in deltas.items():
        local_delta = tuple(inverse @ Vector(delta))
        # Quantize before committing: the stored float32 delta (rather than
        # only the ideal double-precision delta) must satisfy the stroke cap.
        factor = 1.0
        for _attempt in range(12):
            position = _rsb_add(old[i], _rsb_mul(local_delta, factor))
            if any(not _rsb_math.isfinite(x) or abs(x) > 1e7 for x in position):
                raise ValueError("Shape edit exceeds finite local coordinate bounds; normalize scale on a working copy.")
            position = tuple(_rsb_struct.unpack("<f", _rsb_struct.pack("<f", x))[0] for x in position)
            actual = _rsb_length(tuple(linear @ Vector(_rsb_sub(position, old[i]))))
            if actual <= max_step:
                if actual > max(1e-12, radius*1e-9):
                    planned[i] = position
                    max_displacement = max(max_displacement, actual)
                break
            factor *= min(.95, max_step/actual*.9999)
        else:
            raise ValueError("Brush is below local coordinate precision; normalize scale and move mesh coordinates near the local origin on a working copy.")
    if not planned:
        raise ValueError("Brush moves no representable coordinates; increase its size or normalize the mesh on a working copy.")
    _rsb_check(ticket)
    original_active = ob.active_shape_key_index
    old_registry = keys.get(_RSB_SHAPES) if keys else None
    original_target, created = target, []
    old_value = target.value if target else None
    try:
        if keys is None:
            basis = ob.shape_key_add(name="Basis", from_mix=False)
            created.append(basis)
            keys = ob.data.shape_keys
        if target is None:
            target = ob.shape_key_add(name=shape_name, from_mix=False)
            created.append(target)
            if target.name != shape_name: raise ValueError("Shape name was truncated or collided; choose another shapeName.")
            target.relative_key = keys.reference_key
            # Start with zero contribution, even if another key is active.
            for i, p in enumerate(keys.reference_key.data):
                if i % 2048 == 0: _rsb_check(ticket)
                target.data[i].co = p.co
            target.slider_min = 0; target.slider_max = 1
            target.interpolation = "KEY_LINEAR"
        for j, (i, p) in enumerate(planned.items()):
            if j % 256 == 0: _rsb_check(ticket)
            target.data[i].co = p
        target.value = 1
        if original_target is None:
            keys[_RSB_SHAPES] = _rsb_json.dumps({"schema": 1, "keys": owned + [shape_name]}, separators=(",", ":"))
        ob.data.update()
        bpy.context.view_layer.update()
        _rsb_check(ticket)
        return {"changed": "mesh.sculpt", "object": ob.name, "shapeKey": target.name,
                "affectedVertices": len(planned), "basePreserved": True, "topologyPreserved": True,
                "uvPreserved": True, "weightsPreserved": True, "mode": a["mode"],
                "maxDisplacementWorld": max_displacement, "displacementLimitWorld": radius*float(a["strength"]),
                "ownedVariants": len(owned) + int(original_target is None)}
    except Exception:
        if original_target is not None:
            for i, p in old.items(): original_target.data[i].co = p
            original_target.value = old_value
        if ob.data.shape_keys:
            if old_registry is None:
                if _RSB_SHAPES in ob.data.shape_keys: del ob.data.shape_keys[_RSB_SHAPES]
            else: ob.data.shape_keys[_RSB_SHAPES] = old_registry
        for key in reversed(created): ob.shape_key_remove(key)
        ob.data.update()
        bpy.context.view_layer.update()
        raise
    finally:
        count = len(ob.data.shape_keys.key_blocks) if ob.data.shape_keys else 0
        ob.active_shape_key_index = min(original_active, max(0, count-1))


# SPDX-License-Identifier: GPL-3.0-or-later
"""Inline before the dispatcher; checkpoint/revision ownership stays there."""
import time as _rsas_time
import math as _rsas_math
from array import array as _rsas_array

_RSAS_MAX_PIXELS = 8388608
_RSAS_MAX_TRIS = 400000


def _rsas_check(t):
    if _rs_control().get("epoch") != t[0]:
        raise ValueError("Style conversion cancelled; the staged copy was discarded.")
    if _RS_REV != t[1]:
        raise ValueError("Stale scene revision during style conversion; retry.")
    if _rsas_time.monotonic() - t[2] > 45:
        raise ValueError("Style conversion exceeded its 45 second work limit.")


def _rsas_args(a):
    if not isinstance(a, dict) or set(a) - {"object", "style", "triangles", "textureSize", "voxelCells", "preserveRig"}:
        raise ValueError("Unknown style parameter.")
    if type(a.get("preserveRig", False)) is not bool:
        raise ValueError("preserveRig must be a boolean.")
    name, style = a.get("object"), a.get("style")
    if not isinstance(name, str) or not 1 <= len(name) <= 120 or any(ord(c) < 32 for c in name):
        raise ValueError("Choose a mesh object by name.")
    if style not in ("detailed", "game", "performance", "retro", "voxel"):
        raise ValueError("Style must be detailed, game, performance, retro or voxel.")
    if type(a.get("triangles")) is not int or not 128 <= a["triangles"] <= 200000:
        raise ValueError("triangles must be an integer in 128..200000.")
    if type(a.get("textureSize")) is not int or a["textureSize"] not in (256, 512, 1024, 2048):
        raise ValueError("textureSize must be 256, 512, 1024 or 2048.")
    if type(a.get("voxelCells", 24)) is not int or not 8 <= a.get("voxelCells", 24) <= 64:
        raise ValueError("voxelCells must be an integer in 8..64.")
    return name, style, a["triangles"], a["textureSize"], a.get("voxelCells", 24)


def _rsas_size(mesh):
    n = sum(len(p.vertices) - 2 for p in mesh.polygons)
    if (not 1 <= len(mesh.vertices) <= 250000 or not 1 <= n <= _RSAS_MAX_TRIS or
            len(mesh.loops) > 1200000 or len(mesh.edges) > 1000000):
        raise ValueError("Style source needs 1..250000 vertices and 1..400000 surface triangles.")
    return n


def _rsas_graph(mat, mesh):
    """Small auditable graph contract; no implicit loss of linked appearance."""
    d = {"material": mat, "color": (.8, .8, .8, 1), "image": None, "images": [], "uv": None, "extension": "REPEAT"}
    if mat is None:
        return d
    if mat.animation_data or mat.library:
        raise ValueError("Unsupported animated or linked material; use a local static material.")
    if not mat.use_nodes:
        d["color"] = tuple(mat.diffuse_color)
    else:
        tree = mat.node_tree
        if tree.animation_data or len(tree.nodes) > 24:
            raise ValueError("Unsupported animated or complex material graph.")
        outputs = [n for n in tree.nodes if n.type == "OUTPUT_MATERIAL" and n.is_active_output]
        if len(outputs) != 1:
            raise ValueError("Unsupported material: one active Material Output is required.")
        out = outputs[0]
        links = list(out.inputs["Surface"].links)
        if (len(links) != 1 or links[0].from_node.type != "BSDF_PRINCIPLED" or
                out.inputs["Volume"].is_linked or out.inputs["Displacement"].is_linked):
            raise ValueError("Unsupported material: use a direct opaque Principled surface.")
        shader = links[0].from_node
        allowed = {out, shader}
        for socket in shader.inputs:
            if socket.is_linked and socket.name not in ("Base Color", "Metallic", "Roughness", "Normal"):
                raise ValueError("Unsupported linked material input: " + socket.name)
        for key in ("Alpha",):
            if abs(float(shader.inputs[key].default_value) - 1) > 1e-6:
                raise ValueError("Unsupported transparent material; style copies need opaque surfaces.")
        for key in ("Transmission Weight", "Transmission", "Coat Weight", "Clearcoat",
                    "Subsurface Weight", "Subsurface"):
            if key in shader.inputs and float(shader.inputs[key].default_value) != 0:
                raise ValueError("Unsupported transmission/coat/subsurface material.")
        emission = shader.inputs.get("Emission Color") or shader.inputs.get("Emission")
        strength = shader.inputs.get("Emission Strength")
        power = float(strength.default_value) if strength else 1
        if not _rsas_math.isfinite(power) or power < 0:
            raise ValueError("Unsupported invalid emission strength.")
        if emission and power > 0 and any(float(v) != 0 for v in emission.default_value[:3]):
            raise ValueError("Unsupported emissive material; use opaque base color.")
        d["color"] = tuple(shader.inputs["Base Color"].default_value)
        links = list(shader.inputs["Base Color"].links)
        if links:
            link = links[0]
            tex = link.from_node
            if tex.type != "TEX_IMAGE" or link.from_socket.name != "Color" or tex.image is None:
                raise ValueError("Unsupported base color: use one UV image Color output directly.")
            if tex.projection != "FLAT" or tex.extension not in ("REPEAT", "EXTEND"):
                raise ValueError("Unsupported image projection/extension; use Flat Repeat or Extend.")
            allowed.add(tex)
            uv = next((v for v in mesh.uv_layers if v.active_render), mesh.uv_layers.active)
            if tex.inputs["Vector"].is_linked:
                link = tex.inputs["Vector"].links[0]
                node = link.from_node
                if node.type == "UVMAP" and not node.from_instancer:
                    uv = mesh.uv_layers.get(node.uv_map) if node.uv_map else uv
                elif node.type != "TEX_COORD" or link.from_socket.name != "UV":
                    raise ValueError("Unsupported texture coordinates; use an untransformed UV map.")
                allowed.add(node)
            if uv is None:
                raise ValueError("The base-color image needs a UV map on the evaluated surface.")
            d.update(image=tex.image, uv=uv.name, extension=tex.extension)
        def visit(node, depth=0):
            if node in allowed:
                return
            if depth > 24 or node.type not in ("TEX_IMAGE", "UVMAP", "TEX_COORD", "SEPRGB", "SEPARATE_COLOR", "NORMAL_MAP", "MATH", "VALUE", "RGB", "REROUTE"):
                raise ValueError("Unsupported PBR material dependency; use UV images and standard channel/normal nodes.")
            if node.type == "TEX_IMAGE":
                if node.image is None or node.projection != "FLAT" or node.extension not in ("REPEAT", "EXTEND"):
                    raise ValueError("PBR maps need loaded Flat UV images with Repeat or Extend.")
                for link in node.inputs["Vector"].links:
                    if not ((link.from_node.type == "UVMAP" and not link.from_node.from_instancer) or
                            (link.from_node.type == "TEX_COORD" and link.from_socket.name == "UV")):
                        raise ValueError("PBR images need untransformed UV coordinates.")
            if node.type == "NORMAL_MAP" and node.space != "TANGENT":
                raise ValueError("Use a tangent-space normal map.")
            allowed.add(node)
            for socket in node.inputs:
                for link in socket.links:
                    visit(link.from_node, depth+1)
        for key in ("Metallic", "Roughness", "Normal"):
            for link in shader.inputs[key].links:
                visit(link.from_node)
        if set(tree.nodes) != allowed:
            raise ValueError("Unsupported extra material nodes; use a minimal opaque base-color graph.")
        d["images"] = list({node.image for node in allowed if node.type == "TEX_IMAGE" and node.image})
        if d["image"] and d["image"].colorspace_settings.name != "sRGB":
            raise ValueError("The base-color image must use sRGB color space.")
    if (len(d["color"]) != 4 or any(not _rsas_math.isfinite(v) or not 0 <= v <= 1 for v in d["color"])
            or abs(d["color"][3] - 1) > 1e-6):
        raise ValueError("Unsupported nonfinite, HDR or transparent base color.")
    return d


def _rsas_pixels(desc, t):
    images = {img for d in desc for img in d.get("images", ([d["image"]] if d["image"] is not None else []))}
    if len(images) > 8 or sum(int(i.size[0]) * int(i.size[1]) for i in images) > _RSAS_MAX_PIXELS:
        raise ValueError("Style textures exceed 8 images or 8388608 aggregate input pixels.")
    buffers = {}
    for img in images:
        _rsas_check(t)
        w, h = tuple(img.size)
        if (img.source not in ("FILE", "GENERATED") or not img.has_data or img.is_float or
                not w or not h or max(w, h) > 8192 or img.colorspace_settings.name not in ("sRGB", "Non-Color") or
                len(img.pixels) != w * h * 4):
            raise ValueError("Unsupported image: use loaded, single, byte sRGB images up to 8192 per axis.")
        buf = _rsas_array("f", [0]) * (w * h * 4)
        img.pixels.foreach_get(buf)
        for start in range(0, len(buf), 65536):
            _rsas_check(t)
            if any(not _rsas_math.isfinite(v) or not 0 <= v <= 1 for v in buf[start:start+65536]):
                raise ValueError("Unsupported nonfinite or HDR image pixels.")
        buffers[img] = buf
    return buffers


def _rsas_image(name, w, h, pixels, owned, t, colorspace="sRGB"):
    _rsas_check(t)
    img = bpy.data.images.new(name, width=w, height=h, alpha=True, float_buffer=False)
    owned["images"].append(img)
    img.colorspace_settings.name = colorspace
    img.file_format = "PNG"
    img.pixels.foreach_set(pixels)
    img.update()
    _rsas_check(t)
    return img


def _rsas_pack(img, size, t):
    w, h = tuple(img.size)
    factor = min(1, size / max(w, h))
    if factor < 1:
        img.scale(max(1, round(w*factor)), max(1, round(h*factor)))
    _rsas_check(t)
    img.pack()
    if not img.packed_file:
        raise ValueError("Cannot safely pack the output image in this Blender build.")
    _rsas_check(t)


def _rsas_materials(mesh, desc, buffers, size, retro, owned, t, retain_maps=False):
    clones, copied = {}, {}
    assignments = [p.material_index for p in mesh.polygons] if retain_maps else None
    mesh.materials.clear()
    for d in desc:
        _rsas_check(t)
        src = d["material"]
        if src in clones:
            mesh.materials.append(clones[src])
            continue
        mat = src.copy() if src is not None else bpy.data.materials.new("RiggerSet base color")
        owned["materials"].append(mat)
        mat.use_fake_user = False  # A copied fake user must not pin failed staging data.
        mat.name = (src.name if src else "Base color") + " styled"
        if src is not None and src.node_tree is not None and mat.node_tree == src.node_tree:
            raise ValueError("Cannot safely isolate the source material node tree.")
        if not mat.use_nodes:
            mat.use_nodes = True
            mat.node_tree.nodes.clear()  # A nodeless source can retain an inactive old graph.
            p = mat.node_tree.nodes.new("ShaderNodeBsdfPrincipled")
            output = mat.node_tree.nodes.new("ShaderNodeOutputMaterial")
            mat.node_tree.links.new(p.outputs["BSDF"], output.inputs["Surface"])
            p.inputs["Base Color"].default_value = d["color"]
            p.inputs["Metallic"].default_value = getattr(src, "metallic", 0) if src else 0
            p.inputs["Roughness"].default_value = getattr(src, "roughness", .5) if src else .5
        if retro and not retain_maps:
            # The retro finish deliberately replaces PBR response with matte shading.
            for node in mat.node_tree.nodes:
                if node.type == "BSDF_PRINCIPLED":
                    for socket in node.inputs:
                        if socket.name != "Base Color":
                            for link in list(socket.links):
                                mat.node_tree.links.remove(link)
            keep = set()
            def retain(node):
                if node in keep:
                    return
                keep.add(node)
                for socket in node.inputs:
                    for link in socket.links:
                        retain(link.from_node)
            for node in mat.node_tree.nodes:
                if node.type == "OUTPUT_MATERIAL" and node.is_active_output:
                    retain(node)
            for node in list(mat.node_tree.nodes):
                if node not in keep:
                    mat.node_tree.nodes.remove(node)
        for node in mat.node_tree.nodes:
            if node.type == "TEX_IMAGE":
                old = node.image
                if old not in copied:
                    img = _rsas_image(old.name + " styled", *tuple(old.size), buffers[old], owned, t, old.colorspace_settings.name)
                    _rsas_pack(img, size, t)
                    copied[old] = img
                node.image = copied[old]
                if retro:
                    node.interpolation = "Closest"
            if retro and node.type == "BSDF_PRINCIPLED":
                for key, val in (("Metallic", 0), ("Roughness", 1),
                                 ("Specular IOR Level", 0), ("Specular", 0)):
                    if key in node.inputs:
                        node.inputs[key].default_value = val
        clones[src] = mat
        mesh.materials.append(mat)
    if assignments is not None:
        for polygon, index in zip(mesh.polygons, assignments):
            polygon.material_index = index


def _rsas_triangles(mesh):
    mesh.calc_loop_triangles()
    return len(mesh.loop_triangles)


def _rsas_weld(mesh, t):
    """Join exactly coincident split vertices on the private copy; loop UVs stay separate."""
    import bmesh
    bm = bmesh.new()
    try:
        bm.from_mesh(mesh)
        found, targets = {}, {}
        for i, vertex in enumerate(bm.verts):
            if i % 2048 == 0:
                _rsas_check(t)
            key = tuple(vertex.co)
            if key in found:
                targets[vertex] = found[key]
            else:
                found[key] = vertex
        if targets:
            bmesh.ops.weld_verts(bm, targetmap=targets)
            bm.to_mesh(mesh)
            mesh.update()
        _rsas_check(t)
    finally:
        bm.free()


def _rsas_reduce(ob, cap, owned, t, rigged=False):
    import bmesh
    mesh = ob.data
    count = _rsas_triangles(mesh)
    if count <= cap:
        return
    # Coincident rest vertices can have different bone weights. A rigged LOD
    # must never use the static path's position-only weld.
    if not rigged:
        _rsas_weld(mesh, t)
    bm = bmesh.new()
    try:
        bm.from_mesh(mesh)
        bmesh.ops.triangulate(bm, faces=list(bm.faces))
        bm.to_mesh(mesh)
    finally:
        bm.free()
    for attempt in range(5):
        _rsas_check(t)
        previous_count = count
        mod = ob.modifiers.new("RiggerSet private reduction", "DECIMATE")
        try:
            mod.decimate_type = "COLLAPSE"
            mod.ratio = min(.99, (cap - 4) / count * (.94 if attempt == 0 else .8))
            mod.use_collapse_triangulate = True
            bpy.context.view_layer.update()
            graph = bpy.context.evaluated_depsgraph_get()
            fresh = bpy.data.meshes.new_from_object(ob.evaluated_get(graph), preserve_all_data_layers=True, depsgraph=graph)
            owned["meshes"].append(fresh)
        finally:
            ob.modifiers.remove(mod)
        ob.data = fresh
        count = _rsas_triangles(fresh)
        _rsas_check(t)
        if 0 < count <= cap:
            return
        if count == 0 or count >= previous_count:
            break
    raise ValueError("Decimation could not meet the triangle maximum: " + str(count) + " triangles remain for a " + str(cap) + " limit. Use a higher budget or repair disconnected surfaces.")


def _rsas_srgb(v):
    return 12.92*v if v <= .0031308 else 1.055*(v ** (1/2.4))-.055


def _rsas_sample(mesh, tris, points, index, point, desc, buffers):
    tri = tris[index]
    d = desc[tri.material_index]
    if d["image"] is None:
        return tuple(_rsas_srgb(v) for v in d["color"][:3]) + (1,)
    p, q, r = (points[i] for i in tri.vertices)
    v0, v1, v2 = q-p, r-p, point-p
    aa, ab, bb, ac, bc = v0.dot(v0), v0.dot(v1), v1.dot(v1), v0.dot(v2), v1.dot(v2)
    denominator = aa*bb-ab*ab
    if denominator <= 1e-30:
        raise ValueError("Unsupported degenerate source triangle during voxel color transfer.")
    b, c = (bb*ac-ab*bc)/denominator, (aa*bc-ab*ac)/denominator
    uv = mesh.uv_layers[d["uv"]].data
    uvs = [uv[i].uv for i in tri.loops]
    u, v = tuple(uvs[0]*(1-b-c) + uvs[1]*b + uvs[2]*c)
    if not _rsas_math.isfinite(u) or not _rsas_math.isfinite(v):
        raise ValueError("Unsupported nonfinite source UV.")
    if d["extension"] == "REPEAT":
        u, v = u % 1, v % 1
    else:
        u, v = max(0, min(1, u)), max(0, min(1, v))
    img = d["image"]
    w, h = tuple(img.size)
    offset = 4*(min(h-1, int(v*h))*w + min(w-1, int(u*w)))
    return buffers[img][offset:offset+4]


_RSAS_FACES = (
    ((-1,0,0), ((0,0,0),(0,0,1),(0,1,1),(0,1,0))),
    ((1,0,0), ((1,0,0),(1,1,0),(1,1,1),(1,0,1))),
    ((0,-1,0), ((0,0,0),(1,0,0),(1,0,1),(0,0,1))),
    ((0,1,0), ((0,1,0),(0,1,1),(1,1,1),(1,1,0))),
    ((0,0,-1), ((0,0,0),(0,1,0),(1,1,0),(1,0,0))),
    ((0,0,1), ((0,0,1),(1,0,1),(1,1,1),(0,1,1))))


def _rsas_volume(mesh, t):
    import bmesh
    _rsas_check(t)
    bm = bmesh.new()
    try:
        bm.from_mesh(mesh)
        if (any(not e.is_manifold or not e.is_contiguous for e in bm.edges) or
                any(not v.is_manifold or not v.link_faces for v in bm.verts)):
            raise ValueError("Voxel conversion needs a closed, consistently wound manifold solid; repair open/loose geometry first.")
        volume = bm.calc_volume(signed=True)
    finally:
        bm.free()
    _rsas_check(t)
    return volume


def _rsas_voxel(ob, cells, size, desc, buffers, owned, t):
    from mathutils import Vector, Matrix
    from mathutils.bvhtree import BVHTree
    mesh, prepass = ob.data, ""
    points = [ob.matrix_world @ v.co for v in mesh.vertices]
    low = Vector(tuple(min(p[k] for p in points) for k in range(3)))
    span = Vector(tuple(max(p[k] for p in points) for k in range(3))) - low
    original_triangles = _rsas_triangles(mesh)
    volume = _rsas_volume(mesh, t)
    if original_triangles > 60000:
        _rsas_reduce(ob, 60000, owned, t)
        mesh = ob.data
        volume = _rsas_volume(mesh, t)
        points = [ob.matrix_world @ v.co for v in mesh.vertices]
        prepass = (" Private evaluated surface pre-simplified from " + str(original_triangles) +
                   " to " + str(_rsas_triangles(mesh)) + " triangles before occupancy/color sampling.")
    if (any(d["uv"] and d["uv"] not in mesh.uv_layers for d in desc) or
            any(p.material_index >= len(desc) for p in mesh.polygons)):
        raise ValueError("Voxel prepass could not preserve UV/material mapping.")
    orientation = volume * ob.matrix_world.to_3x3().determinant()
    step = max(span) / cells
    if (step < 1e-6 or min(span) < step*1e-4 or abs(orientation) < step**3*1e-6 or
            max(abs(v) for p in points for v in p) / step > 1e7):
        raise ValueError("Voxel solid is empty, too thin or outside safe coordinate precision.")
    dims = tuple(max(1, _rsas_math.ceil(v/step-1e-8)) for v in span)
    nx, ny, nz = dims
    tris = list(mesh.loop_triangles)
    tree = BVHTree.FromPolygons(points, [tuple(p.vertices) for p in tris], all_triangles=True)
    solid, queries = bytearray(nx*ny*nz), 0
    eps, direction = step*1e-5, Vector((1,0,0))
    for z in range(nz):
        for y in range(ny):
            _rsas_check(t)
            origin = Vector((low.x-step, low.y+(y+.5)*step, low.z+(z+.5)*step))
            crossings = []
            while True:
                queries += 1
                if queries > 131072 or len(crossings) > 128:
                    raise ValueError("Voxel ray work limit exceeded; simplify the solid or lower voxelCells.")
                hit, normal, index, distance = tree.ray_cast(origin, direction, span.x+2*step)
                if hit is None:
                    break
                if abs(normal.x) < 1e-7:
                    raise ValueError("Ambiguous tangent voxel scanline; repair the solid or change voxelCells.")
                crossings.append((hit.x, normal.x))
                origin.x = hit.x+eps
            if len(crossings) % 2 or any((n*(1 if orientation > 0 else -1) >= 0) != (i % 2 == 1)
                                          for i, (x, n) in enumerate(crossings)):
                raise ValueError("Ambiguous/open/intersecting voxel solid; repair winding and intersections first.")
            for i in range(0, len(crossings), 2):
                enter, leave = crossings[i][0], crossings[i+1][0]
                start = max(0, _rsas_math.ceil((enter-low.x)/step-.5))
                stop = min(nx, _rsas_math.ceil((leave-low.x)/step-.5))
                for x in range(start, stop):
                    solid[(z*ny+y)*nx+x] = 1
    if not any(solid):
        raise ValueError("No solid cell centers at this resolution; increase voxelCells or thicken the source.")
    vertices, faces, colors, corners = [], [], [], {}
    for z in range(nz):
        for y in range(ny):
            _rsas_check(t)
            for x in range(nx):
                if not solid[(z*ny+y)*nx+x]:
                    continue
                for normal, offsets in _RSAS_FACES:
                    q = (x+normal[0], y+normal[1], z+normal[2])
                    if all(0 <= q[k] < dims[k] for k in range(3)) and solid[(q[2]*ny+q[1])*nx+q[0]]:
                        continue
                    if len(faces) >= min(100000, size*size):
                        raise ValueError("Voxel surface exceeds 200000 triangles or atlas capacity; lower voxelCells or increase textureSize.")
                    face = []
                    for off in offsets:
                        key = (x+off[0], y+off[1], z+off[2])
                        if key not in corners:
                            corners[key] = len(vertices)
                            vertices.append(tuple(v*step for v in key))
                        face.append(corners[key])
                    faces.append(face)
                    center = low + Vector(((x+.5)*step, (y+.5)*step, (z+.5)*step)) + Vector(normal)*(step*.5)
                    nearest, n, index, dist = tree.find_nearest(center)
                    if nearest is None:
                        raise ValueError("Cannot transfer source color to a voxel face.")
                    colors.append(_rsas_sample(mesh, tris, points, index, nearest, desc, buffers))
    _rsas_check(t)
    out = bpy.data.meshes.new("RiggerSet cubic surface")
    owned["meshes"].append(out)
    out.from_pydata(vertices, [], faces)
    out.update()
    uv = out.uv_layers.new(name="Voxel face atlas")
    atlas = _rsas_array("f", (0, 0, 0, 1)) * (size*size)
    for i, poly in enumerate(out.polygons):
        if i % 256 == 0:
            _rsas_check(t)
        atlas[4*i:4*i+4] = _rsas_array("f", colors[i])
        for li in poly.loop_indices:
            uv.data[li].uv = ((i % size+.5)/size, (i//size+.5)/size)
    img = _rsas_image("RiggerSet voxel base colors", size, size, atlas, owned, t)
    _rsas_pack(img, size, t)
    mat = bpy.data.materials.new("RiggerSet voxel matte")
    owned["materials"].append(mat)
    mat.use_nodes = True
    shader = next(n for n in mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
    shader.inputs["Roughness"].default_value = 1
    tex = mat.node_tree.nodes.new("ShaderNodeTexImage")
    tex.image, tex.interpolation, tex.extension = img, "Closest", "EXTEND"
    mat.node_tree.links.new(tex.outputs["Color"], shader.inputs["Base Color"])
    out.materials.append(mat)
    ob.data, ob.matrix_world = out, Matrix.Translation(low)
    ob["riggerset_voxel_cell_size"] = step
    return prepass


def _rsas_clean(owned, discard):
    for kind in ("objects", "meshes", "materials", "images"):
        collection = getattr(bpy.data, kind)
        for item in reversed(owned[kind]):
            if kind == "objects":
                if discard:
                    collection.remove(item, do_unlink=True)
            elif item.users == 0:
                collection.remove(item)


def _rsas_rig_local(ob, label):
    if (ob.library or ob.override_library or not ob.is_editable or ob.data.library or
            getattr(ob.data, "override_library", None) or ob.data.users - int(ob.data.use_fake_user) != 1):
        raise ValueError(label + " needs unique local editable object data; shared/linked data is unsupported.")
    for owner in (ob, ob.data):
        data = owner.animation_data
        if data and (data.drivers or data.nla_tracks or getattr(data, "use_tweak_mode", False)):
            raise ValueError(label + " has drivers/NLA; only a plain FK active action is supported.")
    if ob.constraints:
        raise ValueError(label + " has object constraints; rig-preserving conversion was refused.")


def _rsas_rig_weights(ob, arm, t, normalize=False):
    """No nearest-bone guesses or pruning. Normalize only the private deform layer."""
    names = {b.name for b in arm.data.bones if b.use_deform}
    groups = {g.index: g.name for g in ob.vertex_groups}
    if not groups or set(groups.values()) - names:
        raise ValueError("Rigged style supports only vertex groups belonging to real deform bones.")
    minimum, maximum, influences = float("inf"), 0., 0
    for i, vertex in enumerate(ob.data.vertices):
        if i % 1024 == 0:
            _rsas_check(t)
        weights = [(g.group, float(g.weight)) for g in vertex.groups]
        if any(g not in groups or not _rsas_math.isfinite(w) or not 0 <= w <= 1 for g, w in weights):
            raise ValueError("Invalid real bone weights on the mesh.")
        positive = [(g, w) for g, w in weights if w > 0]
        total = sum(w for g, w in positive)
        if not 1 <= len(positive) <= 4 or total <= 1e-8:
            raise ValueError("Every LOD vertex needs 1..4 real bone influences; weights are never invented or pruned.")
        if normalize:
            for g, w in positive:
                ob.vertex_groups[groups[g]].add([vertex.index], w / total, "REPLACE")
            total = sum(g.weight for g in vertex.groups if g.weight > 0)
            if abs(total - 1) > 1e-5:
                raise ValueError("Decimated bone weights could not be normalized.")
        minimum, maximum = min(minimum, total), max(maximum, total)
        influences = max(influences, len(positive))
    return {"vertices": len(ob.data.vertices), "maxInfluences": influences,
            "minSum": minimum, "maxSum": maximum, "normalized": maximum <= 1.00001 and minimum >= .99999}


def _rsas_rig_uv(mesh, expected=None):
    names = [uv.name for uv in mesh.uv_layers]
    if len(names) > 8 or (expected is not None and names != expected):
        raise ValueError("Decimation did not preserve the source UV map set (maximum 8 maps).")
    if any(len(uv.data) != len(mesh.loops) or
           any(not _rsas_math.isfinite(c) for item in uv.data for c in item.uv) for uv in mesh.uv_layers):
        raise ValueError("The rigged mesh contains invalid UV coordinates.")
    return names


def _rsas_rig_style(name, style, cap, size, t):
    """Stage an undeformed rest mesh; bind to the unchanged skeleton only last."""
    if style == "voxel":
        raise ValueError("Voxel conversion cannot preserve a rig. Choose a mesh LOD style or a static copy.")
    _rsas_check(t)
    source = _rs_obj(name)
    if (source.type != "MESH" or bpy.context.mode != "OBJECT" or source.mode != "OBJECT" or
            source.name not in bpy.context.view_layer.objects or not source.visible_get()):
        raise ValueError("Choose a visible rigged mesh in Object Mode in the current view layer.")
    _rsas_rig_local(source, "Source mesh")
    if (source.data.shape_keys or source.data.animation_data or source.animation_data or
            len(source.data.vertices) > 100000):
        raise ValueError("Rigged LOD needs <=100000 rest vertices, no morph keys and no mesh/object animation.")
    source_triangles = _rsas_size(source.data)
    if len(source.modifiers) != 1 or source.modifiers[0].type != "ARMATURE":
        raise ValueError("Rigged LOD needs exactly one Armature modifier and no other modifiers.")
    modifier = source.modifiers[0]
    arm = modifier.object
    if (arm is None or arm.type != "ARMATURE" or not modifier.show_viewport or not modifier.show_render or
            not modifier.use_vertex_groups or modifier.use_bone_envelopes or modifier.use_multi_modifier or
            modifier.vertex_group or modifier.use_deform_preserve_volume):
        raise ValueError("Use one enabled linear vertex-group Armature modifier without envelopes, masks or preserve-volume.")
    _rsas_rig_local(arm, "Armature")
    if (arm.mode != "OBJECT" or arm.name not in bpy.context.view_layer.objects or not arm.visible_get() or
            arm.parent or source.parent not in (None, arm) or source.parent_type != "OBJECT" or
            not 1 <= len(arm.data.bones) <= 128 or arm.data.animation_data):
        raise ValueError("Use a visible local FK armature with 1..128 bones and simple object parenting.")
    if any(b.constraints or b.custom_shape or not b.bone.use_deform or b.bone.bbone_segments != 1 or
           b.bone.inherit_scale != "FULL" or not b.bone.use_inherit_rotation or not b.bone.use_local_location
           for b in arm.pose.bones):
        raise ValueError("Control/constraint/B-Bone or nonstandard inheritance rigs are unsupported for this LOD.")
    data = arm.animation_data
    action = data.action if data else None
    slot = getattr(data, "action_slot", None) if data else None
    if action:
        if action.library or action.users - int(action.use_fake_user) > 1:
            raise ValueError("A shared/linked armature action is unsupported; make a single-user action first.")
        if getattr(action, "is_action_layered", False) and (len(action.slots) != 1 or slot is None):
            raise ValueError("Rigged LOD needs one explicitly assigned action slot.")
    for owner in (source, arm):
        matrix = owner.matrix_world
        if (any(not _rsas_math.isfinite(v) or abs(v) > 1e7 for row in matrix for v in row) or
                abs(matrix.to_3x3().determinant()) < 1e-12):
            raise ValueError("Unsupported singular/nonfinite rig transform.")
    if any(not _rsas_math.isfinite(c) or abs(c) > 1e7 for v in source.data.vertices for c in v.co):
        raise ValueError("Invalid rest-mesh coordinates.")
    uv_names = _rsas_rig_uv(source.data)
    if not _rsas_rig_weights(source, arm, t)["normalized"]:
        raise ValueError("Normalize the source's real bone weights before making a rigged LOD; authored weighting is never guessed.")
    slots = [s.material for s in source.material_slots] or [None]
    if len(slots) > 16 or any(p.material_index >= len(slots) for p in source.data.polygons):
        raise ValueError("Rigged LOD supports at most 16 valid material slots.")
    desc = [_rsas_graph(m, source.data) for m in slots]
    for mat in slots:
        if mat and mat.use_nodes:
            for node in mat.node_tree.nodes:
                if node.type == "UVMAP" and node.uv_map and node.uv_map not in uv_names:
                    raise ValueError("A material references a missing UV map.")
                if node.type == "NORMAL_MAP" and node.uv_map and node.uv_map not in uv_names:
                    raise ValueError("A normal map references a missing UV map.")
    buffers = _rsas_pixels(desc, t)  # Read/validate all source maps before allocating a copy.
    owned = {k: [] for k in ("objects", "meshes", "materials", "images")}
    hidden, render_hidden, success = source.hide_get(), source.hide_render, False
    try:
        _rsas_check(t)
        mesh = source.data.copy()  # Raw undeformed rest data, NEVER evaluated_get(source).
        owned["meshes"].append(mesh)
        mesh.use_fake_user = False
        ob = bpy.data.objects.new(source.name + " " + style + " LOD", mesh)
        owned["objects"].append(ob)
        wanted_groups = [group.name for group in source.vertex_groups]
        # Blender builds differ on whether a copied Mesh carries group names.
        # Never clear those groups: doing so can erase its actual deform weights.
        if not ob.vertex_groups:
            for group in source.vertex_groups:
                ob.vertex_groups.new(name=group.name)
        if [group.name for group in ob.vertex_groups] != wanted_groups:
            raise ValueError("The private rest copy did not preserve bone-group definitions.")
        for group in source.vertex_groups:
            ob.vertex_groups[group.name].lock_weight = group.lock_weight
        _rsas_rig_weights(ob, arm, t)
        ob.parent = source.parent
        ob.matrix_parent_inverse = source.matrix_parent_inverse.copy()
        ob.matrix_world = source.matrix_world.copy()
        bpy.context.scene.collection.objects.link(ob)
        _rsas_reduce(ob, cap, owned, t, rigged=True)  # No armature on staged copy yet.
        _rsas_size(ob.data)
        _rsas_rig_uv(ob.data, uv_names)
        if [group.name for group in ob.vertex_groups] != wanted_groups:
            raise ValueError("Decimation did not preserve bone-group definitions.")
        if uv_names:
            ob.data.uv_layers.active_index = source.data.uv_layers.active_index
        for uv in source.data.uv_layers:
            if uv.active_render:
                ob.data.uv_layers[uv.name].active_render = True
        if any(p.material_index >= len(desc) for p in ob.data.polygons):
            raise ValueError("Decimation did not preserve material assignments.")
        weights = _rsas_rig_weights(ob, arm, t, normalize=True)
        # Rigged retro retains all authored PBR map connections as well as UVs.
        _rsas_materials(ob.data, desc, buffers, size, style == "retro", owned, t, retain_maps=True)
        for poly in ob.data.polygons:
            poly.use_smooth = style != "retro"
        ob.data.update()
        triangles = _rsas_triangles(ob.data)
        if not 1 <= triangles <= cap:
            raise ValueError("Rigged LOD failed the measured triangle maximum.")
        bind = ob.modifiers.new(modifier.name, "ARMATURE")
        bind.object = arm
        bind.use_vertex_groups, bind.use_bone_envelopes = True, False
        bind.use_deform_preserve_volume = False
        used = {node.image for m in ob.data.materials if m and m.use_nodes
                for node in m.node_tree.nodes if node.type == "TEX_IMAGE" and node.image}
        textures = [{"name": i.name, "width": int(i.size[0]), "height": int(i.size[1])}
                    for i in sorted(used, key=lambda image: image.name)]
        if any(max(item["width"], item["height"]) > size for item in textures):
            raise ValueError("Rigged LOD failed the measured texture maximum.")
        ob["riggerset_style"], ob["riggerset_style_source"] = style, source.name
        ob["riggerset_style_preserve_rig"] = True
        result = dict(changed="mesh.style", object=ob.name, source=source.name, style=style,
                      vertices=len(ob.data.vertices), triangles=triangles, sourceTriangles=source_triangles,
                      sourceVertices=len(source.data.vertices), textureSize=size, textures=textures,
                      originalPreserved=True, rigged=True, armature=arm.name, weights=weights,
                      action=action.name if action else None, actionSlot=slot.identifier if slot else None,
                      note="Rest-mesh LOD on the original unchanged skeleton and clips; no bone weights invented or pruned.")
        _rsas_check(t)
        source.hide_set(True)
        source.hide_render = True
        _rsas_check(t)
        _rsas_clean(owned, False)
        success = True
        return result
    finally:
        if not success:
            source.hide_set(hidden)
            source.hide_render = render_hidden
            _rsas_clean(owned, True)
            bpy.context.view_layer.update()


def _rs_asset_style(a):
    from mathutils import Matrix
    t = (_rs_control().get("epoch"), _RS_REV, _rsas_time.monotonic())
    name, style, cap, size, cells = _rsas_args(a)
    if a.get("preserveRig", False):
        return _rsas_rig_style(name, style, cap, size, t)
    _rsas_check(t)
    source = _rs_obj(name)
    if (source.type != "MESH" or bpy.context.mode != "OBJECT" or source.mode != "OBJECT" or
            source.name not in bpy.context.view_layer.objects or not source.visible_get()):
        raise ValueError("Choose a visible mesh in Object Mode in the current view layer.")
    if source.library or source.data.library or source.override_library or not source.is_editable:
        raise ValueError("Unsupported linked/overridden source; use a local working copy.")
    _rsas_size(source.data)
    if (len(source.modifiers) > 2 or any(m.type != "ARMATURE" for m in source.modifiers) or
            any(m.show_render != m.show_viewport for m in source.modifiers)):
        raise ValueError("Unsupported modifier stack: only up to two matching viewport/render Armature modifiers are bounded; apply other modifiers on a working copy first.")
    owned = {k: [] for k in ("objects", "meshes", "materials", "images")}
    active, selected = bpy.context.view_layer.objects.active, set(bpy.context.selected_objects)
    hidden, render_hidden, success = source.hide_get(), source.hide_render, False
    try:
        graph = bpy.context.evaluated_depsgraph_get()
        evaluated = source.evaluated_get(graph)
        mesh = bpy.data.meshes.new_from_object(evaluated, preserve_all_data_layers=True, depsgraph=graph)
        owned["meshes"].append(mesh)
        _rsas_check(t)
        _rsas_size(mesh)
        if mesh.shape_keys:
            raise ValueError("Cannot safely isolate evaluated shape keys into a static mesh.")
        ob = bpy.data.objects.new(source.name + " " + style, mesh)
        owned["objects"].append(ob)
        ob.vertex_groups.clear()  # Evaluated meshes can retain deform-group definitions.
        ob.matrix_world = evaluated.matrix_world.copy()
        if (any(not _rsas_math.isfinite(v) or abs(v) > 1e7 for row in ob.matrix_world for v in row) or
                abs(ob.matrix_world.to_3x3().determinant()) < 1e-12):
            raise ValueError("Unsupported singular/nonfinite world transform.")
        for i, vertex in enumerate(mesh.vertices):
            if i % 2048 == 0:
                _rsas_check(t)
            if any(not _rsas_math.isfinite(v) or abs(v) > 1e7 for v in vertex.co):
                raise ValueError("Unsupported nonfinite or excessive evaluated coordinates.")
        bpy.context.scene.collection.objects.link(ob)
        if style in ("game", "performance", "retro", "voxel"):
            _rsas_weld(ob.data, t)
        _rsas_check(t)
        slots = [s.material for s in evaluated.material_slots] or [None]
        if len(slots) > 16 or any(p.material_index >= len(slots) for p in mesh.polygons):
            raise ValueError("Style conversion supports at most 16 valid material slots.")
        desc = [_rsas_graph(m, mesh) for m in slots]
        buffers = _rsas_pixels(desc, t)
        if style == "voxel":
            prepass_note = _rsas_voxel(ob, cells, size, desc, buffers, owned, t)
        else:
            _rsas_reduce(ob, cap, owned, t)
            if (any(d["uv"] and d["uv"] not in ob.data.uv_layers for d in desc) or
                    any(p.material_index >= len(desc) for p in ob.data.polygons)):
                raise ValueError("Decimation could not preserve UV/material mapping.")
            _rsas_materials(ob.data, desc, buffers, size, style == "retro", owned, t)
        ob.vertex_groups.clear()  # Also strip definitions carried by a replacement mesh.
        for poly in ob.data.polygons:
            poly.use_smooth = style in ("detailed", "game", "performance")
        for edge in ob.data.edges:
            edge.use_edge_sharp = False
        if hasattr(ob.data, "use_auto_smooth"):
            ob.data.use_auto_smooth = False
        if getattr(ob.data, "has_custom_normals", False):
            ob.data.normals_split_custom_set([(0., 0., 0.)] * len(ob.data.loops))
        ob.data.update()
        triangles = _rsas_triangles(ob.data)
        if not 1 <= triangles <= (200000 if style == "voxel" else cap):
            raise ValueError("Styled copy failed its final triangle maximum.")
        ob["riggerset_style"], ob["riggerset_style_source"] = style, source.name
        used = {n.image for m in ob.data.materials if m and m.use_nodes
                for n in m.node_tree.nodes if n.type == "TEX_IMAGE" and n.image}
        textures = [{"name": i.name, "width": int(i.size[0]), "height": int(i.size[1])}
                    for i in sorted(used, key=lambda i: i.name)]
        note = "Unrigged static copy of the current evaluated pose; no detail was invented or upscaled."
        if style == "voxel":
            note += " Triangle target ignored; exposed cubic faces use a nearest-source base-color atlas." + prepass_note
        result = dict(changed="mesh.style", object=ob.name, source=source.name, style=style,
                      vertices=len(ob.data.vertices), triangles=triangles, textureSize=size,
                      textures=textures, originalPreserved=True, rigged=False, note=note)
        if style == "voxel":
            result["voxelCells"] = cells
        _rsas_check(t)
        source.hide_set(True)
        source.hide_render = True
        _rsas_check(t)  # Includes cancellation after object creation AND after visibility commit.
        _rsas_clean(owned, False)
        success = True
        return result
    finally:
        if not success:
            source.hide_set(hidden)
            source.hide_render = render_hidden
            _rsas_clean(owned, True)
            bpy.context.view_layer.update()
            for item in tuple(bpy.context.view_layer.objects):
                if item is not None:
                    item.select_set(item in selected)
            bpy.context.view_layer.objects.active = active if active and active.name in bpy.context.view_layer.objects else None

# END RIGGERSET AUTOMATIC MOTION

def _rs_tool(tool,a):
    if tool == "rig.joint.inspect": return _rs_joint_inspect(a)
    if tool == "rig.joint.plan": return _rs_joint_plan(a)
    if tool == "rig.joint.apply": return _rs_joint_apply(a)
    if tool == "animation.arthropod": return _rs_apply_arthropod_motion(a)
    if tool == "animation.retarget": return _rs_animation_retarget(a)
    if tool == "mesh.style": return _rs_asset_style(a)
    if tool == "mesh.cut.plan": return _rs_cut_plan(a)
    if tool == "mesh.cut": return _rs_cut_apply(a)
    if tool == "mesh.build": return _rs_build(a)
    if tool == "mesh.sculpt": return _rs_sculpt(a)
    scene = bpy.context.scene
    if tool == "mesh.selection": return _rs_selection_create(a)
    if tool == "mesh.repair": return _rs_selection_repair(a)
    if tool == "texture.variant": return _rs_texture_variant(a)
    if tool == "rig.rest": return _rs_rig_rest(a)
    if tool == "rig.joint.set": return _rs_joint_set(a)
    if tool == "rig.limb.configure": return _rs_limb_configure(a)
    if tool == "rig.weights.rigid": return _rs_selection_weights(a)
    if tool == "animation.validate": return _rs_motion_validate(a)
    if tool == "contact.set": return _rs_contact_set(a)
    if tool == "contact.remove": return _rs_contact_remove(a)
    if tool == "contacts.inspect": return _rs_contacts_report(a)
    if tool == "asset.scale": return _rs_asset_scale(a)
    if tool == "scene.inspect":
        return _rs_inspect()
    if tool == "object.transform":
        ob=_rs_obj(a["object"])
        if "location" in a: ob.location=_rs_vec(a["location"],3,-100,100)
        if "rotation" in a: ob.rotation_mode="XYZ"; ob.rotation_euler=_rs_vec(a["rotation"],3,-math.pi*4,math.pi*4)
        if "scale" in a: ob.scale=_rs_vec(a["scale"],3,.01,100)
    elif tool == "mesh.offset":
        ob=_rs_obj(a["object"])
        if ob.type != "MESH" or len(ob.data.vertices)>500000: raise ValueError("Use a mesh up to 500,000 vertices")
        center=Vector(_rs_vec(a["center"],3,-100,100)); radius=_rs_num(a["radius"],.0001,2); strength=_rs_num(a["strength"],-.1,.1)
        for vertex in ob.data.vertices:
            distance=(vertex.co-center).length
            if distance < radius:
                vertex.co += vertex.normal * (strength * (1-distance/radius)**2)
        ob.data.update()
    elif tool == "material.set":
        mat=bpy.data.materials.get(str(a["material"]))
        if mat is None: raise ValueError("Material not found")
        if "color" in a: mat.diffuse_color=_rs_vec(a["color"],4,0,1)
        if "roughness" in a: mat.roughness=_rs_num(a["roughness"],0,1)
        if "metallic" in a: mat.metallic=_rs_num(a["metallic"],0,1)
        if mat.use_nodes:
            node=next((n for n in mat.node_tree.nodes if n.type=="BSDF_PRINCIPLED"),None)
            if node:
                for key,socket in (("color","Base Color"),("roughness","Roughness"),("metallic","Metallic")):
                    if key in a: node.inputs[socket].default_value=a[key]
    elif tool == "light.set":
        name=str(a["name"])[:120]; typ=a["type"]
        if typ not in ("AREA","POINT","SUN"): raise ValueError("Unknown light type")
        ob=bpy.data.objects.get(name)
        if ob is None:
            ob=bpy.data.objects.new(name,bpy.data.lights.new(name,typ)); scene.collection.objects.link(ob)
        if ob.type != "LIGHT": raise ValueError("Name belongs to a non-light object")
        ob.data.type=typ; ob.data.energy=_rs_num(a["energy"],0,10000); ob.data.color=_rs_vec(a["color"],3,0,1)
        if "location" in a: ob.location=_rs_vec(a["location"],3,-100,100)
        if "rotation" in a: ob.rotation_euler=_rs_vec(a["rotation"],3,-math.pi*4,math.pi*4)
    elif tool == "texture.paint":
        image=bpy.data.images.get(str(a["image"]))
        if image is None or not image.has_data: raise ValueError("Loaded texture not found")
        width,height=image.size[:]; channels=image.channels
        if width*height>4194304 or channels!=4: raise ValueError("Painting supports RGBA textures up to 2048 by 2048")
        points=a["points"]; color=_rs_vec(a["color"],4,0,1); radius=int(_rs_num(a["radius"],1,64))
        if not isinstance(points,list) or not 1<=len(points)<=128: raise ValueError("Invalid brush stroke")
        pixels=array.array("f",[0])*(width*height*channels); image.pixels.foreach_get(pixels)
        for point in points:
            u,v=_rs_vec(point,2,0,1); cx=int(u*(width-1)); cy=int(v*(height-1))
            for y in range(max(0,cy-radius),min(height,cy+radius+1)):
                for x in range(max(0,cx-radius),min(width,cx+radius+1)):
                    dist=math.hypot(x-cx,y-cy)
                    if dist>radius: continue
                    alpha=color[3]*(1-dist/radius); at=(y*width+x)*4
                    for c in range(3): pixels[at+c]=pixels[at+c]*(1-alpha)+color[c]*alpha
        image.pixels.foreach_set(pixels); image.update(); image.pack()
    elif tool == "bone.pose":
        ob=_rs_obj(a["armature"])
        if ob.type!="ARMATURE": raise ValueError("Object is not an armature")
        bone=ob.pose.bones.get(str(a["bone"]))
        if bone is None: raise ValueError("Bone not found")
        bone.rotation_mode="XYZ"; bone.rotation_euler=_rs_vec(a["rotation"],3,-math.pi*2,math.pi*2)
        if "location" in a: bone.location=_rs_vec(a["location"],3,-2,2)
    elif tool == "animation.preset":
        return _rs_apply_motion(a)
    elif tool == "animation.creature":
        return _rs_apply_creature_motion(a)
    elif tool == "face.pose":
        return _rs_face_pose(a)
    elif tool == "animation.lipsync":
        return _rs_face_lipsync(a)
    elif tool == "keyframe.insert":
        ob=_rs_obj(a["object"]); frame=int(_rs_num(a["frame"],1,10000)); target=ob
        if "bone" in a:
            if ob.type!="ARMATURE": raise ValueError("Bone keyframe needs an armature")
            target=ob.pose.bones.get(str(a["bone"]))
            if target is None: raise ValueError("Bone not found")
        channels=a["channels"]
        if not isinstance(channels,list) or not 1<=len(channels)<=3: raise ValueError("Invalid keyframe channels")
        for channel in channels:
            if channel not in ("rotation","location","scale"): raise ValueError("Invalid channel")
            if channel=="rotation":
                rotation=_rs_euler(target); target.rotation_mode="XYZ"; target.rotation_euler=rotation
            target.keyframe_insert(data_path="rotation_euler" if channel=="rotation" else channel,frame=frame)
    elif tool == "timeline.set":
        if "start" in a: scene.frame_start=int(_rs_num(a["start"],1,10000))
        if "end" in a: scene.frame_end=int(_rs_num(a["end"],1,10000))
        if scene.frame_start>scene.frame_end: raise ValueError("Invalid timeline range")
        if "fps" in a: scene.render.fps=int(_rs_num(a["fps"],1,60))
        scene.frame_set(int(_rs_num(a["frame"],1,10000)))
    elif tool == "timeline.play":
        if not isinstance(a.get("playing"),bool): raise ValueError("Invalid playback switch")
        active=bool(bpy.context.screen and bpy.context.screen.is_animation_playing)
        if active != a["playing"]:
            window=_rs_window()
            if window is None: raise ValueError("Playback requires a visible Blender screen")
            with bpy.context.temp_override(window=window,screen=window.screen):
                if not bpy.ops.screen.animation_play.poll(): raise ValueError("Playback requires a visible Blender screen")
                bpy.ops.screen.animation_play()
    elif tool == "scene.undo":
        if not _RS_UNDO: raise ValueError("No tool checkpoint to undo")
        file=_RS_UNDO.pop()
        _rs_restore(file)
    else:
        raise ValueError("Unknown tool")
    bpy.context.view_layer.update()
    return {"changed":tool}

def _rs_do(token,spec):
    global _RS_REV, _RS_BUSY, _RS_UNDO
    _RS_BUSY=True
    rolled_back=False
    try:
        if not isinstance(token,str) or not token.replace("-","").replace("_","").isalnum(): raise ValueError("Invalid command identity")
        op=spec.get("op"); before=_rs_control()
        if spec.get("epoch") != before.get("epoch"): raise ValueError("Command cancelled")
        if op=="tool" and spec.get("expectedRevision") != _RS_REV: raise ValueError("Stale scene revision")
        if before.get("paused") and op=="tool" and spec.get("remote"): raise ValueError("Remote editing is paused")
        result={}
        if op=="load_glb":
            src=RS_IO+"/in/"+token+".glb"
            _rs_mode_object()
            bpy.ops.object.select_all(action="SELECT"); bpy.ops.object.delete(use_global=False)
            bpy.ops.import_scene.gltf(filepath=src,merge_vertices=_rs_glb_mergeable(src))
            try: os.remove(src)
            except OSError: pass
            _rs_clear_undo(); _RS_REV+=1; _rs_view_all(); result=_rs_inspect()
        elif op=="load_blend":
            src=RS_IO+"/in/"+token+".blend"
            try: bpy.ops.wm.open_mainfile(filepath=src,load_ui=False,use_scripts=False)
            finally: _rs_unlink(src)
            _rs_clear_undo(); _RS_REV+=1; _rs_view_all(); result=_rs_inspect()
        elif op=="save_blend":
            dst=RS_IO+"/out/"+token+".blend"
            _rs_mode_object(); bpy.ops.wm.save_as_mainfile(filepath=dst,copy=True,check_existing=False)
            result={"file":dst,"bytes":os.path.getsize(dst),"revision":_RS_REV}
        elif op=="export_glb":
            dst=RS_IO+"/out/"+token+".glb"; _rs_mode_object()
            styled_scene=any(ob.get("riggerset_style") for ob in bpy.context.scene.objects)
            bpy.ops.export_scene.gltf(filepath=dst,export_format="GLB",export_animations=bool(spec.get("animated",True)),export_extras=True,use_visible=styled_scene,use_active_scene=styled_scene)
            result={"file":dst,"bytes":os.path.getsize(dst),"revision":_RS_REV}
        elif op=="viewport":
            result=_rs_viewport(bool(spec.get("visible")))
        elif op=="cut_discard":
            _rs_cut_forget(spec.get("previewId")); result={"revision":_RS_REV}
        elif op=="cut_preview":
            dst=RS_IO+"/out/"+token+".glb"
            result=_rs_cut_preview_file(spec.get("previewId"),dst)
        elif op=="selection_preview":
            dst=RS_IO+"/out/"+token+".glb"
            result=_rs_selection_preview_file(spec.get("selectionId"),dst)
        elif op=="motion_preview":
            if spec.get("expectedRevision") != _RS_REV: raise ValueError("Stale scene revision; run the motion check again.")
            result=_rs_motion_preview_export(spec,RS_IO+"/out/"+token+".glb")
        elif op=="tool":
            if spec.get("sceneCheckpoint") is not None: _rs_motion_checkpoint(spec["sceneCheckpoint"])
            tool=spec.get("tool"); args=spec.get("args",{})
            if not isinstance(args,dict): raise ValueError("Invalid tool arguments")
            mutation=tool not in ("scene.inspect","timeline.play","mesh.selection","mesh.cut.plan","animation.validate","contacts.inspect","rig.joint.inspect","rig.joint.plan")
            if mutation and tool!="scene.undo": _rs_checkpoint()
            try:
                result=_rs_tool(tool,args)
                if _rs_control().get("epoch") != before.get("epoch"): raise ValueError("Command interrupted; restored the last checkpoint")
            except Exception:
                if mutation and tool!="scene.undo" and _RS_UNDO:
                    file=_RS_UNDO.pop(); _rs_restore(file); rolled_back=True
                raise
            if mutation: _RS_REV+=1
            result["revision"]=_RS_REV
        else:
            raise ValueError("Unknown bridge operation")
        if _rs_control().get("epoch") != before.get("epoch"): raise ValueError("Command interrupted; reload the last saved checkpoint")
        return {"ok":True,"result":result}
    except Exception as error:
        message=str(error)[:400]
        code="cancelled" if any(t in message.lower() for t in ("cancel", "interrupt", "stopped")) else "stale-input" if any(t in message.lower() for t in ("stale", "digest", "expired", "changed")) else "unsupported" if any(t in message.lower() for t in ("unsupported", "shape key", "ambiguous", "cannot safely", "not supported")) else "invalid-input" if isinstance(error,ValueError) else "operation-failed"
        return {"ok":False,"error":message,"failure":{"code":code,"rolledBack":rolled_back},"revision":_RS_REV}
    finally:
        _RS_BUSY=False

def _rs_poll():
    try:
        pending=sorted(f for f in os.listdir(RS_IO+"/cmd") if f.endswith(".json"))
        for filename in pending[:1]:
            if not filename.endswith(".json"): continue
            token=filename[:-5]; source=RS_IO+"/cmd/"+filename
            try:
                with open(source) as handle: spec=json.load(handle)
                os.remove(source)
                result=_rs_do(token,spec)
            except Exception as error:
                _rs_unlink(source)
                result={"ok":False,"error":str(error)[:400],"revision":_RS_REV}
            target=RS_IO+"/ack/"+token+".json"
            with open(target+".tmp","w") as handle: json.dump(result,handle)
            os.replace(target+".tmp",target)
    except Exception:
        pass
    return .15

def rs_install():
    bpy.context.scene.render.fps=24
    bpy.context.scene.frame_end=60
    bpy.context.preferences.view.show_splash=False
    bpy.app.timers.register(_rs_poll,first_interval=.1,persistent=True)
    with open(RS_IO+"/ready","w") as handle: handle.write("ready")
    print("RIGGERSET_BRIDGE_READY",flush=True)
