"""Tutorial - Wires 9: Wire-wire contacts

Wires can collide with other wires when collisions are enabled between them with
agxWire.WireController. This tutorial shows wires that meet each other under high tension
and at high speed, at a 60 Hz time step:

  1. Two crane falls braided by a slewing load, then unwound.
  2. A tensioned wire is cut and snaps back over two crossing wires.
  3. Taut wires pushed onto crossing wires at 2, 5 and 10 m/s.
  4. A hoist wire running over a crossing wire, used as a sheave.
  5. Five falls braided by a slewing crane top.

The contacts are kept between the closest points of the wire segments and remember which side
of the other wire they are on, so the wires do not pass through each other.
"""

import agx
import agxCollide
import agxOSG
import agxWire
from agxPythonModules.utils.callbacks import StepEventCallback as sec
from agxPythonModules.utils.environment import application, init_app, root, simulation


def setup(title, eye, center):
    """Common scene setup: time step, ground, camera and help text."""
    sim = simulation()
    sim.setTimeStep(1.0 / 60.0)

    ground = agx.RigidBody(agxCollide.Geometry(agxCollide.Box(30, 30, 0.5)))
    ground.setMotionControl(agx.RigidBody.STATIC)
    ground.setPosition(0, 0, -1.5)
    sim.add(ground)
    agxOSG.setDiffuseColor(
        agxOSG.createVisual(ground, root()), agx.Color.LightGray()
    )

    decorator = application().getSceneDecorator()
    decorator.setEnableShadows(True)
    decorator.setShadowMethod(agxOSG.SceneDecorator.SOFT_SHADOWMAP)
    decorator.setBackgroundColor(agx.Vec3(0.8, 0.8, 0.9), agx.Vec3(0.65, 0.65, 0.7))

    camera_data = application().getCameraData()
    camera_data.eye = agx.Vec3(4.5722, -30.8596, 11.7194)
    camera_data.center = agx.Vec3(2.3758, 0.9014, 3.7455)
    camera_data.up = agx.Vec3(-0.0271, 0.2417, 0.9700)
    camera_data.nearClippingPlane = 0.1
    camera_data.farClippingPlane = 5000
    application().applyCameraData(camera_data)

    decorator.setText(0, title)
    decorator.setText(1, "Press e to start the simulation, 1-5 to change scene")
    return Scene(sim)


class Scene:
    def __init__(self, sim):
        self.sim = sim
        self.wires = []

        # Steel wires.
        self.material = agx.Material("steelWire")
        self.material.getBulkMaterial().setDensity(7800)
        self.material.getWireMaterial().setYoungsModulusStretch(6e10)
        self.contactMaterial(self.material, self.material)

    def contactMaterial(self, m1, m2):
        """The wire-wire contacts use these contact material parameters."""
        cm = self.sim.getMaterialManager().getOrCreateContactMaterial(m1, m2)
        cm.setYoungsModulus(2e11)
        cm.setFrictionCoefficient(0.3)
        # Important for performance: the default friction compliance (5e-9) is very stiff, and wires
        # braided under tension can be several times slower to solve with it. Around 1e-5 is
        # recommended, see the user manual (Wire-wire interaction).
        cm.setFrictionCompliance(1e-5)

    def body(self, shape, position, motion=agx.RigidBody.DYNAMICS, mass=None):
        rb = agx.RigidBody(agxCollide.Geometry(shape))
        rb.setPosition(agx.Vec3(*position))
        rb.setMotionControl(motion)
        rb.getGeometries()[0].setMaterial(self.material)
        if mass is not None:
            rb.getMassProperties().setMass(mass)
        self.sim.add(rb)
        node = agxOSG.createVisual(rb, root())
        agxOSG.setDiffuseColor(
            node,
            agx.Color.DarkGoldenrod()
            if motion == agx.RigidBody.DYNAMICS
            else agx.Color.SlateGray(),
        )
        return rb

    def wire(self, radius, nodes, resolution=2.0, material=None, attachedTo=()):
        wire = agxWire.Wire(radius, resolution)
        wire.setMaterial(material or self.material)
        for node in nodes:
            wire.add(node)
        self.sim.add(wire)
        for body in attachedTo:
            wire.setEnableCollisions(body, False)
        renderer = agxOSG.WireRenderer(wire, root())
        renderer.setColor(agx.Color.getColor(len(self.wires) % 10))
        self.sim.add(renderer)
        self.wires.append(wire)
        return wire

    def span(self, radius, p0, p1, sag):
        """A wire fixed in the world at both ends, with some sag. A straight span has no slack,
        and gravity alone would give it a huge tension."""
        mid = [(a + b) / 2 for a, b in zip(p0, p1)]
        return self.wire(
            radius,
            [
                agxWire.BodyFixedNode(None, *p0),
                agxWire.FreeNode(mid[0], mid[1], mid[2] - sag),
                agxWire.BodyFixedNode(None, *p1),
            ],
        )

    def collide(self, wire1, wire2):
        """Wire-wire collisions are enabled per pair of wires."""
        agxWire.WireController.instance().setEnableCollisions(wire1, wire2, True)

    def collideAll(self):
        for i, w1 in enumerate(self.wires):
            for w2 in self.wires[i + 1 :]:
                self.collide(w1, w2)


def slew(load, inertiaZ, omegaOf, maxTorque):
    """Rotate the load about the vertical axis, like a slewing crane or a tagline would."""

    def pre(t):
        tau = inertiaZ * 4.0 * (omegaOf(t) - load.getAngularVelocity().z())
        load.addTorque(agx.Vec3(0, 0, max(-maxTorque, min(maxTorque, tau))))

    sec.preCallback(pre)


def buildScene1():
    """Two falls from a crane tip to a 7.8 t load. The load is slewed 2 rad/s for 14 s so the falls
    braid around each other, then slewed back to unwind them."""
    s = setup("Two crane falls braided by a slewing load", (0, -25, 14), (0, 0, 8))
    tip = s.body(agxCollide.Box(1.0, 0.3, 0.2), (0, 0, 20.2), agx.RigidBody.STATIC)
    load = s.body(agxCollide.Box(1.0, 0.4, 0.25), (0, 0, 2.0))
    for x in (-0.6, 0.6):
        s.wire(
            0.02,
            [
                agxWire.BodyFixedNode(tip, x, 0, -0.2),
                agxWire.BodyFixedNode(load, x, 0, 0.25),
            ],
            attachedTo=(tip, load),
        )
    s.collideAll()
    mass = load.getMassProperties().getMass()
    slew(
        load,
        mass * (4 * 1.0**2 + 4 * 0.4**2) / 12.0,
        lambda t: 2.0 if 1 < t < 15 else (-2.0 if 18 < t < 32 else 0.0),
        2e5,
    )


def buildScene2():
    """A wire tensioned to about 250 kN and deflected over a crossing wire is cut at t = 3 s.
    The free end recoils at more than 20 m/s across the wire below it and the wire above it."""
    s = setup("A tensioned wire is cut and snaps back", (-2, -22, 9), (0, 0, 3))
    snapMaterial = agx.Material("snapWire")
    snapMaterial.getBulkMaterial().setDensity(7800)
    snapMaterial.getWireMaterial().setYoungsModulusStretch(1e10)
    s.contactMaterial(snapMaterial, s.material)

    r = 0.02
    sag = 0.15
    end = s.body(
        agxCollide.Box(0.2, 0.2, 0.2), (10.2, 0, 2.8), agx.RigidBody.KINEMATICS
    )
    below = s.span(r, (4, -8, 3.0 + sag), (4, 8, 3.0 + sag), sag)
    snapping = s.wire(
        r,
        [
            agxWire.BodyFixedNode(None, -10, 0, 2.8),
            agxWire.FreeNode(4, 0, 3.0 + 2 * r),
            agxWire.BodyFixedNode(end, -0.2, 0, 0),
        ],
        material=snapMaterial,
        attachedTo=(end,),
    )
    zAbove = 2.8 + (3.0 + 2 * r - 2.8) * 0.5 + r + 0.03
    above = s.span(r, (-3, -8, zAbove + sag), (-3, 8, zAbove + sag), sag)
    s.collide(snapping, below)
    s.collide(snapping, above)

    state = {"cut": False}

    def pre(t):
        # Pull the end to tension the wire, then cut it at the end.
        end.setVelocity(agx.Vec3(0.2 if 0.5 < t < 2.5 else 0.0, 0, 0))
        if t >= 3.0 and not state["cut"]:
            state["cut"] = snapping.detach(False)

    sec.preCallback(pre)


def buildScene3():
    """Taut 10 mm wires are pushed down onto crossing wires at 2, 5 and 10 m/s. The moving ends
    continue 0.5 m past the crossing wire, which loads the wires to about 100 kN."""
    s = setup(
        "Taut wires pushed onto crossing wires at 2, 5 and 10 m/s",
        (6, -9, 4),
        (6, 0, 0),
    )
    radius = 0.005
    travel = 0.44 + 0.5  # down to the crossing wire, and then past it
    movers = []
    for i, speed in enumerate((2.0, 5.0, 10.0)):
        x = i * 6.0
        fixed = s.wire(
            radius,
            [
                agxWire.BodyFixedNode(None, x, -2, 0),
                agxWire.BodyFixedNode(None, x, 2, 0),
            ],
            resolution=4,
        )
        ends = [
            s.body(
                agxCollide.Box(0.05, 0.05, 0.05),
                (x + side * 2, 0, 0.5),
                agx.RigidBody.KINEMATICS,
            )
            for side in (-1, 1)
        ]
        moving = s.wire(
            radius,
            [agxWire.BodyFixedNode(ends[0]), agxWire.BodyFixedNode(ends[1])],
            resolution=4,
            attachedTo=ends,
        )
        s.collide(moving, fixed)
        movers.append((ends, speed))

    def pre(t):
        for ends, speed in movers:
            v = -speed if t < travel / speed else 0.0
            for end in ends:
                end.setVelocity(agx.Vec3(0, 0, v))

    sec.preCallback(pre)


def buildScene4():
    """A winch hauls a 2 t load with a hoist wire that runs over a crossing wire, used as a sheave.
    The crossing wire carries about twice the hoist tension. Haul in for 8 s, hold, then pay out."""
    s = setup("A hoist wire running over a crossing wire", (14, -16, 9), (0, 0, 4))
    rHoist, rSpan = 0.015, 0.025
    sag = 0.12
    # The sag node is off the crossing point so the two wires do not start in contact.
    span = s.span(rSpan, (-5.5, 0, 5.0 + sag), (6.5, 0, 5.0 + sag), sag)
    zSpan = 5.0 + sag * 0.5 / 6.0
    load = s.body(agxCollide.Box(1.0, 0.4, 0.25), (0, 2.0, 0.5), mass=2000)
    winchPosition = agx.Vec3(0, -6, 3)
    direction = agx.Vec3(0, 0, 5) - winchPosition
    direction.normalize()
    winch = agxWire.Winch(None, winchPosition, direction, 5.0)
    winch.setForceRange(1e6)
    hoist = s.wire(
        rHoist,
        [
            winch,
            agxWire.FreeNode(0, 0, zSpan + rHoist + rSpan + 0.05),
            agxWire.BodyFixedNode(load, 0, 0, 0.25),
        ],
        attachedTo=(load,),
    )
    s.collide(hoist, span)

    sec.preCallback(
        lambda t: winch.setSpeed(-0.3 if 1 < t < 9 else (0.3 if 12 < t < 20 else 0.0))
    )


def buildScene5():
    """Five falls from a slewing crane top to a 2 t beam that can only move vertically, like a load
    held by taglines. All neighbouring falls braid at once and the braid lifts the load."""
    s = setup("Five falls braided by a slewing crane top", (0, -20, 11), (0, 0, 8))
    top = s.body(agxCollide.Box(1.5, 0.3, 0.2), (0, 0, 15.2), agx.RigidBody.KINEMATICS)
    load = s.body(agxCollide.Box(1.5, 0.3, 0.15), (0, 0, 3.0), mass=2000)
    s.sim.add(agx.Prismatic(agx.Vec3(0, 0, 1), load))
    for i in range(5):
        x = -1.2 + 0.6 * i
        s.wire(
            0.012,
            [
                agxWire.BodyFixedNode(top, x, 0, -0.2),
                agxWire.BodyFixedNode(load, x, 0, 0.15),
            ],
            attachedTo=(top, load),
        )
    s.collideAll()
    sec.preCallback(
        lambda t: top.setAngularVelocity(agx.Vec3(0, 0, 0.5 if 1 < t < 21 else 0.0))
    )


SCENES = [buildScene1, buildScene2, buildScene3, buildScene4, buildScene5]


def buildScene():
    """Entry point when running this script using agxViewer."""
    app = application()
    if app.getNumScenes() == 1:
        scriptFileName = app.getArguments().getArgumentName(1).replace("agxscene:", "")
        for key, scene in enumerate(SCENES[1:], start=2):
            app.addScene(scriptFileName, scene.__name__, ord(str(key)), True)
    buildScene1()


# Entry point when this script is started with the python executable.
init = init_app(
    name=__name__,
    scenes=[(scene, str(i + 1)) for i, scene in enumerate(SCENES)],
    autoStepping=False,
)
