00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
#include "Spring.h"
00013
#include <OpenCAL/PhysicalObject.h>
00014
#include <OpenCAL/System.h>
00015
#include <OpenCAL/Renderer.h>
00016
using namespace OpenCAL;
00017
00018
#include <OpenCAL/Material.h>
00019
#include <OpenCAL/Color.h>
00020
using namespace Utils;
00021
00022
using namespace std;
00023
00024
00025
00026
00027
00028
00029 Spring::Spring(
PhysicsSystem *parent,
PhysicalObject *object1,
PhysicalObject *object2)
00030 :
Force(parent), m_object1(object1), m_object2(object2), m_stiffness(0.1f),
00031 m_damping(0.1f), m_restLength(0.0f), m_snapFactor(0.0f)
00032 {
00033 }
00034
00035 Spring::~Spring()
00036 {
00037 }
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
void Spring::initialize()
00050 {
00051 Force::initialize();
00052
00053
00054
if(m_restLength == 0.0f)
00055 calculateRestLength();
00056 }
00057
00063 void Spring::execute(
float seconds)
00064 {
00065
00066
if(!isConnected())
return;
00067 Force::execute(seconds);
00068
00069
if(!m_object1 || !m_object2)
return;
00070
00071
Vector3 deltaP = m_object1->
getPosition() - m_object2->
getPosition();
00072
Vector3 deltaV = m_object1->
getVelocity() - m_object2->
getVelocity();
00073
float length = deltaP.
length();
00074
00075
float term1 = -m_stiffness * (length - m_restLength);
00076
float term2 = -m_damping * deltaV.
dotProduct(deltaP) / length;
00077
00078
Vector3 force = (term1 + term2) * deltaP.
normalized();
00079
00080 m_object1->
addForce(force);
00081 m_object2->
addForce(-force);
00082
00083
00084
if(m_snapFactor > 1.0f && length > (m_restLength * m_snapFactor))
00085 m_object1 = m_object2 = 0;
00086 }
00087
00088
00089
00090
00091
00092
00093
void Spring::render()
00094 {
00095
Renderer *renderer = m_parent->
getRenderer();
00096
if(!renderer)
return;
00097
00098
00099
if(!m_enabled)
return;
00100
if(!isConnected())
return;
00101
00102 renderer->
renderLine(m_object1->
getPosition(), m_object2->
getPosition(), 3.0f);
00103 }
00104
00105
00106
00107
00108
00109
00110
void Spring::calculateRestLength( )
00111 {
00112
if(!m_object1 || !m_object2)
00113 m_restLength = 0.0f;
00114
else
00115 m_restLength = m_object1->
getPosition().distance(m_object2->
getPosition());
00116 }
00117
00118
00119
00120
00121
00122
00123
00124
00125
00126
00127
00128
00129
00130
00131
00132
00133
00134
00135
00136
00137
00138
00139
00140
00141
00142
00143
00144
00145