# render_loop.py: a loop of the slider crank, from SliderCrank.blend (made by render_still.py). Blender 5.3.
#   machine:   the crank turns once, the rod and the slider follow, the camera stays still.
#   turntable: the machine stays as FreeCAD placed it, the camera goes once round it.
# In the Blender window: open SliderCrank.blend, Scripting tab, Open this file, set MODE, Run Script, then press
# Space in the 3D view to play it. Render > Render Animation writes the frames.
# Without a window:  nice blender -b SliderCrank.blend -P render_loop.py -- machine /abs/out/dir render
import bpy, sys, os, re, math

args = sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else []
MODE = args[0] if args else 'machine'          # or 'turntable'
OUT = args[1] if len(args) > 1 else bpy.path.abspath('//')
RENDER = 'render' in args[2:]
FRAMES, FPS = 72, 24                           # 72 frames: 5 degrees a frame, one turn in 3 seconds
R, L = 0.030, 0.100                            # crank radius and rod length in metres: lesson 1's spreadsheet, 30 and 100 mm

sc = bpy.context.scene
sc.frame_start, sc.frame_end = 1, FRAMES; sc.render.fps = FPS
def base_name(o): return re.sub(r'(\s*\(as assembled\))?(\.?\d{3})?$', '', o.name)
P = {base_name(o): o for o in bpy.data.objects if o.type == 'MESH' and o.name != 'Floor'}
for o in P.values(): o.animation_data_clear(); o.rotation_mode = 'XYZ'

# ---- the slider-crank equations: where each part is when the crank has turned theta ----
def pin(t):    return R * math.cos(t), R * math.sin(t)                         # crank pin centre
def slider(t): return R * math.cos(t) + math.sqrt(L * L - (R * math.sin(t)) ** 2)  # wrist pin, on the line of stroke
def lean(t):   return -math.asin(R * math.sin(t) / L)                           # rod angle, from the crank pin to the wrist pin

print('check   theta   slider x, mm   rod angle, deg')
for d in (0, 90, 180):
    t = math.radians(d); print('       %5d   %10.3f   %10.3f' % (d, 1000 * slider(t), math.degrees(lean(t))))
# FreeCAD's assembly, solved at the same angles: 130.000, 95.394, 70.000 mm and 0, -17.458, 0 deg.

if MODE == 'machine':
    z = {n: o.location.z for n, o in P.items()}         # heights stay as FreeCAD placed them
    for k in range(1, FRAMES + 1):
        t = 2 * math.pi * (k - 1) / FRAMES
        px, py = pin(t); xs = slider(t)
        moves = {'Crank': ((0, 0), t), 'CrankPin': ((px, py), t), 'ConnectingRod': ((px, py), lean(t)),
                 'Slider': ((xs, 0), 0), 'WristPin': ((xs, 0), 0)}
        for n, ((x, y), a) in moves.items():
            o = P[n]; o.location = (x, y, z[n]); o.rotation_euler = (0, 0, a)
            o.keyframe_insert('location', frame=k); o.keyframe_insert('rotation_euler', frame=k)
else:   # turntable: an Empty at the target carries the camera once round
    cam, target = sc.camera, bpy.data.objects['Target']
    cam.data.lens = 42                                   # a little wider: side on, the machine is longer
    orbit = bpy.data.objects.get('Orbit') or bpy.data.objects.new('Orbit', None)
    if orbit.name not in sc.collection.objects: sc.collection.objects.link(orbit)
    orbit.location = target.location; orbit.rotation_euler = (0, 0, 0)
    mw = cam.matrix_world.copy(); cam.parent = orbit; cam.matrix_parent_inverse = orbit.matrix_world.inverted(); cam.matrix_world = mw
    orbit.keyframe_insert('rotation_euler', frame=1)
    orbit.rotation_euler = (0, 0, 2 * math.pi); orbit.keyframe_insert('rotation_euler', frame=FRAMES + 1)   # frame 73 = frame 1
    for lay in orbit.animation_data.action.layers:      # Blender 5: an action keeps its curves in layers
        for st in lay.strips:
            for cb in st.channelbags:
                for fc in cb.fcurves:
                    for kp in fc.keyframe_points: kp.interpolation = 'LINEAR'   # a steady turn, no slowing at the ends

sc.render.filepath = os.path.join(OUT, 'frames-' + MODE, '')
if RENDER:
    sc.render.resolution_x, sc.render.resolution_y = int(os.environ.get('W', 960)), int(os.environ.get('H', 540))
    sc.cycles.samples = int(os.environ.get('SAMPLES', 24))
    sc.frame_start, sc.frame_end = int(os.environ.get('FIRST', 1)), int(os.environ.get('LAST', FRAMES))
    bpy.ops.render.render(animation=True)
    print('frames in', sc.render.filepath)
