Continuous for Wires with Adaptive Resolution

Michael Brandl

Friday 31st March, 2017 Master’s Thesis in Computing Science, 30 ECTS credits Supervisor at CS-UmU: Martin Berggren Examiner: Eddie Wadbro

Umeå University Department of Computing Science SE-901 87 UMEÅ SWEDEN

Abstract

For interactive simulations using a , a fixed time step is often necessary in order to maintain real-time performance. Furthermore, collisions between the simulated geo- metric objects have to be detected by solving a computational problem called collision detection. In its discrete formulation, the geometric configurations of the bodies are evaluated at each sim- ulation time step, whereas its continuous variant also considers the bodies’ motion in between the time steps. A fixed simulation time step can lead to missed collisions if only discrete colli- sion detection is performed. This problem arises especially when simulating thin objects such as wires, chains, or ropes for applications like heavy lifting or anchor handling. In order to be able to simulate wires interacting with each other in real-time simulations, continuous collision detection is therefore necessary. An existing simulation model for wires, chains, and ropes using adaptive wire resolution has been augmented using continuous collision detection. This addition has been integrated into the physics engine AGX Dynamics. Issues in existing methods for continuous collision detection of moving line segments caused by co-linearity and co-planarity have been identified, classified and addressed. Using this augmented approach to continuous collision detection allows for a larger fixed simulation step size compared to discrete collision detection, and thus decreases the total run time by up to 58.22% in relevant scenarios. Sammanfattning

För interaktiva simuleringar med en fysikmotor är det ofta nödvändigt att använda ett fast tids- steg för att bibehålla realtidsprestanda. Dessutom måste kollisioner mellan de simulerade geo- metriska objekt upptäckas genom att lösa ett beräkningsproblem som kallas för kollisionsde- tektering. I dess diskreta formulering utvärderas kropparnas geometriska konfiguration i varje simuleringstidssteg, medan den kontinuerliga varianten även tar hänsyn till kropparnas rörelse under tidssteget. Ett fast tidssteg kan leda till att kollisioner missas om bara diskret kollisionsde- tektering används. Detta problem uppstår speciellt när tunna objekt såsom vajrar, kättingar eller rep simuleras i tillämpningar som tunga lyft eller ankarhantering. För att kunna simulera vajrar som interagerar med varandra i realtidssimuleringar behövs därför kontinuerlig kollisionsdetek- tering. En existerande simuleringsmodell för vajrar, kättingar och rep som använder sig av adaptiv vajerupplösning har utökats med kontinuerlig kollisionsdetektering. Utökningen har integrerats i fysikmotorn AGX Dynamics. Problem inom existerande metoder för kontinuerlig kollisions- detektering av rörliga linjesegment som orsakas av kolinjäritet och koplanaritet har identifierats, klassificerats och behandlats. Användningen av denna variant av kontinuerlig kollisionsdetek- tering tillåter ett större fast simuleringstidssteg jämfört med diskret kollisionsdetektering, och minskar därmed den totala exekveringstiden med upp till 58.22% i relevanta scenarion. ii Contents

Contents iii

List of Figures vii

List of Tables xi

List of xiii

1 Introduction 1

2 Theory 5 2.1 Physics Engine ...... 5 2.1.1 Multibody Simulation ...... 5 2.1.2 General Design ...... 5 2.1.3 Simulation Step Pipeline ...... 6 2.1.4 Real-Time Simulation ...... 6 2.2 Collision Detection in a Physics Engine ...... 6 2.2.1 Output of Discrete Collision Detection ...... 8 2.2.2 Output of Continuous Collision Detection ...... 9 2.3 Collision Detection Pipeline ...... 10 2.3.1 Broad Phase ...... 11 2.3.1.1 Bounding Volumes ...... 11 2.3.1.2 Sweep and Prune ...... 12 2.3.1.3 Hierarchical Grid ...... 13 2.3.2 Middle Phase ...... 14 2.3.3 Narrow Phase ...... 16 2.3.3.1 Sphere-Sphere Collision Detection ...... 16 2.3.3.2 Separating Axis Test ...... 17 2.3.3.3 GJK with EPA ...... 18 2.3.3.4 Non-Convex Objects ...... 20 2.4 Overview of Continuous Collision Detection ...... 20 2.4.1 General Approaches ...... 20

iii iv CONTENTS

2.4.2 In-Between Motion ...... 22 2.4.3 Continuous Broad Phase and Middle Phase ...... 23 2.5 Continuous Collision Detection of Triangle-Triangle Pairs ...... 24 2.5.1 Original Approach by Moore ...... 24 2.5.2 Solving Polynomials Numerically ...... 26 2.5.3 Provot’s Method ...... 28 2.5.4 Issues with Co-Planarity and Co-Linearity ...... 29 2.6 Wire Simulation ...... 29 2.6.1 Recent Approaches ...... 30 2.6.2 Hybrid, Multi-Resolution Wires with Massless Frictional Contacts ... 30 2.7 AGX Dynamics ...... 32 2.7.1 Spook Stepper ...... 33 2.7.2 Collision Detection ...... 33 2.7.3 Constraints ...... 33 2.7.4 Wires ...... 34

3 Method 35 3.1 Continuous Collision Detection Edge-Edge ...... 35 3.1.1 Detection of Co-Planarity and Co-Linearity ...... 35 3.1.1.1 Detection of Case 1: Line Segments Degenerate ...... 38 3.1.1.2 Detection of Case 2: Line Segment Starting Points Identical . 38 3.1.1.3 Detection of Case 3: Parallel Case ...... 38 3.1.1.4 Detection of Case 4: 2D-Case ...... 39 3.1.2 The Parallel Case ...... 41 3.1.2.1 Detection of the Parallel Co-Linear Case ...... 42 3.1.2.2 Handling the Parallel Co-Linear Case ...... 43 3.1.2.3 Handling the Parallel Non-Degenerate Case ...... 45 3.1.3 The 2D-Case ...... 46 3.1.3.1 Testing for Initial Overlap ...... 46 3.1.3.2 The Permanent Point-On-Line Case ...... 49 3.1.3.3 The General 2D Case ...... 49 3.1.4 The General Case ...... 49 3.1.5 A Note on Thresholds ...... 49 3.2 Implementation ...... 50 3.2.1 Libraries ...... 50 3.2.2 WireShape-Class ...... 51 3.2.3 Broad Phase ...... 51 3.2.4 Narrow Phase ...... 52 3.2.5 Hardware ...... 52 CONTENTS v

4 Results and Discussions 59 4.1 WireShape Collision Cases ...... 59 4.1.1 Explanation of Visualization ...... 59 4.1.2 The Non-Degenerate Case ...... 60 4.1.3 Case 2: Line Segment Starting Points Identical ...... 60 4.1.4 Case 3: The Parallel Case ...... 60 4.1.5 Case 4: The 2D-Case ...... 62 4.2 Wire Collision Scenarios ...... 67 4.2.1 Scenario Descriptions ...... 67 4.2.1.1 Scenario 1: Basic Collision ...... 67 4.2.1.2 Scenario 2: Wire Pulling Anchor ...... 67 4.2.1.3 Scenario 3: Twisting under Load ...... 67 4.2.1.4 Scenario 4: Chains on Deck ...... 71 4.2.2 Occurrence of Degenerate Cases ...... 71 4.2.3 Computation Time ...... 71

5 Conclusion 77 5.1 Achievements ...... 77 5.2 Shortcomings ...... 77 5.3 Future Work ...... 78

6 Acknowledgments 79

References 81 vi CONTENTS List of Figures

1.1 Real-time simulation of cranes with wires...... 1

1.2 Objects s1 and s2 tunneling through each other within the time step from time

t0 to t1...... 2 1.3 Two wires tunneling through each other...... 2

2.1 Typical pipeline for a physics engine...... 7 2.2 Contact points at beginning of time step, time of impact, and end of time step. . 8

2.3 Intersection depth and corresponding normal nd not equal to contact normal

from movement of bodies nv...... 9 2.4 Non-convex contact of capsule in triangle mesh-torus, using contacts with dif- ferent normals. The orange spheres indicate the contact points, and the orange arrows the contact normals. Visualized in AGX Dynamics...... 10 2.5 Typical pipeline for collision detection...... 11 2.6 Different bounding volumes...... 12 2.7 for moving object in continuous collision detection...... 12 2.8 Sweep and Prune on objects in 2D...... 13 2.9 Objects in a uniform grid (2D)...... 13 2.10 Objects in a hierarchical grid (2D)...... 14 2.11 An AABB-tree in 2D. The edges of the arrow-shaped geometry with red bound- aries are surrounded by black AABBs, which are the leaf-nodes of the tree. The tree’s root is the green AABB covering the whole geometry. Its children are the two blue AABBs covering part of it, each enclosing two black AABBs. The tree node structure is shown in Figure 2.12...... 15 2.12 The node-structure of the AABB-tree shown in Figure 2.11...... 15 2.13 Two identical objects with AABB trees collide, leading to overlapping leaf nodes. 16

2.14 Two spheres with points P1, P2 and radii r1, r2 collide, resulting in contact nor-

mal n and points C1, C2...... 17 2.15 Two convex polyhedra A and B are separated by a hyperplane formed by vector v and distance c...... 18 2.16 Minkowski difference and support points of two objects A and B...... 19 2.17 Two steps in the EPA starting from a simplex from GJK...... 19

vii viii LIST OF FIGURES

2.18 A non-convex object as triangle mesh (right) and as convex decomposition, in an explosion view (left). Visualized in AGX Dynamics...... 20

2.19 Object A moving and passing through object B. Bounding spheres S 1 and S 2

bound A’s movement from t0 to (t1 − t0)/2 as well as from (t1 − t0)/2 to t1. ... 21

2.20 Triangle A moves and rotates from t0 to t1 in one time step. The in-between

motion of linearly moving vertices leads to A(t1−t0)/2 being smaller than A. The AABB B contains A’s movement during the whole time step...... 22 2.21 An enlarged bounding volume B of an object A with constant linear and angular

velocity moving from t0 to t1 within one time step...... 23 2.22 Triangle-triangle contact configurations...... 25 2.23 Bisection used for finding a root of a polynomial equation, starting from divid-

ing I0 in the middle, choosing the interval I0 where f has different signs on the

end points and continuing recursively with I1,I2, I3, and so on. This approach happens to isolate root R here out of the three possible roots...... 27 2.24 Different node types of a wire, freely hanging, in contact, and under tension. .. 31

2.25 Wire with three segments and four nodes at t0 gets stretched and removes two

inner nodes, having one segment and two nodes left at t1...... 31 2.26 One beige wire tunneling through two other wires (turquoise and red). The thin beige lines indicate the previous position and movement of the beige wire during the time step. Visualized in AGX Dynamics...... 32 2.27 Harbor crane with wires lifting container. Simulated in AGX Dynamics. .... 32

3.1 The parallelepiped formed by the vectors a, b, c. Source: https://upload. wikimedia.org/wikipedia/commons/3/3e/Parallelepiped_volume.svg. 36 3.2 Flowchart for detection and treatment of the various degenerate cases and the non-degenerate case...... 37 3.3 Inheritance structure of classes Shape, Capsule and WireShape...... 51 3.4 Bounding box around WireShape in previous and current position...... 52

4.1 Both segments move in a non-degenerate configuration. The blue segment moves from the left to the right, and the green one from the right to the left. They intersect at t ≈ 0.69. For an explanation of the colors and symbols in the visualization, see section 4.1.1...... 60 4.2 Both segments move in a non-degenerate way. The green segment moves from the left to the right, and the blue one from the right to the left. Both turn 90 degrees, and the segments intersect at t = 0.5 in a temporarily parallel config- uration. For an explanation of the colors and symbols in the visualization, see section 4.1.1...... 61 LIST OF FIGURES ix

4.3 Both segments move in a non-degenerate way. The green segment moves from the front left to the right, and the blue one from the bottom to the top, inverting its orientation and temporarily degenerating to a point at t = 0.5. At this time, the segments intersect. For an explanation of the colors and symbols in the visualization, see section 4.1.1...... 61 4.4 The green and blue line segments move from their initial state in the right side of the picture, to the final one on the left side. The beginning points A(t) and C(t) are identical for all t, and move along a common line. The segments are thus already initially in contact at t = 0, indicated by an orange sphere. For an explanation of the colors and symbols in the visualization, see section 4.1.1. .. 62 4.5 Two wire segments move along the same line in opposite directions. They are in initial contact at t = 0 indicated by the orange spheres, which show the beginning and end of the overlap. During their movement, the segments pass through each other and are in non-contacting state at the end of the time step. For an explanation of the colors and symbols in the visualization, see section 4.1.1...... 63 4.6 Two wire segments move along the same line in opposite directions. They get into contact (indicated by the orange sphere) later in the time step at t = 0.0625 and pass through each other. For an explanation of the colors and symbols in the visualization, see section 4.1.1...... 63 4.7 Two wire segments move along almost the same line in opposite directions. The capsules should get into contact, but continuous collision detection is only done on the line segments. The line segments pass by next to each other, so not contacts are generated. For an explanation of the colors and symbols in the visualization, see section 4.1.1...... 64 4.8 Two wire segments move while maintaining parallelity with regard to each other. They intersect at t = 0.6. The green wire segment moves from the top right to the middle, and the blue one from the bottom to the top. For an explanation of the colors and symbols in the visualization, see section 4.1.1. .. 64 4.9 Two wire segments are in initial overlap at t = 0, and move apart from each other. The movement is co-planar. The green wire segment turns and moves from the middle to the left, and the blue one turns and moves from the middle to the right. For an explanation of the colors and symbols in the visualization, see section 4.1.1...... 65 4.10 The lower end point of the blue segment is permanently on the line of the green segment. Both segments move from the left to the right within the same plane; the blue segment also turns. Overlap occurs at t ≈ 0.41 and is due to the lower end point of the blue segment passing through the green segment. For an expla- nation of the colors and symbols in the visualization, see section 4.1.1...... 65 x LIST OF FIGURES

4.11 The lower end point of the blue segment is permanently on the line of the green segment. Both segments move from the left to the right; the blue one also turns. Overlap occurs at t = 0.5 and is due to the upper end point of the blue seg- ment passing through the green segment. The segments are temporarily parallel, therefore two contact points are created. For an explanation of the colors and symbols in the visualization, see section 4.1.1...... 66 4.12 Both segments move in the same plane. This plane is not identical to the view plane, since the view is slightly tilted. The green segment moves from the right to the left, and the blue one from the left middle to the right. The segments intersect at t ≈ 0.56. For an explanation of the colors and symbols in the visual- ization, see section 4.1.1...... 66 4.13 A simulation of four time steps of a moving steel wire of 2m length and 0.02m radius colliding with two other identical wires whose end points are firmly at- tached to the world. Continuous collision detection is used to detect tunneling. The size of the time step is 1/60s...... 68 4.14 A simulation of a cylinder of mass 1570.8kg hanging on a 25m long wire with radius 0.02m, interacting with by a 50m long wire being pulled by two mov- ing bodies with fixed speed. Continuous collision detection is used to detect tunneling. The size of the time step is 1/60s...... 69 4.15 A simulation of a box with mass of 8000kg hanging on four wires of length 12m and radius 0.02m attached to an upper box. The lower box has with initial angular velocity 4π/s. Continuous collision detection is used to detect tunneling between the wires. The size of the time step is 1/60s...... 70 4.16 A simulation of two chains, simulated as wires with radius 0.01m and no bend- ing resistance. Each chain is connected to a box and a cylinder of the same color, and rests on the surface. The boxes are 0.8m above the ground. The blue box remains in its position, whereas the brown box moves first in positive x direc- tion, an after 5s in positive y direction. Its motion leads to interaction between the two chains. The size of the time step is 1/60s...... 72 List of Tables

2.1 Table showing colliders between shape types in AGX Dynamics. x: collider exists; -: no collider needed since only static shapes. Source: [1]...... 33

3.1 Chosen Values for Thresholds ...... 50 3.2 Table showing colliders between shape types in AGX Dynamics after introduc- tion of WireShape-class. x: collider exists; -: no collider needed since only static shapes; c: fallback to respective collider using capsule; W: WireShape- WireShape-collider...... 52

4.1 Table showing occurrence of special cases in the scenarios introduced in section 4.2.1...... 73 4.2 Table showing performance measurements in the scenarios introduced in section 4.2.1. The performance is both measured for the code with CCD at the default time step, as well as for a code version with discrete collision detection at a lower time step where no tunneling occurs. The values for the run time have a relatively high standard deviation, e.g. the value for Total Run Time (CCD) (in s) for scenario 4 is 0.2s...... 75

xi xii LIST OF TABLES

1 Detect Case 1: Line Segments Degenerate ...... 38 2 Detect Case 2: Line Segment Starting Points Identical ...... 38 3 Compute Quadratic Coefficients from Cross Product ...... 40 4 Detect if Two Vectors are Permanently Parallel ...... 40 5 Detect Case 3: Parallel Case ...... 41 6 Compute Cubic Coefficients ...... 41 7 Detect Case 4: 2D-Case ...... 42 8 Detect if Moving Point is Permanently on Line ...... 43 9 Static Co-Linear Overlap ...... 44 10 Moving Point-Point Intersection ...... 45 11 Handle Parallel Co-Linear Case ...... 46 12 Solve 3 Quadratic Equations ...... 47 13 Handle Parallel Non-Degenerate Case ...... 48 14 Handle Parallel Case ...... 48 15 Static Point-Segment Intersection ...... 54 16 Static Segment-Segment Intersection ...... 55 17 Moving Point-Segment Intersection ...... 56 18 Handle 2D-Case ...... 56 19 Handle Non-Degenerate Case ...... 57 20 Handle General Case ...... 57

xiii xiv LIST OF ALGORITHMS Chapter 1

Introduction

Simulation has become a valuable tool for training operators of vehicles and machines for dif- ficult tasks. Often, specialized hardware such as motion platforms with screens and control consoles are used to provide more feedback to the operator, as can be seen in Figure 1.1a.

(a) Training simulator for a harbor crane with (b) Simulation of a harbor crane in the physics wires. Courtesy of Oryx Simulations AB. engine AGX Dynamics.

Figure 1.1: Real-time simulation of cranes with wires.

For giving the operator direct feedback, the simulation has to run in real-time. Computer programs responsible for simulation of mechanical systems that aim towards real-time simu- lation are known as physics engines, which are used in engineering, gaming, and the movie industry. A physics engine typically defines the interacting objects as simple (most often rigid) bodies, that can interact via joints and/or contacts. Figure 1.1b shows an example of the physics engine AGX Dynamics, a simulation of a harbor crane lifting a container with wires. One important part of a physics engine is collision detection. This term stands for various techniques for detecting if bodies collide by testing if their respective geometries overlap. If such a case occurs, it is treated as a contact, and the resulting contact forces are computed. These and other forces such as gravity give the motion of the bodies, leading to the position at the next time step. In order to let the simulation run at real-time, a physics engine often has a time step with

1 2 Chapter 1. Introduction a fixed size for performance reasons, e.g. 1/60s. If such a fixed time step is used, and if collision detection only considers the bodies’ positions at the beginning of each time step (so called discrete collision detection), it is possible to miss some collisions that occur while bodies move through each other during the time step. This effect is called tunneling. See Figure 1.2 for an example. The risk for tunneling is higher if the bodies are thin and move fast. There are techniques called continuous collision detection (CCD) to compute also those collisions that discrete collision detection misses. The disadvantage of continuous collision detection is that it is often more computationally costly and might thus prevent real-time performance of the physics engine if used for all bodies in the simulation.

s2 at t1 s1 at t0

s at t s2 at t0 1 1

Figure 1.2: Objects s1 and s2 tunneling through each other within the time step from time t0 to t1.

Wires are one example of thin bodies that move fast. Simulation of wires is important in contexts such as operator training for cranes or anchor handling in offshore scenarios, where wires can be very long and hold heavy loads. In these applications, situations can occur where wires collide with each other. It is important for the simulation of wire-wire interaction that collisions between wires are detected. In a simulation with a fixed time step, discrete collision detection can lead to tunneling, as can be seen in Figure 1.3. Therefore, continuous collision detection is needed for simulation of wires interacting with each other.

(a) Two wires just before tunneling. The thin (b) Next time step. The wires have tunneled. lines indicate the previous positions, the thick lines the current ones. The thick lines are not touching.

Figure 1.3: Two wires tunneling through each other. 3

In this thesis, an existing approach[46] for simulating wires will be augmented by contin- uous collision detection for wire-wire interaction. Several approaches for continuous collision detection exist (as reviewed in section 2.4). The goal of this thesis is to choose one that is easy to implement, performs fast enough for real-time simulation and is robust. Many of the existing approaches for continuous collision detection suffer from robustness problems since they do not take into consideration cases of co-linearity and co-planarity, e.g. if the two line segments move along the same line[20]. That shortcoming will be addressed in the approach chosen in the the- sis. The augmented approach will then be implemented in the physics engine AGX Dynamics, and tested in real-time simulations of heavy lifting. The main results of the thesis are the following: A line segment-based approach for con- tinuous collision detection has been chosen, and problems with robustness due to co-linearity and co-planarity have been addressed. The resulting has been implemented in AGX Dynamics, and is used for improving the collision detection for an existing approach for simu- lating wires[46]. Test cases for real-time simulations of heavy lifting and maritime operations including wires that collide with each other have been modeled and evaluated. This thesis was done at the company Algoryx Simulation AB [5]. Algoryx develops the physics engine AGX Dynamics, which is used in professional simulators for maritime applica- tions, robotics, forestry, mining and construction, as well as in virtual prototyping and CAD. The remaining part of the thesis is structured as follows: • Chapter 2 introduces theory and background. • Chapter 3 elaborates on the algorithms and implementations used. • Chapter 4 presents and discusses results of the implementation.

• Chapter 5 provides final thoughts and a conclusion. 4 Chapter 1. Introduction Chapter 2

Theory

This chapter will introduce the theoretical concepts used in the thesis.

2.1 Physics Engine

2.1.1 Multibody Simulation The focus of physics engines is often on classical mechanics. Within mechanics, the field of multibody dynamics deals with the forces acting on and between particles and rigid bodies, as well as the resulting motion. Flexible bodies and larger mechanical systems can be modeled by combining several particles or rigid bodies by constraints (such as mechanical joints). For a general introduction to the topic of multibody dynamics, see Amirouche’s book[6]. The concept of simulating the dynamics of multibody systems is called multibody simula- tion. Computer programs for multibody simulation go by several different labels: Multibody simulation software or -toolkit, or software for physics-based animation, as in the book by Er- leben et al.[22]. They have in common that they consider the equations of motion of a system of interacting bodies, and compute the resulting forces, accelerations, velocities, and positions.

2.1.2 General Design In order to understand the role that collision detection plays within a physics engine, it is nec- essary to consider the general design of the latter. This general design is quite similar for many physics engines,[30] where the equations of motion are discretized and time-integrated. This can be performed using an explicit or implicit method such as the Runge-Kutta methods, or explicit or implicit Euler[22, chapter 23.1]. Another alternative is to derive a time-integration method based on the variational principle and discretize that, as in Lacoursière’s thesis [27]. All of these approaches yield a discrete time stepping scheme, where forces, accelerations or changes in velocity have to be computed for one time step, based on the current configuration on the system. Then the results can be applied to integrate the bodies’ velocities and positions in time. Forces or accelerations have to be computed based on the current state of the simulation. For forces like gravity, this can in many cases be straight-forward. For constraints such as e.g. the hinges of a door, the violation of the constraints has to be computed, which gives an indication of the changes in the simulation needed in e.g. position or velocity of the involved bodies in order to fulfill the constraint. For the forces stemming from contacts between two bodies, first

5 6 Chapter 2. Theory it has to be detected whether the bodies are in contact. This is achieved by testing the bodies for geometric contact or overlap with the help of collision detection. Collision detection consists in algorithms whose input is the bodies’ geometries, positions and velocities, and whose output is the answer if the bodies are in contact, as well as additional contact information needed to compute forces or accelerations.

2.1.3 Simulation Step Pipeline A typical flow-chart for multibody simulation using a physics engine can be seen in Figure 2.1. After an initialization phase to set up the simulation, the simulation loop starts. External input can be provided, such as user input from keyboard, mouse, or other input devices, input from other software packages, or sensor data from hardware in the loop simulations. Similarly, output can be read from the simulation and provided via e.g. graphics devices or to motion platforms. These external input/output signals can be synced each time step, or after either a given number of time steps or a certain amount of wall clock time has passed. From this step, the simulation loop continues with collision detection and update of con- straints, which includes the computation of the constraints’ violation, as well as the Jacobians when using an implicit time stepping method. Then, the collisions and constraint violations are resolved. Depending on the formulation and time stepping scheme, this resolution can be achieved either by considering one collision and constraint at a time, or by considering the whole system at once and solving a linear complementarity problem. The results of this step are then used in the time integration, where forces, velocities, and positions are updated, and the simulation time is increased, returning to the external input/output step[30, chapter 1.3]. Interactive simulations can allow for call-backs on different stages of this pipeline, in or- der to modify the simulation based on certain events such as user input. Co-simulation with other simulation tools can also be achieved by exchanging data such as positions and velocities of bodies, or interaction forces. This exchange can be performed by call-backs or at certain synchronization points within the time step, e.g. at its beginning.

2.1.4 Real-Time Simulation In this thesis, the expression real-time simulation is mentioned several times, and it should be explained what is meant by this term. It is related to the concept of hard real-time computing, whose definition is that a computational operation has to give not only correct results, but also within a pre-defined time frame. Missing the deadline for this time-frame would be a system failure. In the context of interactive simulation, such as in training simulator scenarios using a physics engine, the system configuration can change at any time, and the computational sys- tem size can suddenly increase with these changes.[28, p 41] Therefore, hard guarantees can usually not be given.1 Instead, the real-time requirements within this thesis shall be considered as best effort, i.e. striving for maintaining real-time performance wherever possible, but without giving guarantees.

2.2 Collision Detection in a Physics Engine

Collision detection deals with computing geometric overlap or intersection between moving and/or static objects in two-dimensional or three-dimensional space. It is used in multibody

1There a however scenarios within the field of interactive simulation where such guarantees are important. Weller’s thesis[55] contains specialized algorithms for these use cases, which are not treated here. 2.2. Collision Detection in a Physics Engine 7

Initialization

first time step sync with external input/output (e.g. next time step graphics)

Collision Constraint Detection Update

Resolution of Colli- sions and Violated Constraints

Time Integration

Figure 2.1: Typical pipeline for a physics engine. 8 Chapter 2. Theory

Body A Body B Body A Body B Body A Body B n p=pA=pB n pB pA

(a) At beginning of time step (b) At time of first contact (c) At end of time step (t = t1). (t = t0). during time step Bodies intersect; points pA and (t0 < t = tc < t1). Contact pB are not identical anymore. normal n and point p.

Figure 2.2: Contact points at beginning of time step, time of impact, and end of time step. simulation, robotics, and . Ericson gives a general introduction to the field in his book[21]. When considering the general problem of collision detection between two bodies, the input consists of the geometries of two bodies, as well as their position (and possibly previous path or velocity) in space. The output to be computed varies in different use cases. For robotic path planning, a simple Boolean yes/no answer to the question if two objects overlap along the path may suffice. However, for multibody simulation in a physics engine, more output data is needed in order to be able to later compute contact forces and the resulting motion. The type of data needed depends on the formulation of the time-stepping algorithms as well as on the contact mechanics. Often, the output is given as contact points, each with a contact normal vector and an intersection depth. Lacoursière[27] describes algorithms for how the output of collision detection then can be used for simulating both physical resting contacts and impacts by formulating the latter two as constraints. This approach allows the resolution step in Figure 2.1 to treat the data from collision detection and constraints in a similar matter.

2.2.1 Output of Discrete Collision Detection Discrete collision detection is performed at the beginning of the time step, without knowledge of the movement in the previous time step. Collisions are thus found after they have occurred, when the two bodies already intersect each other. Ericson [21] calls this approach therefore a posteriori; another common term is static collision detection[50]. 2 At the moment of first contact, the corresponding contact points on each body are on the same location in space, but since the bodies move further during the rest of the time step, these contact points will usually have moved apart from each other at the end of the time step, as can be seen in Figure 2.2. Discrete collision detection means giving up on finding the exact time and point where the bodies first got into contact, and instead trying to find the shortest way to get the now overlapping bodies out of each other. In this approach, the bodies are considered in their current position, without considering their previous movement. Then it is computed whether the bodies indeed overlap, and if so, • in which direction the bodies have to be moved in order to separate (the contact normal), • how much to move them (the intersection depth), • and where to apply force in order to move the bodies (the contact point).

2The corresponding terms for continuous collision detection are a priori and dynamic collision detection, respec- tively. 2.2. Collision Detection in a Physics Engine 9

Body A Body A Body B Body B v nv

nd

(a) At beginning of time step (t = t0), with (b) At end of time step (t = t1). Scaled movement v during time step. contact normal from intersection depth nd smaller than the one from incoming velocity nv.

Figure 2.3: Intersection depth and corresponding normal nd not equal to contact normal from movement of bodies nv.

The distance that one body moves into the other one can end up being larger than the inter- section depth, if the traveling direction and the found contact normal are not parallel. An exam- ple for this is shown in Figure 2.3. The effective computation of the intersection depth between convex and/or non-convex objects is an area of research in itself within collision detection; see Weller’s thesis for an overview over the literature [54, chapter 2.3.3.]. In a physics engine, inter- section depth computation is usually implemented within the so-called narrow phase collision detection, which will be treated in more detail in section 2.3.3. The intersection volume between the two bodies is called the contact manifold. Often this volume is approximated with several contact points at the deepest intersection and at the bound- ary of the intersection. Each contact point can then be formulated as a contact constraint, maintaining non-penetration conditions[31, chapter 5.1]. Methods for computing contact vol- ume exist, but are less common[54, chapter 2.3.4.]. AGX Dynamics uses the point-based model described above[1], and therefore the thesis focuses on this one. When using the point-based model, several contact points are needed in order to have stable resting contacts e.g. for a box on a plane [12, chapter 6.3]. When non-convex bodies are involved, the different contact points might even have non-identical contact normals — see Figure 2.4 for an example. This makes it possible to simulate effects such as gears interlocking into each other, or other more complicated mechanisms.

2.2.2 Output of Continuous Collision Detection In contrast to discrete collision detection, continuous collision detection attempts to compute the exact time of and point of impact. Thus, several of the shortcomings of discrete collision detection mentioned above can be avoided: intersections do not occur, the impacting contact normal is used instead of the potentially erroneous normal corresponding to the intersection depth, and no contacts are missed due to tunneling. The data resulting from continuous collision detection is therefore:

• The point of impact (also called point of contact), identical for body A and B in space.

• The time of impact/contact.

• The contact normal — a normalized vector separating the two bodies locally at the points, usually the relative velocity in the point. 10 Chapter 2. Theory

Figure 2.4: Non-convex contact of capsule in triangle mesh-torus, using contacts with different normals. The orange spheres indicate the contact points, and the orange arrows the contact normals. Visualized in AGX Dynamics.

The intersection depth would not be needed since it is zero at the time of impact. As men- tioned before, continuous collision is prohibitively expensive for real-time simulation of larger systems. Moreover, if the time-stepping scheme has to be adapted to accommodate for the time of impact, this approach can lead to so-called Zeno-points[27, p. 18]: when an object bounces in smaller and smaller intervals on a surface, the time step length adapted to the time of next impact are reduced towards zero, and the time integration progress stagnates. This problem can be overcome with a threshold below which very small movement is considered as resting; how- ever, this approach still slows down the computation for the rest of the system. This shortcoming can be addressed by approaches like Mirtich’s time warp[32], where non-interacting parts of the system are stepped in separate time step lengths. For strongly connected systems such as the ones focusing on wires and chains, such an approach cannot be used, since large parts of the system interact with each other. Therefore and because of the real-time performance require- ments mentioned earlier, the simulations will have to have a fixed time step. Here, continuous collision detection has to be used as a means to detect collisions which might be missed by discrete collision detection, but its results have to be treated in a similar fashion as in the latter.

2.3 Collision Detection Pipeline

Collision detection can be computationally expensive. This is true for discrete collision detec- tion, and for continuous collision detection even more so. Its cost can dominate the compu- tational time needed for multibody dynamics. The naive approach of collision detection in a simulation with many bodies would be to test for collisions of each body against each other, and similarly for each feature of any more complex body against each feature of any other. This approach scales quadratically with the problem size. It is not possible to escape this quadratic scaling in the worst case — e.g. if all bodies are created initially at the same position, which is physically impossible but might well be set up in a simulation. However, the average case can be improved, which is the goal of the division into the pipeline of broad phase, middle phase, and narrow phase collision detection, as shown in Figure 2.5. These three phases are described in more detail below. Note that only the narrow phase collision detection is strictly necessary, the other steps are used for speed-up by reducing the input to narrow phase collision detection. 2.3. Collision Detection Pipeline 11

Broad Middle Narrow Phase Phase Phase

Figure 2.5: Typical pipeline for collision detection.

Ericson[21] gives a more thorough information on the collision detection pipeline as well as an overview over commonly used algorithms.

2.3.1 Broad Phase

The aim of the broad phase collision detection is to reduce the number of pairs of bodies to test. It does so by only including pairs where the two bodies are close enough to potentially collide. These pairs are then sent on to the other phases of the collision detection pipeline. Broad phase collision detection is allowed to have false positives, but no false negatives. When choosing or designing a broad phase algorithm, there is usually a trade-off involved between how much time can be spent in broad phase collision detection in order to get as high a reduction of false positives as possible, and between the time saved by not having to treat these false positives later in middle and narrow phase collision detection.

2.3.1.1 Bounding Volumes

A general approach for most broad phase-techniques is to surround each body’s geometry com- pletely with a geometrically simple bounding volume, e.g. a sphere or a cuboid. These simple bounding volumes are then fed to a broad phase algorithm, which is aimed at producing as few pairs of potentially overlapping bodies as possible. Examples for bounding volumes include (see Figure 2.6)

• Bounding Sphere — a sphere including the geometry of the whole body. For a rigid body, its size and position relative to the body is constant during the simulation. It will often not fit tightly around geometries such as long line segments, and which thus lead to false positives in such cases.

• Axis-aligned Bounding Box (AABB) — a box that is adapted to the world’s coordinate axes. It has to be recomputed each time step, also for rigid bodies. An AABB fits tighter than the bounding sphere for many non-spherical objects, and integrates well with many broad phase algorithms.

• Oriented Bounding Box (OBB) — a box that is defined in the rigid body’s local coordinate system, and thus not aligned to the world’s coordinate axes. For rigid bodies, it is constant during the simulation. OBBs tend to fit the geometry tighter than Bounding Spheres or AABBs. 12 Chapter 2. Theory

(a) The object is (b) The object is (c) The object is surrounded by a bounding surrounded by an surrounded by an sphere. axis-aligned bounding object-oriented bounding box. box.

Figure 2.6: Different bounding volumes.

In discrete collision detection, only the geometry itself has to be contained inside the bound- ing volume. However, for continuous collision detection, the geometry along its path during a time step has to be contained, including translation and rotation, as shown in Figure 2.7. This aspect will be treated in more detail in section 2.4.3.

Figure 2.7: Bounding volume for moving object in continuous collision detection.

Below, some examples for broad phase algorithms will be discussed. They are chosen since they are the ones used in AGX Dynamics[1].

2.3.1.2 Sweep and Prune One example of a broad phase algorithm is Sweep and Prune. It is also called Sort and Sweep, especially in its introduction in Baraff’s thesis[11, chapter 5.3]). Sweep and Prune belongs to the Spatial Partitioning schemes, which have one general approach in common: the three- dimensional space is divided up in such a way that only bodies close to each other will be considered for further testing. Sweep and Prune achieves this effect by maintaining ordered lists of intervals for each of the three dimensions. Each body is surrounded by an Axis Aligned Bounding Box. The projection of this AABB onto each dimensions’ axis gives an interval each. If the intervals of two bodies overlap in all dimensions, their AABBs overlap, and Sweep and Prune will report the two as a potentially colliding pair of bodies. This approach is illustrated in 2D in Figure 2.8: In the y-dimension, the intervals of all three bodies overlap. In x however, only the intervals of the red and blue body overlap. Thus, there is only one overlap to pass on: namely the one between the bounding boxes of the red and blue body. An interval can be represented by its end points, and thus the end points of all bodies in one dimension can be represented in a sorted list. This reduces the work for Sweep and Prune to maintaining three sorted lists, one for each dimension, and reporting overlaps as soon as they occur on all three lists. Updating a nearly-sorted linked list from one time step to the next can have average case run time of O(n). However, having many objects on the same position in one dimension, e.g. resting on a plane, can deteriorate this behavior to O(n2)[21, chapter 7.5]. 2.3. Collision Detection Pipeline 13

y

x Figure 2.8: Sweep and Prune on objects in 2D.

2.3.1.3 Hierarchical Grid Hierarchical Grid is another subdivision strategy, which is based on the similar but simpler Uniform Grid.[21, chapter 7.2] A uniform grid is a multidimensional grid with uniform cell size. Uniform grids are well- suited if a simulation consists of many objects of the same size. The space containing all objects in the simulation is subdivided into grid cells. Each object is assigned the grid-cell were its center is located, but the remainder of the object can still overlap with the directly neighboring grid cells. Creating a list of potentially colliding pairs of bodies consists then in adding all combinations of bodies which share the same grid cell, as well as directly neighboring ones. Another strategy for uniform grids include registering the object for all grid cells it overlaps. This strategy is illustrated in Figure 2.9, where the green and blue body share cells 2 and 5 and have therefore be reported as a potentially overlapping pair, as well as the blue and red body since they share cells 3 and 6.

y 1 2 3

4 5 6 x Figure 2.9: Objects in a uniform grid (2D).

When objects of different sizes are part of the same simulation, uniform grids have the 14 Chapter 2. Theory

drawback that since the grid size has to be adapted to the largest object, the number nc of smaller objects per grid-cell tends to grow. Then, the number of potentially overlapping body 2 pairs in each grid cell scales with O(nc). Hierarchical grids try to alleviate this problem by introducing a hierarchy of grid cells, where the cells higher up in the hierarchy include several cells of the lower hierarchy. Objects get only introduced in a cell in the hierarchy that fits their size, but tests will be performed also with objects in the cells of lower hierarchy included in the larger cell of higher hierarchy. This can be seen in Figure 2.10, where the purple object lives in the larger, red grid cell labeled 0, and will be tested against all objects in the grid cells 1–6 since grid cell 0 contains these cells. Uniform and hierarchical grids can be used with various kinds of bounding volumes.

y 1 2 3 0

4 5 6 x Figure 2.10: Objects in a hierarchical grid (2D).

2.3.2 Middle Phase When objects consist of a large number of details, testing all these details against another object can be computationally expensive. As an example, testing a triangle mesh with m triangles against another triangle mesh with n triangles can result in m × n triangle-triangle tests. Middle phase collision detection is used when performing collision detection of detailed objects. It works similarly to broad phase collision detection, but where broad phase collision detection reduces the problem size of testing all bodies against each other, middle phase collision detection reduces the problem size of testing all features of one body against all features of another one. The output is the a list of feature-feature pairs to consider in the latter stages of the collision detection pipeline. Middle phase is quite similar to broad phase, and some algorithms for broad phase can be adapted for middle phase with slight adaptations. However, when considering rigid bodies, there are some assumptions which can be made which make certain approaches for middle phase collision detection computationally cheaper:

1. In contrast to a flexible body, a rigid body cannot collide with itself. Therefore, the features of a rigid body do not have to be tested against each other.

2. Since a rigid body moves only with the rigid motion of translation and rotation, its fea- tures will remain static in the body’s local coordinate system. Therefore, a structure for 2.3. Collision Detection Pipeline 15

accelerating middle phase testing that makes use of this fact can be pre-computed and reused during the simulation. The second assumption makes it possible to use so-called bounding volume hierarchies, which enclose the features of the object in a hierarchical structure built on top of bounding volumes around each feature. An example would be trees of bounding volumes of various kinds — see [21, chapter 6] for a general overview. If the bounding volume hierarchy is defined in the body’s local coordinate system, it remains constant during the simulation. Of the different variants of bounding volume hierarchies, only one will be presented here since it is the one which is used in AGX Dynamics:[1] The AABB tree. It is a binary tree of AABBs defined in the body’s local coordinate system, where each leaf node is an AABB enclosing one feature (e.g. a triangle), and the inner nodes are AABBs enclosing two smaller AABBs.[21, chapter 6.4.2]. An example for an AABB-tree can be seen in Figure 2.11.

Figure 2.11: An AABB-tree in 2D. The edges of the arrow-shaped geometry with red boundaries are surrounded by black AABBs, which are the leaf-nodes of the tree. The tree’s root is the green AABB covering the whole geometry. Its children are the two blue AABBs covering part of it, each enclosing two black AABBs. The tree node structure is shown in Figure 2.12.

Root

Inner node Inner node

Leaf Node Leaf Node Leaf Node Leaf Node

Figure 2.12: The node-structure of the AABB-tree shown in Figure 2.11.

When a simple object without an AABB-tree collides with a complicated object that has one, the simple object’s bounding volume is tested against the AABB-tree in a common coordinate 16 Chapter 2. Theory system. This is achieved by first testing against the bounding box of the root node, and if they overlap, by continuing the testing recursively against the bounding boxes of the child nodes. Each leaf-node whose bounding box overlaps with the simple object’s bounding volume is then added to a list of objects to test against the simple object in narrow phase. When two objects with an AABB-tree collide, both trees have to be propagated. First, the root nodes’ bounding boxes are tested against each other. If they overlap, the two child nodes of the root node of one tree have to be tested against the two child nodes of the other tree’s root node, and recursion has to continue in both trees. The end result is a list of pairs of leaf nodes that overlap, and which corresponds to a list of feature pairs to investigate in narrow phase. Figure 2.13 gives an illustration of such a collision.

Figure 2.13: Two identical objects with AABB trees collide, leading to overlapping leaf nodes.

2.3.3 Narrow Phase Narrow phase collision detection considers two bodies whose geometries might intersect. It computes if they intersect, and if they do, it computes further details on the intersection. As de- scribed in section 2.2, these details might be different between discrete and continuous collision detection when used in a physics engine. In this section, only discrete collision detection will be treated; see section 2.4 for details on continuous collision detection. Narrow phase collision detection is carried out using many different algorithms and ap- proaches, which often depend on the types of geometric shapes involved. Examples of shape types are sphere, plane, box, capsule, cylinder, convex triangle mesh, and general (also non- convex) triangle mesh. The reason for supporting different shape types is that the geometry of simple shapes such as sphere, box, capsule, or cylinder can be represented exactly using very little data, whereas triangle meshes make it possible to represent more irregular geometry. In the worst case, each pair of two shape types needs a different collision detection algorithm. If a collision detection framework supports n geometric shape types, this would make it necessary to have (n × (n + 1))/2 = O(n2) collision detection algorithms. Sections 2.3.3.2 and 2.3.3.3 show algorithms which can be reused for several combinations of shape types.

2.3.3.1 Sphere-Sphere Collision Detection One of the simplest examples of a collision detection algorithm is the one for discrete sphere- sphere collision detection (see also [21, chapter 4.3.1]). Let two spheres be represented by the center points P1, P2 in the world coordinate system. Let r1, r2 be their respective radii. The spheres overlap if ||P1 − P2|| ≤ r1 + r2. If there is an overlap, the intersection depth is just the 2.3. Collision Detection Pipeline 17

difference d = r1 + r2 − ||P1 − P2||. The contact normal is given as n = (P1 − P2)/||P1 − P2||, unless P1 and P2 are identical, in which case any normal can be chosen. The sign of the normal is arbitrary; here it is chosen as the direction that sphere 1 has to move in order to get out the collision. Sphere 1 has then to move exactly nd in order to get from a overlapping to a touching configuration with sphere 2. In discrete collision detection, the shapes have generally already moved into overlap, and thus the contact point on one shape is not identical to the one on the other one anymore. For sphere 1, the point is C1 = P1 − n ∗ r1. For sphere 2, it is C2 = P2 + n ∗ r2. The distance between these two points is just the intersection depth d. For an illustration, see Figure 2.14. If one common point C is enough to represent the contact, one choice would be to place it half-ways: C = (C1 + C2)/2. The original points can be recovered by moving d/2 in both directions along the normal.

n P1 C2 C1 P2 d

Figure 2.14: Two spheres with points P1, P2 and radii r1, r2 collide, resulting in contact normal n and points C1, C2.

2.3.3.2 Separating Axis Test One approach of collision detection that can be applied to test all combinations of convex objects is the so-called separating axis test. It is described in detail in [21, chapter 5.2.1]. The approach is based on the hyperplane separation theorem, which states that for two disjoint nonempty convex subsets of Rn A and B, there exists a nonzero vector v and a real number c such that ⟨x, v⟩ > c and ⟨y, v⟩ < c for all x ∈ A and y ∈ B, which means that the hyperplane formed by c and v separates A and B. In 3D, this means that for two convex disjoint objects, there is a plane that can be placed between them. See Figure 2.15 for an example. The separating axis test then consists in finding such a plane. The test derives its name from the fact that one way of finding such a plane is by considering an axis, and projecting both objects onto this axis. If the projections are disjoint, any plane which is normal to the axis and placed between the disjoint projections is a separating plane. The axis is then called a separating axis. Overlap occurs if there is no separating axis. For round objects, there can be infinitely many possible axes, but for two convex polyhedra, it can be seen that there is a finite possible number, given by: • The normals of all faces of polyhedron A. • The normals of all faces of polyhedron B. • The cross-products of all edges of A with all edges of B. Note that symmetrical axes have only to be tested once. For example, for a box-box test, there are 3 non-parallel axes from the faces of A, three more from B, and thus 3 × 3 cross products, 18 Chapter 2. Theory yielding a total of 3 + 3 + 9 = 15 axes to test for. Since the number of axes is finite for polyhedra (but not for round objects), all of the axes can be tested, and overlap can be reported if none is separating. In case of overlap, the axis with the least overlap is the contact normal, and the overlap along this axis it the intersection depth.

y v

A B

c x Figure 2.15: Two convex polyhedra A and B are separated by a hyperplane formed by vector v and distance c.

2.3.3.3 GJK with EPA As mentioned above, the separating axis test can only be applied easily for collision detection of convex polyhedra. Another disadvantage is that its computational complexity scales with EA × EB, where EA and EB are the number of edges in polyhedra A and B. For identical polyhedra, it thus scales quadratically in the number of edges. One approach to address both of these issues is the Gilbert-Johnson-Keerthi-algorithm, also called GJK, which is treated in [21, chapter 9.5]. GJK is an approach for computing the distance between convex objects by considering their Minkowski difference. The Minkowski difference between two point sets A and B is defined as A ⊖ B : {a − b : a ∈ A, b ∈ B}.3 The distance of A ⊖ B from the origin equals the distance of A and B, and if the origin is enclosed in A ⊖ B, then A and B touch or overlap. Figure 2.16a shows an example. GJK does not compute the Minkowski difference explicitly, but tries to iteratively find the closest point of A ⊖ B to the origin. It does so by creating an initial simplex in A ⊖ B, and updating it in each iteration. A simplex in 2D is a triangle, in 3D a tetrahedron. The details of the initialization and update process of the simplex can be found in [21, chapter 9.5]. It is important to note here that in order to create and update the simplex, GJK does not need an explicit representation of A and B, but only a function that is a so-called support mapping.A support mapping S A(D) is a function that computes a supporting point p on shape A given a direction D, where p is a point on A which maximizes D · P. A support mapping for A ⊖ B is then S A⊖B(D) = S A(D)−S B(−D). Figure 2.16b shows support points for PA, PB and PA⊖B given direction D. The iteration can be terminated successfully after a simplex enclosing the origin has been found. If no such overlap has been found after a pre-defined number of steps, GJK reports non-overlap. Other termination criteria are possible[13, chapter 4.3.2]. If GJK reports an overlap, the next challenge is to compute the intersection depth and the contact normal. For this, an approach called the Expanding Polytope Algorithm (EPA) can be used, which is introduced in Van den Bergen’s book[13, chapter 4.3.8]. As its starting polytope, the simplex in A ⊖ B resulting from GJK can be chosen. Then, EPA tries to expand this polytope in several directions to the boundary of A ⊖ B until the shortest direct connection from the origin to the boundary is found. The distance is then the intersection depth, and the direction the contact normal. The expansion is done in an iterative process similar to GJK. EPA keeps an ordered list of all the edges (if in 2D) or faces (if in 3D) of the polytope, sorted by increasing

3The Minkowski sum is defined analogously as A ⊕ B : {a + b : a ∈ A, b ∈ B}. 2.3. Collision Detection Pipeline 19

P y y B B B

A A D PA x x A ⊖ B A ⊖ B

PA⊖B

(a) Two convex polyhedra A and B, and their (b) Support points PA = S A(D), PB = S B(−D) Minkowski difference A ⊖ B. and PA⊖B = S A(D) − S B(−D) given direction D.

Figure 2.16: Minkowski difference and support points of two objects A and B.

y y

A ⊖ B A ⊖ B

x x

(a) The Minkowski difference A ⊖ B, and one (b) A new vertex is created where the ray hit simplex enclosing the origin. A ray is shot A ⊖ B. Another ray is shot to the edge which is from the origin through the closest edge of the now closest to the simplex. simplex.

Figure 2.17: Two steps in the EPA starting from a simplex from GJK.

distance to the origin. In each iteration, it sends an orthogonal ray from the origin through the closest edge or face, creating an intersection with the boundary of A ⊖ B, as can be seen in Figure 2.17. In 2D, the edge has to be removed from the list, and two new ones have to be created connecting the previous points with the intersection point of the ray with the boundary, and sorted into the list. In the 3D-case, the closest face will be intersected instead, yielding 3 new faces. If A ⊖ B is a polytope, this iterative process will end in a finite amount of steps when the distance to the closest edge does not improve anymore, yielding the closest edge or face and thus the intersection depth. If A ⊖ B has round features, the iterative process might continue indefinitely, and can be terminated after a fixed amount of steps, or if the iterative increase in depths falls below a pre-defined threshold.

Thus, GJK and EPA make it possible to do collision detection on more general convex objects than SAP, and their iterative nature allows the reduction of computational complexity for cases where EA × EB is high. 20 Chapter 2. Theory

Figure 2.18: A non-convex object as triangle mesh (right) and as convex decomposition, in an explosion view (left). Visualized in AGX Dynamics.

2.3.3.4 Non-Convex Objects The techniques for discrete collision detection described above are limited to convex objects. For non-convex objects, there are fewer general algorithms[8]. One approach is to divide up non-convex objects into a collection of convex objects using convex decomposition, and then use the approaches for convex objects described above. For rigid objects, this decomposition can be pre-computed, but for deformable objects, it has to be re-computed, in the worst case at each time step. The result of convex decomposition is often a rather crude approximation of the real non-convex object, especially when treating round cavities as e.g. a bowl. Figure 2.18 shows an example of convex decomposition. Another approach is to approximate the geometry by simpler geometries such as spheres, as suggested by Weller[54]. This makes it possible to re- use simple algorithms for sphere-sphere collisions, but is a crude approximation when dealing with planar surfaces. General non-convex objects are often represented by a collection of primitives such as tri- angles. Middle phase collision detection as described in section 2.3.2 can be used to reduce the potentially colliding triangle-triangle pairs. Given a set of overlapping triangles, local contact data can be computed for each triangle-triangle intersection[9, chapter 5.3.4], but this does not give enough data to resolve the contact in case of deeper overlaps where triangles are completely inside the other object. It is possible to improve on this approach by traversing the overlapping volume. Other approaches include the meshing of the enclosed volume into tetrahedra like in Heidel- berger’s thesis[24, chapter 6], or using signed-distance fields[48]. Both approaches need heavy pre-computation and have quite a large memory-overhead, since volumetric data has to be stored instead of only surface data.

2.4 Overview of Continuous Collision Detection

With the understanding of the general collision detection pipeline as described above, it makes sense to study continuous collision detection more closely.

2.4.1 General Approaches The textbook by Ericson[21] from 2005 gives a general overview over the field of collision detection, but dedicates only a few pages to continuous collision detection. A more up-to-date review on literature on both discrete and continuous collision detection is presented in a paper by Asyrani et al.[7]. It compares different methods of discrete collision detection, but does not 2.4. Overview of Continuous Collision Detection 21

B

− A t1 t0 At1 At0 2

S 1 S 2

Figure 2.19: Object A moving and passing through object B. Bounding spheres S 1 and S 2 bound A’s movement from t0 to (t1 − t0)/2 as well as from (t1 − t0)/2 to t1. go into details on continuous collision detection. For the topic of continuous collision detection, Weller’s thesis[54, chapter 2.3.2] is helpful, since it summarizes several aspects of the research status. One way of dealing with the problem of tunneling is to reduce the size of the time step. This approach increases the likelihood of detecting all contacts, but does not meet the thesis’ requirements of a fixed time step, which is needed for real-time simulation. Interval halving is one approach of adapting the time step size[21, chapter 5.5.2]. It consists in dividing the movement of object A from t0 to t1 into two, from 0 to (t1 − t0)/2 and from (t1 − t0)/2 to t1. The approach then continues with computing bounding spheres that enclose each of these movements, as can be seen in Figure 2.19. If object B moves as well, it receives the same treatment. If the bounding spheres around A’s and B’s movement for the same time period overlap, the respective time interval is halved again, and the process continues iteratively until a certain threshold for the time-step is reached. For faster convergence, the movement can be enclosed with AABBs or OBBs instead of bounding spheres where this gives a tighter fit. If a measure of distance between disjoint bodies is available as well as a measure of in- tersection depth — or negative distance — for overlapping bodies, the problem of finding the collision time tc ∈ [t0, t1] can be considered as a root-finding algorithm, as Baraff observes in (1) one of his papers[10, chapter 7]. An approximation tc of tc can be computed by assuming lin- (1) ear or quadratic movement starting from t0, and calculating tc by finding a root to the distance function given this model of the movement. Since the true movement might differ from the cho- (1) (2) sen model, tc may differ from tc. A closer approximation tc can be obtained by computing the (1) distance or intersection depth at tc , and iteratively continuing from there in the same manner. As the root finding algorithm, bisection or Newton’s method can be chosen. These general root finding algorithms will be described in more detail in section 2.5.2. Another approach called conservative advancement is proposed by Mirtich[31, chapter 5.2.2]. It consists in computing a safe bound for the time-step until which the bodies can be advanced, and then computing forces for this reduced time step. The safe bound is based on functions of the bodies’ linear and angular velocities and accelerations, projected onto a distance vector Dˆ between the bodies. Since Dˆ might change during the movement, Mirtich proposes a slack factor of 1.2 in order to let the estimation of tc err on the conservative side. Cameron[15] introduces a more geometrical approach by considering the movement of the bodies in 4D-space-time, and testing for intersections in 4D. However, due to the cost of per- forming the 4D space-time extrusions, only linear motion can be considered. Since it is cheaper to do computations in 3D, 3D-swept volumes as described in [2] can be used to find intersec- tions between a dynamic and static object. They can not be used for intersections between two dynamic objects, since the swept objects might overlap even if the dynamic objects just passed 22 Chapter 2. Theory

B

At1

− A t1 t0 At0 2

Figure 2.20: Triangle A moves and rotates from t0 to t1 in one time step. The in-between motion of linearly moving vertices leads to A(t1−t0)/2 being smaller than A. The AABB B contains A’s movement during the whole time step. through the same space at different times. Also, the time of impact is not computed from the swept volume-swept volume overlap. These limitations are not shared by the method proposed by Müller et al.[34], where the space between objects is tessellated, and inversion of elements of the tessellation in between time-steps is detected. This method is also applied to simulation of a rope in 2D. However, in the 3D-case it can only be applied to cloth and tissue simulation.

2.4.2 In-Between Motion There is a group of methods for computing the time of contact by considering an assumed motion of the objects in between the configurations at the beginning and end of the time step. The question of which in-between motion to choose for such an approach depends also on the time integration of the equations of motion, as described in section 2.1.2. If the time integration scheme uses e.g. a constant linear and angular motion within a time step, the use of the same type of motion for collision detection will give the expected results. If a different type of in- between motion is used for continuous collision detection, such as as screw motion described below, the results might differ. For objects represented by triangle meshes, Moore and Wilhelms[33] suggest linear motion of the vertices from the starting position to the ending position during the time step. This corresponds exactly to a object’s motion if it only moves linearly. However, if the object also has angular motion, this linear approximation will lead to the triangles not being of constant size during the time step, as shown in Figure 2.20. For rigid bodies this limitation will usually not be tolerable, but it might be usable for simulation of deformable objects such as cloth or wires. Assuming linear motion of the vertices makes it possible to do continuous collision detection of two moving triangles by solving several cubic equations. Section 2.5 treats this approach in more detail. For constant linear and angular motion, Canny[16] represents rotation as a quaternion with a unit-length constraint. Rotation and translation can then be represented in a 6-dimensional space, yielding a 12-dimensional configuration space for for two moving objects. On this space, constraints are defined for avoiding collisions, and each constraint corresponds to a polynomial equation of degree 5. However, the complexity of this approach makes it unsuitable for real-time applications [41, p. 2]. Redon[41] argues that due to the interpolative nature of time integration, the in-between motion for collision detection can be chosen arbitrarily as long as it fulfills the beginning and end configurations from time integrations as well as rigid body motion. He proposes screw 2.4. Overview of Continuous Collision Detection 23

B

At1

At0

Figure 2.21: An enlarged bounding volume B of an object A with constant linear and angular velocity moving from t0 to t1 within one time step. motion as in-between motion, which has the limitation that it can generate non-natural motion if large rotations are involved[39]. In such cases, continuous collision detection assuming screw motion might report different kinds of collisions than other in-between motion types. Albocher et al.[4] suggest an approach based on the Minkowski sum for finding the intersec- tion time of two oriented bounding boxes undergoing rational motion. Limiting the supported shape type to bounding boxes reduces the applicability for general bodies, but makes it possible to also use this approach for broad phase and middle phase in continuous collision detection, as long as AABBs or OBBs are used as bounding volumes. This aspect will be treated in more detail in section 2.4.3. Many of the approaches described above involve finding roots in equations. There, Re- don[40] proposes interval arithmetic in order to find upper and lower bounds for the time of contact given an error threshold, using any of these in-between-motions.

2.4.3 Continuous Broad Phase and Middle Phase

The previous section focuses on general techniques for continuous collision detection between two objects. However, also broad phase-strategies for reducing the computational complexity of n-body collision detection problem have to be adapted for continuous collision detection in order not to miss collisions, as well as middle phase approaches dealing with the n × m features between bodies with many details. Bounding volumes for broad phase collision detection have been introduced in section 2.3.1.1. They enclose the potentially complex geometry of an object in a simpler bounding volume, which can easily be tested against other bounding volumes. However, for continuous collision detection, a bounding volume does not only have to enclose the object at the end of the time step, but also at its beginning as well as during the in-between motion. As the bounding volume of a triangle whose vertices are assumed to move linearly during the time step, a bound- ing box containing the vertices at the beginning and end of the time step can be chosen[33, chapter 2.1], which is illustrated in Figure 2.20. However, for a body moving with constant lin- ear and angular velocity, the body’s rotational motion has to be taken into consideration, as can be seen in Figure 2.21. Using bounding volumes which have thus been enlarged to contain the motion of the object during the whole time step, the broad phase strategies described in section 2.3.1 can be used without modification. 24 Chapter 2. Theory

These enlarged bounding volumes will lead to more false positives in broad phase collision detection. This problem is being addressed by the approach of kinetic data structures[23], which consist of

• a collection of geometric relations,

• events that describe if such a geometric relation fails and when, and

• an event queue that is sorted after the time of failure for the events.

This approach allows the adaptation of discrete broad phase strategies such as sweep and prune to continuous ones such as kinetic sweep and prune[18]. Here, the sorted lists of ordinary sweep and prune have been extended to keep track of kinetic data, and get updated during the time step for each of the events mentioned above, e.g. when two objects’ bounding boxes get into contact. Since the bounding boxes get updated during the time step instead of having to contain the object and its whole motion during a time step, they can fit more tightly around the objects, which reduces the number of false positives. The same considerations as for the broad phase collision detection apply also for the middle phase collision detection. Increased bounding volumes allow the re-use of discrete middle phase algorithms for continuous collision detection, with the cost of more false positives. However, continuous middle phase algorithms exist as well: Chen et al.[17] use a continuous version of the separating axis test for middle phase collision detection, and Weller[54, chapter 3.3] proposes a kinetic separation list, which corresponds to AABB-trees introduced in section 2.3.2, but augmented with kinetic data structures.

2.5 Continuous Collision Detection of Triangle-Triangle Pairs

Complex 3D objects are often represented on the computer as triangular meshings of their boundaries, partially since triangles are well supported by rendering hardware such as graphics cards. One way of finding collisions between two triangle meshes is to test each relevant pair of a triangle from one mesh against one triangle from the other one. Therefore, work has been spent on continuous collision detection of triangle-triangle pairs. A continuous collision test for a triangle-triangle intersection consists in testing each vertex of one triangle against the surface (also called face) of the other one, and vice versa. Further- more, triangles can collide edge against edge — so each edge from one triangle has to be tested against each edge of the other one, resulting in a total of 15 necessary tests (3 × 2 vertex-face tests and 3 × 3 edge-edge tests). Figure 2.22 shows the two test configurations. The edge-edge test is relevant for continuous collision detection of wire segments, since triangle edges are line segments, and thus, the edge-edge test can be reused for testing the mid- lines of wire segments against each other. Several techniques will be discussed in the sections below. They assume the linear in-between motion of of the vertices, as described in section 2.4.2.

2.5.1 Original Approach by Moore Moore and Wilhelms[33, chapter 2.1] present a method for solving the problem of continuous collision detection for flexible surfaces. They focus on the sub-problem of a moving point intersecting a moving surface, which is the vertex-face test mentioned above. However, they also note that this problem is mathematically similar to the line segment-line segment case (also 2.5. Continuous Collision Detection of Triangle-Triangle Pairs 25

A A

P B P B

(a) Triangles A and B in contact with a ver- (b) Triangles A and B in contact with edge tex of A on the face of B at contact point against edge at contact point P. P.

Figure 2.22: Triangle-triangle contact configurations.

called edge-edge case); both cases involve finding points in time when four linearly moving points lie in a common plane.

It is known that a point P lies in a plane defined by three non-collinear points P0, P1, P2 if there exist numbers u, v solving the equation

P = P0 + (P1 − P0)u + (P2 − P0)v. (2.1)

If furthermore 0 ≤ u, v and u + v ≤ 1 then P lies within the triangle P0, P1, P2. Going from this static (or discrete) case to the dynamic (or continuous) one, let P + Vt describe the motion of the point over time t, with starting position P and constant velocity V. Similarly, let the surface be defined by three points with positions Pi and velocities Vi, i = 0, 1, 2.

Assume for the sake of simplicity that 0 ≤ t ≤ 1 (and V, Vi have been adapted accordingly). Then, the equation to solve is

P + Vt = P0 + V0t + ((P1 − P0) + (V1 − V0)t)u + ((P2 − P0) + (V2 − V0)t)v. (2.2)

Since the points and velocities are in 3-dimensional space, this equation can be reformulated as a system of 3 linear equations with 3 unknowns u, v, t:4

au + bv + ct = d eu + f v + gt = h (2.3) iu + jv + kt = l,

4Note that the system is dependent on t non-linearly and t is still included in the coefficients (see equation (2.4)). 26 Chapter 2. Theory where a = (P1x − P0x) + (V1x − V0x)t

b = (P2x − P0x) + (V2x − V0x)t

c = −Vx

d = Px − (P0x + V0xt)

e = (P1y − P0y) + (V1y − V0y)t

f = (P2y − P0y) + (V2y − V0y)t (2.4) g = −Vy

h = Py − (P0y + V0yt)

i = (P1z − P0z) + (V1z − V0z)t

j = (P2z − P0z) + (V2z − V0z)t

k = −Vz

l = Pz − (P0z + V0zt).

The indices x, y and z are the x, y and z-components of the points and vectors. Assuming that the system of equations (2.3) has a full rank of 3,5 it can be solved for t and expanded to 0 = a(a j − bi)(ah − de) − a(a j − ib)(ag − ce)t (2.5) + (a f − be)(ak − ci)t − (al − di)(a f − be). If the system of equations has a rank of lower than 3, then the system gets reduced to a permanently 2D- or 1D-case. This degeneracy will be discussed in section 2.5.4. Since the terms a, b, d, e, f, h, i, j, l depend linearly on t, the whole equation (2.5) is a polyno- mial of degree 5 in t. General polynomials of degree 5 or higher cannot be solved algebraically (as given by the Abel-Ruffini theorem). Details on how to solve them numerically will be treated below in section 2.5.2. For each of the up to 5 solutions ti, i = 1, ··· , 5 of equation (2.5), it has to be checked that 0 ≤ ti ≤ 1, so that the collision of the point with the plane actually occurs within the time bounds for this time step. Once there is a solution ti in the time bounds, it can be re-substituted into the terms a to l in equation (2.3), to obtain corresponding ui and vi. If a solution ui and vi can be obtained, it has to be checked that 0 ≤ ui, vi as well as ui +vi ≤ 1, otherwise the point is within the plane, but not within the triangle. This point-vertex test can be modified to an edge-edge test by defining edge 1 as (P0 + V0t)(1 − u) + (P1 + V1t)u, and edge 2 as (P2 + V2t)(1 − v) + (P3 + V3t)v. Setting

(P0 + V0t)(1 − u) + (P1 + V1t)u = (P2 + V2t)(1 − v) + (P3 + V3t)v, (2.6) and following through the calculations above in a similar matter gives solutions for t. The check for valid parameters ui, vi for each solution ti is then 0 ≤ ui, vi ≤ 1, otherwise the intersection point is outside of the bounds of at least one of the edges.

2.5.2 Solving Polynomials Numerically Moore and Wilhelms’ approach mentioned in section 2.5.1 involves finding the roots of a poly- nomial of degree 5.

5The assumption about the rank of (2.3) is not stated in Moore’s and Wilhelms’ paper[33, chapter 2.1], but is clearly necessary for being able to solve the system. 2.5. Continuous Collision Detection of Triangle-Triangle Pairs 27

R

I3 I2 I1 I0

Figure 2.23: Bisection used for finding a root of a polynomial equation, starting from dividing I0 in the middle, choosing the interval I0 where f has different signs on the end points and continuing recursively with I1,I2, I3, and so on. This approach happens to isolate root R here out of the three possible roots.

ff ∑ There are di erent methods for numerically finding the roots of single-valued polynomials n n ffi ∈ R , i=0 ai x with coe cients ai , an 0, and thus degree n. Due to the fundamental theorem of algebra, a real-valued polynomial with degree n has up to n roots, which can be real-valued or complex-valued. There are some limitations of the solutions of interest for the application in the thesis:

• Complex-valued solutions are not of interest, so only real-valued solutions will be con- sidered.

• Only solutions lying within a pre-defined interval [0, 1] are of interest.

• Also, a polynomial can have multiple roots; e.g. (x − 1)2 = 0 has the root 1 two times. For the application in this thesis, it is enough to consider such a multiple root only once, i.e. only the distinct roots are of interest.

Moore and Wilhelms [33, chapter 2.1] use the bisection method, an application of binary search on an interval. The method can be used for finding a real-valued root of a continuous function f : R → R, within an interval [x0, x1] for which sgn( f (x0)) , sgn( f (x1)). Given these conditions that f is continuous and has different signs on both end points of the interval [x0, x1], a real-valued root is guaranteed to exist, since f has to have the value 0 at some point within this interval due to the intermediate value theorem. The method itself consists then in dividing the interval at xh with x0 < xh < x1 (e.g. by halving it, which gives rise to the name bisection). This results in two sub-intervals [x0, xh] and [xh, x1]. At least one of the sub-intervals will have bounds where f will have different signs, and thus contain a root. Continuing this interval-halving until a certain threshold for the interval size is reached will bound the root within a fixed number of steps. Figure 2.23 visualizes the method. Multiple identical roots will be treated as a single one by this approach. Since this method only finds a single root, there are difficulties in applying it to the problem of finding all distinct real roots of a polynomial within an interval. For each root of interest, solving this problem involves finding an interval bounding the root, and with end points where f has values with different signs. This process is called root isolation[47, p. 8]. 28 Chapter 2. Theory

To illustrate why this process is necessary, the problem introduced in section 2.5.1 will be considered, where we are interested in distinct real roots of a polynomial of degree 5 in the interval [0, 1]. Simply evaluating f (0) and f (1) will lead to one of those cases:

• f has different signs on both sides. There is at least one root of f within the interval, but there might be up to five.

• f is zero on both sides. There are at least two roots (x0 and x1 themselves), but there might be up to three more within the interval.

• f has the same (non-zero) sign on both end points. There might be no root in the interval, or there might be up to four. The equality of the signs of f at the interval end-points does not say anything about the number of roots in the interval, except that there cannot be five roots within the interval. The reason for this is that for a polynomial with odd degree, sgn(limx→−∞ f (x)) = − sgn(limx→∞ f (x)), so there is another crossing of the value 0 and thus at least one root outside of such an interval.

Moore and Wilhelms [33, chapter 2.1] divide the interval in a number of sub-intervals and proceed from there, but do not give details on how exactly the sub-intervals are chosen for isolating the roots. However, for the problem of isolating real roots, there are many approaches in the literature.[47, chapter 2.2.2] One simple approach is the following procedure[47, p. 15]: Let f be a polynomial as defined above. Then, the real roots of its derivative f ′ within the interval I can be used as borders of the isolating sub-intervals, together with the original interval borders. The reason for this is that any root of f can only lie between two extrema of f due to Rolle’s theorem. The extrema of f are the interval borders, as well as roots of f ′. The roots of f ′ can in turn be obtained from a bisection method on f ′, with subintervals given by the roots of f ′′, and proceeding recursively. The recursion can end when polynomials of rank 4 or lower are obtained, for which analytical solutions exist.6 Given such isolating sub-intervals containing one real root each, Newton’s method can be used on each of these sub-intervals as well instead of the bisection method. Newton’s method is an iterative method for finding roots of a real-valued function f (x). It works by starting with an initial guess x0 and refining by = − f (xn) . xn+1 xn ′ (2.7) f (xn) The advantage of using Newton’s method is that it can have quadratic convergence, while bi- section only converges linearly. However, Newton’s method might diverge from a root unless the initial guess is within the root’s so called basin of attraction, which in general might be arbitrarily small,[26, chapter 3.3.1] and can have fractal, non-connected nature.[19] Strategies for addressing these problems are subsumed under the term globalization[35]. An overview over other methods for solving polynomial roots can be found in Spencer’s thesis[47]. Many of them either treat special cases, or are computationally more costly, e.g. by finding the eigenvalues of an n × n matrix (where n is the degree of the polynomial).

2.5.3 Provot’s Method In contrast with the method by Moore and Wilhelms[33] introduced above, Provot[38] suggests a method where instead of a polynomial of degree 5, only one of degree 3 has to be solved for

6However, waiting with analytical approaches until polynomials of rank 2 or lower are encountered might make computations easier. 2.6. Wire Simulation 29 the edge-edge and vertex-face tests. Ericson[20] gives an overview over the history and usage of the method. In Provot’s method, both the vertex-point test and the edge-edge test are treated. The focus here will be on the latter, since that case is of interest for the continuous collision detection of wire segments. Like in section 2.5.1, let edge 1 be (P0 + V0t)(1 − u) + (P1 + V1t)u, and edge 2 be (P2 + V2t)(1 − v) + (P3 + V3t)v, with 0 ≤ u, v, t ≤ 1. Let the linearly moving end points of the edges be defined as A(t) = P0 + V0t

B(t) = P1 + V1t (2.8) C(t) = P2 + V2t

D(t) = P3 + V3t. At the time of a collision, the four end points A, B, C, D have to lie in the same plane, and thus the dot product of a vector connecting one point from each edge (e.g. B(t) − A(t)) with the cross product of the two edge directions should vanish:

((B(t) − A(t)) × (D(t) − C(t)) · (C(t) − A(t)) = 0. (2.9)

Since each of the points A(t), B(t), C(t), D(t) depends linearly on t, this leads to a polynomial of degree 3. Solving it gives up to three solutions ti, i =∈ {1, 2, 3}. Each solution ti is only valid if it occurs within the time frame of interest (0 ≤ ti ≤ 1). Each valid ti can be entered into equation (2.6) which thus turns into a linear system of equations of size 3 × 2 with unknowns ui, vi. If this system has a solution and if the resulting edge parameters are within the bounds 0 ≤ ui, vi, ≤ 1, then there is a collision at time ti. The smallest ti which fulfills these criteria can be reported as the first time of collision within the time frame (0, 1).

2.5.4 Issues with Co-Planarity and Co-Linearity Ericson[20] warns that the methods by Moore and Wilhelms as well as by Provot are vulnerable to robustness problems in permanent cases of co-planarity or co-linearity, e.g. if the two edges move within the same plane during the whole time step. These situations lead to degeneracies in the systems of equations, and so they have to be detected and treated separately by reducing the problems from 3D to 2D (or even 1D in case of further degeneracies in the 2D case). Examples of these problems for Provot’s method include cases where both line segments are constantly parallel. Then, the term (B(t) − A(t)) × (D(t) − C(t)) from equation (2.9) will collapse to 0, and equation (2.9) itself to 0 = 0, which would be true for all t. One example for Moore’s method for the point-triangle test is that if the point P is permanently moving in the triangle’s plane, then equation (2.2) is true for all values of t. In that case, all values of t ∈ (0, 1) would have to be tested for 0 ≤ t ≤ 1, and each resulting pair u, v for the conditions 0 ≤ u, v ≤ 1 as well as u + v ≤ 1. In physics simulation, co-planarity and co-linearity of the geometries of the involved bodies are not rare special cases, but rather appear quite frequently due to aligning forces such as contact forces and gravity. Therefore, a good treatment of these cases has to be at focus for the stable simulation of of wires based on continuous collision detection.

2.6 Wire Simulation

Some more background on wire simulation will be provided here, since it is the main use case for continuous collision detection in this thesis. The focus here is on wire simulation approaches 30 Chapter 2. Theory that support frictional contacts as well as large tension, and can that run in real-time for industry- size applications. Note that the expressions wire or cable will be used interchangeably: the general numerical methods for simulating these are assumed to be the same, and it is further assumed that differ- ences in real-world behavior can be simulated by changing relevant material parameters such as density, Young’s modulus, Poisson’s ratio, friction coefficient.

2.6.1 Recent Approaches The wire model used in this thesis was originally introduced in a paper by Servin and Lacour- sière[43] as a massless wire, and augmented with interior rigid body mass nodes in a further paper by the same authors[44]. Adaptive resolution based on tension[45] and and frictional contacts with rigid bodies[46] were added in further papers by Servin et alii. This thesis will build upon that work by enabling continuous collision detection for wire-wire interaction. Work on wire simulation with frictional contacts has also been presented in a paper by Brown et al.[14], where a real-time capable method involving collisions and self-collisions is proposed. Tunneling is prevented by not allowing segments of the rope to travel more than a cer- tain distance per time-step. This approach limits the method’s usefulness in real-time simulation of the kind of scenarios dealt with in this thesis. Martin et al.[29] propose a method based on a unified formulation for elastic rods, shells and solids. The resolution of the elastic elements is constant, which would make a small time-step necessary due to numerical reasons when simulating wires under high tension, thus increasing the computational time. The collision detection is discrete and based on approximating the objects by many spheres. A similar collision detection method is used by Phillips et al.[37] for simulation of knot tying in ropes. Imanishi et al.[25] use the Finite Element Method (FEM) in order to simulate the wire of a crane with a hydraulic winch drum. The rope’s contact interaction is limited to the winch drum, and based on specific criteria and not general collision detection. Similar to that, Takehara et al.[49] apply an Absolute Nodal Coordinate Formulation. Also here, contacts are created as boundary conditions based on external criteria, and not on collision detection.

2.6.2 Hybrid, Multi-Resolution Wires with Massless Frictional Contacts The wire simulation model used in this thesis and in AGX Dynamics is based on the approach introduced in the papers by Servin et. al. mentioned above. This approach discretizes the wire into segments of non-uniform length. The discretization can change over time, based on tension in the wire and contacts with rigid bodies, using a technique called adaptive resolu- tion[45], which allows slacking at low tension, and maintains numerical stability by coarsening the discretization at high tension. The nodes at the end-points of the wire segments can represent different effects of the wire as shown in Figure 2.24. They can be either point masses along the wire, nodes fixed to rigid bodies for modeling e.g. eyes, or contact nodes which are an internal representation for frictional contacts with rigid bodies. The interaction between the nodes is defined by constraints which resist stretching and bending, and who can be relaxed by parameters such as elastic moduli and damping for both stretching and bending. Within a time step, nodes of all types described above can move linearly in space, depending on the forces acting on them from contacts, wire constraints, gravity and other sources. Thus, the movement of the wire segments is defined by the linear movement of their endpoints, and the segments’ lengths will not be constant during the time step. Also, adaptive resolution and 2.6. Wire Simulation 31

Contact nodes

Free mass nodes

Nodes fixed at rigid bodys

Figure 2.24: Different node types of a wire, freely hanging, in contact, and under tension. contacts can lead to segments (and nodes) being removed or added during the time step, as can be seen in Figure 2.25.

t1

t0

Figure 2.25: Wire with three segments and four nodes at t0 gets stretched and removes two inner nodes, having one segment and two nodes left at t1.

The wire model so far uses discrete collision detection at the beginning of each time step in order to detect overlaps between wire segments and rigid bodies. This approach works well as long as the wire segments are not moving too much with regard to their radius and the size and movement of the rigid bodies. If one of these criteria is not fulfilled, tunneling can occur, as visualized in Figure 1.2 for an example. The phenomenon of tunneling is much more prone to occur when simulating wires that can interact with each other rather than just with rigid bodies, since wires typically have small radii compared to their relative motion within a time step. Therefore, two potentially colliding wires could easily move more than the sum of their radii within one time step, and discrete collision detection would miss their passing through each other — see figures 1.3 and 2.26 for examples. Thus, continuous collision detection is necessary in order to reliably simulate wires interacting with other wires. The focus of the thesis is on solving this problem. 32 Chapter 2. Theory

Figure 2.26: One beige wire tunneling through two other wires (turquoise and red). The thin beige lines indicate the previous position and movement of the beige wire during the time step. Visualized in AGX Dynamics.

Figure 2.27: Harbor crane with wires lifting container. Simulated in AGX Dynamics.

However, the wire-wire interaction model that then makes use of the outputs from the con- tinuous collision detection will not be treated here, since it has been developed at Algoryx Sim- ulation AB outside of the scope of this thesis. The thesis will instead focus on the continuous collision detection itself.

2.7 AGX Dynamics

AGX Dynamics is a physics engine fitting into the scheme presented in section 2.1.3. It is a commercial product that is developed and sold by Algoryx Simulation AB[5]. AGX Dynamics is used for interactive simulation (often run in real-time), but also for non-interactive simulations of larger systems. In AGX Dynamics, it is possible to simulate mechanical systems, including rigid body dynamics, particle systems, wires, and more, such as in Figure 2.27. AGX Dynamics is typically used as a middle-ware and thus integrated into other programs which have their own graphical user interface (GUI). However, the product comes with the library agxOSG, which is an integration into the 3D rendering engine OpenSceneGraph[36] and serves as an example for how the integration of AGX into 3D rendering engines can be achieved. This library was used for generating the simulation screen-shots used in the thesis. Some details about AGX Dynamics will be presented below. 2.7. AGX Dynamics 33 Box Capsule Convex Cylinder Plane Sphere Trimesh Composite HeightField Line

Box x x x x x x x x x x Capsule x x x x x x x x x x Convex x x x x x x x x x x Cylinder x x x x x x x x x x Line x x x x x x x x x x Plane x x x x x - x x x - Sphere x x x x x x x x x x Trimesh x x x x x x x x x x Composite x x x x x x x x x x HeightField x x x x x - x x x -

Table 2.1: Table showing colliders between shape types in AGX Dynamics. x: collider exists; -: no collider needed since only static shapes. Source: [1].

2.7.1 Spook Stepper The time integration scheme used in the thesis and in by AGX Dynamics[1] is called Spook. It is introduced by Lacoursière in one of his papers[28] and his thesis[27]. With regard to collision detection, it is of relevance to note that Spook is a first-order, fixed time step integrator. That means that the time-step size is known, and no configurations from in-between the time step or earlier than the previous time step will be used (as can be the case with higher order integrators). This leads to the in-between motion of constant linear and angular velocity. Further details of the time-stepping scheme are not important for the collision detection and will therefore not be treated here; see the paper by Lacoursière[28] for a derivation and more details.

2.7.2 Collision Detection AGX Dynamics offers discrete collision detection for a variety of shape types, such as spheres, boxes, cylinders, capsules, but also unions of these shapes labeled composite, as well as general convex or non-convex triangle meshes. The algorithms for detecting collisions between two shape types are called colliders in AGX Dynamics.[1] Table 2.1 shows an overview over the provided shape types and colliders. Before this thesis, no continuous collision detection was used in AGX Dynamics, but only discrete collision detection. For broad phase collision detection, both sweep and prune and hierarchical grid can be used. Hierarchical grid performs better in scenes with a large number of objects with similar size, such as granular simulations. Sweep and prune performs better in scenes with objects with a more heterogeneous size distribution, such as the wire simulation scenes in this thesis. For middle phase collision detection for collisions involving mesh shapes, AABB-trees are used.

2.7.3 Constraints In AGX Dynamics, constraints can be formulated mathematically by giving their Jacobians and violation functions. There exist also pre-defined constraint types, such as hinges, cylindricals, 34 Chapter 2. Theory prismatics, ball-joints, or lock-joints. Internally, contacts stemming from collision detection are also treated as constraints.[1]

2.7.4 Wires The wire simulation used in AGX Dynamics is built on top of the existing framework including collision detection, constraints, the numerical time stepper, and the numerical solver. The ap- proach introduced in section 2.6.2 called hydrid, multi-resolution wires with massless frictional contacts is used. The collision detection part of the wire simulation is performed in the following manner: For each wire segment used in the approach described in section 2.6.2, a capsule shape is created, which is one of the collision shapes used in AGX as introduced in section 2.7.2. A capsule is a line segment surrounded by a radius. It can also be described as a cylinder with a half-sphere at each end. These capsules do not carry any mass in themselves, but are only used for collision detection. If collisions occur, wire contact nodes (introduced in section 2.6.2) are placed at the contact points. Discrete collision detection is used for the capsules against rigid bodies. Chapter 3

Method

Based on the theory presented in the chapter above, an approach has been chosen for the con- tinuous collision detection of wire segments. This approach has been augmented by taking into consideration co-planarity and co-linearity. The results have been implemented in C++ and in- tegrated into AGX Dynamics’ collision detection pipeline. The following sections will show the details of these steps. Test cases and results will be shown in chapter 4.

3.1 Continuous Collision Detection Edge-Edge

As described in section 2.6.2, wires in AGX are described as connected wire segments. Each segment is represented by a capsule (a line segment with a radius), and existing capsule-capsule collision detection can be used for discrete collision detection. However, continuous collision detection is needed in order to avoid tunneling. For the case of wire-wire collisions, it is impor- tant to detect all cases where wires pass through each other. It is less important to detect cases where wires glide alongside each other. Therefore, continuous collision detection for the wire segment mid lines is sufficient. Since the wire segment end points move linearly, the methods for continuous collision de- tection of triangle edges described in section 2.5 can be used for the wire segment mid lines. Of these methods, Provot’s method has been chosen since it involves only solutions of cubic polynomials. Also, the combination of a dot-product and a cross-product makes it conceptually easier to see which kinds of degeneracies lead to equation (2.9) being identically zero. The general problem to solve is equation (2.9), which is repeated here again:

((B(t) − A(t)) × (D(t) − C(t)) · (C(t) − A(t)) = 0. (3.1)

3.1.1 Detection of Co-Planarity and Co-Linearity In section 2.5.4, it was shown that cases of co-planarity and co-linearity can make it impossible to use equation (3.1). These cases lead to the left hand side of equation (3.1) degenerating to 0 for all values of t. The equation consists of a dot product of a difference between two points, and a cross- product between two differences of points, which can in its general form be written as (a × b) · c. This is a so-called scalar triple product, which geometrically corresponds to the signed volume of the parallelepiped formed by the three vectors a, b, c, see Figure 3.1. This geometrical interpretation shows that there are three different ways the scalar triple product can be zero:

35 36 Chapter 3. Method

• Any one of the three vectors a, b, c is zero.

• Any two of the three vectors are parallel.

• All three vectors are co-planar.

α a h

base c θ b

Figure 3.1: The parallelepiped formed by the vectors a, b, c. Source: https://upload. wikimedia.org/wikipedia/commons/3/3e/Parallelepiped_volume.svg.

These cases lead to several configurations where the left hand side of equation (3.1) can be zero for all values of t:

1. B(t) − A(t) = 0 ∀t or D(t) − C(t) = 0 ∀t. This covers the case where a or b in the general description above are 0. This means that one of the two line segments or both degenerate to a point for the whole time period. This is a case which can be excluded beforehand by making sure that no line segments of length 0 are created, since they do not make sense in the context of wire simulation.

2. C(t) − A(t) = 0 ∀t. This corresponds to c being zero. This case means that the two line segments share their beginning point during the whole time interval. Sharing the same point means intersection, thus the first time of collision is t = 0.

3. (B(t)−A(t))×(D(t)−C(t)) = 0 ∀t. Assuming that case 1 above does not occur and thus the line segments do not degenerate to points, this means that the two line segment directions are permanently parallel, since their cross product is zero. Parallelity includes the case of co-linearity. This case will be treated in section 3.1.2. This encompasses only one of the possible three parallel cases described above, the one between the vectors a and b.

4. Cases 1-3 do not occur, but ((B(t) − A(t)) × (D(t) − C(t)) · (C(t) − A(t)) = 0 ∀t. Since the connection between the line segments is permanently orthogonal to the cross products of the line segment directions, this means that the line segments are moving within a common plane during the whole time step. Thus, this configuration can be handled in 2D by considering this common plane. This case will be treated in section 3.1.3. In the general description above, it covers the case where the vectors a, b, c are co-planar. Also, it implicitly considers the case where a and c or b and c are parallel, since the result of the cross product will then be orthogonal to c. 3.1. Continuous Collision Detection Edge-Edge 37

Start

no

Case 1 yes Exit with detected? error

no

Case 2 yes Contact detected? at t = 0

no

Handle Case 3 yes parallel detected? case

no

Case 4 yes Handle detected? 2D case

no Handle non- degenerate case

Figure 3.2: Flowchart for detection and treatment of the various degenerate cases and the non- degenerate case. 38 Chapter 3. Method

Based on the division into these distinct configurations, Figure 3.2 shows a flow-chart for handling continuous collision detection of line segments by taking into account co-linearity and co-planarity. The question is then how cases 1–4 can be detected given the three-dimensional parameters Pi, Vi, i = 0, 1, 2, 3 from which A(t), B(t), C(t) and D(t) have been defined in equation (2.8).

3.1.1.1 Detection of Case 1: Line Segments Degenerate

Case 1 is encountered, as described above, if B(t) − A(t) = 0 ∀t or D(t) − C(t) = 0 ∀t. The first variant given by B(t) − A(t) = 0 ∀t is equivalent to P1 − P0 + (V1 − V0)t = 0. This equation in turn is equivalent to three linear equations, which are only true for all t if P0 = P1 and V0 = V1. Similarly, for D(t) − C(t) = 0 ∀t, it holds that P2 = P3 and V2 = V3. Given a simple function StaticEquality for testing the approximative equality of 3-dimensional points or vectors relative to a numerical threshold ϵdist, this test can be formulated in algorithm 1.

Algorithm 1 Detect Case 1: Line Segments Degenerate

function DetectCase1(P0, P1, P2, P3, V0, V1, V2, V3, ϵdist) if StaticEquality(P0, P1, ϵdist) and StaticEquality(V0, V1, ϵdist) then return true end if if StaticEquality(P2, P3, ϵdist) and StaticEquality(V2, V3, ϵdist) then return true end if return false end function

3.1.1.2 Detection of Case 2: Line Segment Starting Points Identical

The test for case 2 is a variant of the tests for case 1, only this time the beginning points of the two line segments are compared rather than each line segment’s beginning point against its end point as in case 1. This yields the conditions P0 = P2 and V0 = V2, as in algorithm 2.

Algorithm 2 Detect Case 2: Line Segment Starting Points Identical

function DetectCase2(P0, P2, V0, V2, ϵdist) if StaticEquality(P0, P2, ϵdist) and StaticEquality(V0, V2, ϵdist) then return true end if return false end function

3.1.1.3 Detection of Case 3: Parallel Case

Detection of case 3 (given that the cases 1 and 2 are not active) is a little more complicated. As shown above, case 3 is encountered if the cross product (B(t) − A(t)) × (D(t) − C(t)) is zero for all t. 3.1. Continuous Collision Detection Edge-Edge 39

By defining two linearly time-dependent vectors K(t) = P + Rt, (3.2) L(t) = Q + S t, with P, Q, R and S being constant coefficients, it can then be seen that the cross product between K(t) and L(t) can be written as three quadratic equations in t:

(K(t) × L(t))h = K(t)iL(t) j − K(t) jL(t)i

= (Pi + Rit)(Q j + S jt) − (P j + R jt)(Qi + S it) = t2(R S − R S ) i j j i (3.3) + t(PiS j − P jS i + RiQ j − R jQi)

+ (PiQ j − P jQi); i ≡ h + 1 (mod 3), j ≡ h + 2 (mod 3), where h = 0, 1, 2, and the indices 0, 1, 2 correspond to the coordinates x, y, z in Euclidean space. These equations can be obtained by inserting equation (3.2) into the cross product, multiplying and collecting terms. K(t) × L(t) = 0 ∀t means then that all three coefficients of the quadratic equations for each value of h = 0, 1, 2 are zero:

RiS j − R jS i = 0

PiS j − P jS i + RiQ j − R jQi = 0 (3.4) PiQ j − P jQi = 0 h = 0, 1, 2, i ≡ h + 1 (mod 3), j ≡ h + 2 (mod 3). This gives nine equations to test for. Choosing for the general K(t) and L(t) the values K(t) = B(t) − A(t) and L(t) = D(t) − C(t) gives P = P1 − P0,

Q = P3 − P2, (3.5) R = V1 − V0,

S = V3 − V2 by inserting equation (3.2) and equation (2.8). Algorithm 5 follows this approach, given algo- rithm 4 for detecting if two vectors are parallel, which is in its turn based on algorithm 3 for computing the coefficients of the quadratic equations. Note that the threshold ϵcoefficientsQuadratic introduced in equation (3.2) might be chosen differently from the ϵdist used in the previous al- gorithms in this section. Both consider that computations on a computer with finite precision arithmetics have to take into account round-off errors, but ϵdist has also a geometric interpreta- tion, since it defines the lowest distance below which points can be considered identical.

3.1.1.4 Detection of Case 4: 2D-Case Case 4 means, given that the cases 1, 2 and 3 do not apply, that the whole equation ((B(t) − A(t)) × (D(t) − C(t)) · (C(t) − A(t)) is zero for all t. Let the general scalar triple product (as introduced in section 3.1.1) of three linearly time dependent vectors K(t), L(t) and M(t) be written as

(K(t) × L(t)) · M(t), (3.6) 40 Chapter 3. Method

Algorithm 3 Compute Quadratic Coefficients from Cross Product function ComputeQuadraticCoefficientsFromCross(P, Q, R, S, h) ◃ Computes the three coefficients of a quadratic equation from the cross product in dimension h. i ← (h + 1) mod 3 j ← (h + 2) mod 3 c0 ← RiS j − R jS i c1 ← PiS j − P jS i + RiQ j − R jQi c2 ← PiQ j − P jQi return c0, c1, c2 end function

Algorithm 4 Detect if Two Vectors are Permanently Parallel

function AreVectorsPermanentlyParallel(P, Q, R, S, ϵcoefficientsQuadratic) ◃ Test if vector P + tR and vector Q + tS are parallel by checking if all quadratic coefficients are zero. for h ← 0, 1, 2 do c0, c1, c2 ← ComputeQuadraticCoefficientsFromCross(P, Q, R, S, h) for n ← 0, 1, 2 do if |cn| > ϵcoefficientsQuadratic then return false end if end for end for return true end function where K(t) and L(t) are defined as in equation (3.2), and M(t) = δ + νt, (3.7) with coefficients δ and ν. As derived in section 3.1.1.3, the cross product K(t) × L(t) leads to three quadratic equations in t. Let them be written as 2 (K(t) × L(t))h = αht + βht + γh , h = 0, 1, 2, (3.8) with coefficients α, β, γ, and the indices 0, 1, 2 corresponding to the indices x, y, z in Euclidean space as in section 3.1.1.3. Then, ∑2 2 (K(t) × L(t)) · M(t) = (δh + νht)(αht + βht + γh) = h 0 (3.9) ∑2 3 2 = αhνht + (αhδh + βhνh)t + (βhδh + γhνh)t + δhγh. h=0 This is a polynomial of degree 3 in t. For it to be zero for all t, all of its coefficients have to be zero, i.e. the following conditions have to hold: αν = 0, αδ + βν = 0, (3.10) βδ + γν = 0, δγ = 0, 3.1. Continuous Collision Detection Edge-Edge 41

Algorithm 5 Detect Case 3: Parallel Case

function DetectCase3(P0, P1, P2, P3, V0, V1, V2, V3, ϵcoefficientsQuadratic) ◃ Test if in case 3 by checking if all quadratic coefficients are zero. P ← P1 − P0 Q ← P3 − P2 R ← V1 − V0 S ← V3 − V2 return AreVectorsPermanentlyParallel(P, Q, R, S, ϵcoefficientsQuadratic) end function keeping in mind that α, β, γ δ, ν are three-dimensional vectors and their products are dot-products. By considering equation (3.7), the coefficients δ and ν can be defined as

δ = P2 − P0, (3.11) ν = V2 − V0. From equation (3.3), we get

αh = RiS j − R jS i,

βh = PiS j − P jS i + RiQ j − R jQi, (3.12)

γh = PiQ j − P jQi, h = 0, 1, 2, i = (h + 1) mod 3, j = (h + 2) mod 3. Based on the conditions formulated in equation (3.10) and the equations for assembling the coefficients (3.11) and (3.12), the algorithm 7 for detecting case 4 can be derived, given algorithm 6 for computing the coefficients of the cubic equation and another numerical threshold ϵcoefficientsCubic.

Algorithm 6 Compute Cubic Coefficients function ComputeCubicCoefficients(α, β, γ δ, ν) ◃ Computes the four coefficients of the cubic equation. c0 ← αν c1 ← αδ + βν c2 ← βδ + γν c3 ← δγ return c0, c1, c2, c3 end function

Given these four degenerate cases which now can be detected, the cases 1 and 2 can be handled directly, as described in section 3.1.1. However, the treatment of cases 3 and 4 is a little more involved and will be described in the following sections 3.1.2 and 3.1.3.

3.1.2 The Parallel Case The permanently parallel case occurs if the cross product between the edge directions is zero, which corresponds to case 3 described in section 3.1.1.3. Here, the only way the two line segments can intersect is if they are part of a common line, and if the segments intersect along this line. Since the line segments are parallel, it is enough to check if one line segment’s end point is on the line formed by the second line segment in order know that both line segments are part of 42 Chapter 3. Method

Algorithm 7 Detect Case 4: 2D-Case

function DetectCase4(P0, P1, P2, P3, V0, V1, V2, V3, ϵcoefficientsCubic) ◃ Test if in case 4 by checking if all cubic coefficients are zero. P ← P1 − P0 Q ← P3 − P2 R ← V1 − V0 S ← V3 − V2 for h ← 0, 1, 2 do αh, βh, γh ← ComputeQuadraticCoefficients(P, Q, R, S, h) end for δ ← P2 − P0 ν ← V2 − V0 c0, c1, c2, c3 ← ComputeCubicCoefficients(α, β, γ δ, ν) for n ← 0, 1, 2, 3 do if |cn| > ϵcoefficientsCubic then return false end if end for return true end function the same line. Let the points A(t), B(t), C(t) and D(t) be given as in equation (2.8). A point lies on a line if the cross product of the line direction with the direction from a point on the line to the point becomes zero. For C(t) being on the line given by the line segment (A(t), B(t)), this means (B(t) − A(t)) × (C(t) − A(t)) = 0 ∀t. (3.13)

This is a quadratic function in t with up to two solutions where the line segments are part of the same line, and for these solutions, segment overlap along the common line has to be checked.

3.1.2.1 Detection of the Parallel Co-Linear Case

However, also for equation (3.13), it is possible to degenerate to 0 = 0 ∀t. B(t) − A(t) and C(t) − A(t) cannot be 0 for all t, since that was already handled in cases 1 and 2 above, but the cross product can be 0 ∀t. In this case, the problem is reduced to a 1D problem, the parallel co-linear case. This case can be detected in the following way. Define two time-dependent vectors K(t) and L(t) as in equation (3.2), the cross product as in equation (3.3), and the conditions as in (3.4). Letting K(t) = B(t) − A(t), (3.14) L(t) = C(t) − A(t) gives

P = P1 − P0,

Q = P2 − P0, (3.15) R = V1 − V0,

S = V2 − V0. 3.1. Continuous Collision Detection Edge-Edge 43

Based on these conditions, algorithm 8 tests if a point is permanently co-linear with a line segment, given algorithm 4 for determining if two vectors are parallel, and the already intro- duced numerical threshold ϵcoefficientsQuadratic.

Algorithm 8 Detect if Moving Point is Permanently on Line

function IsPointPermanentlyOnLine(P0, P1, P2, V0, V1, V2, ϵcoefficientsQuadratic) ◃ Test if point P2 + tV2 is permanently on line formed by P0 + tV0 and P1 + tV1. P ← P1 − P0 Q ← P2 − P0 R ← V1 − V0 S ← V2 − V0 return AreVectorsPermanentlyParallel(P, Q, R, S, ϵcoefficientsQuadratic) end function

3.1.2.2 Handling the Parallel Co-Linear Case If the parallel co-linear case is encountered, it has to be handled as follows.

• First it has to be checked if the line segments already overlap at t = 0 along their common line.

• If not, it has to be determined if the line segments intersect later within the time frame t ∈ (0, 1] along their common line.

Regarding the initial overlap at t = 0, a check for overlap of line segments (A(t), B(t)) and (C(t), D(t)) along a common line l at a certain point in time tk can be done by projecting on the common line defined by a point P and a non-zero direction R,

Al = (A(tk) − P) · R,

Bl = (B(tk) − P) · R, (3.16) Cl = (C(tk) − P) · R,

Dl = (D(tk) − P) · R.

Then it has to be checked if the projected intervals overlap,

I = [min(Al, Bl), max(Al, Bl)] ∩ [min(Cl, Dl), max(Cl, Dl)]. (3.17)

If I , ∅, then there is an intersection at time tk. However, one difficulty is in finding a line with a non-zero direction R. There are two line segments to choose from, (A(tk), B(tk)) and (C(tk), D(tk)). If one of them degenerates to a point at time tk, the other one has to be selected. If both degenerate at tk, the approach in equation (3.16) cannot be chosen. Instead, it then suffices to check if the two points which the line segments degenerate to are identical. The test for initial overlap outlined so far is formalized in algorithm 9. If the line segments do not already overlap at tk = 0, it has to be determined if they do so at a later t ∈ (0, 1]. In this case, the line segments are initially separated and move along a common line. Therefore, they can only intersect when one end point of one line segment is identical with one end point of the other segment. A brute force approach gives thus 2 × 2 tests for moving point-moving point identity, where each point is moving linearly over time. One improvement 44 Chapter 3. Method

Algorithm 9 Static Co-Linear Overlap tatic o inear verlap , , , , ϵ ◃ , function S C L O (Atk Btk Ctk Dtk dist) Test if line segments (Atk Btk and , (Ctk Dtk ) overlap along common line. tatic quality ϵ ◃ if S E (Atk ,Btk , dist) then At least one line segment degenerates. tatic quality ϵ ◃ if S E (Ctk ,Dtk , dist) then Both line segments degenerate. tatic quality ϵ return S E (Atk , Ctk , dist) else ← − ◃ R Dtk Ctk Take second segment as line. ← P Ctk end if else ← − ◃ R Btk Atk Take first segment as line. ← P Atk end if ← − · Al (P Atk ) R ← − · Bl (P Btk ) R ← − · Cl (P Ctk ) R ← − · Dl (P Dtk ) R I ← [min(Al, Bl), max(Al, Bl)] ∩ [min(Cl, Dl), max(Cl, Dl)] if I = ∅ then return false else return true end if end function would be to order the points of each segment to reduce the number of tests from four to one — the one between the closest end points from the two segments. But since each point can move in an independent direction along the line and thus the order of the end points within a segment can be inverted, this reduction would involve some book-keeping. For that reason and since point-point identity tests are relatively cheap, the brute force method is used here. Testing the identity between two moving points can be performed in the following manner: Assuming as before two linearly moving points K(t) and L(t) defined as in equation (3.2), the following condition for equality holds:

K(t) = L(t), P + Rt = Q + S t, (3.18) (R − S )t = (Q − P).

This condition involves three linear equations — one for each of the three spatial dimensions — with one unknown t. Even though R and S cannot be zero in all three dimensions since this possibility is treated by cases 1 and 2 already, their difference (R−S )h can be zero in one, two or all three dimensions h. In these cases, (Q − P)h has also to be zero for these h in order to fulfill the equality condition; then however, it fulfills it for all t. Only if all three equations are fulfilled at some t there is an intersection. This point-point equality test is formalized in algorithm 10, introducing numerical thresholds for time ϵt and distance in one dimension ϵdist1D. The permanently parallel co-linear case can thus be addressed by first testing for initial overlap, and in case it does not occur, by testing the moving end points for identity. If there are 3.1. Continuous Collision Detection Edge-Edge 45

Algorithm 10 Moving Point-Point Intersection

function MovingPointPointIntersection(P, Q, R, S, ϵt, ϵdist1D) ◃ Computes if there is an intersection between moving points within t ∈ [0, 1]. α ← R − S β ← Q − P foundPreviousT ← false tprevious ← 0 for h ← 0, 1, 2 do if |αh| ≤ ϵdist1D then ◃ Directions zero in this dimension? if |βh| > ϵdist1D then return false ◃ Directions zero and points not identical. end if else t ← βh/αh if t < [0, 1] then return false end if if foundPreviousT then if |t − tprevious| > ϵt then return false end if else foundPreviousT ← true tprevious ← t end if end if end for return true, tprevious ◃ Even valid with no foundPreviousT. Then, 0 = 0, and tprevious = 0. end function several solutions, the earliest t ∈ [0, 1] is the time of contact. This approach is formalized in algorithm 11.

3.1.2.3 Handling the Parallel Non-Degenerate Case

The alternative to the parallel co-linear case is the parallel non-degenerate case. There, the quadratic equation (3.13) does not change to 0 = 0∀t. The equation has therefore to be solved in order to find points in time when the two line segments share a common line. For each of the up to two solutions tn, it has to be determined if the two line segments intersect along their common line. The coefficients for solving the quadratic equation can be assembled as shown in equation (3.15) and algorithm 3. After solving the quadratic equation, for each tn in the solution, overlap along the same line can be tested by algorithm 9. Assuming there is a function Solve which computes the real root of polynomials within t ∈ [0, 1] and returns the number of those roots as well as the roots in ascending order, algorithm 12 finds solutions which fulfill three quadratic equations simultaneously, and algorithm 13 uses the results to handle the parallel non-degenerate case. Algorithm 14 treats the general parallel case, corresponding to case 3 in section 3.1.1, by first testing if the parallel co-linear or the non-degenerate case occurs, and then handling the 46 Chapter 3. Method

Algorithm 11 Handle Parallel Co-Linear Case

function HandleParallelCoLinearCase(P0, P1, P2, P3, V0, V1, V2, V3, ϵdist, ϵt, ϵdist1D) ◃ Detect overlap along same line. if StaticCoLinearOverlap(P0, P1, P2, P3, ϵdist) then return true, 0 else t ← ∞ , ← oving oint oint ntersection , , , , ϵ , ϵ overlap0 t0 M P P I (P0 P2 V0 V2 t dist1D) , ← oving oint oint ntersection , , , , ϵ , ϵ overlap1 t1 M P P I (P0 P3 V0 V3 t dist1D) , ← oving oint oint ntersection , , , , ϵ , ϵ overlap2 t2 M P P I (P1 P2 V1 V2 t dist1D) , ← oving oint oint ntersection , , , , ϵ , ϵ overlap3 t3 M P P I (P1 P3 V1 V3 t dist1D) for n ← 0, 1, 2, 3 do if overlapn then t ← min(t, tn) ◃ Select earliest t out of the valid ones. end if end for if t < ∞ then return true, t ◃ Have found a valid t. else return false end if end if end function respective case accordingly. Note that several computations are repeated unnecessarily in the way the algorithms are based upon each other. This repetition is intended since the focus here is on clarity of the presentation. A more optimized set of algorithms would avoid re-computation of already known results.

3.1.3 The 2D-Case After having treated case 3 from section 3.1.1 in the previous section, case 4 will be discussed here. As mentioned above, it occurs if cases 1–3 can be excluded, but ((B(t) − A(t)) × (D(t) − C(t)) · (C(t) − A(t)) = 0 ∀t. Thus, it corresponds to a reduction to 2D since both line segments are moving in a common plane for all t. It can easily be seen that two initially intersection-free line segments moving in 2D can only get into first contact by one line segment’s end point colliding with the other line seg- ment. Therefore, it is sufficient to test each line segment’s two end points against the other line segment, resulting in four point-segment tests.

3.1.3.1 Testing for Initial Overlap Since approach of testing end points against line segments only works given there is no initial overlap, a test for initial overlap has first to be done at tk = 0. For any given tk, let there be two general lines K(u) = P + Ru, (3.19) L(v) = Q + S v, 3.1. Continuous Collision Detection Edge-Edge 47

Algorithm 12 Solve 3 Quadratic Equations

function SolveThreeQuadraticEquations(P, Q, R, S, ϵcoefficientsQuadratic) foundAnySolutions ← false solutions ← ∅ for h ← 0, 1, 2 do c0, c1, c2 ← ComputeQuadraticCoefficientsFromCross(P, Q, R, S, h) if |c0| < ϵcoefficientsQuadratic and |c1| < ϵcoefficientsQuadratic and |c2| < ϵcoefficientsQuadratic then Continue ◃ Can only happen 0, 1 or 2 times. end if tmpSolutions ← Solve(c0, c1, c2) ◃ Can have size 0, 1 or 2. if tmpSolutions== ∅ then return ∅ ◃ Optimization: Return early. end if if foundAnySolutions == true then solutions ← solutions ∩ tmpSolutions if solutions== ∅ then return ∅ ◃ Optimization: Return early. end if else foundAnySolutions ← true solutions ← tmpSolutions end if end for return solutions end function depending on line parameters u and v. The condition for intersection of these lines can be posed (similarly to equation (2.6)) as P + Ru = Q + S v, (3.20) which gives the system of equations

Ru − S v = Q − P, (3.21) a linear system of equations with unknowns u, v. If the problem is formulated in 2D space with 2 coordinates, the size of the matrix corresponding to the system is 2x2. The system is then guaranteed to be solvable if it has full rank of 2. A rank of less than 2 would mean that the line directions degenerate to zero or are parallel. The permanent versions of these cases have already been treated in cases 1–3 for and are excluded here, but the degeneracies can still occur in a temporary configuration for a given tk. The temporary parallel configuration can be detected by testing if R × S = 0. If a temporary parallel configuration occurs at tk, it has to be tested if the segments are part of the same line, e.g. by testing if one point of one segment is on the line of the other segment. If this is the case, the approach described in section 3.1.2.2 and formulated in algorithm 9 can be used in order to test for static overlap along the same line; if not, there is no overlap at tk. With regards to the non-degenerate case: if the problem given in equation (3.21) is formu- lated in 3D, its size is 3x2. Such a system of equations is not in general solvable even given rank 2, since it is overdetermined; geometrically, two lines can be skew in 3D. However, since case 4 is treated here, where movement in a common 2D-plane is given, there is no possibility 48 Chapter 3. Method

Algorithm 13 Handle Parallel Non-Degenerate Case

function HandleParallelNonDegenerateCase(P0, P1, P2, P3, V0, V1, V2, V3, ϵdist, ϵcoefficientsQuadratic) P ← P1 − P0 Q ← P2 − P0 R ← V1 − V0 S ← V2 − V0 solutions ← SolveThreeQuadraticEquations(P, Q, R, S, ϵcoefficientsQuadratic) for each tk in solutions do if StaticCoLinearOverlap(P0 + V0 · tk, P1 + V1 · tk, P2 + V2 · tk, P3 + V3 · tk, ϵdist) then return true, tk ◃ Can already return since tk in ascending order. end if end for return false end function

Algorithm 14 Handle Parallel Case

function HandleParallelCase(P0, P1, P2, P3, V0, V1, V2, V3, ϵdist, ϵt, ϵdist1D, ϵcoefficientsQuadratic) if IsPointPermanentlyOnLine(P0, P1, P2, V0, V1, V2, ϵcoefficientsQuadratic) then return HandleParallelCoLinearCase(P0, P1, P2, P3, V0, V1, V2, V3, ϵdist, ϵt, ϵdist1D) else return HandleParallelNonDegenerateCase(P0, P1, P2, P3, V0, V1, V2, V3, ϵdist, ϵcoefficientsQuadratic) end if end function

for skew lines. Thus, the equations can be stated in 3D and will still yield one unique solution for u, v. Written out in 3 components, the system of equations becomes:

Rxu − S xv = Qx − Px,

Ryu − S yv = Qy − Py, (3.22)

Rzu − S zv = Qz − Pz,

[ ] [ ] u which can be written Ax = b, where A = R −S , x = and b = Q − P. Since this system is v solvable, a least-square solution will also be a solution of equation (3.22). Multiplying with AT from the left gives

AT Ax = AT b, (3.23) which is a 2x2-system. Matrix AT A is non-singular since the columns of A are linearly indepen- dent, so the system can be solved for x by Gaussian elimination with partial pivoting. Pivoting is needed since R and S can be almost parallel - the completely parallel case is treated above in the current section. The residual δ = Ax − b should then be 0 since equation(3.22) is solvable. u and v can be obtained from x. If u and v are within [0, 1], then not only the lines intersect at tk, but also the line segments. This approach is formalized in algorithm 16, assuming a func- tion GaussianEliminationWithPivoting as well as a function LineSegmentsCoLinear, and using algorithm 15 which tests if a static point and segment have an intersection. 3.1. Continuous Collision Detection Edge-Edge 49

3.1.3.2 The Permanent Point-On-Line Case Given that the line segments do not initially overlap, there are four tests to perform for moving point-segment overlap, as mentioned in section 3.1.3. Testing that a point C(t) lies permanently on the line given by segment (A(t), B(t) involves solving equation (3.13), repeated here: (B(t) − A(t)) × (C(t) − A(t)) = 0 ∀t. Like mentioned in section 3.1.2.1, this equation can degenerate to 0 = 0 ∀t, and a permanent point-on-line case has to be considered. Algorithm 8 can be used to test for this degenerate case. If it is encountered, a test for intersection can be performed by checking for equality of moving points between the point and the segment’s end points, re-using algorithm 10. There can be no initial overlap, as this has already been treated in section 3.1.3.1.

3.1.3.3 The General 2D Case

If the point is not permanently on the line, up to two intersection times ti can be found by solving the quadratic equation (3.13). The earliest ti ∈ (0, 1] for which the point lies within the segment boundaries is the intersection time. Given a method Solve like in algorithm 13, this approach can be formalized by algorithm 17, which tests for intersection of a linearly moving point P2 + V2t on a line segment with linearly moving end points (P0 + V0t , P1 + V1t). The general 2D case can then be handled by algorithm 18, which reuses algorithm 16 for testing for initial overlap. If no initial overlap occurs, the algorithm compares all four segment end points against the respective other line segment using algorithm 17, and selects the earliest valid overlap time as the final intersection time.

3.1.4 The General Case After having treated the various cases of degeneracies, it is time to consider the general case. First, the non-degenerate configuration should be considered. Here, cases 1–4 from section 3.1.1 do not occur, and equation (3.1) does not degenerate to 0 = 0 ∀t. Following the presen- tation in section 3.1.1.4, the cubic equation (3.9) can be derived. Solving it yields up to three ti ∈ [0, 1]. The earliest ti for which u, v are within the segment bounds [0, 1] is the intersection time. This approach is formalized in algorithm 19, using the Solve-method as in earlier algo- rithms, as well as algorithm 16 for testing if the line-line overlap found at a certain ti also results in a valid segment-segment overlap. The general case can then be addressed by first testing for the various cases of degenera- cies and handling them. If no degeneracies occur, the non-degenerate case can be handled as explained above. Algorithm 20 formalizes this approach. Again, several computations are repeated unnecessarily, but this is done to make the presentation clearer; a more optimized for- mulation would avoid that.

3.1.5 A Note on Thresholds

In the algorithms presented above, several numerical thresholds where introduced, ϵdist, ϵdist1D, ϵt, ϵcoefficientsQuadratic, and ϵcoefficientsCubic. The choice of the thresholds with geometric meaning such as ϵdist and ϵdist1D can depend on the domain size of interest, while for the other ones, it can depend on the accuracy of the input data as well as the underlying floating point representation (e.g. single or double precision). For the current implementation, the values as presented in table 3.1 have been chosen. Here, the values of ϵcoefficientsQuadratic and ϵcoefficientsCubic correspond to 100∗DBL_EPSILON. The latter constant is defined in the C++ header-file cfloat. The value was chosen due to double precision 50 Chapter 3. Method

Threshold Value ϵdist 1.0e-6 ϵdist1D 1.0e-6 ϵt 1.0e-9 ϵcoefficientsQuadratic 2.2204460492503131e-14 ϵcoefficientsCubic 2.2204460492503131e-14

Table 3.1: Chosen Values for Thresholds being the chosen floating precision, with the multiplication with a factor to account for round-off errors in the input data due to matrix multiplication when doing rotations and translations. The thresholds with direct geometric meaning such as ϵdist and ϵdist1D have been chosen relatively high since the domain size can vary from millimeters to tens of meters. The other thresholds have been chosen as low as possible while still giving good results in testing. However, a more thorough analysis of the thresholds should be performed, possible leading to a reduction of the number of independent thresholds.

3.2 Implementation

3.2.1 Libraries The approach above as well as further functionality was implemented within the framework of AGX Dynamics as described in section 2.7. AGX consists of several C++ libraries[1], out of which the following are of relevance to the thesis:

• agxCore contains mathematical types, containers and other general functionality, and is used by the other libraries below.

• agxPhysics treats the general physics simulation, and contains the time integration, con- straints, and collision detection, as well as utility functionality. This library was aug- mented in order to support continuous collision detection of wire segments, which will be described in more detail in the sections below.

• agxWire allows its user to model wires as well as related functionality such as winches, pulleys and similar objects. It was modified slightly to use the WireShape-class described in section 3.2.2 for collision detection.

• agxOSG enables visualization of the simulation via the OpenSceneGraph. This was used in order to obtain to analyze the simulations visually, as well as generate screen-shots for the figures in the thesis.

• agxLua allows accessing parts of AGX’ C++ API via the scripting language Lua[52]. It was used within the thesis for quickly setting up test simulations and modifying them without the need for re-compilation or re-starting the application. It had to be augmented slightly to expose the WireShape-class to Lua.

AGX contains further libraries. Some of these were used indirectly since the libraries above rely on them. Others such as agxHydraulics were not used within the thesis, since they were not relevant to the topic. 3.2. Implementation 51

Shape transform : Affine4x4Matrix

Capsule radius : double length : double

WireShape previousEndPoint0 : Vec3 previousEndPoint1 : Vec3

Figure 3.3: Inheritance structure of classes Shape, Capsule and WireShape.

3.2.2 WireShape-Class

Wires in AGX are represented by connected linearly moving mass points, connected by wire segments, as described in section 2.6.2. Each wire segment is represented by a capsule. In order to introduce continuous collision detection between wire segments, the capsule class had to be augmented to account for the previous position of its corresponding segment end points in the world coordinate system. For this, the WireShape-class inheriting from the Capsule-class was introduced into the AGX-library agxPhysics. Figure 3.3 shows the inheritance structure in C++, including the inheritance of the Capsule-class from the Shape-class. Here, Vec3 is a class for describing points or vectors in three-dimensional space, and AffineMatrix4x4 is a class for describing both translation and rotation in a common affine matrix with size 4 × 4. The class members previousEndPoint0 and previousEndPoint1 describe the line segment end points in world coordinates in the previous time step.

3.2.3 Broad Phase

In order to integrate the WireShape-class into AGX’ broad phase (see section 2.7.2), its AABB used in the broad phase algorithms sweep and prune and hierarchical grid was adapted to encompass both its current configuration as well as the one in the previous time step. Fig- ure 3.4 visualizes such a bounding box. This approach is sufficient to enclose the motion of the WireShape, since linear motion of the end points is assumed as discussed in section 2.4.3. In that section, it is also mentioned that enlarged bounding volumes can lead to more false positives, and that kinetic versions of the broad phase algorithms can alleviate that problem. This step was not taken in the implementation for the thesis, since typically only a minor part of typical simulation scenes is formed by WireShape objects, and the effort did therefore not seem justified. The chosen approach makes it also possible to reuse the discrete middle phase collision detection with AABB-trees. 52 Chapter 3. Method

Figure 3.4: Bounding box around WireShape in previous and current position. Line Box Capsule Convex Cylinder Plane Sphere Trimesh Composite HeightField WireShape

Box x x x x x x x x x x c Capsule x x x x x x x x x x c Convex x x x x x x x x x x c Cylinder x x x x x x x x x x c Line x x x x x x x x x x c Plane x x x x x - x x x - c Sphere x x x x x x x x x x c Trimesh x x x x x x x x x x c Composite x x x x x x x x x x c HeightField x x x x x - x x x - c WireShape c c c c c c c c c c W

Table 3.2: Table showing colliders between shape types in AGX Dynamics after introduction of WireShape-class. x: collider exists; -: no collider needed since only static shapes; c: fallback to respective collider using capsule; W: WireShape-WireShape-collider.

3.2.4 Narrow Phase For the narrow phase collision detection, new colliders had to be introduced for collision detec- tion between WireShape-objects and other shapes, as can be seen in Table 3.2. The WireShape- WireShape-collider first implements the algorithms introduced in section 3.1, and creates con- tact points if tunneling is detected. If no tunneling is detected, discrete collision detection is performed using the Capsule-Capsule-collider. All other WireShape-colliders reuse the re- spective colliders involving Capsule-shapes — there is no continuous collision detection im- plemented against other shape types yet.

3.2.5 Hardware The computations where performed on an Intel(R) Core(TM) i7-6700HQ machine with 8 cores with 4.01GHz each (four cores with hyper-threading), with 16313964 kB RAM and running Windows 10 64bit. Since narrow phase collision detection is trivially parallelizable on the 3.2. Implementation 53 collider-level, all cores could be used for larger scenes. The code runs only on the CPU currently, no GPU parallelization has been done yet. 54 Chapter 3. Method

Algorithm 15 Static Point-Segment Intersection

function StaticPointSegmentIntersection(P, Q, S, ϵdist, ϵdist1D) ◃ Check if a static point and line segment intersect. if S == 0 then ◃ Line degenerating to point? if StaticEquality(P, Q, ϵdist) then return true else return false end if end if B ← P − Q foundU ← false u ← 0 for i = 0, 1, 2 do if |S i| ≤ ϵdist1D then if |Bi| > ϵdist1D then return false ◃ Direction 0 and points do not agree in this dimension. else continue ◃ Fulfilled for any u. end if end if ui ← Bi/S i if foundU then if |u − ui| > ϵdist1D then return false ◃ The line parameters for different dimensions do not agree. end if else foundU ← true u ← ui end if end for if u ∈ [0, 1] then return true else return false end if end function 3.2. Implementation 55

Algorithm 16 Static Segment-Segment Intersection

function StaticSegmentSegmentIntersection(P, Q, R, S, ϵdist, ϵdist1D) ◃ Check if two static line segments intersect. if StaticEquality(R,0) then ◃ Does first line degenerate to point? return StaticPointSegmentIntersection(P, Q, S , ϵdist, ϵdist1D) end if if StaticEquality(S ,0) then ◃ Does second line degenerate to point? return StaticPointSegmentIntersection(Q, P, R, ϵdist, ϵdist1D) end if if StaticEquality(S × R,0) and LineSegmentsCoLinear(P, Q, R, S ) then ◃ Line segments are parallel and co-linear. return StaticCoLinearOverlap(P, Q, P + R, Q + S , ϵdist) end if B ← Q − P T M0,0 ← R · R ◃ Compute matrix M as A A. M0,1 ← M1,0 ← −R · S M1,1 ← S · S T L0 ← R · B ◃ Compute vector L as A B. L1 ← −S · B X ← GaussianEliminationWithPivoting(M,L) u ← X0 v ← X1 if u < [0, 1] or v < [0, 1] then return false end if δ ← Ri ∗ u − S i ∗ v − Bi ◃ Check third equation. if |δ| ≤ ϵdist1D then return true else return false end if end function 56 Chapter 3. Method

Algorithm 17 Moving Point-Segment Intersection

function MovingPointSegmentIntersection(P, P0, P1, V, V0, V1, ϵdist, ϵdist1D) ◃ Finds out if a moving point P2 + V2t intersects with a line segment between moving points P0 + V0t and P1 + V1t. P ← P1 − P0 Q ← P2 − P0 R ← V1 − V0 S ← V2 − V0 solutions ← SolveThreeQuadraticEquations(P, Q, R, S, ϵcoefficientsQuadratic) for each tk in solutions do if StaticPointSegmentIntersection(P2 + V2tk, P0 + V0tk, P1 + V1tk, ϵdist, ϵdist1D) then return true, tk ◃ Can already return since tk in ascending order. end if end for return false end function

Algorithm 18 Handle 2D-Case

function Handle2DCase(P0, P1, P2, P3, V0, V1, V2, V3, ϵdist, ϵdist1D, ϵt) overlap, t ← StaticSegmentSegmentIntersection(P0, P1 − P0, P2, P3 − P2, ϵdist, ϵdist1D) if overlap then return true, 0 end if t ← ∞ , ← oving oint egment ntersection , , , , , , ϵ , ϵ overlap0 t0 M P S I (P0 P2 P3 V0 V2 V3 dist dist1D) , ← oving oint egment ntersection , , , , , , ϵ , ϵ overlap1 t1 M P S I (P1 P2 P3 V1 V2 V3 dist dist1D) , ← oving oint egment ntersection , , , , , , ϵ , ϵ overlap2 t2 M P S I (P2 P0 P1 V2 V0 V1 dist dist1D) , ← oving oint egment ntersection , , , , , , ϵ , ϵ overlap3 t3 M P S I (P3 P0 P1 V3 V0 V1 dist dist1D) for n ← 0, 1, 2, 3 do if overlapn then t ← min(t, tn) ◃ Select earliest t out of the valid ones. end if end for if t < ∞ then return true, t ◃ Have found a valid t. else return false end if end function 3.2. Implementation 57

Algorithm 19 Handle Non-Degenerate Case

function HandleNonDegenerateCase(P0, P1, P2, P3, V0, V1, V2, V3, ϵcoefficientsCubic, ϵdist, ϵdist1D) P ← P1 − P0 Q ← P3 − P2 R ← V1 − V0 S ← V3 − V2 for h ← 0, 1, 2 do αh, βh, γh ← ComputeQuadraticCoefficients(P, Q, R, S, h) end for δ ← P2 − P0 ν ← V2 − V0 c0, c1, c2, c3 ← ComputeCubicCoefficients(α, β, γ δ, ν) n, t0, t1, t2 ← Solve(c0, c1, c2, c3) if n == 0 then return false end if for k ← 0, n − 1 do Pk ← P0 + V0tk Qk ← P2 + V2tk Rk ← P1 − P0 + (V1 − V0)tk S k ← P3 − P2 + (V3 − V2)tk if StaticSegmentSegmentIntersection(Pk, Qk, Rk, S k, ϵdist, ϵdist1D) then return true, tk ◃ Can return already now since t0 < t1 < t2. end if end for return false end function

Algorithm 20 Handle General Case

function HandleGeneralCase(P0, P1, P2, P3, V0, V1, V2, V3, ϵdist, ϵdist1D, ϵt, ϵcoefficientsQuadratic, ϵcoefficientsCubic) if DetectCase1(P0, P1, P2, P3, V0, V1, V2, V3, ϵdist) then return false ◃ Should not come here by design. end if if DetectCase2(P0, P2, V0, V2, ϵdist) then return true, 0 ◃ P0 and P2 are identical. end if if DetectCase3(P0, P1, P2, P3, V0, V1, V2, V3, ϵcoefficientsQuadratic) then return HandleParallelCase(P0, P1, P2, P3, V0, V1, V2, V3, ϵdist, ϵt, ϵdist1D, ϵcoefficientsQuadratic) end if if DetectCase4(P0, P1, P2, P3, V0, V1, V2, V3, ϵcoefficientsCubic) then return Handle2DCase(P0, P1, P2, P3, V0, V1, V2, V3, ϵdist, ϵdist1D, ϵt) end if return HandleNonDegenerateCase(P0, P1, P2, P3, V0, V1, V2, V3, ϵcoefficientsCubic, ϵdist, ϵdist1D) end function 58 Chapter 3. Method Chapter 4

Results and Discussions

This chapter presents and discusses the results of the method and implementation described in the previous chapter.

4.1 WireShape Collision Cases

The different degenerate and non-degenerate cases described in section 3.1 have been set up as test cases during the implementation phase, following a process called test-driven develop- ment[51]. This process starts by writing a test, making sure that it fails, writing the code which should solve the problem, re-running the test, and verifying that it now passes. This approach to software development makes sense when working with collision detection, since the initial tests give a clear definition about the goals to reach. Also, having tests fail again that passed earlier gives a clear indication that changes in the code introduced some error. Thus, a good test suite gives a safe ground to stand on when augmenting the code with further functionality. The developer version of AGX Dynamics has a unit testing framework, which allows tests to be defined, and manually or automatically executed. This framework makes it easy to add new tests, as well as quickly run all tests to see that changes in the code do not break existing tests. For collision detection of the WireShape-WireShape collider, tests have been set up to verify that collisions are found also in the case of tunneling. For each test, criteria about point, normal, and depth have been specified that are required to let the test pass. The tests have been written in the scripting language Lua, making use of the API-bindings provided by the library agxLua. By starting a test manually, it can be visualized for debugging and analysis, using the library agxOSG. These visualizations will be shown below. Case 1 described in section 3.1.1.1 where a complete line segment permanently degenerates to a point will not be treated, since line segments of permanent length 0 will not be created. However, line segments can temporarily have length 0, typically at the beginning or ending of a time step. This is due to the fact that adaptive resolution can lead to line segments being created or removed during the time step, as shown in Figure 2.25.

4.1.1 Explanation of Visualization In all images in this section, gray solid renderings (surrounded partially by blue or green wire- frame) show the line segments at the current time step. Blue or green wire-frame renderings show the line segments at the previous time step. The line segments’ positions at time of im-

59 60 Chapter 4. Results and Discussions

Figure 4.1: Both segments move in a non-degenerate configuration. The blue segment moves from the left to the right, and the green one from the right to the left. They intersect at t ≈ 0.69. For an explanation of the colors and symbols in the visualization, see section 4.1.1. pact are visualized as thinner blue and green lines, and contact points are visualized as orange spheres. The movement of the end points is shown by thin blue or green lines.

4.1.2 The Non-Degenerate Case The first case to be presented is the non-degenerate case. It is derived in section 3.1.4. An ex- ample visualizing such a collision is shown in Figure 4.1. Here, the permanent co-linearity and co-planarity, which this thesis focuses on, do not occur. However, there can also be occurrences where they get into contact in a temporarily parallel state. Figure 4.2 presents such a case, and Figure 4.3 shows a case where one of the segments temporarily degenerates to a point.

4.1.3 Case 2: Line Segment Starting Points Identical Case 2 where the segments’ starting points A(t) and C(t) are identical for all t was introduced in section 3.1.1.2. A simulation involving this case is shown in Figure 4.4. Here, the segments are in contacts initially at t = 0, and thus the contact is visualized already in the segments’ initial position. For algorithms making use of the data from collision detection, cases with initial overlap are hard to treat, since is not known in which direction to recover from the overlap. A treatment of this problem is outside of the scope of the thesis however; here the focus is only the detection of the case itself.

4.1.4 Case 3: The Parallel Case The parallel case is described in detail in section 3.1.2. There, the distinction is made between the parallel co-linear case and the non-degenerate parallel case, and the presentation here will follow this distinction. 4.1. WireShape Collision Cases 61

Figure 4.2: Both segments move in a non-degenerate way. The green segment moves from the left to the right, and the blue one from the right to the left. Both turn 90 degrees, and the segments intersect at t = 0.5 in a temporarily parallel configuration. For an explanation of the colors and symbols in the visualization, see section 4.1.1.

Figure 4.3: Both segments move in a non-degenerate way. The green segment moves from the front left to the right, and the blue one from the bottom to the top, inverting its orientation and temporarily degenerating to a point at t = 0.5. At this time, the segments intersect. For an explanation of the colors and symbols in the visualization, see section 4.1.1. 62 Chapter 4. Results and Discussions

Figure 4.4: The green and blue line segments move from their initial state in the right side of the picture, to the final one on the left side. The beginning points A(t) and C(t) are identical for all t, and move along a common line. The segments are thus already initially in contact at t = 0, indicated by an orange sphere. For an explanation of the colors and symbols in the visualization, see section 4.1.1.

When considering the parallel co-linear case, a test for initial overlap has first to be made, as shown in section 3.1.2.2. Such an initial overlap is visualized in Figure 4.5. Figure 4.6 shows the case where the overlap occurs later during the time step. Note that only the line segments themselves are considered, and that the additional radius is ignored. This limitation of the current approach makes it possible that the capsules pass through each other in parallel or near-parallel configurations as long as the line segments themselves do not intersect, as is shown in Figure 4.7. Here, the approach based on continuous collision detection of only the line segments shows its shortcomings, and an approach taking the radius into account might be considered in future work. Finally, the parallel non-degenerate case which is described in section 3.1.2.3 is visualized in Figure 4.8.

4.1.5 Case 4: The 2D-Case

The treatment of the 2D-Case is presented in section 3.1.3. There, a distinction is made between the case of initial overlap, the case where one of the end points is permanently on the other segment’s line, and the non-degenerate 2D case. The presentation here follows this distinction. The test for initial overlap is described in section 3.1.3.1. Figure 4.9 visualizes a constella- tion where this test is used. The other special case occurs if one of the end points is permanently on the other segment’s line. It is handled in section 3.1.3.2, and Figure 4.10 gives one example of such a collision case. The slightly modified setup in Figure 4.11 shows a case where there is an intersection due the other point being on the same line as well, which leads to a tem- porarily parallel constellation. The non-degenerate 2D-case is treated in section 3.1.3.3, and in Figure 4.12, an example is shown where this case occurs. 4.1. WireShape Collision Cases 63

Figure 4.5: Two wire segments move along the same line in opposite directions. They are in initial contact at t = 0 indicated by the orange spheres, which show the beginning and end of the overlap. During their movement, the segments pass through each other and are in non- contacting state at the end of the time step. For an explanation of the colors and symbols in the visualization, see section 4.1.1.

Figure 4.6: Two wire segments move along the same line in opposite directions. They get into contact (indicated by the orange sphere) later in the time step at t = 0.0625 and pass through each other. For an explanation of the colors and symbols in the visualization, see section 4.1.1. 64 Chapter 4. Results and Discussions

Figure 4.7: Two wire segments move along almost the same line in opposite directions. The capsules should get into contact, but continuous collision detection is only done on the line segments. The line segments pass by next to each other, so not contacts are generated. For an explanation of the colors and symbols in the visualization, see section 4.1.1.

Figure 4.8: Two wire segments move while maintaining parallelity with regard to each other. They intersect at t = 0.6. The green wire segment moves from the top right to the middle, and the blue one from the bottom to the top. For an explanation of the colors and symbols in the visualization, see section 4.1.1. 4.1. WireShape Collision Cases 65

Figure 4.9: Two wire segments are in initial overlap at t = 0, and move apart from each other. The movement is co-planar. The green wire segment turns and moves from the middle to the left, and the blue one turns and moves from the middle to the right. For an explanation of the colors and symbols in the visualization, see section 4.1.1.

Figure 4.10: The lower end point of the blue segment is permanently on the line of the green segment. Both segments move from the left to the right within the same plane; the blue segment also turns. Overlap occurs at t ≈ 0.41 and is due to the lower end point of the blue segment passing through the green segment. For an explanation of the colors and symbols in the visual- ization, see section 4.1.1. 66 Chapter 4. Results and Discussions

Figure 4.11: The lower end point of the blue segment is permanently on the line of the green segment. Both segments move from the left to the right; the blue one also turns. Overlap occurs at t = 0.5 and is due to the upper end point of the blue segment passing through the green segment. The segments are temporarily parallel, therefore two contact points are created. For an explanation of the colors and symbols in the visualization, see section 4.1.1.

Figure 4.12: Both segments move in the same plane. This plane is not identical to the view plane, since the view is slightly tilted. The green segment moves from the right to the left, and the blue one from the left middle to the right. The segments intersect at t ≈ 0.56. For an explanation of the colors and symbols in the visualization, see section 4.1.1. 4.2. Wire Collision Scenarios 67

4.2 Wire Collision Scenarios

4.2.1 Scenario Descriptions Whereas the previous section tested and visualized the various cases for single wire segments which had been introduced in section 3.1, the current section will consider more complex sim- ulations involving wires which consist of several wire segments. Note that as mentioned earlier, the use the results of continuous collision detection for the wire simulation was implemented outside of the scope of this thesis. However, the presentation of wire collision cases still makes sense here, since they show use cases which would not have been possible to simulate without continuous collision detection of the wire segments. As in the previous section, the visualization is done with AGX Dynamics, using its visualization library agxOSG.

4.2.1.1 Scenario 1: Basic Collision

The first scenario is visualized in Figure 4.13, which shows a moving steel wire interacting with two hanging ones. The moving wire is above the other two and has a downward velocity of 10 m/s, whereas the end points of the other two wires are firmly attached to the world at their current positions. Each of the three wires has a length of 2m and a radius of 0.02m. Since the simulation time step is 1/60s, the moving wire tunnels through the other two wires in the first time step. The thin lines in Figure 4.13b indicate the previous position and the movement to the current one. Figure 4.13c shows how the tunneling is detected due to the use of CCD, and contact points with new wire segments being inserted. These contacts result in the moving wire resting on the other two wires, as Figure 4.13d illustrates.

4.2.1.2 Scenario 2: Wire Pulling Anchor

The second scenario consists of a cylinder with mass 1570.8kg hanging on a wire of 25m length, and another wire hanging freely between two moving boxes. The boxes move with a speed of 2m/s past the hanging load, and the two wires interact, as Figure 4.14 illustrates. The contin- ued motion of the boxes leads to both wires getting into tension as shown in Figure 4.14e and Figure 4.14f, and finally to the cylinder getting caught between the two wires as visualized in Figure 4.14h. This scenario is an idealized example of operations that occur in the maritime and offshore industry, where systems such as anchor chains or buoys are handled with the help of other chains or wires. For simulation these operations, wire-wire interaction is important.

4.2.1.3 Scenario 3: Twisting under Load

The third scenario consists of a load with mass 8000kg hanging on four initially parallel wires of 12m length and radius 0.02m each. It is visualized in Figure 4.15. The load is in the form of a box, which has an initial angular velocity of 4π/s. This scenario is an extreme example of problem cases which can occur in heavy lifting operations where loads on cranes can experience angular motion, which leads to wires twisting around each other. At t = 0.55s, the wires have come into contact, which is presented in Figure 4.15c and Figure 4.15d. At t = 2.1, the load has made 1.5 turns around its axis, and has slowed down to an angular velocity of about 2.83π/s due to the wire contacts. This configuration is shown in Figure 4.15e and Figure 4.15f. 68 Chapter 4. Results and Discussions

(a) t = 0s. Initial state. The moving wire is (b) t = 1/60s. The moving wire has tunneled above the other two wires, but has high through the two other wires. downwards velocity.

(c) t = 2/60s. The tunneling has been detected (d) t = 3/60s. The moving wire has been using continuous collision detection, and caught by the other two wires, and will get to a contact points for the wire have been resting position after some oscillations. generated. This latter part was covered outside of the work of the thesis.

Figure 4.13: A simulation of four time steps of a moving steel wire of 2m length and 0.02m radius colliding with two other identical wires whose end points are firmly attached to the world. Continuous collision detection is used to detect tunneling. The size of the time step is 1/60s. 4.2. Wire Collision Scenarios 69

(a) t = 3.7s. The boxes are moving with fixed (b) t = 8.85s. Collision between the two wires, speed of 2m/s, pulling the blue wire that is detected using continuous collision detection. hanging between them. The cylinder is hanging The contact point is indicated by an orange dot; motionless on the pink wire. its normal by an orange line.

(c) t = 13.33s. The cylinder is dragged by the (d) t = 17.75s. The tension in the blue wire interaction of the two wires. starts to increase.

(e) t = 25.33s. Change in camera angle. (f) t = 26.75s. There are vibrations in the wires Stick/slip transitions due to the friction due to the sudden motion. between the wires lead to sudden movements between the wires, which make it necessary to use continuous collision detection in order to detect overlaps.

(g) t = 28.33s. Another release of friction (h) t = 31.6s. The cylinder is caught between along the wires. the two wires.

Figure 4.14: A simulation of a cylinder of mass 1570.8kg hanging on a 25m long wire with radius 0.02m, interacting with by a 50m long wire being pulled by two moving bodies with fixed speed. Continuous collision detection is used to detect tunneling. The size of the time step is 1/60s. 70 Chapter 4. Results and Discussions

(a) t = 0s. Initial state. The lower box has an (b) t = 0.2s. The lower box has started turning, initial angular velocity of 4π/s. but the wires have not come into contact yet.

(c) t = 0.55s. The lower box has made almost a (d) t = 0.55s. Zoom-in on same configuration full turn, and the wires have come into contact as in previous figure, showing the wires and the with each other. wire segments from a closer view.

(e) t = 2.1s. The lower box has made another (f) t = 2.1s. Zoom-in on same configuration as 1.5 turns. It has slowed down from its initial in previous figure, showing the wires and the angular velocity of 4π/s to about 2.83π/s due wire segments from a closer view. to the wire contacts.

Figure 4.15: A simulation of a box with mass of 8000kg hanging on four wires of length 12m and radius 0.02m attached to an upper box. The lower box has with initial angular velocity 4π/s. Continuous collision detection is used to detect tunneling between the wires. The size of the time step is 1/60s. 4.2. Wire Collision Scenarios 71

4.2.1.4 Scenario 4: Chains on Deck The fourth scenario includes two chains which are simulated as wires without bending resis- tance, and with a radius of 0.01m. Each chain is connected to a box and a cylinder, and partially rests on a flat surface. The chains as well as their corresponding connected bodies are visualized in blue and brown color in Figure 4.16. The brown box moves past the blue box with a constant speed of 0.6m/s in positive x direction. At t = 3.08s, the two chains get into contact relatively close to the boxes, which is visualized in Figure 4.16c. Figure 4.16d and Figure 4.16e show how the brown box’s continued motion leads to tension building up in the chains. The brown box then changes its direction and moves in positive y direction with 2m/s, which releases the tension in the chains, but lets new tension build up as the motion with this new direction con- tinues. Figure 4.16f and Figure 4.16g visualize this process. Finally, the brown box comes to a halt, which again releases the tension and is shown in Figure 4.16h. This scenario exemplifies cases which can occur in chain and wire operations on the deck of a maritime vessel, or in submarine cable systems. Due to the motion along a common plane which both wires rest on, degenerate collision cases are to be expected.

4.2.2 Occurrence of Degenerate Cases Given these scenarios which model real-world use cases, it is interesting to see how often the different cases treated in section 3.1 occur, and how often a test for tunneling falls out positively or negatively. Therefore, the scenarios described in the previous section were run over a certain period of simulation time each, and the relevant data was extracted. The occurrence of the parallel case, the two-dimensional case and the non-degenerate case was logged. Furthermore, the occurrence of the temporary parallel case was of interest in two- dimensional or non-degenerate configurations. It was also determined if each test resulted in tunneling or not. These results are summarized in table 4.1. Two things can be noted here:

• Firstly, there is a large number of test cases considered, between 5366 and 154416 per scenario. In all four scenarios, only a small minority of the test cases included tunneling: between 0.01% and 0.08%. This shows that the fixed time step of 1/60s is chosen well with regard to the velocities and object sizes involved — if tunneling was the norm, a reduction of the time step size would make sense. However, it might be considered if it is overkill to test each of these configurations for tunneling. It might be possible to exclude some configurations early on. Section 4.2.3 will investigate this question further.

• Secondly, it can be noted that the non-degenerate case is the norm in the chosen scenarios. Degenerate cases occur only in scenario 4. There, case 4 occurs in 7.72% of the cases, and case 3 does not occur at all. However, temporary parallel configurations occur in seven tests; three times during the non-degenerate case, and four times in case 4. Thus, the work spent on the degenerate cases has its justification. Case 3 did not occur in “natural” test setups, only in artificial setups where both wires are created in an initially parallel configuration. Such setups are not included in the chosen scenarios, but tend to appear in test simulations, such as the ones set up in section 4.1.

4.2.3 Computation Time This section investigates the computational performance of the implemented approach to con- tinuous collision detection. The computational cost is relevant for the its use in real-time simu- lation. It is interesting to determine if CCD is more costly than discrete collision detection on 72 Chapter 4. Results and Discussions

(a) t = 0.50s. The brown box starts moving in (b) t = 2.10s. The brown and blue chain get positive x direction with a constant speed of into contact, and parts of the chains align with 0.6m/s. each other.

(c) t ≈ 3.08s. The blue and brown chains get (d) t = 4.2s. At the contact region where the into contact also closer to the boxes. chains aligned earlier, the brown chain moves over the blue one.

(e) t = 4.6s. Tension is created in the chains (f) t = 5.05s. The brown box changes its since the brown box continues in positive x direction and moves in positive y direction with direction. a speed of 2m/s. That releases the tension in the chains.

(g) t ≈ 7.23s. Due to the brown box’s (h) t = 8.35s. The brown box comes to a halt, continued movement in positive y direction and which releases tension in the chains. friction in the wire-wire-contact, new tension in the chains is created.

Figure 4.16: A simulation of two chains, simulated as wires with radius 0.01m and no bending resistance. Each chain is connected to a box and a cylinder of the same color, and rests on the surface. The boxes are 0.8m above the ground. The blue box remains in its position, whereas the brown box moves first in positive x direction, an after 5s in positive y direction. Its motion leads to interaction between the two chains. The size of the time step is 1/60s. 4.2. Wire Collision Scenarios 73

Scenario 1 Scenario 2 Scenario 3 Scenario 4 Simulation time (in s) 5 32 5 9 Number of time steps 300 1920 300 540 Total tests 5366 9919 154416 26958 Tunneled 2 7 12 22 Non-degenerate case 5366 9919 154416 24877 Case 3 0 0 0 0 Case 4 0 0 0 2081 Tunneled in % of total 0.04% 0.07% 0.01% 0.08% None-degenerate case in % of total 100.00% 100.00% 100.00% 92.28% Case 3 in % of total 0.00% 0.00% 0.00% 0.00% Case 4 in % of total 0.00% 0.00% 0.00% 7.72% Non-degenerate case, temporary parallel 0 0 0 3 Case 4 temporary parallel 0 0 0 4

Table 4.1: Table showing occurrence of special cases in the scenarios introduced in section 4.2.1. the one hand, and if the additional cost can be made up for by being able to choose a larger time step when using CCD on the other hand. Table 4.2 shows measurements which have been done by running the four scenarios for a pre-determined amount of simulation time on a reference system. This system is the same as mentioned in section 3.2.5: an Intel(R) Core(TM) i7-6700HQ machine with 8 cores with 4.01GHz each (four cores with hyper-threading), with 16313964 kB RAM and running Win- dows 10 64bit. Two versions of the code have been run: The one with CCD introduced in this thesis at a time step of 1/60s for each scenario, and a pre-existing discrete version of the collision detection code at a lower time step which has been chosen per scenario. For each scenario, the largest time step which still allows the use of the discrete code has been determined by running the CCD code and modifying the time step until no tunneling occurs. The values for the to- tal run-time and the total time needed for narrow-phase collision detection have been extracted from AGX Dynamics by using its statistics-framework [1, p. 222]. Some things have to be taken into consideration when considering these measurements: • The value for the narrow-phase tests can include other tests than just WireShape-WireShape tests. In the scenarios 1 and 3, the two numbers are identical, and in scenario 2, the WireShape-WireShape tests dominate. However, in scenario 4, they only constitute about 1/6th of the total tests. Here, contacts of the wire with the ground dominate the num- ber of narrow-phase collision tests, and the narrow-phase timings for this scenario cannot directly be connected to the performance of WireShape-WireShape collision detection. • Performance measurement on a non-real-time hardware system can be subject to varia- tion. In order to reduce this variation, other performance-intense processes on the testing machine have been reduced, the OS settings have been set to full performance, and the simulation has been run on only one core in order to avoid threading-related issues. Still, the performance measurements vary relatively much, with e.g. a standard deviation of 0.2s for a mean value of 2.850s for the value Run time (CCD) (in s) for scenario 4, based on 10 samples. • It should also be noted that the strategy employed here for comparison between the dis- 74 Chapter 4. Results and Discussions

crete and continuous version is only valid if the simulation is known beforehand, since it consists of running the continuous version with a lower time step in order to find a time step where tunneling just does not occur anymore. For a general simulation, techniques would have to be employed such as reducing the time step as soon as the motion within a time step exceeds the radius. These techniques typically yield much lower time steps, and cannot be used in real-time simulation either since the maximum velocity is not known beforehand. Keeping these considerations in mind, the following observations can be made: • Narrow phase testing takes only a minor part of the run-time — between 1.33% and 3.72%. Most of the run-time is be spent on other parts of the simulation. When investi- gating the statistics data which has been extracted from AGX Dynamics more closely, it shows that the largest part of the time (e.g. 1.957s out of 2.850s for the value Run time (CCD) (in s) for scenario 4) is spent on the category called Dynamics System in AGX Dynamics, which includes the solver with 1.519s. These parts dominate the computation cost in all four scenarios. • As expected, the average time per test is lower for the discrete version of the code com- pared to the continuous one. The discrete version costs between 59.46% and 86.08% of the continuous version. • However, this additional cost for the continuous version is made up for by being able to choose a larger time step, which in its turn reduces the overall run-time. In all four scenarios, the continuous version with the larger time-step is faster than the discrete one. In scenario 3, the discrete variant is only slightly slower. In scenario 4 however, the CCD-version one is much faster, and in scenarios 1 and 2, the run-time scaling is almost identical to the ratio of the time steps. In the larger scenarios 2, 3, and 4, using the approach presented here decreases the total run time thus by between 6.67% and 58.22%. It should furthermore be noted that any number of narrow-phase collision tests is trivially parallelizable, since the tests are independent of each other. Any additional cost in narrow- phase collision detection can therefore be reduced by running the problem on more cores, if available. As mentioned in the previous section, optimizations for CCD can be considered, e.g. by excluding cases where both objects move slowly with regards to their radii from testing for tunneling. 4.2. Wire Collision Scenarios 75

Scenario 1 Scenario 2 Scenario 3 Scenario 4 Simulation time (in s) 5 32 5 9 Time step (CCD) (in s) 0.017 0.017 0.017 0.017 Number of time steps (CCD) 300 1920 300 540 Number of WireShape tests (CCD) 5384 9919 154416 26958 Number of Narrow-Phase tests (CCD) 5384 15159 154416 147173 Run time (CCD) (in s) 0.118 2.236 4.269 2.850 Narrow phase run time (CCD) (in s) 0.004 0.040 0.069 0.100 Time step for (discrete) (in s) 0.004 0.010 0.010 0.006 Number of time steps (discrete) 1250 3200 500 1500 Number of WireShape tests (discrete) 22169 13927 230959 68380 Number of Narrow-Phase tests (discrete) 22169 22454 230959 594294 Run time (discrete) (in s) 0.489 3.649 4.574 6.822 Narrow phase run time (discrete) (in s) 0.012 0.051 0.061 0.254 Narrow phase time / total time (CCD) 3.39% 1.79% 1.62% 3.51% Narrow phase time / total time (discrete) 2.45% 1.40% 1.33% 3.72% Average time / test (CCD)(in s) 7.43E-07 2.64E-06 4.44E-07 6.79E-07 Average time / test (discrete) (in s) 5.41E-07 2.27E-06 2.64E-07 4.27E-07 Average time / test (discrete / CCD) 72.86% 86.08% 59.46% 62.83% Factor time step (discrete / CCD) 4.167 1.667 1.667 2.778 Factor total run time (discrete / CCD) 4.144 1.632 1.071 2.394 Total run time change: (CCD-discrete)/discrete -75.87% -38.72% -6.67% -58.22%

Table 4.2: Table showing performance measurements in the scenarios introduced in section 4.2.1. The performance is both measured for the code with CCD at the default time step, as well as for a code version with discrete collision detection at a lower time step where no tunneling occurs. The values for the run time have a relatively high standard deviation, e.g. the value for Total Run Time (CCD) (in s) for scenario 4 is 0.2s. 76 Chapter 4. Results and Discussions Chapter 5

Conclusion

As a concluding summary to the previous chapters, this chapter lists the achievements as well as shortcomings of the thesis, and gives an outlook on possible future work.

5.1 Achievements

An existing approach to continuous collision detection for triangle edges has been adapted for the use in wire simulation. Robustness problems in the existing approach when dealing with de- generate cases such as co-linearity and co-planarity have been identified and treated in section 3.1.1. The resulting improved approach has been implemented in AGX Dynamics, and results for the WireShape-collision cases have been presented in section 4.1. The application of the results of continuous collision detection of WireShape-WireShape collisions to the wire simula- tion was done outside of the scope of the thesis. However, wire simulation scenarios presented in section 4.2 show the importance of the use of continuous collision detection implemented in the thesis. The occurrence of tunneling cases as well as degenerate cases has been shown in order to highlight this point. Also, computation time analysis has been done, which shows collision detection is a minor part of the computational cost for the wire simulation, and any additional cost for continuous collision detection is made up for by being able to choose a larger time step.

5.2 Shortcomings

However, the work presented above has several shortcomings.

• For the polynomial root finding treated in section 2.5.2, approaches without the problems of Newton’s method could be investigated, such as interval arithmetics. Another possi- ble approach would be the VAS-method as introduced in [3], which is used in several numerics toolboxes [42].

• The approach to continuous collision detection presented in this thesis makes it necessary to choose several numerical and geometrical thresholds (see section 3.1.5). The choice of these thresholds is not always obvious, and can lead to false positives if chosen too tight, and false negatives otherwise. Modifications to the approach such as suggested in [53] could be applied in order to reduce sources of failures and the need to set thresholds by the user.

77 78 Chapter 5. Conclusion

• Since the method applied in this thesis only considers the wire segments’ mid lines when doing continuous collision detection and ignores the wires’ radii, cases where tunneling occurs outside of the mid lines are not handled. One example is shown in Figure 4.7 in section 4.1.4. This shortcoming could be handled either by choosing another method for continuous collision detection such as the ones introduced in section 2.4, which would have to be augmented in order to accommodate for the fact that the wire shape can change its size during a time step. Another possible way of addressing the shortcoming would be to adjust equation (2.9) in order to take the wire shapes’ radii into consideration, which would most likely result in a polynomial equation with higher degree.

5.3 Future Work

Except for addressing the shortcomings mentioned in the previous section, further work could be spent on the following issues:

• As mentioned in section 4.2.3, it could be investigated if the average runtime perfor- mance of the implemented CCD-approach can be improved by excluding slowly moving WireShape-pairs from testing for tunneling. • In wire simulation, continuous collision detection does not only make sense between wires, but also between wires and thin rigid bodies. If the current method were to be applied to this problem, the in-between motion for edges on the rigid bodies would have to be adapted however, since linear motion of the end points would be too coarse as an approximation. • If the problem in the previous item can be solved, then the approach could also be used for robust continuous collision detection between rigid and/or deformable bodies which are represented as triangle meshes. There has been much effort spent on this goal, but ad- dressing the degenerate cases of co-linearity and co-planarity might add value. However, not only the edge-edge case, but also the vertex-plane case would have to be treated, as introduced in section 2.5. • Finally, an implementation of the presented approach for continuous collision detection on the GPU could improve computational performance in larger simulation scenarios com- pared to the current CPU-based implementation. Chapter 6

Acknowledgments

I would like to thank my supervisor Martin Berggren for his support and patience. Furthermore, I am greatly indebted to the people at Algoryx for making it possible to write this thesis at the company, and for their support and help. Especially I would like to thank Fredrik Nordfelth who guided me through the thesis project, Niklas Merlin for making use of my results, and for Claude Lacoursière for many helpful discussions. Finally, I would like to thank my wife Elena Brandl for her love and support.

79 80 Chapter 6. Acknowledgments References

[1] Algoryx Simulation AB. AGX Dynamics User Manual. 2.16.0.1. Personal communication. 2016-6. [2] Karim Abdel-Malek, Denis Blackmore, and Kenneth Joy. “Swept volumes: Foundations, Perspectives, and Applications”. In: International Journal of Shape Modeling (2000), pp. 1–25. [3] Alkiviadis G. Akritas and Adam W. Strzebonski. “A Comparative Study of Two Real Root Isolation Methods”. In: Nonlinear Analysis: Modelling and Control 10.4 (2005), pp. 297–304. [4] Dan Albocher, Uzi Sarel, and Yi-King Choi. “Efficient Continuous Collision Detection for Bounding Boxes under Rational Motion”. In: Robotics and Automation, 2006. ICRA 2006. Proceedings 2006 IEEE International Conference on. May. 2006, pp. 3017–3022. [5] Algoryx Simulation AB. http://www.algoryx.se/. Accessed: 2016-12-07. [6] Farid Amirouche. Fundamentals of Multibody Dynamics: Theory and Applications. 2006. [7] Hamzah Asyrani et al. “Review on Narrow Phase Collision Detection System in Virtual Environment”. In: ARPN Journal of Engineering and Applied Sciences 10.2 (2015), pp. 691–700. [8] Quentin Avril, Valérie Gouranton, and Bruno Arnaldi. “New Trends in Collision Detection Performance”. In: Virtual Reality International Conference (VRIC) 2009. 2009, pp. 53–62. [9] Nils Bäckman. “Collision Detection of Triangle Meshes using GPU”. Master’s thesis. Umeå University, 2010. [10] David Baraff. “Curved Surfaces and Coherence for Non-Penetrating Rigid Body Simulation”. In: ACM SIGGRAPH Computer Graphics 24.4 (1990-09), pp. 19–28. [11] David Baraff. “Dynamic Simulation of Non-Penetrating Rigid Bodies”. PhD thesis. 1992. [12] Jan Bender et al. “Interactive Simulation of Rigid Body Dynamics in Computer Graphics”. In: STAR Proceedings of Eurographics. 2012. [13] Gino van den Bergen. Collision Detection in Interactive 3D Environments. 2004. [14] Joel Brown, Jean-Claude Latombe, and Kevin Montgomery. “Real-time knot-tying simulation”. In: The Visual Computer 20.2 (2004), pp. 165–179. [15] Stephen Cameron. “Collision detection by four-dimensional intersection testing”. In: Robotics and Automation, IEEE Transactions on June (1990).

81 82 REFERENCES

[16] John F. Canny. “Collision detection for moving polyhedra”. In: IEEE Transactions on Pattern Analysis and Machine Intelligence 8.2 (1986), pp. 200–209. [17] Lu Chen et al. “Efficient Collision Determination for Dynamic Scenes using Coherent Separating Axis”. In: IJVR 6.4 (2007), pp. 17–22. [18] Daniel S. Coming and Oliver G. Staadt. “Kinetic sweep and prune for multi-body continuous motion”. In: Computers \& Graphics 30.3 (2006), pp. 439–449. [19] James F. Epperson. Basins of Attraction. Tech. rep. 2015, pp. 1–11. url: http://www.jfepperson.org/2edition-web/basins.pdf. [20] Christer Ericson. Coplanarity is teH eVil!!!11!1!! 2007. url: http://realtimecollisiondetection.net/blog/?p=41 (visited on 2017-01-19). [21] Christer Ericson. Real-time collision detection. Vol. 1. 2005, p. 633. [22] Kenny Erleben et al. Physics-Based Animation. 2005. [23] Leonidas J. Guibas. “Kinetic Data Structures”. In: Mehta, Dinesh P.; Sahni, Sartaj, Handbook of Data Structures and Applications. 2001, pp. 23–1–23–18. [24] Bruno Heidelberger. “Consistent Collision and Self-Collision Handling for Deformable Objects”. PhD thesis. ETH Zurich, 2007. [25] Etsujiro Imanishi, Takao Nanjo, and Takahiro Kobayashi. “Dynamic simulation of wire rope with contact”. In: Journal of Mechanical Science and Technology 23.4 (2009), pp. 1083–1088. [26] Gereon Kremer. “Isolating Real Roots Using Adaptable-Precision Interval Arithmetic”. Master’s thesis. RWTH Aachen, 2013. [27] Claude Lacoursière. “Ghosts and Machines: Regularized Variational Methods for Interactive Simulations of Multibodies with Dry Frictional Contacts”. PhD thesis. Umeå University, 2007. [28] Claude Lacoursière. “Regularized, stabilized, variational methods for multibodies”. In: The 48th Scandinavian Conference on Simulation and Modeling (SIMS 2007). 48. 2007, pp. 40–48. [29] Sebastian Martin et al. “Unified Simulation of Elastic Rods, Shells, and Solids”. In: IEICE Electronics Express 6.22 (2009), pp. 1602–1607. [30] Ian Millington. engine development. 2007. [31] Brian Vincent Mirtich. “Impulse-based dynamic simulation of rigid body systems”. PhD thesis. 1996. [32] Brian Vincent Mirtich. “Timewarp rigid body simulation”. In: Proceedings of the 27th annual conference on Computer graphics and interactive techniques (2000), pp. 193–200. [33] Matthew Moore and Jane Wilhelms. “Collision detection and response for computer animation”. In: ACM Siggraph Computer Graphics 22.4 (1988), pp. 289–298. [34] Matthias Müller et al. “Air Meshes for Robust Collision Handling”. In: ACM Transactions on Graphics (TOG) - Proceedings of ACM SIGGRAPH 2015 34.4 (2015). [35] Jorge Nocedal and Stephen J. Wright. Numerical optimization. 2006, xxii, 664 p. [36] OpenSceneGraph. http://www.openscenegraph.org/. Accessed: 2016-12-07. [37] J. Phillips, A. Ladd, and L.E. Kavraki. “Simulated knot tying”. In: Proceedings 2002 IEEE International Conference on Robotics and Automation 1 (2002), pp. 1–6. REFERENCES 83

[38] Xavier Provot. “Collision and self-collision handling in cloth model dedicated to design garments”. In: Computer Animation and Simulation ’97. 1997, pp. 177–189. [39] Stéphane Redon. “Continuous Collision Detection for Rigid and Articulated Bodies”. In: International Journal of Clinical Practice 58 (2004-11), pp. 1–2. [40] Stéphane Redon, Abderrahmane Kheddar, and Sabine Coquillart. “An Algebraic Solution to the Problem of Collision Detection for Rigid Polyhedral Objects”. In: Conf. on Robotics and Automation April (2000), pp. 3733–3738. [41] Stéphane Redon, Abderrahmane Kheddar, and Sabine Coquillart. “Fast continuous collision detection between rigid bodies”. In: Computer graphics forum 21.3 (2002), pp. 279–287. [42] Root-finding algorithm on Wikipedia. https://en.wikipedia.org/wiki/Root-finding_algorithm. Accessed: 2017-01-15. [43] Martin Servin and Claude Lacoursière. “Massless cable for real-time simulation”. In: Computer Graphics Forum 26.2 (2007), pp. 172–184. [44] Martin Servin and Claude Lacoursière. “Rigid body cable for virtual environments”. In: IEEE Transactions on Visualization and Computer (2008), pp. 1–15. [45] Martin Servin, Claude Lacoursière, and Fredrik Nordfelth. “Adaptive resolution in physics based virtual environments”. In: SIGRAD 2008 Conference Proceedings. 2008, pp. 47–52. [46] Martin Servin et al. “Hybrid, Multi-Resolution Wires with Massless Frictional Contacts.” In: IEEE transactions on visualization and computer graphics 17.7 (2011-09). [47] Melvin R Spencer. “Polynomial Real Root Finding in Bernstein Form”. PhD thesis. 1994. [48] Erik Sundholm. “Distance Fields Accelerated with OpenCL”. Master’s thesis. Umeå University, 2010. [49] Shoichiro Takehara, Masaya Kawarada, and Kazunori Hase. “Dynamic Contact between a Wire Rope and a Pulley Using Absolute Nodal Coordinate Formulation”. In: Machines 4.1 (2016), p. 4. [50] Min Tang, Young J. Kim, and Dinesh Manocha. “C 2 A: Controlled Conservative Advancement for Continuous Collision Detection of Polygonal Models”. In: graphics.ewha.ac.kr (2009). [51] Test-Driven Development on Wikipedia. https://en.wikipedia.org/wiki/Test-driven_development. Accessed: 2016-12-08. [52] The programming language Lua. https://www.lua.org/. Accessed: 2016-12-07. [53] Huamin Wang. “Defending continuous collision detection against errors”. In: ACM Transactions on Graphics (TOG) - Proceedings of ACM SIGGRAPH 2014 33.4 (2014). [54] Rene Weller. “New Geometric Data Structures For Collision Detection”. PhD thesis. 2012. [55] Rene Weller, Udo Frese, and Gabriel Zachmann. “Parallel Collision Detection in Constant Time”. In: Workshop on Virtual Reality Interaction and Physical Simulation. 2013. 84 REFERENCES