# dekaleg.py
# No copyright, 2026 Garth Zeglin.  This file is explicitly placed in the public domain.
# Sample Webots controller file for driving a disc-shaped body with many simple legs and offset-mass rotor.

print("dekaleg.py waking up.")

# Import standard Python libraries.
import math

# Import the Webots simulator API.
from controller import Robot

# Define the time step in milliseconds between controller updates.
EVENT_LOOP_DT = 20

# Request a proxy object representing the robot to control.
robot = Robot()
robot_name = robot.getName()
print("%s: controller connected." % (robot_name))
print("%s has %d devices." % (robot_name, robot.getNumberOfDevices()))

# Fetch handles for the motors.
legs = []
for i in range(robot.getNumberOfDevices()):
    dev = robot.getDeviceByIndex(i)
    if dev.name.startswith('motor'):
        legs.append(dev)
num_legs = len(legs)


# Set position control mode.
for leg in legs:
    leg.setPosition(0.0)

# Configure the rotor to constant velocity.
rotor = robot.getDevice('rotor')
rotor.setPosition(math.inf)
rotor.setVelocity(6*math.pi)

# Set time constants for the overall oscillation.
period = 4.0

# Run loop to execute a periodic script until the simulation quits.
# If the controller returns -1, the simulator is quitting.
while robot.step(EVENT_LOOP_DT) != -1:
    # Read simulator clock time.
    t = robot.getTime()

    # Oscillate each leg out of phase.
    for i, leg in enumerate(legs):
        phase = (math.pi * 2 * t / period) + (math.pi * i / num_legs)
        leg.setPosition(0.5 * math.sin(phase))
