NLS Engine  v0.1
The Next Logical Step in game engine design.
 All Classes Namespaces Files Functions Variables Enumerations Enumerator Defines
ComponentLinearVelocity.cpp
Go to the documentation of this file.
00001 
00011 #pragma once
00012 
00013 #include "ComponentLinearVelocity.h"
00014 
00015 #include "../../sharedbase/Entity.h"
00016 
00017 namespace Physics {
00018   /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
00019   ComponentLinearVelocity::ComponentLinearVelocity(EntitySPTR owner, ModuleInterface* module) :
00020     InterfaceUpdateable(owner, module),
00021     primaryBuffer(ComponentLinearVelocityDataPointer(new ComponentLinearVelocityData())),
00022     secondaryBuffer(ComponentLinearVelocityDataPointer(new ComponentLinearVelocityData()))
00023   {
00024     this->swap.needed = false;
00025     this->SetVelocity(ZERO_VECTOR_3D);
00026   }
00027   
00028   ComponentLinearVelocity::~ComponentLinearVelocity() {
00029   }
00030   
00031   /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
00032   bool ComponentLinearVelocity::SetVelocity(Vector3D velocity) {
00033     // Low-level copy just to be sure
00034     {
00035       Threading::WriteLock w_lock(this->secondaryBuffer->mutex);
00036       this->secondaryBuffer->velocity.x = velocity.x;
00037       this->secondaryBuffer->velocity.y = velocity.y;
00038       this->secondaryBuffer->velocity.z = velocity.z;
00039     }
00040     
00041     {
00042       Threading::WriteLock w_lock(this->swap.mutex);
00043       this->swap.needed = true;
00044     }
00045     
00046     return true;
00047   }
00048   
00049   /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
00050   void ComponentLinearVelocity::Update(double dt) {
00051     // Attempt buffer swap here if needed.  If it fails, try again next time.
00052     {
00053       Threading::UpgradeLock swap_lock(this->swap.mutex);
00054       if (this->swap.needed) {
00055         Threading::UpgradeToUniqueLock unique_lock(swap_lock);
00056         this->swap.needed = false;
00057         
00058         Threading::WriteLock w1_lock(this->secondaryBuffer->mutex);
00059         Threading::WriteLock w2_lock(this->primaryBuffer->mutex);
00060         Threading::Swap<ComponentLinearVelocityDataPointer>(this->primaryBuffer, this->secondaryBuffer);
00061       }
00062     }
00063     
00064     if (this->owner.get() != nullptr) {
00065       Threading::ReadLock lock(this->primaryBuffer->mutex);
00066       
00067       this->owner->location += this->primaryBuffer->velocity * (float) dt;
00068     }
00069   }
00070 }