From 069d079594559b1b5361b0a9270126f04d21d7ea Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Wed, 16 Apr 2014 01:33:05 +0200 Subject: [PATCH 01/37] Car physics not working, yet! --- src/Components/Physics.h | 3 +- src/Components/Vehicle.h | 16 + src/GameWorld.cpp | 25 +- src/GameWorld.h | 1 + src/Physics/VehicleSetup.cpp | 339 ++++++++++++++++++ src/Physics/VehicleSetup.h | 54 +++ src/Systems/PhysicsSystem.cpp | 82 ++++- src/Systems/PhysicsSystem.h | 11 +- vs11/Returngeance/Returngeance.vcxproj | 7 +- .../Returngeance/Returngeance.vcxproj.filters | 12 + 10 files changed, 535 insertions(+), 15 deletions(-) create mode 100644 src/Components/Vehicle.h create mode 100644 src/Physics/VehicleSetup.cpp create mode 100644 src/Physics/VehicleSetup.h diff --git a/src/Components/Physics.h b/src/Components/Physics.h index 956ae7a..df819c4 100644 --- a/src/Components/Physics.h +++ b/src/Components/Physics.h @@ -9,9 +9,10 @@ namespace Components struct Physics : Component { Physics() - : Mass(0.f) { } + : Mass(0.f), Static(false){} float Mass; + bool Static; }; } diff --git a/src/Components/Vehicle.h b/src/Components/Vehicle.h new file mode 100644 index 0000000..6ab1498 --- /dev/null +++ b/src/Components/Vehicle.h @@ -0,0 +1,16 @@ +#ifndef Components_Vehicle_h__ +#define Components_Vehicle_h__ + +#include "Component.h" + +namespace Components +{ + + struct Vehicle : Component +{ + +}; + +} + +#endif // Components_Vehicle_h__ diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 9272005..e274828 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -5,6 +5,7 @@ void GameWorld::Initialize() { World::Initialize(); + { auto camera = CreateEntity(); auto transform = AddComponent(camera, "Transform"); @@ -33,13 +34,14 @@ void GameWorld::Initialize() auto physics = AddComponent(ground, "Physics"); physics->Mass = 10; + physics->Static = true; } - for(int i = 0; i < 10; i++) + for(int i = 0; i < 1; i++) { auto ball = CreateEntity(); auto transform = AddComponent(ball, "Transform"); - transform->Position = glm::vec3(0, 5 + i*2, 0); + transform->Position = glm::vec3(0, 5, 0); transform->Scale = glm::vec3(1.0f, 1.0f, 1.0f); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(ball, "Model"); @@ -50,6 +52,23 @@ void GameWorld::Initialize() physics->Mass = 1; } + { + auto car = CreateEntity(); + auto transform = AddComponent(car, "Transform"); + transform->Position = glm::vec3(0, 5, 0); + transform->Scale = glm::vec3(1.0f, 1.0f, 1.0f); + transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); + auto model = AddComponent(car, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Box.obj"; + auto physics = AddComponent(car, "Physics"); + physics->Mass = 1; + auto box = AddComponent(car, "Box"); + box->Width = 3; + box->Height = 1; + box->Depth = 5; + auto vehicle = AddComponent(car, "Vehicle"); + } + /*{ auto entity = CreateEntity(); AddComponent(entity, "Transform"); @@ -82,6 +101,8 @@ void GameWorld::RegisterComponents() m_ComponentFactory.Register("Physics", []() { return new Components::Physics(); }); m_ComponentFactory.Register("Sphere", []() { return new Components::Sphere(); }); m_ComponentFactory.Register("Box", []() { return new Components::Box (); }); + + m_ComponentFactory.Register("Vehicle", []() { return new Components::Vehicle(); }); } void GameWorld::RegisterSystems() diff --git a/src/GameWorld.h b/src/GameWorld.h index b40807e..2945556 100755 --- a/src/GameWorld.h +++ b/src/GameWorld.h @@ -30,6 +30,7 @@ #include "Components/Physics.h" #include "Components/Sphere.h" #include "Components/Box.h" +#include "Components/Vehicle.h" class GameWorld : public World { diff --git a/src/Physics/VehicleSetup.cpp b/src/Physics/VehicleSetup.cpp new file mode 100644 index 0000000..b656c7b --- /dev/null +++ b/src/Physics/VehicleSetup.cpp @@ -0,0 +1,339 @@ +#include "PrecompiledHeader.h" +#include "Physics/VehicleSetup.h" + + + +void VehicleSetup::buildVehicle(const hkpWorld* world, hkpVehicleInstance& vehicle) +{ + // + // All memory allocations are made here. + // + + vehicle.m_data = new hkpVehicleData; + vehicle.m_driverInput = new hkpVehicleDefaultAnalogDriverInput; + vehicle.m_steering = new hkpVehicleDefaultSteering; + vehicle.m_engine = new hkpVehicleDefaultEngine; + vehicle.m_transmission = new hkpVehicleDefaultTransmission; + vehicle.m_brake = new hkpVehicleDefaultBrake; + vehicle.m_suspension = new hkpVehicleDefaultSuspension; + vehicle.m_aerodynamics = new hkpVehicleDefaultAerodynamics; + vehicle.m_velocityDamper = new hkpVehicleDefaultVelocityDamper; + + // For illustrative purposes we use a custom hkpVehicleRayCastWheelCollide + // which implements varying 'ground' friction in a very simple way. + //vehicle.m_wheelCollide = new hkpVehicleRayCastWheelCollide; + + setupVehicleData(world, *vehicle.m_data); + + // initialise the tyremarks controller with 128 tyremark points. + vehicle.m_tyreMarks = new hkpTyremarksInfo(*vehicle.m_data, 128); + + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_driverInput)); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_steering)); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_engine)); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_transmission)); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_brake)); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_suspension)); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_aerodynamics)); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_velocityDamper)); + + setupWheelCollide(world, vehicle, *static_cast(vehicle.m_wheelCollide)); + + setupTyremarks(*vehicle.m_data, *static_cast(vehicle.m_tyreMarks)); + + // + // Check that all components are present. + // + HK_ASSERT(0x0, vehicle.m_data); + HK_ASSERT(0x7708674a, vehicle.m_driverInput); + HK_ASSERT(0x5a324a2d, vehicle.m_steering); + HK_ASSERT(0x7bcb2aff, vehicle.m_engine); + HK_ASSERT(0x29bddb50, vehicle.m_transmission); + HK_ASSERT(0x2b0323a2, vehicle.m_brake); + HK_ASSERT(0x7a7ade23, vehicle.m_suspension); + HK_ASSERT(0x6ec4d0ed, vehicle.m_aerodynamics); + HK_ASSERT(0x67161206, vehicle.m_wheelCollide); + HK_ASSERT(0x295015f1, vehicle.m_tyreMarks); + + // + // Set up any variables that store cached data. + // + + + // Give driver input default values so that the vehicle (if this input is a default for non + // player cars) will drive, even if it is in circles! + + // Accelerate. + vehicle.m_deviceStatus = new hkpVehicleDriverInputAnalogStatus; + hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)vehicle.m_deviceStatus; + deviceStatus->m_positionY = -0.4f; + + // Turn. + deviceStatus->m_positionX = 0.3f; + + // Defaults + deviceStatus->m_handbrakeButtonPressed = false; + deviceStatus->m_reverseButtonPressed = false; + + + // + // Don't forget to call init! (This function is necessary to set up derived data) + // + vehicle.init(); +} + +void VehicleSetup::setupVehicleData(const hkpWorld* world, hkpVehicleData& data) +{ + data.m_gravity = world->getGravity(); + + // + // The vehicleData contains information about the chassis. + // + + // The coordinates of the chassis system, used for steering the vehicle. + // up forward right + data.m_chassisOrientation.setCols(hkVector4(0, 1, 0), hkVector4(1, 0, 0), hkVector4(0, 0, 1)); + + data.m_frictionEqualizer = 0.5f; + + + // Inertia tensor for each axis is calculated by using : + // (1 / chassis_mass) * (torque(axis)Factor / chassisUnitInertia) + data.m_torqueRollFactor = 0.625f; + data.m_torquePitchFactor = 0.5f; + data.m_torqueYawFactor = 0.35f; + + data.m_chassisUnitInertiaYaw = 1.0f; + data.m_chassisUnitInertiaRoll = 1.0f; + data.m_chassisUnitInertiaPitch = 1.0f; + + // Adds or removes torque around the yaw axis + // based on the current steering angle. This will + // affect steering. + data.m_extraTorqueFactor = -0.5f; + data.m_maxVelocityForPositionalFriction = 0.0f; + + // + // Wheel specifications + // + data.m_numWheels = 4; + + data.m_wheelParams.setSize(data.m_numWheels); + + data.m_wheelParams[0].m_axle = 0; + data.m_wheelParams[1].m_axle = 0; + data.m_wheelParams[2].m_axle = 1; + data.m_wheelParams[3].m_axle = 1; + + data.m_wheelParams[0].m_friction = 1.5f; + data.m_wheelParams[1].m_friction = 1.5f; + data.m_wheelParams[2].m_friction = 1.5f; + data.m_wheelParams[3].m_friction = 1.5f; + + data.m_wheelParams[0].m_slipAngle = 0.0f; + data.m_wheelParams[1].m_slipAngle = 0.0f; + data.m_wheelParams[2].m_slipAngle = 0.0f; + data.m_wheelParams[3].m_slipAngle = 0.0f; + + for (int i = 0; i < data.m_numWheels; i++) + { + // This value is also used to calculate the m_primaryTransmissionRatio. + data.m_wheelParams[i].m_radius = 0.4f; + data.m_wheelParams[i].m_width = 0.2f; + data.m_wheelParams[i].m_mass = 10.0f; + + data.m_wheelParams[i].m_viscosityFriction = 0.25f; + data.m_wheelParams[i].m_maxFriction = 2.0f * data.m_wheelParams[i].m_friction; + data.m_wheelParams[i].m_forceFeedbackMultiplier = 0.1f; + data.m_wheelParams[i].m_maxContactBodyAcceleration = hkReal(data.m_gravity.length3()) * 2; + } +} + + +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultAnalogDriverInput& driverInput) +{ + // We also use an analog "driver input" class to help converting user input to vehicle behavior. + + driverInput.m_slopeChangePointX = 0.8f; + driverInput.m_initialSlope = 0.7f; + driverInput.m_deadZone = 0.0f; + driverInput.m_autoReverse = true; +} + +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultSteering& steering) +{ + steering.m_doesWheelSteer.setSize(data.m_numWheels); + + // degrees + steering.m_maxSteeringAngle = 35 * (HK_REAL_PI / 180); + + // [mph/h] The steering angle decreases linearly + // based on your overall max speed of the vehicle. + steering.m_maxSpeedFullSteeringAngle = 70.0f * (1.605f / 3.6f); + steering.m_doesWheelSteer[0] = true; + steering.m_doesWheelSteer[1] = true; + steering.m_doesWheelSteer[2] = false; + steering.m_doesWheelSteer[3] = false; +} + +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultEngine& engine) +{ + engine.m_maxTorque = 500.0f; + + engine.m_minRPM = 1000.0f; + engine.m_optRPM = 5500.0f; + + // This value is also used to calculate the m_primaryTransmissionRatio. + engine.m_maxRPM = 7500.0f; + + engine.m_torqueFactorAtMinRPM = 0.8f; + engine.m_torqueFactorAtMaxRPM = 0.8f; + + engine.m_resistanceFactorAtMinRPM = 0.05f; + engine.m_resistanceFactorAtOptRPM = 0.1f; + engine.m_resistanceFactorAtMaxRPM = 0.3f; +} + +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultTransmission& transmission) +{ + int numGears = 4; + + transmission.m_gearsRatio.setSize(numGears); + transmission.m_wheelsTorqueRatio.setSize(data.m_numWheels); + + transmission.m_downshiftRPM = 3500.0f; + transmission.m_upshiftRPM = 6500.0f; + + transmission.m_clutchDelayTime = 0.0f; + transmission.m_reverseGearRatio = 1.0f; + transmission.m_gearsRatio[0] = 2.0f; + transmission.m_gearsRatio[1] = 1.5f; + transmission.m_gearsRatio[2] = 1.0f; + transmission.m_gearsRatio[3] = 0.75f; + transmission.m_wheelsTorqueRatio[0] = 0.2f; + transmission.m_wheelsTorqueRatio[1] = 0.2f; + transmission.m_wheelsTorqueRatio[2] = 0.3f; + transmission.m_wheelsTorqueRatio[3] = 0.3f; + + const hkReal vehicleTopSpeed = 130.0f; + const hkReal wheelRadius = 0.4f; + const hkReal maxEngineRpm = 7500.0f; + transmission.m_primaryTransmissionRatio = hkpVehicleDefaultTransmission::calculatePrimaryTransmissionRatio(vehicleTopSpeed, + wheelRadius, + maxEngineRpm, + transmission.m_gearsRatio[numGears - 1]); +} + +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultBrake& brake) +{ + brake.m_wheelBrakingProperties.setSize(data.m_numWheels); + + const float bt = 1500.0f; + brake.m_wheelBrakingProperties[0].m_maxBreakingTorque = bt; + brake.m_wheelBrakingProperties[1].m_maxBreakingTorque = bt; + brake.m_wheelBrakingProperties[2].m_maxBreakingTorque = bt; + brake.m_wheelBrakingProperties[3].m_maxBreakingTorque = bt; + + // Handbrake is attached to rear wheels only. + brake.m_wheelBrakingProperties[0].m_isConnectedToHandbrake = false; + brake.m_wheelBrakingProperties[1].m_isConnectedToHandbrake = false; + brake.m_wheelBrakingProperties[2].m_isConnectedToHandbrake = true; + brake.m_wheelBrakingProperties[3].m_isConnectedToHandbrake = true; + brake.m_wheelBrakingProperties[0].m_minPedalInputToBlock = 0.9f; + brake.m_wheelBrakingProperties[1].m_minPedalInputToBlock = 0.9f; + brake.m_wheelBrakingProperties[2].m_minPedalInputToBlock = 0.9f; + brake.m_wheelBrakingProperties[3].m_minPedalInputToBlock = 0.9f; + brake.m_wheelsMinTimeToBlock = 1000.0f; +} + +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultSuspension& suspension) +{ + suspension.m_wheelParams.setSize(data.m_numWheels); + suspension.m_wheelSpringParams.setSize(data.m_numWheels); + + suspension.m_wheelParams[0].m_length = 0.35f; + suspension.m_wheelParams[1].m_length = 0.35f; + suspension.m_wheelParams[2].m_length = 0.35f; + suspension.m_wheelParams[3].m_length = 0.35f; + + const float str = 50.0f; + suspension.m_wheelSpringParams[0].m_strength = str; + suspension.m_wheelSpringParams[1].m_strength = str; + suspension.m_wheelSpringParams[2].m_strength = str; + suspension.m_wheelSpringParams[3].m_strength = str; + + const float wd = 3.0f; + suspension.m_wheelSpringParams[0].m_dampingCompression = wd; + suspension.m_wheelSpringParams[1].m_dampingCompression = wd; + suspension.m_wheelSpringParams[2].m_dampingCompression = wd; + suspension.m_wheelSpringParams[3].m_dampingCompression = wd; + + suspension.m_wheelSpringParams[0].m_dampingRelaxation = wd; + suspension.m_wheelSpringParams[1].m_dampingRelaxation = wd; + suspension.m_wheelSpringParams[2].m_dampingRelaxation = wd; + suspension.m_wheelSpringParams[3].m_dampingRelaxation = wd; + + // + // NB: The hardpoints MUST be positioned INSIDE the chassis. + // + { + const hkReal hardPointFrontX = 1.3f; + const hkReal hardPointBackX = -1.1f; + const hkReal hardPointY = -0.05f; + const hkReal hardPointZ = 1.1f; + + suspension.m_wheelParams[0].m_hardpointChassisSpace.set(hardPointFrontX, hardPointY, -hardPointZ); + suspension.m_wheelParams[1].m_hardpointChassisSpace.set(hardPointFrontX, hardPointY, hardPointZ); + suspension.m_wheelParams[2].m_hardpointChassisSpace.set(hardPointBackX, hardPointY, -hardPointZ); + suspension.m_wheelParams[3].m_hardpointChassisSpace.set(hardPointBackX, hardPointY, hardPointZ); + } + + const hkVector4 downDirection(0.0f, -1.0f, 0.0f); + suspension.m_wheelParams[0].m_directionChassisSpace = downDirection; + suspension.m_wheelParams[1].m_directionChassisSpace = downDirection; + suspension.m_wheelParams[2].m_directionChassisSpace = downDirection; + suspension.m_wheelParams[3].m_directionChassisSpace = downDirection; +} + +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultAerodynamics& aerodynamics) +{ + aerodynamics.m_airDensity = 1.3f; + // In m^2. + aerodynamics.m_frontalArea = 1.0f; + + aerodynamics.m_dragCoefficient = 0.7f; + aerodynamics.m_liftCoefficient = -0.3f; + + // Extra gavity applies in world space (independent of m_chassisCoordinateSystem). + aerodynamics.m_extraGravityws.set(0.0f, -5.0f, 0.0f); +} + +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper) +{ + // Caution: setting negative damping values will add energy to system. + // Setting the value to 0 will not affect the angular velocity. + + // Damping the change of the chassis angular velocity when below m_collisionThreshold. + // This will affect turning radius and steering. + velocityDamper.m_normalSpinDamping = 0.0f; + + // Positive numbers dampen the rotation of the chassis and + // reduce the reaction of the chassis in a collision. + velocityDamper.m_collisionSpinDamping = 4.0f; + + // The threshold in m/s at which the algorithm switches from + // using the normalSpinDamping to the collisionSpinDamping. + velocityDamper.m_collisionThreshold = 1.0f; +} + +void VehicleSetup::setupWheelCollide(const hkpWorld* world, const hkpVehicleInstance& vehicle, hkpVehicleRayCastWheelCollide& wheelCollide) +{ + // Set the wheels to have the same collision filter info as the chassis. + wheelCollide.m_wheelCollisionFilterInfo = vehicle.getChassis()->getCollisionFilterInfo(); +} + +void VehicleSetup::setupTyremarks(const hkpVehicleData& data, hkpTyremarksInfo& tyreMarks) +{ + tyreMarks.m_minTyremarkEnergy = 100.0f; + tyreMarks.m_maxTyremarkEnergy = 1000.0f; +} \ No newline at end of file diff --git a/src/Physics/VehicleSetup.h b/src/Physics/VehicleSetup.h new file mode 100644 index 0000000..7b7d9a5 --- /dev/null +++ b/src/Physics/VehicleSetup.h @@ -0,0 +1,54 @@ +#ifndef Physics_Vehicle_h__ +#define Physics_Vehicle_h__ + +//#include "PrecompiledHeader.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +// Vehicle page 425 in documentation +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +class VehicleSetup +{ +public: + virtual void buildVehicle(const hkpWorld* world, hkpVehicleInstance& vehicle); + +public: + + virtual void setupVehicleData(const hkpWorld* world, hkpVehicleData& data); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultAnalogDriverInput& driverInput); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultSteering& steering); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultEngine& engine); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultTransmission& transmission); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultBrake& brake); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultSuspension& suspension); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultAerodynamics& aerodynamics); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper); + + virtual void setupWheelCollide(const hkpWorld* world, const hkpVehicleInstance& vehicle, hkpVehicleRayCastWheelCollide& wheelCollide); + virtual void setupTyremarks(const hkpVehicleData& data, hkpTyremarksInfo& tyremarkscontroller); +}; + +#endif // Physics_Vehicle_h__ diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index c70c8fc..b77fc1b 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -29,6 +29,7 @@ Systems::PhysicsSystem::PhysicsSystem(World* world) : System(world) { + m_Accumulator = 0; { hkMemorySystem::FrameInfo finfo(500 * 1024); // Allocate 500KB of Physics solver buffer hkMemoryRouter* memoryRouter = hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, finfo); @@ -63,7 +64,30 @@ Systems::PhysicsSystem::PhysicsSystem(World* world) : System(world) void Systems::PhysicsSystem::Update(double dt) { - m_PhysicsWorld->stepDeltaTime(0.0166f); + for (auto pair : *m_World->GetEntities()) + { + EntityID entity = pair.first; + + if (m_RigidBodies.find(entity) == m_RigidBodies.end()) + continue; + + auto transformComponent = m_World->GetComponent(entity, "Transform"); + if (!transformComponent) + continue; + + + hkVector4 position(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); + hkQuaternion rotation(transformComponent->Orientation.x, transformComponent->Orientation.y, transformComponent->Orientation.z, transformComponent->Orientation.w); + m_RigidBodies[entity]->setPositionAndRotation(position, rotation); + } + + static const double timestep = 1 / 60.0; + m_Accumulator += dt; + while (m_Accumulator >= timestep) + { + m_PhysicsWorld->stepDeltaTime(timestep); + m_Accumulator -= timestep; + } // Step the visual debugger StepVisualDebugger(); @@ -113,17 +137,32 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent) { shape = new hkpSphereShape(sphereComponent->Radius); rigidBodyInfo.m_shape = shape; - rigidBodyInfo.m_motionType = hkpMotion::MOTION_SPHERE_INERTIA; + + if (physicsComponent->Static) + { + rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; + } + else + { + rigidBodyInfo.m_motionType = hkpMotion::MOTION_SPHERE_INERTIA; + } hkpInertiaTensorComputer::computeSphereVolumeMassProperties(sphereComponent->Radius, physicsComponent->Mass, massProperties); } else if (boxComponent) { - shape = new hkpBoxShape(hkVector4(boxComponent->Width, boxComponent->Height, boxComponent->Depth)); + hkReal thickness = 0.05; + shape = new hkpBoxShape(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness)); rigidBodyInfo.m_shape = shape; - rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; - hkReal thickness = 0.1; + if (physicsComponent->Static) + { + rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; + } + else + { + rigidBodyInfo.m_motionType = hkpMotion::MOTION_BOX_INERTIA; + } hkpInertiaTensorComputer::computeBoxSurfaceMassProperties(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness), physicsComponent->Mass, thickness, massProperties); } else @@ -138,14 +177,39 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent) // Create RigidBody hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo); - shape->removeReference(); + - m_PhysicsWorld->addEntity(rigidBody); - m_RigidBodies[entity] = rigidBody; - rigidBody->removeReference(); + auto vehicleComponent = m_World->GetComponent(entity, "Vehicle"); + if (vehicleComponent && m_Vehicles.find(entity) == m_Vehicles.end()) + { + VehicleSetup vehicleSetup; + // Create the vehicle. + m_Vehicles[entity] = new hkpVehicleInstance(rigidBody); + // Create the basic vehicle. + m_Vehicles[entity] = new hkpVehicleInstance(rigidBody); + vehicleSetup.buildVehicle(m_PhysicsWorld, *m_Vehicles[entity]); + // Add the vehicle's entities and phantoms to the world + m_Vehicles[entity]->addToWorld(m_PhysicsWorld); + // The vehicle is an action + m_PhysicsWorld->addAction(m_Vehicles[entity]); + + m_Vehicles[entity]->m_rpm = 0.0f; // Not sure why this one should be here + + shape->removeReference(); + rigidBody->removeReference(); + } + else + { + m_PhysicsWorld->addEntity(rigidBody); + m_RigidBodies[entity] = rigidBody; + shape->removeReference(); + rigidBody->removeReference(); + } } + + void Systems::PhysicsSystem::TearDownPhysicsState(EntityID entity, EntityID parent) { diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index e0856ed..77c4c21 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -10,6 +10,7 @@ #include "Components/Physics.h" #include "Components/Sphere.h" #include "Components/Box.h" +#include "Components/Vehicle.h" // Math and base include @@ -39,6 +40,11 @@ #include #include + + +#include "Physics/VehicleSetup.h" + + #include namespace Systems { @@ -54,7 +60,7 @@ public: private: - + double m_Accumulator; hkpWorld* m_PhysicsWorld; void SetUpPhysicsState(EntityID entity, EntityID parent); @@ -67,7 +73,10 @@ private: void SetupPhysics(hkpWorld* physicsWorld); std::unordered_map m_RigidBodies; + std::unordered_map m_Vehicles; + + hkpVehicleInstance* Systems::PhysicsSystem::createVehicle(VehicleSetup& vehicleSetup, hkpRigidBody* chassis); }; } diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 662155f..7145402 100644 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -65,7 +65,7 @@ true - OpenAL32.lib;opengl32.lib;glu32.lib;SOIL.lib;glew32d.lib;glfw3.lib;hkBase.lib;hkVisualize.lib;hkInternal.lib;hkSerialize.lib;hkGeometryUtilities.lib;hkcdInternal.lib;hkcdCollide.lib;hkpCollide.lib;hkpConstraint.lib;hkpConstraintSolver.lib;hkpDynamics.lib;hkpInternal.lib;hkpUtilities.lib;hkSceneData.lib;%(AdditionalDependencies) + OpenAL32.lib;opengl32.lib;glu32.lib;SOIL.lib;glew32d.lib;glfw3.lib;hkBase.lib;hkVisualize.lib;hkInternal.lib;hkSerialize.lib;hkGeometryUtilities.lib;hkcdInternal.lib;hkcdCollide.lib;hkpCollide.lib;hkpConstraint.lib;hkpConstraintSolver.lib;hkpDynamics.lib;hkpInternal.lib;hkpUtilities.lib;hkSceneData.lib;hkpVehicle.lib;%(AdditionalDependencies) /ignore:4221 @@ -89,7 +89,7 @@ true true true - OpenAL32.lib;opengl32.lib;glu32.lib;SOIL.lib;glew32.lib;glfw3.lib;hkaAnimation.lib;hkaInternal.lib;hkaPhysics2012Bridge.lib;hkBase.lib;hkcdCollide.lib;hkcdInternal.lib;hkCompat.lib;hkgBridge.lib;hkgCommon.lib;hkgDx11.lib;hkgDx9s.lib;hkGeometryUtilities.lib;hkgOglES.lib;hkgOglES2.lib;hkgOgls.lib;hkgSoundCommon.lib;hkgSoundXAudio2.lib;hkInternal.lib;hkpCollide.lib;hkpConstraint.lib;hkpConstraintSolver.lib;hkpDynamics.lib;hkpInternal.lib;hkpUtilities.lib;hkpVehicle.lib;hkSceneData.lib;hkSerialize.lib;hkVisualize.lib;%(AdditionalDependencies) + OpenAL32.lib;opengl32.lib;glu32.lib;SOIL.lib;glew32.lib;glfw3.lib;hkBase.lib;hkVisualize.lib;hkInternal.lib;hkSerialize.lib;hkGeometryUtilities.lib;hkcdInternal.lib;hkcdCollide.lib;hkpCollide.lib;hkpConstraint.lib;hkpConstraintSolver.lib;hkpDynamics.lib;hkpInternal.lib;hkpUtilities.lib;hkSceneData.lib;hkpVehicle.lib;%(AdditionalDependencies) @@ -100,6 +100,7 @@ + @@ -133,6 +134,7 @@ + @@ -140,6 +142,7 @@ + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 346e46f..2b30567 100644 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -34,6 +34,9 @@ Systems + + Physics + @@ -48,6 +51,9 @@ {1a6674dd-e1ce-4a28-a6e8-3f28468bb2f0} + + {5f790fcc-08a9-4dd1-96da-9d642acc7ffe} + @@ -139,6 +145,12 @@ Components + + Components + + + Physics + From aa64b7074cf5357cc07770bf0ec02113a3827339 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Thu, 17 Apr 2014 00:47:53 +0200 Subject: [PATCH 02/37] Vehicle working, ready for entity-component implementation. --- src/GameWorld.cpp | 50 +++++++++++++++++++---------------- src/Physics/VehicleSetup.cpp | 21 +++++---------- src/Physics/VehicleSetup.h | 2 -- src/Systems/PhysicsSystem.cpp | 13 ++++++--- 4 files changed, 42 insertions(+), 44 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index e274828..2d0c4f3 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -22,14 +22,14 @@ void GameWorld::Initialize() { auto ground = CreateEntity(); auto transform = AddComponent(ground, "Transform"); - transform->Position = glm::vec3(0, 0, 0); - transform->Scale = glm::vec3(1000.0f, 1.0f, 1000.0f); + transform->Position = glm::vec3(0, -5, 0); + transform->Scale = glm::vec3(1000.0f, 10.0f, 1000.0f); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(ground, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube.obj"; auto box = AddComponent(ground, "Box"); box->Width = 500; - box->Height = 0.5; + box->Height = 5; box->Depth = 500; auto physics = AddComponent(ground, "Physics"); @@ -37,38 +37,42 @@ void GameWorld::Initialize() physics->Static = true; } - for(int i = 0; i < 1; i++) - { - auto ball = CreateEntity(); - auto transform = AddComponent(ball, "Transform"); - transform->Position = glm::vec3(0, 5, 0); - transform->Scale = glm::vec3(1.0f, 1.0f, 1.0f); - transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); - auto model = AddComponent(ball, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Sphere.obj"; - auto sphere = AddComponent(ball, "Sphere"); - sphere->Radius = 0.5; - auto physics = AddComponent(ball, "Physics"); - physics->Mass = 1; - } { auto car = CreateEntity(); auto transform = AddComponent(car, "Transform"); transform->Position = glm::vec3(0, 5, 0); - transform->Scale = glm::vec3(1.0f, 1.0f, 1.0f); + transform->Scale = glm::vec3(3, 1, 5); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(car, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Box.obj"; + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; auto physics = AddComponent(car, "Physics"); - physics->Mass = 1; + physics->Mass = 1200; auto box = AddComponent(car, "Box"); - box->Width = 3; - box->Height = 1; - box->Depth = 5; + box->Width = 1.5f; + box->Height = 0.5f; + box->Depth = 2.5f; auto vehicle = AddComponent(car, "Vehicle"); } + for(int i = 0; i < 50; i++) + { + auto ball = CreateEntity(); + auto transform = AddComponent(ball, "Transform"); + transform->Position = glm::vec3(243, 10 + i*10, 0); + transform->Scale = glm::vec3(10); + transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); + auto model = AddComponent(ball, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + auto physics = AddComponent(ball, "Physics"); + physics->Mass = 100; + auto box = AddComponent(ball, "Box"); + box->Width = 5.f; + box->Height = 5.f; + box->Depth = 5.f; + + } + /*{ auto entity = CreateEntity(); AddComponent(entity, "Transform"); diff --git a/src/Physics/VehicleSetup.cpp b/src/Physics/VehicleSetup.cpp index b656c7b..44a2d26 100644 --- a/src/Physics/VehicleSetup.cpp +++ b/src/Physics/VehicleSetup.cpp @@ -21,12 +21,10 @@ void VehicleSetup::buildVehicle(const hkpWorld* world, hkpVehicleInstance& vehic // For illustrative purposes we use a custom hkpVehicleRayCastWheelCollide // which implements varying 'ground' friction in a very simple way. - //vehicle.m_wheelCollide = new hkpVehicleRayCastWheelCollide; + vehicle.m_wheelCollide = new hkpVehicleRayCastWheelCollide; setupVehicleData(world, *vehicle.m_data); - // initialise the tyremarks controller with 128 tyremark points. - vehicle.m_tyreMarks = new hkpTyremarksInfo(*vehicle.m_data, 128); setupComponent(*vehicle.m_data, *static_cast(vehicle.m_driverInput)); setupComponent(*vehicle.m_data, *static_cast(vehicle.m_steering)); @@ -39,7 +37,6 @@ void VehicleSetup::buildVehicle(const hkpWorld* world, hkpVehicleInstance& vehic setupWheelCollide(world, vehicle, *static_cast(vehicle.m_wheelCollide)); - setupTyremarks(*vehicle.m_data, *static_cast(vehicle.m_tyreMarks)); // // Check that all components are present. @@ -53,7 +50,6 @@ void VehicleSetup::buildVehicle(const hkpWorld* world, hkpVehicleInstance& vehic HK_ASSERT(0x7a7ade23, vehicle.m_suspension); HK_ASSERT(0x6ec4d0ed, vehicle.m_aerodynamics); HK_ASSERT(0x67161206, vehicle.m_wheelCollide); - HK_ASSERT(0x295015f1, vehicle.m_tyreMarks); // // Set up any variables that store cached data. @@ -92,7 +88,7 @@ void VehicleSetup::setupVehicleData(const hkpWorld* world, hkpVehicleData& data) // The coordinates of the chassis system, used for steering the vehicle. // up forward right - data.m_chassisOrientation.setCols(hkVector4(0, 1, 0), hkVector4(1, 0, 0), hkVector4(0, 0, 1)); + data.m_chassisOrientation.setCols(hkVector4(0, 1, 0), hkVector4(0, 0, 1), hkVector4(-1, 0, 0)); data.m_frictionEqualizer = 0.5f; @@ -138,8 +134,8 @@ void VehicleSetup::setupVehicleData(const hkpWorld* world, hkpVehicleData& data) for (int i = 0; i < data.m_numWheels; i++) { // This value is also used to calculate the m_primaryTransmissionRatio. - data.m_wheelParams[i].m_radius = 0.4f; - data.m_wheelParams[i].m_width = 0.2f; + data.m_wheelParams[i].m_radius = 0.6f; + data.m_wheelParams[i].m_width = 0.3f; data.m_wheelParams[i].m_mass = 10.0f; data.m_wheelParams[i].m_viscosityFriction = 0.25f; @@ -215,8 +211,8 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultT transmission.m_wheelsTorqueRatio[2] = 0.3f; transmission.m_wheelsTorqueRatio[3] = 0.3f; - const hkReal vehicleTopSpeed = 130.0f; - const hkReal wheelRadius = 0.4f; + const hkReal vehicleTopSpeed = 50.0f; + const hkReal wheelRadius = 0.6f; const hkReal maxEngineRpm = 7500.0f; transmission.m_primaryTransmissionRatio = hkpVehicleDefaultTransmission::calculatePrimaryTransmissionRatio(vehicleTopSpeed, wheelRadius, @@ -332,8 +328,3 @@ void VehicleSetup::setupWheelCollide(const hkpWorld* world, const hkpVehicleInst wheelCollide.m_wheelCollisionFilterInfo = vehicle.getChassis()->getCollisionFilterInfo(); } -void VehicleSetup::setupTyremarks(const hkpVehicleData& data, hkpTyremarksInfo& tyreMarks) -{ - tyreMarks.m_minTyremarkEnergy = 100.0f; - tyreMarks.m_maxTyremarkEnergy = 1000.0f; -} \ No newline at end of file diff --git a/src/Physics/VehicleSetup.h b/src/Physics/VehicleSetup.h index 7b7d9a5..2a0ce95 100644 --- a/src/Physics/VehicleSetup.h +++ b/src/Physics/VehicleSetup.h @@ -24,7 +24,6 @@ #include #include #include -#include #include @@ -48,7 +47,6 @@ public: virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper); virtual void setupWheelCollide(const hkpWorld* world, const hkpVehicleInstance& vehicle, hkpVehicleRayCastWheelCollide& wheelCollide); - virtual void setupTyremarks(const hkpVehicleData& data, hkpTyremarksInfo& tyremarkscontroller); }; #endif // Physics_Vehicle_h__ diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index b77fc1b..39d2e93 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -75,13 +75,17 @@ void Systems::PhysicsSystem::Update(double dt) if (!transformComponent) continue; + hkVector4 position(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); hkQuaternion rotation(transformComponent->Orientation.x, transformComponent->Orientation.y, transformComponent->Orientation.z, transformComponent->Orientation.w); m_RigidBodies[entity]->setPositionAndRotation(position, rotation); } - static const double timestep = 1 / 60.0; + + + + static const double timestep = 1 / 30.0; m_Accumulator += dt; while (m_Accumulator >= timestep) { @@ -184,17 +188,18 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent) { VehicleSetup vehicleSetup; - // Create the vehicle. - m_Vehicles[entity] = new hkpVehicleInstance(rigidBody); // Create the basic vehicle. m_Vehicles[entity] = new hkpVehicleInstance(rigidBody); vehicleSetup.buildVehicle(m_PhysicsWorld, *m_Vehicles[entity]); // Add the vehicle's entities and phantoms to the world m_Vehicles[entity]->addToWorld(m_PhysicsWorld); + + m_RigidBodies[entity] = rigidBody; + // The vehicle is an action m_PhysicsWorld->addAction(m_Vehicles[entity]); - m_Vehicles[entity]->m_rpm = 0.0f; // Not sure why this one should be here + //m_Vehicles[entity]->m_rpm = 0.0f; // Not sure why this one should be here shape->removeReference(); rigidBody->removeReference(); From 4e5038a163849b28cadc7acfbbbdb00a7858639e Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 22 Apr 2014 01:45:36 +0200 Subject: [PATCH 03/37] Fixed vehicle steering bug. "The distance between the axles must be non zero" Weird Havok coordinate system for specifying hardpoints was different to our coordinate system. Resulted in wheel axels without any separation! --- src/Physics/VehicleSetup.cpp | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/src/Physics/VehicleSetup.cpp b/src/Physics/VehicleSetup.cpp index 44a2d26..d40fb0e 100644 --- a/src/Physics/VehicleSetup.cpp +++ b/src/Physics/VehicleSetup.cpp @@ -59,19 +59,14 @@ void VehicleSetup::buildVehicle(const hkpWorld* world, hkpVehicleInstance& vehic // Give driver input default values so that the vehicle (if this input is a default for non // player cars) will drive, even if it is in circles! - // Accelerate. + // Steering Defaults vehicle.m_deviceStatus = new hkpVehicleDriverInputAnalogStatus; hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)vehicle.m_deviceStatus; - deviceStatus->m_positionY = -0.4f; - - // Turn. - deviceStatus->m_positionX = 0.3f; - - // Defaults + deviceStatus->m_positionY = 0.f; + deviceStatus->m_positionX = 0.f; deviceStatus->m_handbrakeButtonPressed = false; deviceStatus->m_reverseButtonPressed = false; - // // Don't forget to call init! (This function is necessary to set up derived data) // @@ -88,7 +83,7 @@ void VehicleSetup::setupVehicleData(const hkpWorld* world, hkpVehicleData& data) // The coordinates of the chassis system, used for steering the vehicle. // up forward right - data.m_chassisOrientation.setCols(hkVector4(0, 1, 0), hkVector4(0, 0, 1), hkVector4(-1, 0, 0)); + data.m_chassisOrientation.setCols(hkVector4(0, 1, 0), hkVector4(0, 0, -1), hkVector4(1, 0, 0)); data.m_frictionEqualizer = 0.5f; @@ -273,15 +268,19 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultS // NB: The hardpoints MUST be positioned INSIDE the chassis. // { - const hkReal hardPointFrontX = 1.3f; - const hkReal hardPointBackX = -1.1f; + const hkReal hardPointFrontZ = -1.3f; + const hkReal hardPointBackZ = 1.1f; const hkReal hardPointY = -0.05f; - const hkReal hardPointZ = 1.1f; + const hkReal hardPointX = 1.1f; - suspension.m_wheelParams[0].m_hardpointChassisSpace.set(hardPointFrontX, hardPointY, -hardPointZ); - suspension.m_wheelParams[1].m_hardpointChassisSpace.set(hardPointFrontX, hardPointY, hardPointZ); - suspension.m_wheelParams[2].m_hardpointChassisSpace.set(hardPointBackX, hardPointY, -hardPointZ); - suspension.m_wheelParams[3].m_hardpointChassisSpace.set(hardPointBackX, hardPointY, hardPointZ); + //suspension.m_wheelParams[0].m_hardpointChassisSpace.set(hardPointFrontX, hardPointY, -hardPointZ); + suspension.m_wheelParams[0].m_hardpointChassisSpace.set(-hardPointX, hardPointY, hardPointFrontZ); + //suspension.m_wheelParams[1].m_hardpointChassisSpace.set(hardPointFrontX, hardPointY, hardPointZ); + suspension.m_wheelParams[1].m_hardpointChassisSpace.set(hardPointX, hardPointY, hardPointFrontZ); + //suspension.m_wheelParams[2].m_hardpointChassisSpace.set(hardPointBackX, hardPointY, -hardPointZ); + suspension.m_wheelParams[2].m_hardpointChassisSpace.set(-hardPointX, hardPointY, hardPointBackZ); + //suspension.m_wheelParams[3].m_hardpointChassisSpace.set(hardPointBackX, hardPointY, hardPointZ); + suspension.m_wheelParams[3].m_hardpointChassisSpace.set(hardPointX, hardPointY, hardPointBackZ); } const hkVector4 downDirection(0.0f, -1.0f, 0.0f); From d2f3adb07e95f941729e7643bff1752711f276b6 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 22 Apr 2014 01:46:29 +0200 Subject: [PATCH 04/37] Vehicle keyboard steering! Steering: Direction keys Handbrake: Right control --- src/GameWorld.cpp | 1 + src/Systems/PhysicsSystem.cpp | 11 ++++++++++- src/Systems/PhysicsSystem.h | 1 + 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 2d0c4f3..1b82b1a 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -53,6 +53,7 @@ void GameWorld::Initialize() box->Height = 0.5f; box->Depth = 2.5f; auto vehicle = AddComponent(car, "Vehicle"); + AddComponent(car, "Input"); } for(int i = 0; i < 50; i++) diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index 39d2e93..c7c6306 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -115,7 +115,16 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); } - + // HACK: Vehicle test-controls + auto vehicleComponent = m_World->GetComponent(entity, "Vehicle"); + auto inputComponent = m_World->GetComponent(entity, "Input"); + if (vehicleComponent && inputComponent) + { + hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)m_Vehicles[entity]->m_deviceStatus; + deviceStatus->m_positionY = inputComponent->KeyState[GLFW_KEY_UP] * -1 + inputComponent->KeyState[GLFW_KEY_DOWN] * 1; + deviceStatus->m_positionX = inputComponent->KeyState[GLFW_KEY_LEFT] * -1 + inputComponent->KeyState[GLFW_KEY_RIGHT] * 1; + deviceStatus->m_handbrakeButtonPressed = inputComponent->KeyState[GLFW_KEY_RIGHT_CONTROL]; + } } void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent) diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index 77c4c21..1bbffdd 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -11,6 +11,7 @@ #include "Components/Sphere.h" #include "Components/Box.h" #include "Components/Vehicle.h" +#include "Components/Input.h" // Math and base include From 84d6911744d3793655592ed7b01cfc8bcda18f84 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 22 Apr 2014 15:42:40 +0200 Subject: [PATCH 05/37] Barebones entity component commit events --- src/GameWorld.cpp | 5 +++++ src/System.h | 2 ++ src/World.cpp | 9 +++++++++ src/World.h | 2 ++ 4 files changed, 18 insertions(+) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 62e3980..d3b9aad 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -20,6 +20,7 @@ void GameWorld::Initialize() cameraComp->FarClip = 2000.f; AddComponent(camera, "Input"); auto freeSteering = AddComponent(camera, "FreeSteering"); + CommitEntity(camera); } @@ -38,6 +39,7 @@ void GameWorld::Initialize() auto physics = AddComponent(ground, "Physics"); physics->Mass = 10; + CommitEntity(ground); } { @@ -47,6 +49,7 @@ void GameWorld::Initialize() auto model = AddComponent(TankTest, "Model"); model->ModelFile = "Models/Placeholders/tank/Chassi.obj"; + CommitEntity(TankTest); } for(int i = 0; i < 83; i++) @@ -65,6 +68,7 @@ void GameWorld::Initialize() auto model = AddComponent(light, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; + CommitEntity(light); } for(int i = 0; i < 500; i++) @@ -80,6 +84,7 @@ void GameWorld::Initialize() sphere->Radius = 0.5; auto physics = AddComponent(ball, "Physics"); physics->Mass = 1; + CommitEntity(ball); } /*{ diff --git a/src/System.h b/src/System.h index 0cd3cc7..ff76450 100755 --- a/src/System.h +++ b/src/System.h @@ -28,6 +28,8 @@ public: virtual void OnComponentCreated(std::string type, std::shared_ptr component) { } // Called when a component is removed virtual void OnComponentRemoved(std::string type, Component* component) { } + // Called when components are committed to an entity + virtual void OnEntityCommit(EntityID entity) { } protected: World* m_World; diff --git a/src/World.cpp b/src/World.cpp index 78b297d..0b6a245 100755 --- a/src/World.cpp +++ b/src/World.cpp @@ -148,6 +148,15 @@ std::shared_ptr World::AddComponent(EntityID entity, std::string comp return AddComponent(entity, componentType); } +void World::CommitEntity(EntityID entity) +{ + for (auto pair : m_Systems) + { + auto system = pair.second; + system->OnEntityCommit(entity); + } +} + void World::AddSystem(std::string systemType) { m_Systems[systemType] = std::shared_ptr(m_SystemFactory.Create(systemType)); diff --git a/src/World.h b/src/World.h index 9deeab9..255ef1b 100755 --- a/src/World.h +++ b/src/World.h @@ -63,6 +63,8 @@ public: std::shared_ptr AddComponent(EntityID entity, std::string componentType); template T* GetComponent(EntityID entity, std::string componentType); + // Triggers commit events in systems + void CommitEntity(EntityID entity); /*std::vector GetEntityChildren(EntityID entity);*/ From 4481c95681d45217f8887fb4af6d2a4fe0160869 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Tue, 22 Apr 2014 17:14:29 +0200 Subject: [PATCH 06/37] VehicleSetup componentbased. --- src/Components/Vehicle.h | 10 +- src/Components/Wheel.h | 32 +++ src/GameWorld.cpp | 60 ++++- src/GameWorld.h | 1 + src/Physics/VehicleSetup.cpp | 207 ++++++++---------- src/Physics/VehicleSetup.h | 31 ++- vs11/Returngeance/Returngeance.vcxproj | 1 + .../Returngeance/Returngeance.vcxproj.filters | 3 + 8 files changed, 209 insertions(+), 136 deletions(-) create mode 100644 src/Components/Wheel.h diff --git a/src/Components/Vehicle.h b/src/Components/Vehicle.h index 6ab1498..026c0aa 100644 --- a/src/Components/Vehicle.h +++ b/src/Components/Vehicle.h @@ -8,7 +8,15 @@ namespace Components struct Vehicle : Component { - + Vehicle() + : MaxTorque(500.0f), MinRPM(1000.0f), OptimalRPM(5500.0f), MaxRPM(7500.0f), MaxSteeringAngle(35), TopSpeed(50.0f) { } + float MaxTorque; + float MinRPM; + float OptimalRPM; + float MaxRPM; + // Degrees + float MaxSteeringAngle; + float TopSpeed; }; } diff --git a/src/Components/Wheel.h b/src/Components/Wheel.h new file mode 100644 index 0000000..d5a8d81 --- /dev/null +++ b/src/Components/Wheel.h @@ -0,0 +1,32 @@ +#ifndef Components_Wheel_h__ +#define Components_Wheel_h__ + +#include "Component.h" + +namespace Components +{ + +struct Wheel : Component +{ + Wheel() + : AxleID(0), Radius(0), Width(0), Mass(0), Steering(false), DownDirection(glm::vec3(0, -1, 0)), Friction(1.5f), SlipAngle(0.0f), + MaxBreakingTorque(1500.0f), ConnectedToHandbrake(false), SuspensionStrength(50.0f) { } + + // The Hardpoint MUST be positioned INSIDE the chassis. + glm::vec3 Hardpoint; + unsigned int AxleID; + float Radius; + float Width; + float Mass; + bool Steering; + glm::vec3 DownDirection; + + float SuspensionStrength; + float Friction; + float SlipAngle; + float MaxBreakingTorque; + bool ConnectedToHandbrake; +}; + +} +#endif // Components_Wheel_h__ diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 1b82b1a..ee282f2 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -54,8 +54,60 @@ void GameWorld::Initialize() box->Depth = 2.5f; auto vehicle = AddComponent(car, "Vehicle"); AddComponent(car, "Input"); + + { + // Front Right Wheel + auto ent = CreateEntity(car); + auto transform = AddComponent(ent, "Transform"); + transform->Position = glm::vec3(1.1f, -0.5f, -1.3f); + auto Wheel = AddComponent(ent, "Wheel"); + Wheel->Hardpoint = glm::vec3(1.1f, 0.f, -1.3f);// HACK: make into component + Wheel->AxleID = 0; + Wheel->Mass = 10; + Wheel->Radius = 0.6f; + Wheel->Steering = true; + } + { + // Front Left Wheel + auto ent = CreateEntity(car); + auto transform = AddComponent(ent, "Transform"); + transform->Position = glm::vec3(-1.1f, -0.5f, -1.3f); + auto Wheel = AddComponent(ent, "Wheel"); + Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, -1.3f); + Wheel->AxleID = 0; + Wheel->Mass = 10; + Wheel->Radius = 0.6f; + Wheel->Steering = true; + } + { + // Back Right Wheel + auto ent = CreateEntity(car); + auto transform = AddComponent(ent, "Transform"); + transform->Position = glm::vec3(1.1f, -0.5f, 1.3f); + auto Wheel = AddComponent(ent, "Wheel"); + Wheel->Hardpoint = glm::vec3(1.1f, 0.f, 1.3f); + Wheel->AxleID = 1; + Wheel->Mass = 10; + Wheel->Radius = 0.6f; + Wheel->Steering = false; + } + { + // Back Left Wheel + auto ent = CreateEntity(car); + auto transform = AddComponent(ent, "Transform"); + transform->Position = glm::vec3(-1.1f, -0.5f, 1.3f); + auto Wheel = AddComponent(ent, "Wheel"); + Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, 1.3f); + Wheel->AxleID = 1; + Wheel->Mass = 10; + Wheel->Radius = 0.6f; + Wheel->Steering = false; + } + } + + for(int i = 0; i < 50; i++) { auto ball = CreateEntity(); @@ -71,17 +123,16 @@ void GameWorld::Initialize() box->Width = 5.f; box->Height = 5.f; box->Depth = 5.f; - } - /*{ + { auto entity = CreateEntity(); AddComponent(entity, "Transform"); auto emitter = AddComponent(entity, "SoundEmitter"); emitter->Path = "Sounds/korvring.wav"; emitter->Loop = true; GetSystem("SoundSystem")->PlaySound(emitter); - }*/ + } } void GameWorld::Update(double dt) @@ -102,12 +153,11 @@ void GameWorld::RegisterComponents() m_ComponentFactory.Register("Template", []() { return new Components::Template(); }); m_ComponentFactory.Register("Transform", []() { return new Components::Transform(); }); m_ComponentFactory.Register("FreeSteering", []() { return new Components::FreeSteering(); }); - m_ComponentFactory.Register("Physics", []() { return new Components::Physics(); }); m_ComponentFactory.Register("Sphere", []() { return new Components::Sphere(); }); m_ComponentFactory.Register("Box", []() { return new Components::Box (); }); - m_ComponentFactory.Register("Vehicle", []() { return new Components::Vehicle(); }); + m_ComponentFactory.Register("Wheel", []() { return new Components::Wheel(); }); } void GameWorld::RegisterSystems() diff --git a/src/GameWorld.h b/src/GameWorld.h index 2945556..647e784 100755 --- a/src/GameWorld.h +++ b/src/GameWorld.h @@ -31,6 +31,7 @@ #include "Components/Sphere.h" #include "Components/Box.h" #include "Components/Vehicle.h" +#include "Components/Wheel.h" class GameWorld : public World { diff --git a/src/Physics/VehicleSetup.cpp b/src/Physics/VehicleSetup.cpp index d40fb0e..559882e 100644 --- a/src/Physics/VehicleSetup.cpp +++ b/src/Physics/VehicleSetup.cpp @@ -3,12 +3,23 @@ -void VehicleSetup::buildVehicle(const hkpWorld* world, hkpVehicleInstance& vehicle) + + +void VehicleSetup::buildVehicle(World *world, const hkpWorld* physicsWorld, hkpVehicleInstance& vehicle, EntityID vehicleEntity, std::vector wheelEntities) { + auto vehicleComponent = world->GetComponent(vehicleEntity, "Vehicle"); + + WheelData wheelData; + for (int i = 0; i < wheelEntities.size(); i++) + { + wheelData.WheelComponent = world->GetComponent(wheelEntities[i], "Wheel"); + wheelData.TransformComponent = world->GetComponent(wheelEntities[i], "Transform"); + m_Wheels.push_back(wheelData); + } + // // All memory allocations are made here. // - vehicle.m_data = new hkpVehicleData; vehicle.m_driverInput = new hkpVehicleDefaultAnalogDriverInput; vehicle.m_steering = new hkpVehicleDefaultSteering; @@ -23,25 +34,25 @@ void VehicleSetup::buildVehicle(const hkpWorld* world, hkpVehicleInstance& vehic // which implements varying 'ground' friction in a very simple way. vehicle.m_wheelCollide = new hkpVehicleRayCastWheelCollide; - setupVehicleData(world, *vehicle.m_data); + setupVehicleData(physicsWorld, *vehicle.m_data); setupComponent(*vehicle.m_data, *static_cast(vehicle.m_driverInput)); - setupComponent(*vehicle.m_data, *static_cast(vehicle.m_steering)); - setupComponent(*vehicle.m_data, *static_cast(vehicle.m_engine)); - setupComponent(*vehicle.m_data, *static_cast(vehicle.m_transmission)); - setupComponent(*vehicle.m_data, *static_cast(vehicle.m_brake)); - setupComponent(*vehicle.m_data, *static_cast(vehicle.m_suspension)); - setupComponent(*vehicle.m_data, *static_cast(vehicle.m_aerodynamics)); - setupComponent(*vehicle.m_data, *static_cast(vehicle.m_velocityDamper)); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_steering), *vehicleComponent); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_engine), *vehicleComponent); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_transmission), *vehicleComponent); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_brake), *vehicleComponent); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_suspension), *vehicleComponent); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_aerodynamics), *vehicleComponent); + setupComponent(*vehicle.m_data, *static_cast(vehicle.m_velocityDamper), *vehicleComponent); - setupWheelCollide(world, vehicle, *static_cast(vehicle.m_wheelCollide)); + setupWheelCollide(physicsWorld, vehicle, *static_cast(vehicle.m_wheelCollide)); // // Check that all components are present. // - HK_ASSERT(0x0, vehicle.m_data); + HK_ASSERT(0x0 , vehicle.m_data); HK_ASSERT(0x7708674a, vehicle.m_driverInput); HK_ASSERT(0x5a324a2d, vehicle.m_steering); HK_ASSERT(0x7bcb2aff, vehicle.m_engine); @@ -73,7 +84,7 @@ void VehicleSetup::buildVehicle(const hkpWorld* world, hkpVehicleInstance& vehic vehicle.init(); } -void VehicleSetup::setupVehicleData(const hkpWorld* world, hkpVehicleData& data) +void VehicleSetup::setupVehicleData(const hkpWorld* world, hkpVehicleData& data ) { data.m_gravity = world->getGravity(); @@ -107,39 +118,33 @@ void VehicleSetup::setupVehicleData(const hkpWorld* world, hkpVehicleData& data) // // Wheel specifications // - data.m_numWheels = 4; + data.m_numWheels = m_Wheels.size(); data.m_wheelParams.setSize(data.m_numWheels); - data.m_wheelParams[0].m_axle = 0; - data.m_wheelParams[1].m_axle = 0; - data.m_wheelParams[2].m_axle = 1; - data.m_wheelParams[3].m_axle = 1; - - data.m_wheelParams[0].m_friction = 1.5f; - data.m_wheelParams[1].m_friction = 1.5f; - data.m_wheelParams[2].m_friction = 1.5f; - data.m_wheelParams[3].m_friction = 1.5f; - - data.m_wheelParams[0].m_slipAngle = 0.0f; - data.m_wheelParams[1].m_slipAngle = 0.0f; - data.m_wheelParams[2].m_slipAngle = 0.0f; - data.m_wheelParams[3].m_slipAngle = 0.0f; - - for (int i = 0; i < data.m_numWheels; i++) + for (int i = 0; i < m_Wheels.size(); i++) { - // This value is also used to calculate the m_primaryTransmissionRatio. - data.m_wheelParams[i].m_radius = 0.6f; - data.m_wheelParams[i].m_width = 0.3f; - data.m_wheelParams[i].m_mass = 10.0f; + data.m_wheelParams[i].m_axle = m_Wheels[i].WheelComponent->AxleID; + data.m_wheelParams[i].m_friction = m_Wheels[i].WheelComponent->Friction; + data.m_wheelParams[i].m_slipAngle = m_Wheels[i].WheelComponent->SlipAngle; + // This value is also used to calculate the m_primaryTransmissionRatio. + data.m_wheelParams[i].m_radius = m_Wheels[i].WheelComponent->Radius; + data.m_wheelParams[i].m_width = m_Wheels[i].WheelComponent->Width; + data.m_wheelParams[i].m_mass = m_Wheels[i].WheelComponent->Mass; + + + // May be in wheelcomponent later data.m_wheelParams[i].m_viscosityFriction = 0.25f; data.m_wheelParams[i].m_maxFriction = 2.0f * data.m_wheelParams[i].m_friction; data.m_wheelParams[i].m_forceFeedbackMultiplier = 0.1f; data.m_wheelParams[i].m_maxContactBodyAcceleration = hkReal(data.m_gravity.length3()) * 2; } -} + + + +} void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultAnalogDriverInput& driverInput) { @@ -151,45 +156,46 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultA driverInput.m_autoReverse = true; } -void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultSteering& steering) +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultSteering& steering, Components::Vehicle vehicleComponent ) { steering.m_doesWheelSteer.setSize(data.m_numWheels); // degrees - steering.m_maxSteeringAngle = 35 * (HK_REAL_PI / 180); + steering.m_maxSteeringAngle = vehicleComponent.MaxSteeringAngle * (HK_REAL_PI / 180); // [mph/h] The steering angle decreases linearly // based on your overall max speed of the vehicle. - steering.m_maxSpeedFullSteeringAngle = 70.0f * (1.605f / 3.6f); - steering.m_doesWheelSteer[0] = true; - steering.m_doesWheelSteer[1] = true; - steering.m_doesWheelSteer[2] = false; - steering.m_doesWheelSteer[3] = false; + steering.m_maxSpeedFullSteeringAngle = 70.0f * (1.605f / 3.6f); //MPH???! + + for (int i = 0; i < m_Wheels.size(); i++) + { + steering.m_doesWheelSteer[i] = m_Wheels[i].WheelComponent->Steering; + } } -void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultEngine& engine) +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultEngine& engine, Components::Vehicle vehicleComponent) { - engine.m_maxTorque = 500.0f; + engine.m_maxTorque = vehicleComponent.MaxTorque; - engine.m_minRPM = 1000.0f; - engine.m_optRPM = 5500.0f; + engine.m_minRPM = vehicleComponent.MinRPM; + engine.m_optRPM = vehicleComponent.OptimalRPM; // This value is also used to calculate the m_primaryTransmissionRatio. - engine.m_maxRPM = 7500.0f; + engine.m_maxRPM = vehicleComponent.MaxRPM; + + engine.m_torqueFactorAtMinRPM = 0.8f; engine.m_torqueFactorAtMaxRPM = 0.8f; - engine.m_resistanceFactorAtMinRPM = 0.05f; engine.m_resistanceFactorAtOptRPM = 0.1f; engine.m_resistanceFactorAtMaxRPM = 0.3f; } -void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultTransmission& transmission) +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultTransmission& transmission, Components::Vehicle vehicleComponent ) { - int numGears = 4; - - transmission.m_gearsRatio.setSize(numGears); + int numberOfGears = 4; + transmission.m_gearsRatio.setSize(numberOfGears); transmission.m_wheelsTorqueRatio.setSize(data.m_numWheels); transmission.m_downshiftRPM = 3500.0f; @@ -206,91 +212,52 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultT transmission.m_wheelsTorqueRatio[2] = 0.3f; transmission.m_wheelsTorqueRatio[3] = 0.3f; - const hkReal vehicleTopSpeed = 50.0f; - const hkReal wheelRadius = 0.6f; - const hkReal maxEngineRpm = 7500.0f; - transmission.m_primaryTransmissionRatio = hkpVehicleDefaultTransmission::calculatePrimaryTransmissionRatio(vehicleTopSpeed, - wheelRadius, - maxEngineRpm, - transmission.m_gearsRatio[numGears - 1]); + + transmission.m_primaryTransmissionRatio = hkpVehicleDefaultTransmission::calculatePrimaryTransmissionRatio( + vehicleComponent.TopSpeed, + m_Wheels[0].WheelComponent->Radius, // HACK: All wheels are the same size right? + vehicleComponent.MaxRPM, + transmission.m_gearsRatio[numberOfGears - 1]); } -void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultBrake& brake) +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultBrake& brake, Components::Vehicle vehicleComponent ) { brake.m_wheelBrakingProperties.setSize(data.m_numWheels); - const float bt = 1500.0f; - brake.m_wheelBrakingProperties[0].m_maxBreakingTorque = bt; - brake.m_wheelBrakingProperties[1].m_maxBreakingTorque = bt; - brake.m_wheelBrakingProperties[2].m_maxBreakingTorque = bt; - brake.m_wheelBrakingProperties[3].m_maxBreakingTorque = bt; + for (int i = 0; i < m_Wheels.size(); i++) + { + brake.m_wheelBrakingProperties[i].m_maxBreakingTorque = m_Wheels[i].WheelComponent->MaxBreakingTorque; + brake.m_wheelBrakingProperties[i].m_isConnectedToHandbrake = m_Wheels[i].WheelComponent->ConnectedToHandbrake; + + brake.m_wheelBrakingProperties[i].m_minPedalInputToBlock = 0.9f; + } - // Handbrake is attached to rear wheels only. - brake.m_wheelBrakingProperties[0].m_isConnectedToHandbrake = false; - brake.m_wheelBrakingProperties[1].m_isConnectedToHandbrake = false; - brake.m_wheelBrakingProperties[2].m_isConnectedToHandbrake = true; - brake.m_wheelBrakingProperties[3].m_isConnectedToHandbrake = true; - brake.m_wheelBrakingProperties[0].m_minPedalInputToBlock = 0.9f; - brake.m_wheelBrakingProperties[1].m_minPedalInputToBlock = 0.9f; - brake.m_wheelBrakingProperties[2].m_minPedalInputToBlock = 0.9f; - brake.m_wheelBrakingProperties[3].m_minPedalInputToBlock = 0.9f; brake.m_wheelsMinTimeToBlock = 1000.0f; } -void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultSuspension& suspension) +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultSuspension& suspension, Components::Vehicle vehicleComponent) { suspension.m_wheelParams.setSize(data.m_numWheels); suspension.m_wheelSpringParams.setSize(data.m_numWheels); - suspension.m_wheelParams[0].m_length = 0.35f; - suspension.m_wheelParams[1].m_length = 0.35f; - suspension.m_wheelParams[2].m_length = 0.35f; - suspension.m_wheelParams[3].m_length = 0.35f; - - const float str = 50.0f; - suspension.m_wheelSpringParams[0].m_strength = str; - suspension.m_wheelSpringParams[1].m_strength = str; - suspension.m_wheelSpringParams[2].m_strength = str; - suspension.m_wheelSpringParams[3].m_strength = str; - - const float wd = 3.0f; - suspension.m_wheelSpringParams[0].m_dampingCompression = wd; - suspension.m_wheelSpringParams[1].m_dampingCompression = wd; - suspension.m_wheelSpringParams[2].m_dampingCompression = wd; - suspension.m_wheelSpringParams[3].m_dampingCompression = wd; - - suspension.m_wheelSpringParams[0].m_dampingRelaxation = wd; - suspension.m_wheelSpringParams[1].m_dampingRelaxation = wd; - suspension.m_wheelSpringParams[2].m_dampingRelaxation = wd; - suspension.m_wheelSpringParams[3].m_dampingRelaxation = wd; - - // - // NB: The hardpoints MUST be positioned INSIDE the chassis. - // + for (int i = 0; i < m_Wheels.size(); i++) { - const hkReal hardPointFrontZ = -1.3f; - const hkReal hardPointBackZ = 1.1f; - const hkReal hardPointY = -0.05f; - const hkReal hardPointX = 1.1f; + float suspensionLength = glm::length(m_Wheels[i].TransformComponent->Position - m_Wheels[i].WheelComponent->Hardpoint); + suspension.m_wheelParams[i].m_length = suspensionLength; + suspension.m_wheelSpringParams[i].m_strength = m_Wheels[i].WheelComponent->SuspensionStrength; - //suspension.m_wheelParams[0].m_hardpointChassisSpace.set(hardPointFrontX, hardPointY, -hardPointZ); - suspension.m_wheelParams[0].m_hardpointChassisSpace.set(-hardPointX, hardPointY, hardPointFrontZ); - //suspension.m_wheelParams[1].m_hardpointChassisSpace.set(hardPointFrontX, hardPointY, hardPointZ); - suspension.m_wheelParams[1].m_hardpointChassisSpace.set(hardPointX, hardPointY, hardPointFrontZ); - //suspension.m_wheelParams[2].m_hardpointChassisSpace.set(hardPointBackX, hardPointY, -hardPointZ); - suspension.m_wheelParams[2].m_hardpointChassisSpace.set(-hardPointX, hardPointY, hardPointBackZ); - //suspension.m_wheelParams[3].m_hardpointChassisSpace.set(hardPointBackX, hardPointY, hardPointZ); - suspension.m_wheelParams[3].m_hardpointChassisSpace.set(hardPointX, hardPointY, hardPointBackZ); + const float wd = 3.0f; + suspension.m_wheelSpringParams[i].m_dampingCompression = wd; + suspension.m_wheelSpringParams[i].m_dampingRelaxation = wd; + + + suspension.m_wheelParams[i].m_hardpointChassisSpace.set(m_Wheels[i].WheelComponent->Hardpoint.x, m_Wheels[i].WheelComponent->Hardpoint.y, m_Wheels[i].WheelComponent->Hardpoint.z); + + suspension.m_wheelParams[0].m_directionChassisSpace = hkVector4(m_Wheels[i].WheelComponent->DownDirection.x, m_Wheels[i].WheelComponent->DownDirection.y, m_Wheels[i].WheelComponent->DownDirection.z); } - - const hkVector4 downDirection(0.0f, -1.0f, 0.0f); - suspension.m_wheelParams[0].m_directionChassisSpace = downDirection; - suspension.m_wheelParams[1].m_directionChassisSpace = downDirection; - suspension.m_wheelParams[2].m_directionChassisSpace = downDirection; - suspension.m_wheelParams[3].m_directionChassisSpace = downDirection; } -void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultAerodynamics& aerodynamics) +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultAerodynamics& aerodynamics, Components::Vehicle vehicleComponent ) { aerodynamics.m_airDensity = 1.3f; // In m^2. @@ -303,7 +270,7 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultA aerodynamics.m_extraGravityws.set(0.0f, -5.0f, 0.0f); } -void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper) +void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper, Components::Vehicle vehicleComponent) { // Caution: setting negative damping values will add energy to system. // Setting the value to 0 will not affect the angular velocity. diff --git a/src/Physics/VehicleSetup.h b/src/Physics/VehicleSetup.h index 2a0ce95..b54adbd 100644 --- a/src/Physics/VehicleSetup.h +++ b/src/Physics/VehicleSetup.h @@ -24,27 +24,38 @@ #include #include #include - #include - #include +#include "World.h" +#include "Components/Vehicle.h" +#include "Components/Wheel.h" +#include "Components/Transform.h" + class VehicleSetup { public: - virtual void buildVehicle(const hkpWorld* world, hkpVehicleInstance& vehicle); + virtual void VehicleSetup::buildVehicle(World *world, const hkpWorld* physicsWorld, hkpVehicleInstance& vehicle, EntityID vehicleEntity, std::vector wheelEntities); public: + struct WheelData + { + Components::Wheel* WheelComponent; + Components::Transform* TransformComponent; + }; + + std::vector m_Wheels; virtual void setupVehicleData(const hkpWorld* world, hkpVehicleData& data); virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultAnalogDriverInput& driverInput); - virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultSteering& steering); - virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultEngine& engine); - virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultTransmission& transmission); - virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultBrake& brake); - virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultSuspension& suspension); - virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultAerodynamics& aerodynamics); - virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultEngine& engine, Components::Vehicle vehicleComponent); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultSteering& steering, Components::Vehicle vehicleComponent); + + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultTransmission& transmission, Components::Vehicle vehicleComponent); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultBrake& brake, Components::Vehicle vehicleComponent ); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultSuspension& suspension, Components::Vehicle vehicleComponent); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultAerodynamics& aerodynamics, Components::Vehicle vehicleComponent ); + virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper, Components::Vehicle vehicleComponent); virtual void setupWheelCollide(const hkpWorld* world, const hkpVehicleInstance& vehicle, hkpVehicleRayCastWheelCollide& wheelCollide); }; diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 7145402..ddea963 100644 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -135,6 +135,7 @@ + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 2b30567..7088b19 100644 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -151,6 +151,9 @@ Physics + + Components + From f0b2f2a6595c97eb0c25a896aa11b5e61961516c Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Tue, 22 Apr 2014 17:18:54 +0200 Subject: [PATCH 07/37] Barebones entity component commit events Conflicts: src/GameWorld.cpp --- src/GameWorld.cpp | 10 ++++++++++ src/System.h | 2 ++ src/World.cpp | 9 +++++++++ src/World.h | 2 ++ 4 files changed, 23 insertions(+) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index ee282f2..7da4e68 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -16,6 +16,7 @@ void GameWorld::Initialize() cameraComp->FarClip = 2000.f; AddComponent(camera, "Input"); auto freeSteering = AddComponent(camera, "FreeSteering"); + CommitEntity(camera); } @@ -35,6 +36,8 @@ void GameWorld::Initialize() auto physics = AddComponent(ground, "Physics"); physics->Mass = 10; physics->Static = true; + + CommitEntity(ground); } @@ -66,6 +69,7 @@ void GameWorld::Initialize() Wheel->Mass = 10; Wheel->Radius = 0.6f; Wheel->Steering = true; + CommitEntity(ent); } { // Front Left Wheel @@ -78,6 +82,7 @@ void GameWorld::Initialize() Wheel->Mass = 10; Wheel->Radius = 0.6f; Wheel->Steering = true; + CommitEntity(ent); } { // Back Right Wheel @@ -90,6 +95,7 @@ void GameWorld::Initialize() Wheel->Mass = 10; Wheel->Radius = 0.6f; Wheel->Steering = false; + CommitEntity(ent); } { // Back Left Wheel @@ -102,8 +108,10 @@ void GameWorld::Initialize() Wheel->Mass = 10; Wheel->Radius = 0.6f; Wheel->Steering = false; + CommitEntity(ent); } + CommitEntity(car); } @@ -123,6 +131,7 @@ void GameWorld::Initialize() box->Width = 5.f; box->Height = 5.f; box->Depth = 5.f; + CommitEntity(ball); } { @@ -132,6 +141,7 @@ void GameWorld::Initialize() emitter->Path = "Sounds/korvring.wav"; emitter->Loop = true; GetSystem("SoundSystem")->PlaySound(emitter); + CommitEntity(entity); } } diff --git a/src/System.h b/src/System.h index cbe9cb8..d433871 100755 --- a/src/System.h +++ b/src/System.h @@ -24,6 +24,8 @@ public: virtual void OnComponentCreated(std::string type, std::shared_ptr component) { } // Called when a component is removed virtual void OnComponentRemoved(std::string type, Component* component) { } + // Called when components are committed to an entity + virtual void OnEntityCommit(EntityID entity) { } protected: World* m_World; diff --git a/src/World.cpp b/src/World.cpp index d7a8ee4..49a5c3b 100755 --- a/src/World.cpp +++ b/src/World.cpp @@ -147,6 +147,15 @@ std::shared_ptr World::AddComponent(EntityID entity, std::string comp return AddComponent(entity, componentType); } +void World::CommitEntity(EntityID entity) +{ + for (auto pair : m_Systems) + { + auto system = pair.second; + system->OnEntityCommit(entity); + } +} + void World::AddSystem(std::string systemType) { m_Systems[systemType] = std::shared_ptr(m_SystemFactory.Create(systemType)); diff --git a/src/World.h b/src/World.h index bae324e..0d15b89 100755 --- a/src/World.h +++ b/src/World.h @@ -64,6 +64,8 @@ public: std::shared_ptr AddComponent(EntityID entity, std::string componentType); template T* GetComponent(EntityID entity, std::string componentType); + // Triggers commit events in systems + void CommitEntity(EntityID entity); /*std::vector GetEntityChildren(EntityID entity);*/ From eb6cc266a3ad9dd8e57a8172a676ff1131843a2d Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Tue, 22 Apr 2014 19:14:35 +0200 Subject: [PATCH 08/37] Vehicle component based, wheel rotation and position not working. --- src/Components/Vehicle.h | 6 +- src/Components/Wheel.h | 7 + src/GameWorld.cpp | 27 +++- src/GameWorld.cpp.orig | 233 ++++++++++++++++++++++++++++++++++ src/Physics/VehicleSetup.cpp | 2 +- src/Systems/PhysicsSystem.cpp | 149 ++++++++++++++++++++-- src/Systems/PhysicsSystem.h | 4 +- 7 files changed, 410 insertions(+), 18 deletions(-) create mode 100644 src/GameWorld.cpp.orig diff --git a/src/Components/Vehicle.h b/src/Components/Vehicle.h index 026c0aa..e61c713 100644 --- a/src/Components/Vehicle.h +++ b/src/Components/Vehicle.h @@ -3,13 +3,15 @@ #include "Component.h" + namespace Components { - struct Vehicle : Component -{ +struct Vehicle : Component +{ Vehicle() : MaxTorque(500.0f), MinRPM(1000.0f), OptimalRPM(5500.0f), MaxRPM(7500.0f), MaxSteeringAngle(35), TopSpeed(50.0f) { } + float MaxTorque; float MinRPM; float OptimalRPM; diff --git a/src/Components/Wheel.h b/src/Components/Wheel.h index d5a8d81..f000058 100644 --- a/src/Components/Wheel.h +++ b/src/Components/Wheel.h @@ -3,11 +3,15 @@ #include "Component.h" +namespace Systems { class PhysicsSystem; } + namespace Components { struct Wheel : Component { + friend class Systems::PhysicsSystem; + Wheel() : AxleID(0), Radius(0), Width(0), Mass(0), Steering(false), DownDirection(glm::vec3(0, -1, 0)), Friction(1.5f), SlipAngle(0.0f), MaxBreakingTorque(1500.0f), ConnectedToHandbrake(false), SuspensionStrength(50.0f) { } @@ -26,6 +30,9 @@ struct Wheel : Component float SlipAngle; float MaxBreakingTorque; bool ConnectedToHandbrake; + +private: + int ID; }; } diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 7da4e68..6c9e5d4 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -41,10 +41,11 @@ void GameWorld::Initialize() } + for (int i = 0; i < 1; i++) { auto car = CreateEntity(); auto transform = AddComponent(car, "Transform"); - transform->Position = glm::vec3(0, 5, 0); + transform->Position = glm::vec3(0, (i+1)*5, 0); transform->Scale = glm::vec3(3, 1, 5); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(car, "Model"); @@ -56,58 +57,74 @@ void GameWorld::Initialize() box->Height = 0.5f; box->Depth = 2.5f; auto vehicle = AddComponent(car, "Vehicle"); + vehicle->TopSpeed = 500.f; + vehicle->MaxTorque = 1000.f; AddComponent(car, "Input"); { // Front Right Wheel auto ent = CreateEntity(car); auto transform = AddComponent(ent, "Transform"); + transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); transform->Position = glm::vec3(1.1f, -0.5f, -1.3f); auto Wheel = AddComponent(ent, "Wheel"); Wheel->Hardpoint = glm::vec3(1.1f, 0.f, -1.3f);// HACK: make into component Wheel->AxleID = 0; Wheel->Mass = 10; - Wheel->Radius = 0.6f; + Wheel->Radius = 0.5f; Wheel->Steering = true; + auto model = AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; CommitEntity(ent); } { // Front Left Wheel auto ent = CreateEntity(car); auto transform = AddComponent(ent, "Transform"); + transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); transform->Position = glm::vec3(-1.1f, -0.5f, -1.3f); auto Wheel = AddComponent(ent, "Wheel"); Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, -1.3f); Wheel->AxleID = 0; Wheel->Mass = 10; - Wheel->Radius = 0.6f; + Wheel->Radius = 0.5f; Wheel->Steering = true; + auto model = AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; CommitEntity(ent); } { // Back Right Wheel auto ent = CreateEntity(car); auto transform = AddComponent(ent, "Transform"); + transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); transform->Position = glm::vec3(1.1f, -0.5f, 1.3f); auto Wheel = AddComponent(ent, "Wheel"); Wheel->Hardpoint = glm::vec3(1.1f, 0.f, 1.3f); Wheel->AxleID = 1; Wheel->Mass = 10; - Wheel->Radius = 0.6f; + Wheel->Radius = 0.5f; Wheel->Steering = false; + Wheel->ConnectedToHandbrake = true; + auto model = AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; CommitEntity(ent); } { // Back Left Wheel auto ent = CreateEntity(car); auto transform = AddComponent(ent, "Transform"); + transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); transform->Position = glm::vec3(-1.1f, -0.5f, 1.3f); auto Wheel = AddComponent(ent, "Wheel"); Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, 1.3f); Wheel->AxleID = 1; Wheel->Mass = 10; - Wheel->Radius = 0.6f; + Wheel->Radius = 0.5f; Wheel->Steering = false; + Wheel->ConnectedToHandbrake = true; + auto model = AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; CommitEntity(ent); } diff --git a/src/GameWorld.cpp.orig b/src/GameWorld.cpp.orig new file mode 100644 index 0000000..73aac8b --- /dev/null +++ b/src/GameWorld.cpp.orig @@ -0,0 +1,233 @@ +#include "PrecompiledHeader.h" +#include "GameWorld.h" + +void GameWorld::Initialize() +{ + World::Initialize(); + + + { + auto camera = CreateEntity(); + auto transform = AddComponent(camera, "Transform"); + transform->Position.z = 20.f; + transform->Position.y = 20.f; + transform->Orientation = glm::quat(glm::vec3(glm::pi() / 8.f, 0.f, 0.f)); + auto cameraComp = AddComponent(camera, "Camera"); + cameraComp->FarClip = 2000.f; + AddComponent(camera, "Input"); + auto freeSteering = AddComponent(camera, "FreeSteering"); + CommitEntity(camera); + } + + + { + auto ground = CreateEntity(); + auto transform = AddComponent(ground, "Transform"); + transform->Position = glm::vec3(0, -5, 0); + transform->Scale = glm::vec3(1000.0f, 10.0f, 1000.0f); + transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); + auto model = AddComponent(ground, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube.obj"; + auto box = AddComponent(ground, "Box"); + box->Width = 500; + box->Height = 5; + box->Depth = 500; + + auto physics = AddComponent(ground, "Physics"); + physics->Mass = 10; +<<<<<<< HEAD + physics->Static = true; +======= + CommitEntity(ground); +>>>>>>> 84d6911... Barebones entity component commit events + } + + + { + auto car = CreateEntity(); + auto transform = AddComponent(car, "Transform"); + transform->Position = glm::vec3(0, 5, 0); + transform->Scale = glm::vec3(3, 1, 5); + transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); + auto model = AddComponent(car, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + auto physics = AddComponent(car, "Physics"); + physics->Mass = 1200; + auto box = AddComponent(car, "Box"); + box->Width = 1.5f; + box->Height = 0.5f; + box->Depth = 2.5f; + auto vehicle = AddComponent(car, "Vehicle"); + AddComponent(car, "Input"); + + { + // Front Right Wheel + auto ent = CreateEntity(car); + auto transform = AddComponent(ent, "Transform"); + transform->Position = glm::vec3(1.1f, -0.5f, -1.3f); + auto Wheel = AddComponent(ent, "Wheel"); + Wheel->Hardpoint = glm::vec3(1.1f, 0.f, -1.3f);// HACK: make into component + Wheel->AxleID = 0; + Wheel->Mass = 10; + Wheel->Radius = 0.6f; + Wheel->Steering = true; + } + { + // Front Left Wheel + auto ent = CreateEntity(car); + auto transform = AddComponent(ent, "Transform"); + transform->Position = glm::vec3(-1.1f, -0.5f, -1.3f); + auto Wheel = AddComponent(ent, "Wheel"); + Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, -1.3f); + Wheel->AxleID = 0; + Wheel->Mass = 10; + Wheel->Radius = 0.6f; + Wheel->Steering = true; + } + { + // Back Right Wheel + auto ent = CreateEntity(car); + auto transform = AddComponent(ent, "Transform"); + transform->Position = glm::vec3(1.1f, -0.5f, 1.3f); + auto Wheel = AddComponent(ent, "Wheel"); + Wheel->Hardpoint = glm::vec3(1.1f, 0.f, 1.3f); + Wheel->AxleID = 1; + Wheel->Mass = 10; + Wheel->Radius = 0.6f; + Wheel->Steering = false; + } + { + // Back Left Wheel + auto ent = CreateEntity(car); + auto transform = AddComponent(ent, "Transform"); + transform->Position = glm::vec3(-1.1f, -0.5f, 1.3f); + auto Wheel = AddComponent(ent, "Wheel"); + Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, 1.3f); + Wheel->AxleID = 1; + Wheel->Mass = 10; + Wheel->Radius = 0.6f; + Wheel->Steering = false; + } + +<<<<<<< HEAD + } + +======= + auto model = AddComponent(TankTest, "Model"); + model->ModelFile = "Models/Placeholders/tank/Chassi.obj"; + CommitEntity(TankTest); + } + + for(int i = 0; i < 83; i++) + { + auto light = CreateEntity(); + auto transform = AddComponent(light, "Transform"); + transform->Position = glm::vec3((float)(2*i)*glm::sin((float)i), 3, (float)(2*i)*glm::cos((float)i)); + + auto pointLight = AddComponent(light, "PointLight"); + pointLight->Specular = glm::vec3(0.1f, 0.1f, 0.1f); + pointLight->Diffuse = glm::vec3(0.05f, 0.36f, 1.f); + pointLight->constantAttenuation = 0.03f; + pointLight->linearAttenuation = 0.009f; + pointLight->quadraticAttenuation = 0.07f; + pointLight->spotExponent = 0.0f; + + auto model = AddComponent(light, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; + CommitEntity(light); + } +>>>>>>> 84d6911... Barebones entity component commit events + + + for(int i = 0; i < 50; i++) + { + auto ball = CreateEntity(); + auto transform = AddComponent(ball, "Transform"); + transform->Position = glm::vec3(243, 10 + i*10, 0); + transform->Scale = glm::vec3(10); + transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); + auto model = AddComponent(ball, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + auto physics = AddComponent(ball, "Physics"); +<<<<<<< HEAD + physics->Mass = 100; + auto box = AddComponent(ball, "Box"); + box->Width = 5.f; + box->Height = 5.f; + box->Depth = 5.f; +======= + physics->Mass = 1; + CommitEntity(ball); +>>>>>>> 84d6911... Barebones entity component commit events + } + + { + auto entity = CreateEntity(); + AddComponent(entity, "Transform"); + auto emitter = AddComponent(entity, "SoundEmitter"); + emitter->Path = "Sounds/korvring.wav"; + emitter->Loop = true; + GetSystem("SoundSystem")->PlaySound(emitter); + } +} + +void GameWorld::Update(double dt) +{ + World::Update(dt); +} + +void GameWorld::RegisterComponents() +{ + m_ComponentFactory.Register("Camera", []() { return new Components::Camera(); }); + m_ComponentFactory.Register("DirectionalLight", []() { return new Components::DirectionalLight(); }); + m_ComponentFactory.Register("Input", []() { return new Components::Input(); }); + m_ComponentFactory.Register("Model", []() { return new Components::Model(); }); + m_ComponentFactory.Register("ParticleEmitter", []() { return new Components::ParticleEmitter(); }); + m_ComponentFactory.Register("PointLight", []() { return new Components::PointLight(); }); + m_ComponentFactory.Register("SoundEmitter", []() { return new Components::SoundEmitter(); }); + m_ComponentFactory.Register("Sprite", []() { return new Components::Sprite(); }); + m_ComponentFactory.Register("Template", []() { return new Components::Template(); }); + m_ComponentFactory.Register("Transform", []() { return new Components::Transform(); }); + m_ComponentFactory.Register("FreeSteering", []() { return new Components::FreeSteering(); }); + m_ComponentFactory.Register("Physics", []() { return new Components::Physics(); }); + m_ComponentFactory.Register("Sphere", []() { return new Components::Sphere(); }); + m_ComponentFactory.Register("Box", []() { return new Components::Box (); }); + m_ComponentFactory.Register("Vehicle", []() { return new Components::Vehicle(); }); + m_ComponentFactory.Register("Wheel", []() { return new Components::Wheel(); }); +} + +void GameWorld::RegisterSystems() +{ + m_SystemFactory.Register("TransformSystem", [this]() { return new Systems::TransformSystem(this); }); + //m_SystemFactory.Register("LevelGenerationSystem", [this]() { return new Systems::LevelGenerationSystem(this); }); + m_SystemFactory.Register("InputSystem", [this]() { return new Systems::InputSystem(this, m_Renderer); }); + //m_SystemFactory.Register("CollisionSystem", [this]() { return new Systems::CollisionSystem(this); }); + ////m_SystemFactory.Register("ParticleSystem", [this]() { return new Systems::ParticleSystem(this); }); + //m_SystemFactory.Register("PlayerSystem", [this]() { return new Systems::PlayerSystem(this); }); + m_SystemFactory.Register("FreeSteeringSystem", [this]() { return new Systems::FreeSteeringSystem(this); }); + m_SystemFactory.Register("SoundSystem", [this]() { return new Systems::SoundSystem(this); }); + + m_SystemFactory.Register("PhysicsSystem", [this]() { return new Systems::PhysicsSystem(this); }); + + m_SystemFactory.Register("RenderSystem", [this]() { return new Systems::RenderSystem(this, m_Renderer); }); + + +} + +void GameWorld::AddSystems() +{ + AddSystem("TransformSystem"); + //AddSystem("LevelGenerationSystem"); + AddSystem("InputSystem"); + //AddSystem("CollisionSystem"); + ////AddSystem("ParticleSystem"); + //AddSystem("PlayerSystem"); + AddSystem("FreeSteeringSystem"); + AddSystem("SoundSystem"); + + AddSystem("PhysicsSystem"); + + AddSystem("RenderSystem"); + + +} \ No newline at end of file diff --git a/src/Physics/VehicleSetup.cpp b/src/Physics/VehicleSetup.cpp index 559882e..1768b1e 100644 --- a/src/Physics/VehicleSetup.cpp +++ b/src/Physics/VehicleSetup.cpp @@ -253,7 +253,7 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultS suspension.m_wheelParams[i].m_hardpointChassisSpace.set(m_Wheels[i].WheelComponent->Hardpoint.x, m_Wheels[i].WheelComponent->Hardpoint.y, m_Wheels[i].WheelComponent->Hardpoint.z); - suspension.m_wheelParams[0].m_directionChassisSpace = hkVector4(m_Wheels[i].WheelComponent->DownDirection.x, m_Wheels[i].WheelComponent->DownDirection.y, m_Wheels[i].WheelComponent->DownDirection.z); + suspension.m_wheelParams[i].m_directionChassisSpace = hkVector4(m_Wheels[i].WheelComponent->DownDirection.x, m_Wheels[i].WheelComponent->DownDirection.y, m_Wheels[i].WheelComponent->DownDirection.z); } } diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index c7c6306..0ba5a2e 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -102,18 +102,36 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p auto transformComponent = m_World->GetComponent(entity, "Transform"); if (!transformComponent) return; - - if (m_RigidBodies.find(entity) == m_RigidBodies.end()) + + auto wheelComponent = m_World->GetComponent(entity, "Wheel"); + if (wheelComponent) { - SetUpPhysicsState(entity, parent); + EntityID car = m_World->GetEntityParent(entity); + if(m_Vehicles.find(car) != m_Vehicles.end()) + { + hkVector4 position; + hkQuaternion orientation; + m_Vehicles[car]->calcCurrentPositionAndRotation(m_RigidBodies[car], m_Vehicles[car]->m_suspension, wheelComponent->ID, position, orientation); + hkVector4 chassisPosition = m_RigidBodies[car]->getPosition(); + hkQuaternion chassisOrientation = m_RigidBodies[car]->getRotation(); + glm::vec3 relativePos = glm::vec3(chassisPosition(0), chassisPosition(1), chassisPosition(2)) - glm::vec3(position(0), position(1), position(2)); + glm::quat relativeOrientation = glm::quat(orientation(3), orientation(0), orientation(1), orientation(2)); + + transformComponent->Position = relativePos; + //transformComponent->Orientation = relativeOrientation; + } } else { - hkVector4 position = m_RigidBodies[entity]->getPosition(); - transformComponent->Position = glm::vec3(position(0), position(1), position(2)); - hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); - transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); + if(m_Vehicles.find(entity) != m_Vehicles.end()) + { + hkVector4 position = m_RigidBodies[entity]->getPosition(); + transformComponent->Position = glm::vec3(position(0), position(1), position(2)); + hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); + transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); + } } + // HACK: Vehicle test-controls auto vehicleComponent = m_World->GetComponent(entity, "Vehicle"); @@ -127,6 +145,118 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p } } +void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) +{ + auto transformComponent = m_World->GetComponent(entity, "Transform"); + if (!transformComponent) + return; + + + auto wheelComponent = m_World->GetComponent(entity, "Wheel"); + if (wheelComponent) + { + wheelComponent->ID = m_Wheels.size(); + m_Wheels.push_back(entity); + } + + auto physicsComponent = m_World->GetComponent(entity, "Physics"); + if (!physicsComponent) + return; + + auto sphereComponent = m_World->GetComponent(entity, "Sphere"); + auto boxComponent = m_World->GetComponent(entity, "Box"); + + + hkpConvexShape* shape; + hkpRigidBodyCinfo rigidBodyInfo; + hkMassProperties massProperties; + + + if (sphereComponent) + { + shape = new hkpSphereShape(sphereComponent->Radius); + rigidBodyInfo.m_shape = shape; + + if (physicsComponent->Static) + { + rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; + } + else + { + rigidBodyInfo.m_motionType = hkpMotion::MOTION_SPHERE_INERTIA; + } + + hkpInertiaTensorComputer::computeSphereVolumeMassProperties(sphereComponent->Radius, physicsComponent->Mass, massProperties); + + } + else if (boxComponent) + { + hkReal thickness = 0.05; + shape = new hkpBoxShape(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness)); + rigidBodyInfo.m_shape = shape; + if (physicsComponent->Static) + { + rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; + } + else + { + rigidBodyInfo.m_motionType = hkpMotion::MOTION_BOX_INERTIA; + } + hkpInertiaTensorComputer::computeBoxSurfaceMassProperties(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness), physicsComponent->Mass, thickness, massProperties); + } + else + { + return; + } + + rigidBodyInfo.m_position.set(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); + rigidBodyInfo.m_inertiaTensor = massProperties.m_inertiaTensor; + rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass; + rigidBodyInfo.m_mass = massProperties.m_mass; + + // Create RigidBody + hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo); + + + auto vehicleComponent = m_World->GetComponent(entity, "Vehicle"); + if (vehicleComponent && m_Vehicles.find(entity) == m_Vehicles.end()) + { + for (int i = 0; i < m_Wheels.size(); i++) + { + if(m_World->GetEntityParent(m_Wheels[i]) != entity) + { + m_Wheels.erase(m_Wheels.begin() + i); + i--; + } + } + VehicleSetup vehicleSetup; + + // Create the basic vehicle. + m_Vehicles[entity] = new hkpVehicleInstance(rigidBody); + vehicleSetup.buildVehicle(m_World, m_PhysicsWorld, *m_Vehicles[entity], entity, m_Wheels); + // Add the vehicle's entities and phantoms to the world + m_Vehicles[entity]->addToWorld(m_PhysicsWorld); + + m_RigidBodies[entity] = rigidBody; + + // The vehicle is an action + m_PhysicsWorld->addAction(m_Vehicles[entity]); + + //m_Vehicles[entity]->m_rpm = 0.0f; // Not sure why this one should be here + m_Wheels.clear(); + shape->removeReference(); + rigidBody->removeReference(); + } + else + { + m_PhysicsWorld->addEntity(rigidBody); + m_RigidBodies[entity] = rigidBody; + shape->removeReference(); + rigidBody->removeReference(); + } +} +/* + void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent) { auto transformComponent = m_World->GetComponent(entity, "Transform"); @@ -221,6 +351,8 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent) rigidBody->removeReference(); } } +*/ + @@ -268,6 +400,7 @@ void Systems::PhysicsSystem::StepVisualDebugger() void HK_CALL Systems::PhysicsSystem::HavokErrorReport(const char* msg, void*) { - LOG_DEBUG("%s", msg); + LOG_INFO("%s", msg); } + diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index 1bbffdd..a7d917f 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -58,7 +58,7 @@ public: void UpdateEntity(double dt, EntityID entity, EntityID parent) override; void OnComponentCreated(std::string type, std::shared_ptr component) override; void OnComponentRemoved(std::string type, Component* component) override; - + void OnEntityCommit(EntityID entity) override; private: double m_Accumulator; @@ -75,7 +75,7 @@ private: std::unordered_map m_RigidBodies; std::unordered_map m_Vehicles; - + std::vector m_Wheels; hkpVehicleInstance* Systems::PhysicsSystem::createVehicle(VehicleSetup& vehicleSetup, hkpRigidBody* chassis); }; From 1e2f7fdd5cf930ed5651e452d4985dd504af3f58 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 22 Apr 2014 19:14:09 +0200 Subject: [PATCH 09/37] Skeleton MessageRelay --- src/GUI/Frame.h | 14 ++++++ src/MessageRelay.h | 43 +++++++++++++++++++ vs11/Returngeance/Returngeance.vcxproj | 2 + .../Returngeance/Returngeance.vcxproj.filters | 7 +++ 4 files changed, 66 insertions(+) create mode 100644 src/GUI/Frame.h create mode 100644 src/MessageRelay.h diff --git a/src/GUI/Frame.h b/src/GUI/Frame.h new file mode 100644 index 0000000..5415d64 --- /dev/null +++ b/src/GUI/Frame.h @@ -0,0 +1,14 @@ +#ifndef GUI_Frame_h__ +#define GUI_Frame_h__ + +namespace GUI +{ + +class Frame +{ + +}; + +} + +#endif // GUI_Frame_h__ diff --git a/src/MessageRelay.h b/src/MessageRelay.h new file mode 100644 index 0000000..692f8a7 --- /dev/null +++ b/src/MessageRelay.h @@ -0,0 +1,43 @@ +#ifndef MessageRelay_h__ +#define MessageRelay_h__ + +#include +#include +#include + +struct Message +{ +protected: + Message() { } +}; + +class MessageRelay +{ +private: + typedef std::string MessageType_t; + typedef std::function MessageCallback_t; + +public: + void Subscribe(std::string messageType, MessageCallback_t callback) + { + m_Callbacks[messageType].push_back(callback); + } + + void Raise(std::string messageType, Message message) + { + auto callbackIt = m_Callbacks.find(messageType); + if (callbackIt == m_Callbacks.end()) + return; + + for (auto &callback : callbackIt->second) + { + callback(message); + } + } + +private: + std::unordered_map> m_Callbacks; + +}; + +#endif // MessageRelay_h__ diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 4726981..f5e903d 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -139,6 +139,8 @@ + + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 672e8dd..4922bd1 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -112,6 +112,9 @@ {9f45f029-46c8-4c0d-b44c-dc9bffd3c6a6} + + {6e633434-4aed-453d-b2f9-8c51ca7f78db} + @@ -214,6 +217,10 @@ + + GUI + + From ee34b15cf17bde11a0cc606496c3538fc6615d1c Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Wed, 23 Apr 2014 01:36:03 +0200 Subject: [PATCH 10/37] Rectangle class. --- src/Util/Rectangle.h | 95 +++++++++++++++++++ vs11/Returngeance/Returngeance.vcxproj | 1 + .../Returngeance/Returngeance.vcxproj.filters | 3 + 3 files changed, 99 insertions(+) create mode 100644 src/Util/Rectangle.h diff --git a/src/Util/Rectangle.h b/src/Util/Rectangle.h new file mode 100644 index 0000000..7e55659 --- /dev/null +++ b/src/Util/Rectangle.h @@ -0,0 +1,95 @@ +#ifndef Util_Rectangle_h__ +#define Util_Rectangle_h__ + +#include + +struct Rectangle +{ + Rectangle() + : X(0), Y(0), Width(0), Height(0) { } + + Rectangle(int x, int y, int width = 0, int height = 0) + : X(x), Y(y), Width(width), Height(height) { } + + /*Rectangle(const Rectangle &rect) + : X(rect.X), Y(rect.Y), Width(rect.Width), Height(rect.Height) { }*/ + + int X; + int Y; + int Width; + int Height; + + const int& GetLeft() const { return X; } + void SetLeft(int left) + { + Width += X - left; + X = left; + } + int GetRight() const { return X + Width; } + void SetRight(int right) + { + Width = right - X; + } + const int& GetTop() const { return Y; } + void SetTop(int top) + { + Height += Y - top; + Y = top; + } + int GetBottom() const { return Y + Height; } + int SetBottom(int bottom) + { + Height = bottom - Y; + } + + Rectangle& operator+=(const Rectangle &rhs) + { + SetLeft(std::min(GetLeft(), rhs.GetLeft())); + SetRight(std::max(GetRight(), rhs.GetRight())); + SetTop(std::min(GetTop(), rhs.GetTop())); + SetBottom(std::max(GetBottom(), rhs.GetBottom())); + } + + static bool Intersects(const Rectangle &r1, const Rectangle &r2) + { + return !(r2.GetLeft() > r1.GetRight() || r2.GetRight() < r1.GetLeft() || r2.GetTop() > r1.GetBottom() || r2.GetBottom() < r1.GetTop()); + } +}; + +inline bool operator==(const Rectangle &r1, const Rectangle &r2) +{ + return (r1.X == r2.X) && (r1.Y == r2.Y) && (r1.Width == r2.Width) && (r1.Height == r2.Height); +} + +inline bool operator!=(const Rectangle &lhs, const Rectangle &rhs) +{ + return !(lhs == rhs); +} + +inline bool operator<(const Rectangle &lhs, const Rectangle &lhs) +{ + return (lhs.Width < lhs.Width) && (lhs.Height < lhs.Height); +} + +inline bool operator>(const Rectangle &lhs, const Rectangle &rhs) +{ + return rhs < lhs; +} + +inline bool operator<=(const Rectangle &lhs, const Rectangle &rhs) +{ + return !(lhs > rhs); +} + +inline bool operator>=(const Rectangle &lhs, const Rectangle &rhs) +{ + return !(lhs < rhs); +} + +inline Rectangle operator+(Rectangle lhs, const Rectangle &rhs) +{ + lhs += rhs; + return lhs; +} + +#endif // Util_Rectangle_h__ diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index f5e903d..f2e85c8 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -159,6 +159,7 @@ + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 4922bd1..67c8abe 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -221,6 +221,9 @@ GUI + + Util + From dfd94254731eb00528702569520e1d54dcf71ed9 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Wed, 23 Apr 2014 02:19:17 +0200 Subject: [PATCH 11/37] WIP Frame --- src/GUI/Frame.h | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/GUI/Frame.h b/src/GUI/Frame.h index 5415d64..f77d29f 100644 --- a/src/GUI/Frame.h +++ b/src/GUI/Frame.h @@ -1,12 +1,31 @@ #ifndef GUI_Frame_h__ #define GUI_Frame_h__ +#include + +#include "Util/Rectangle.h" + namespace GUI { -class Frame +class Frame : public Rectangle { +public: + enum class Anchor + { + Left, + Right, + Top, + Bottom + }; + Frame() { } + + Frame(const Frame &parent) + : Rectangle(static_cast(parent)) + , Parent(std::shared_ptr(&parent)) { } + + std::shared_ptr Parent; }; } From 530b16e31b0b1e15dab740e7dff677f0f298ccee Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Wed, 23 Apr 2014 16:55:51 +0200 Subject: [PATCH 12/37] Extended OBJ loader to parse specular and normal maps --- src/Model.cpp | 2 +- src/OBJ.cpp | 191 +++++++++++++++++++++++++++++++++++++++++++++----- src/OBJ.h | 78 ++++++++++++++++++--- 3 files changed, 242 insertions(+), 29 deletions(-) diff --git a/src/Model.cpp b/src/Model.cpp index 5f10f29..a2f42e9 100755 --- a/src/Model.cpp +++ b/src/Model.cpp @@ -18,7 +18,7 @@ Model::Model(OBJ &obj, ResourceManager* rm) { currentMaterial = face.Material; // Load texture - auto texture = std::shared_ptr(rm->Load("Texture", currentMaterial->TextureFile)); + auto texture = std::shared_ptr(rm->Load("Texture", currentMaterial->DiffuseTexture.FileName)); // TODO: Load material parameters // Create new texture group (start index of new group is upcoming index) TextureGroup texGroup = { texture, index, index }; diff --git a/src/OBJ.cpp b/src/OBJ.cpp index 683f9e2..a8b9f03 100755 --- a/src/OBJ.cpp +++ b/src/OBJ.cpp @@ -126,9 +126,11 @@ void OBJ::ParseMaterial() std::string currentMaterialName; MaterialInfo* currentMaterial = nullptr; + unsigned int currentLine = 0; std::string line; while (std::getline(file, line)) { + currentLine++; if (line.length() == 0) continue; @@ -140,19 +142,7 @@ void OBJ::ParseMaterial() // Create a new material definition if (prefix == "newmtl") { - MaterialInfo mat = - { - "", - std::make_tuple(0.2f, 0.2f, 0.2f), - std::make_tuple(0.8f, 0.8f, 0.8f), - std::make_tuple(1.0f, 1.0f, 1.0f), - std::make_tuple(1.0f, 1.0f, 1.0f), - 1.0f, - 1.0f, - 0.0f, - 0, - }; - + MaterialInfo mat; ss >> currentMaterialName; LOG_INFO("Parsing material %s", currentMaterialName.c_str()); Materials[currentMaterialName] = mat; @@ -243,14 +233,177 @@ void OBJ::ParseMaterial() currentMaterial->IlluminationModel = illum; continue; } - // Texture file - // TODO: - if (prefix == "map_Ka" || prefix == "map_Kd") + // Diffuse texture + if (prefix == "map_Kd") { - std::string textureFile; - ss >> textureFile; - currentMaterial->TextureFile = (m_MaterialPath.branch_path() / textureFile).string(); + MaterialInfo::ColorMap colorMap; + + std::string fileName; + std::string arg; + while (ss >> arg) + { + ParseColorMap(currentLine, ss, prefix, arg, colorMap); + } + + // HACK: Should we really have to specify the full path here? + colorMap.FileName = (m_MaterialPath.branch_path() / colorMap.FileName).string(); + currentMaterial->DiffuseTexture = colorMap; + continue; + } + // Specular map + if (prefix == "map_Ks") + { + MaterialInfo::ColorMap colorMap; + + std::string fileName; + std::string arg; + while (ss >> arg) + { + ParseColorMap(currentLine, ss, prefix, arg, colorMap); + } + + // HACK: Should we really have to specify the full path here? + colorMap.FileName = (m_MaterialPath.branch_path() / colorMap.FileName).string(); + currentMaterial->SpecularMap = colorMap; + continue; + } + // Normal map (bump map) + if (prefix == "bump") + { + MaterialInfo::BumpMap bumpMap; + + std::string fileName; + std::string arg; + while (ss >> arg) + { + ParseBumpMap(currentLine, ss, prefix, arg, bumpMap); + } + + // HACK: Should we really have to specify the full path here? + bumpMap.FileName = (m_MaterialPath.branch_path() / bumpMap.FileName).string(); + currentMaterial->NormalMap = bumpMap; continue; } } } + +void OBJ::ParseTextureMap(unsigned int line, std::stringstream &ss, std::string prefix, std::string arg, MaterialInfo::TextureMap &textureMap) +{ + if (arg == "-blendu") + { + std::string val; + ss >> val; + if (val == "off") + textureMap.blendu = false; + else if (val == "on") + textureMap.blendu = true; + else + LOG_ERROR("Unrecognized MTL value \"%s\" to argument \"%s %s\" on line %i", val.c_str(), prefix.c_str(), arg.c_str(), line); + } + else if (arg == "-blendv") + { + std::string val; + ss >> val; + if (val == "off") + textureMap.blendv = false; + else if (val == "on") + textureMap.blendv = true; + else + LOG_ERROR("Unrecognized MTL value \"%s\" to argument \"%s %s\" on line %i", val.c_str(), prefix.c_str(), arg.c_str(), line); + } + else if (arg == "-clamp") + { + std::string val; + ss >> val; + if (val == "off") + textureMap.clamp = false; + else if (val == "on") + textureMap.clamp = true; + else + LOG_ERROR("Unrecognized MTL value \"%s\" to argument \"%s %s\" on line %i", val.c_str(), prefix.c_str(), arg.c_str(), line); + } + else if (arg == "-o") + { + float u, v, w; + if (ss >> u >> v >> w) + { + textureMap.o = std::make_tuple(u, v, w); + } + else + { + LOG_ERROR("Unrecognized MTL value to argument \"%s %s\" on line %i", prefix.c_str(), arg.c_str(), line); + } + } + else if (arg == "-s") + { + float u, v, w; + if (ss >> u >> v >> w) + { + textureMap.s = std::make_tuple(u, v, w); + } + else + { + LOG_ERROR("Unrecognized MTL value to argument \"%s %s\" on line %i", prefix.c_str(), arg.c_str(), line); + } + } + // Assume unrecognized options is part of the file name + else + { + if (!textureMap.FileName.empty()) + textureMap.FileName += " "; + textureMap.FileName += arg; + } +} + +void OBJ::ParseColorMap(unsigned int line, std::stringstream &ss, std::string prefix, std::string arg, MaterialInfo::ColorMap &colorMap) +{ + if (arg == "-cc") + { + if (prefix != "map_Kd" || prefix != "map_Ks") + { + LOG_ERROR("Invalid MTL argument \"%s\" to option \"%s\" on line %i", arg.c_str(), prefix.c_str(), line); + return; + } + + std::string val; + if (ss >> val) + { + if (val == "off") + colorMap.cc = false; + else if (val == "on") + colorMap.cc = true; + else + LOG_ERROR("Unrecognized MTL value \"%s\" to argument \"%s %s\" on line %i", val.c_str(), prefix.c_str(), arg.c_str(), line); + } + else + { + LOG_ERROR("Unrecognized MTL value to argument \"%s %s\" on line %i", prefix.c_str(), arg.c_str(), line); + } + } + else + { + ParseTextureMap(line, ss, prefix, arg, colorMap); + } +} + +void OBJ::ParseBumpMap(unsigned int line, std::stringstream &ss, std::string prefix, std::string arg, MaterialInfo::BumpMap &bumpMap) +{ + if (arg == "-bm") + { + if (prefix != "bump") + { + LOG_ERROR("Invalid MTL argument \"%s\" to option \"%s\" on line %i", arg.c_str(), prefix.c_str(), line); + return; + } + + float val; + if (ss >> val) + bumpMap.bm = val; + else + LOG_ERROR("Unrecognized MTL value to argument \"%s %s\" on line %i", prefix.c_str(), arg.c_str(), line); + } + else + { + ParseTextureMap(line, ss, prefix, arg, bumpMap); + } +} \ No newline at end of file diff --git a/src/OBJ.h b/src/OBJ.h index 62bce8d..2ef10e0 100755 --- a/src/OBJ.h +++ b/src/OBJ.h @@ -10,21 +10,78 @@ #include #include +#include class OBJ { public: struct MaterialInfo { - std::string TextureFile; - std::tuple AmbientColor; - std::tuple DiffuseColor; - std::tuple SpecularColor; - std::tuple TransmissionFilter; - float OpticalDensity; - float Alpha; - float Shininess; - int IlluminationModel; + struct TextureMap + { + TextureMap() + : blendu(true) + , blendv(true) + , clamp(false) + , o(std::make_tuple(0.f, 0.f, 0.f)) + , s(std::make_tuple(1.f, 1.f, 1.f)) { } + + std::string FileName; + + // http://paulbourke.net/dataformats/mtl/ + // "These options are described in detail in 'Options for texture map statements' on page 5-18." + + // Horizontal texture blending + bool blendu; // = true + // Vertical texture blending + bool blendv; // = true + // Clamping + bool clamp; // = false + // Offset + std::tuple o; // = (0, 0, 0) + // Scale + std::tuple s; // = (1, 1, 1) + }; + + struct ColorMap : public TextureMap + { + ColorMap() + : cc(false) { } + + // Color correction + bool cc; // = false + }; + + struct BumpMap : public TextureMap + { + BumpMap() + : bm(1.f) { } + + // Bump multiplier + float bm; // = 1? + }; + + MaterialInfo() + : AmbientColor(std::make_tuple(0.2f, 0.2f, 0.2f)) + , DiffuseColor(std::make_tuple(0.8f, 0.8f, 0.8f)) + , SpecularColor(std::make_tuple(1.0f, 1.0f, 1.0f)) + , TransmissionFilter(std::make_tuple(1.0f, 1.0f, 1.0f)) + , OpticalDensity(1.0f) + , Alpha(1.0f) + , Shininess(0.0f) + , IlluminationModel(0) { } + + ColorMap DiffuseTexture; + ColorMap SpecularMap; + BumpMap NormalMap; + std::tuple AmbientColor; // = (0.2, 0.2, 0.2) + std::tuple DiffuseColor; // = (0.8, 0.8, 0.8) + std::tuple SpecularColor; // = (1, 1, 1) + std::tuple TransmissionFilter; // = (1, 1, 1) + float OpticalDensity; // = 1 + float Alpha; // = 1 + float Shininess; // = 0 + int IlluminationModel; // = 0 }; struct FaceDefinition @@ -59,6 +116,9 @@ private: MaterialInfo* m_CurrentMaterial; void ParseMaterial(); + void ParseTextureMap(unsigned int line, std::stringstream &ss, std::string prefix, std::string arg, MaterialInfo::TextureMap &textureMap); + void ParseColorMap(unsigned int line, std::stringstream &ss, std::string prefix, std::string arg, MaterialInfo::ColorMap &textureMap); + void ParseBumpMap(unsigned int line, std::stringstream &ss, std::string prefix, std::string arg, MaterialInfo::BumpMap &textureMap); }; #endif // OBJ_h__ \ No newline at end of file From de1290bf67cbc96bfba2523f55f6544fbfb7ebc0 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Wed, 23 Apr 2014 17:58:11 +0200 Subject: [PATCH 13/37] Added a few debug messages to ResourceManager. No longer warns about hot-loading when a resource which causes a load chain is preloaded. --- src/ResourceManager.cpp | 18 ++++++++++++++---- src/ResourceManager.h | 27 +++++++++++++++++++++++---- 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/src/ResourceManager.cpp b/src/ResourceManager.cpp index 4b864d6..1361c11 100644 --- a/src/ResourceManager.cpp +++ b/src/ResourceManager.cpp @@ -9,10 +9,6 @@ Resource* ResourceManager::CreateResource(std::string resourceType, std::string LOG_ERROR("Failed to load resource \"%s\" of type \"%s\": Type not registered", resourceName.c_str(), resourceType.c_str()); return nullptr; } - - auto resIt = m_ResourceCache.find(resourceName); - if (resIt != m_ResourceCache.end()) - return resIt->second; // Call the factory function Resource* resource = facIt->second(resourceName); @@ -32,7 +28,16 @@ void ResourceManager::RegisterType(std::string resourceType, std::function factoryFunction); // Loads a resource and caches it for future use void Preload(std::string resourceType, std::string resourceName); - + + // Checks if a resource is in cache + bool IsResourceLoaded(std::string resourceName); + template // Hot-loads a resource and caches it for future use T* Load(std::string resourceType, std::string resourceName); @@ -44,6 +47,8 @@ private: std::unordered_map m_ResourceTypeIDs; // Number of resources of a type. Doubles as local ID. std::unordered_map m_ResourceCount; + // Flag to suppress hot-load warnings when a preloading resource chain loads another resource + bool m_Preloading; unsigned int GetTypeID(std::string resourceType); unsigned int GetNewResourceID(unsigned int typeID); @@ -55,20 +60,34 @@ private: template T* ResourceManager::Load(std::string resourceType, std::string resourceName) { + auto it = m_ResourceCache.find(resourceName); + if (it != m_ResourceCache.end()) + return static_cast(it->second); + + if (m_Preloading) + { + LOG_INFO("Preloading resource \"%s\"", resourceName.c_str()); + } + else + { + LOG_WARNING("Hot-loading resource \"%s\"", resourceName.c_str()); + } + return static_cast(CreateResource(resourceType, resourceName)); } template T* ResourceManager::Fetch(std::string resourceName) const { - if (m_ResourceCache.find(resourceName) == m_ResourceCache.end()) + auto it = m_ResourceCache.find(resourceName); + if (it == m_ResourceCache.end()) { LOG_ERROR("Failed to fetch resource \"%s\": Resource not loaded!", resourceName.c_str()); return nullptr; } else { - return static_cast(m_ResourceCache.at(resourceName)); + return static_cast(it->second); } } From 3412fa42f7992c66148c1be765ab2c1821bbe3c2 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Wed, 23 Apr 2014 23:25:41 +0200 Subject: [PATCH 14/37] Jeep entity setup. --- src/GameWorld.cpp | 48 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index d3b9aad..69f8353 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -42,6 +42,54 @@ void GameWorld::Initialize() CommitEntity(ground); } + { + auto jeep = CreateEntity(); + auto transform = AddComponent(jeep, "Transform"); + transform->Position = glm::vec3(0, 1, 0); + + auto model = AddComponent(jeep, "Model"); + model->ModelFile = "Models/JeepV2/Chassi/chassi.OBJ"; + CommitEntity(jeep); + + { + auto wheel = CreateEntity(jeep); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(1.4f, 0.5546f, -0.9242f); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; + CommitEntity(wheel); + } + + { + auto wheel = CreateEntity(jeep); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(-1.4f, 0.5546f, -0.9242f); + transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; + CommitEntity(wheel); + } + + { + auto wheel = CreateEntity(jeep); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(0.2726f, 0.2805f, 1.9307f); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; + CommitEntity(wheel); + } + + { + auto wheel = CreateEntity(jeep); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(-0.2726f, 0.2805f, 1.9307f); + transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; + CommitEntity(wheel); + } + } + { auto TankTest = CreateEntity(); auto transform = AddComponent(TankTest, "Transform"); From e95d78aba634260c85e8b9919dcd59381fb08176 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Thu, 24 Apr 2014 00:02:06 +0200 Subject: [PATCH 15/37] Fixed quaternion relative rotations! --- src/Systems/TransformSystem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Systems/TransformSystem.cpp b/src/Systems/TransformSystem.cpp index a23d92b..494acd0 100755 --- a/src/Systems/TransformSystem.cpp +++ b/src/Systems/TransformSystem.cpp @@ -40,7 +40,7 @@ glm::quat Systems::TransformSystem::AbsoluteOrientation(EntityID entity) do { auto transform = m_World->GetComponent(entity, "Transform"); - absOrientation *= transform->Orientation; + absOrientation = transform->Orientation * absOrientation; entity = m_World->GetEntityParent(entity); } while (entity != 0); From c1cb4da6846c759b5a29378922fccac863839e03 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Thu, 24 Apr 2014 00:02:06 +0200 Subject: [PATCH 16/37] Fixed quaternion relative rotations! --- src/Systems/TransformSystem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Systems/TransformSystem.cpp b/src/Systems/TransformSystem.cpp index a23d92b..494acd0 100755 --- a/src/Systems/TransformSystem.cpp +++ b/src/Systems/TransformSystem.cpp @@ -40,7 +40,7 @@ glm::quat Systems::TransformSystem::AbsoluteOrientation(EntityID entity) do { auto transform = m_World->GetComponent(entity, "Transform"); - absOrientation *= transform->Orientation; + absOrientation = transform->Orientation * absOrientation; entity = m_World->GetEntityParent(entity); } while (entity != 0); From afbe58e4f3a94bba3c617e927d275943f35f7fc1 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Thu, 24 Apr 2014 00:11:49 +0200 Subject: [PATCH 17/37] Wheels now turning and spinning properly. --- src/Components/Wheel.h | 7 ++++++ src/GameWorld.cpp | 43 +++++++++++++++++++---------------- src/Systems/PhysicsSystem.cpp | 42 ++++++++++++++++++++-------------- 3 files changed, 56 insertions(+), 36 deletions(-) diff --git a/src/Components/Wheel.h b/src/Components/Wheel.h index f000058..212aad5 100644 --- a/src/Components/Wheel.h +++ b/src/Components/Wheel.h @@ -37,3 +37,10 @@ private: } #endif // Components_Wheel_h__ + +/* +m_currentSuspensionLength +m_suspension +m_steeringOrientationChassisSpace +m_spinAngle +*/ \ No newline at end of file diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 6c9e5d4..f40ac63 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -24,14 +24,14 @@ void GameWorld::Initialize() auto ground = CreateEntity(); auto transform = AddComponent(ground, "Transform"); transform->Position = glm::vec3(0, -5, 0); - transform->Scale = glm::vec3(1000.0f, 10.0f, 1000.0f); + transform->Scale = glm::vec3(400.0f, 10.0f, 400.0f); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(ground, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube.obj"; auto box = AddComponent(ground, "Box"); - box->Width = 500; + box->Width = 200; box->Height = 5; - box->Depth = 500; + box->Depth = 200; auto physics = AddComponent(ground, "Physics"); physics->Mass = 10; @@ -66,13 +66,14 @@ void GameWorld::Initialize() auto ent = CreateEntity(car); auto transform = AddComponent(ent, "Transform"); transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(1.1f, -0.5f, -1.3f); + transform->Position = glm::vec3(1.1f, -1.5f, -1.3f); auto Wheel = AddComponent(ent, "Wheel"); Wheel->Hardpoint = glm::vec3(1.1f, 0.f, -1.3f);// HACK: make into component Wheel->AxleID = 0; Wheel->Mass = 10; Wheel->Radius = 0.5f; Wheel->Steering = true; + Wheel->SuspensionStrength = 20.f; auto model = AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; CommitEntity(ent); @@ -82,13 +83,14 @@ void GameWorld::Initialize() auto ent = CreateEntity(car); auto transform = AddComponent(ent, "Transform"); transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(-1.1f, -0.5f, -1.3f); + transform->Position = glm::vec3(-1.1f, -1.5f, -1.3f); auto Wheel = AddComponent(ent, "Wheel"); Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, -1.3f); Wheel->AxleID = 0; Wheel->Mass = 10; Wheel->Radius = 0.5f; Wheel->Steering = true; + Wheel->SuspensionStrength = 20.f; auto model = AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; CommitEntity(ent); @@ -98,7 +100,7 @@ void GameWorld::Initialize() auto ent = CreateEntity(car); auto transform = AddComponent(ent, "Transform"); transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(1.1f, -0.5f, 1.3f); + transform->Position = glm::vec3(1.1f, -1.5f, 1.3f); auto Wheel = AddComponent(ent, "Wheel"); Wheel->Hardpoint = glm::vec3(1.1f, 0.f, 1.3f); Wheel->AxleID = 1; @@ -106,6 +108,7 @@ void GameWorld::Initialize() Wheel->Radius = 0.5f; Wheel->Steering = false; Wheel->ConnectedToHandbrake = true; + Wheel->SuspensionStrength = 20.f; auto model = AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; CommitEntity(ent); @@ -115,7 +118,7 @@ void GameWorld::Initialize() auto ent = CreateEntity(car); auto transform = AddComponent(ent, "Transform"); transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(-1.1f, -0.5f, 1.3f); + transform->Position = glm::vec3(-1.1f, -1.5f, 1.3f); auto Wheel = AddComponent(ent, "Wheel"); Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, 1.3f); Wheel->AxleID = 1; @@ -123,6 +126,7 @@ void GameWorld::Initialize() Wheel->Radius = 0.5f; Wheel->Steering = false; Wheel->ConnectedToHandbrake = true; + Wheel->SuspensionStrength = 20.f; auto model = AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; CommitEntity(ent); @@ -133,22 +137,23 @@ void GameWorld::Initialize() - for(int i = 0; i < 50; i++) + for(int i = 0; i < 10; i++) { - auto ball = CreateEntity(); - auto transform = AddComponent(ball, "Transform"); - transform->Position = glm::vec3(243, 10 + i*10, 0); - transform->Scale = glm::vec3(10); + auto cube = CreateEntity(); + auto transform = AddComponent(cube, "Transform"); + transform->Position = glm::vec3(20, 10 + i*2, 0); + transform->Scale = glm::vec3(1); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); - auto model = AddComponent(ball, "Model"); + auto model = AddComponent(cube, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - auto physics = AddComponent(ball, "Physics"); + + auto physics = AddComponent(cube, "Physics"); physics->Mass = 100; - auto box = AddComponent(ball, "Box"); - box->Width = 5.f; - box->Height = 5.f; - box->Depth = 5.f; - CommitEntity(ball); + auto box = AddComponent(cube, "Box"); + box->Width = 0.5f; + box->Height = 0.5f; + box->Depth = 0.5f; + CommitEntity(cube); } { diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index 0ba5a2e..837ed5a 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -76,10 +76,13 @@ void Systems::PhysicsSystem::Update(double dt) continue; - - hkVector4 position(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); - hkQuaternion rotation(transformComponent->Orientation.x, transformComponent->Orientation.y, transformComponent->Orientation.z, transformComponent->Orientation.w); - m_RigidBodies[entity]->setPositionAndRotation(position, rotation); + if(m_RigidBodies[entity]->isActive()) + { + hkVector4 position(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); + hkQuaternion rotation(transformComponent->Orientation.x, transformComponent->Orientation.y, transformComponent->Orientation.z, transformComponent->Orientation.w); + m_RigidBodies[entity]->setPositionAndRotation(position, rotation); + } + } @@ -109,26 +112,31 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p EntityID car = m_World->GetEntityParent(entity); if(m_Vehicles.find(car) != m_Vehicles.end()) { - hkVector4 position; - hkQuaternion orientation; - m_Vehicles[car]->calcCurrentPositionAndRotation(m_RigidBodies[car], m_Vehicles[car]->m_suspension, wheelComponent->ID, position, orientation); - hkVector4 chassisPosition = m_RigidBodies[car]->getPosition(); - hkQuaternion chassisOrientation = m_RigidBodies[car]->getRotation(); - glm::vec3 relativePos = glm::vec3(chassisPosition(0), chassisPosition(1), chassisPosition(2)) - glm::vec3(position(0), position(1), position(2)); - glm::quat relativeOrientation = glm::quat(orientation(3), orientation(0), orientation(1), orientation(2)); + m_Vehicles[car]->getChassis()->activate(); - transformComponent->Position = relativePos; - //transformComponent->Orientation = relativeOrientation; + hkVector4 hardPoint = m_Vehicles[car]->m_suspension->m_wheelParams[wheelComponent->ID].m_hardpointChassisSpace; + hkVector4 suspensionDirection = m_Vehicles[car]->m_suspension->m_wheelParams[wheelComponent->ID].m_directionChassisSpace; + hkReal suspensionLength = m_Vehicles[car]->m_wheelsInfo[wheelComponent->ID].m_currentSuspensionLength; + glm::vec3 position = glm::vec3(hardPoint(0) + (suspensionDirection(0) * suspensionLength), hardPoint(1) + (suspensionDirection(1) * suspensionLength), hardPoint(2) + (suspensionDirection(2) * suspensionLength)); + transformComponent->Position = position; + + hkQuaternion steeringOrientation = m_Vehicles[car]->m_wheelsInfo[wheelComponent->ID].m_steeringOrientationChassisSpace; + hkReal spinAngle = -m_Vehicles[car]->m_wheelsInfo[wheelComponent->ID].m_spinAngle; + glm::quat orientation = glm::quat(steeringOrientation(3), steeringOrientation(0), steeringOrientation(1), steeringOrientation(2)) * glm::angleAxis(spinAngle, glm::vec3(1, 0, 0)); + transformComponent->Orientation = orientation; } } else { if(m_Vehicles.find(entity) != m_Vehicles.end()) { - hkVector4 position = m_RigidBodies[entity]->getPosition(); - transformComponent->Position = glm::vec3(position(0), position(1), position(2)); - hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); - transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); + if(m_RigidBodies[entity]->isActive()) + { + hkVector4 position = m_RigidBodies[entity]->getPosition(); + transformComponent->Position = glm::vec3(position(0), position(1), position(2)); + hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); + transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); + } } } From 6ccb196b3baf80d823df53fb6c59bb0226418dac Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Thu, 24 Apr 2014 01:20:13 +0200 Subject: [PATCH 18/37] Jeep physics --- src/Components/Wheel.h | 1 + src/GameWorld.cpp | 253 ++++++++++++++++++++++------------ src/GameWorld.cpp.orig | 172 +++++++++++++++-------- src/Shaders/Fragment.glsl | 4 +- src/Systems/PhysicsSystem.cpp | 4 +- 5 files changed, 287 insertions(+), 147 deletions(-) diff --git a/src/Components/Wheel.h b/src/Components/Wheel.h index 212aad5..5c005c7 100644 --- a/src/Components/Wheel.h +++ b/src/Components/Wheel.h @@ -33,6 +33,7 @@ struct Wheel : Component private: int ID; + glm::quat OriginalOrientation; }; } diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index f40ac63..06b965f 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -41,100 +41,183 @@ void GameWorld::Initialize() } - for (int i = 0; i < 1; i++) { - auto car = CreateEntity(); - auto transform = AddComponent(car, "Transform"); - transform->Position = glm::vec3(0, (i+1)*5, 0); - transform->Scale = glm::vec3(3, 1, 5); - transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); - auto model = AddComponent(car, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - auto physics = AddComponent(car, "Physics"); + auto jeep = CreateEntity(); + auto transform = AddComponent(jeep, "Transform"); + transform->Position = glm::vec3(0, 2, 0); + + auto physics = AddComponent(jeep, "Physics"); physics->Mass = 1200; - auto box = AddComponent(car, "Box"); - box->Width = 1.5f; - box->Height = 0.5f; - box->Depth = 2.5f; - auto vehicle = AddComponent(car, "Vehicle"); + auto box = AddComponent(jeep, "Box"); + box->Width = 1.487f; + box->Height = 0.727f; + box->Depth = 2.594f; + auto vehicle = AddComponent(jeep, "Vehicle"); vehicle->TopSpeed = 500.f; vehicle->MaxTorque = 1000.f; - AddComponent(car, "Input"); - + AddComponent(jeep, "Input"); + { - // Front Right Wheel - auto ent = CreateEntity(car); - auto transform = AddComponent(ent, "Transform"); - transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(1.1f, -1.5f, -1.3f); - auto Wheel = AddComponent(ent, "Wheel"); - Wheel->Hardpoint = glm::vec3(1.1f, 0.f, -1.3f);// HACK: make into component - Wheel->AxleID = 0; - Wheel->Mass = 10; - Wheel->Radius = 0.5f; - Wheel->Steering = true; - Wheel->SuspensionStrength = 20.f; - auto model = AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - CommitEntity(ent); - } - { - // Front Left Wheel - auto ent = CreateEntity(car); - auto transform = AddComponent(ent, "Transform"); - transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(-1.1f, -1.5f, -1.3f); - auto Wheel = AddComponent(ent, "Wheel"); - Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, -1.3f); - Wheel->AxleID = 0; - Wheel->Mass = 10; - Wheel->Radius = 0.5f; - Wheel->Steering = true; - Wheel->SuspensionStrength = 20.f; - auto model = AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - CommitEntity(ent); - } - { - // Back Right Wheel - auto ent = CreateEntity(car); - auto transform = AddComponent(ent, "Transform"); - transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(1.1f, -1.5f, 1.3f); - auto Wheel = AddComponent(ent, "Wheel"); - Wheel->Hardpoint = glm::vec3(1.1f, 0.f, 1.3f); - Wheel->AxleID = 1; - Wheel->Mass = 10; - Wheel->Radius = 0.5f; - Wheel->Steering = false; - Wheel->ConnectedToHandbrake = true; - Wheel->SuspensionStrength = 20.f; - auto model = AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - CommitEntity(ent); - } - { - // Back Left Wheel - auto ent = CreateEntity(car); - auto transform = AddComponent(ent, "Transform"); - transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(-1.1f, -1.5f, 1.3f); - auto Wheel = AddComponent(ent, "Wheel"); - Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, 1.3f); - Wheel->AxleID = 1; - Wheel->Mass = 10; - Wheel->Radius = 0.5f; - Wheel->Steering = false; - Wheel->ConnectedToHandbrake = true; - Wheel->SuspensionStrength = 20.f; - auto model = AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - CommitEntity(ent); + auto chassis = CreateEntity(jeep); + auto transform = AddComponent(chassis, "Transform"); + transform->Position = glm::vec3(0, -0.6577f, 0); + auto model = AddComponent(chassis, "Model"); + model->ModelFile = "Models/JeepV2/Chassi/chassi.OBJ"; } - CommitEntity(car); + { + auto wheel = CreateEntity(jeep); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(1.4f, 0.5546f - 0.6577f - 0.2, -0.9242f); + transform->Scale = glm::vec3(1.0f); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; + auto Wheel = AddComponent(wheel, "Wheel"); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); + Wheel->AxleID = 0; + Wheel->Mass = 10; + Wheel->Radius = 0.837f; + Wheel->Steering = true; + Wheel->SuspensionStrength = 50.f; + Wheel->Friction = 4.0f; + Wheel->ConnectedToHandbrake = true; + CommitEntity(wheel); + } + + { + auto wheel = CreateEntity(jeep); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(-1.4f, 0.5546f - 0.6577f - 0.2, -0.9242f); + transform->Scale = glm::vec3(1.0f); + transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; + auto Wheel = AddComponent(wheel, "Wheel"); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); + Wheel->AxleID = 0; + Wheel->Mass = 10; + Wheel->Radius = 0.837f; + Wheel->Steering = true; + Wheel->SuspensionStrength = 50.f; + Wheel->Friction = 4.0f; + Wheel->ConnectedToHandbrake = true; + CommitEntity(wheel); + } + + { + auto wheel = CreateEntity(jeep); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(0.2726f, 0.2805f - 0.6577f, 1.9307f); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; + auto Wheel = AddComponent(wheel, "Wheel"); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); + Wheel->AxleID = 1; + Wheel->Mass = 10; + Wheel->Radius = 0.737f; + Wheel->Steering = false; + Wheel->SuspensionStrength = 50.f; + Wheel->Friction = 4.0f; + CommitEntity(wheel); + } + + { + auto wheel = CreateEntity(jeep); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(-0.2726f, 0.2805f - 0.6577f, 1.9307f); + transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; + auto Wheel = AddComponent(wheel, "Wheel"); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); + Wheel->AxleID = 1; + Wheel->Mass = 10; + Wheel->Radius = 0.737f; + Wheel->Steering = false; + Wheel->SuspensionStrength = 50.f; + Wheel->Friction = 4.0f; + CommitEntity(wheel); + } + CommitEntity(jeep); } +/* + + { + // Front Right Wheel + auto ent = CreateEntity(car); + auto transform = AddComponent(ent, "Transform"); + transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); + transform->Position = glm::vec3(1.1f, -1.5f, -1.3f); + auto Wheel = AddComponent(ent, "Wheel"); + Wheel->Hardpoint = glm::vec3(1.1f, 0.f, -1.3f);// HACK: make into component + Wheel->AxleID = 0; + Wheel->Mass = 10; + Wheel->Radius = 0.5f; + Wheel->Steering = true; + Wheel->SuspensionStrength = 20.f; + auto model = AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + CommitEntity(ent); + } + { + // Front Left Wheel + auto ent = CreateEntity(car); + auto transform = AddComponent(ent, "Transform"); + transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); + transform->Position = glm::vec3(-1.1f, -1.5f, -1.3f); + auto Wheel = AddComponent(ent, "Wheel"); + Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, -1.3f); + Wheel->AxleID = 0; + Wheel->Mass = 10; + Wheel->Radius = 0.5f; + Wheel->Steering = true; + Wheel->SuspensionStrength = 20.f; + auto model = AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + CommitEntity(ent); + } + { + // Back Right Wheel + auto ent = CreateEntity(car); + auto transform = AddComponent(ent, "Transform"); + transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); + transform->Position = glm::vec3(1.1f, -1.5f, 1.3f); + auto Wheel = AddComponent(ent, "Wheel"); + Wheel->Hardpoint = glm::vec3(1.1f, 0.f, 1.3f); + Wheel->AxleID = 1; + Wheel->Mass = 10; + Wheel->Radius = 0.5f; + Wheel->Steering = false; + Wheel->ConnectedToHandbrake = true; + Wheel->SuspensionStrength = 20.f; + auto model = AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + CommitEntity(ent); + } + { + // Back Left Wheel + auto ent = CreateEntity(car); + auto transform = AddComponent(ent, "Transform"); + transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); + transform->Position = glm::vec3(-1.1f, -1.5f, 1.3f); + auto Wheel = AddComponent(ent, "Wheel"); + Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, 1.3f); + Wheel->AxleID = 1; + Wheel->Mass = 10; + Wheel->Radius = 0.5f; + Wheel->Steering = false; + Wheel->ConnectedToHandbrake = true; + Wheel->SuspensionStrength = 20.f; + auto model = AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + CommitEntity(ent); + } + + CommitEntity(car); + } +*/ + for(int i = 0; i < 10; i++) diff --git a/src/GameWorld.cpp.orig b/src/GameWorld.cpp.orig index 73aac8b..34dc849 100644 --- a/src/GameWorld.cpp.orig +++ b/src/GameWorld.cpp.orig @@ -24,29 +24,88 @@ void GameWorld::Initialize() auto ground = CreateEntity(); auto transform = AddComponent(ground, "Transform"); transform->Position = glm::vec3(0, -5, 0); - transform->Scale = glm::vec3(1000.0f, 10.0f, 1000.0f); + transform->Scale = glm::vec3(400.0f, 10.0f, 400.0f); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(ground, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube.obj"; auto box = AddComponent(ground, "Box"); - box->Width = 500; + box->Width = 200; box->Height = 5; - box->Depth = 500; + box->Depth = 200; auto physics = AddComponent(ground, "Physics"); physics->Mass = 10; -<<<<<<< HEAD physics->Static = true; -======= + CommitEntity(ground); ->>>>>>> 84d6911... Barebones entity component commit events } +<<<<<<< HEAD +======= + { + auto jeep = CreateEntity(); + auto transform = AddComponent(jeep, "Transform"); + transform->Position = glm::vec3(0, 1, 0); + auto model = AddComponent(jeep, "Model"); + model->ModelFile = "Models/JeepV2/Chassi/chassi.OBJ"; + CommitEntity(jeep); + + { + auto wheel = CreateEntity(jeep); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(1.4f, 0.5546f, -0.9242f); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; + CommitEntity(wheel); + } + + { + auto wheel = CreateEntity(jeep); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(-1.4f, 0.5546f, -0.9242f); + transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; + CommitEntity(wheel); + } + + { + auto wheel = CreateEntity(jeep); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(0.2726f, 0.2805f, 1.9307f); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; + CommitEntity(wheel); + } + + { + auto wheel = CreateEntity(jeep); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(-0.2726f, 0.2805f, 1.9307f); + transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; + CommitEntity(wheel); + } + } + + { + auto TankTest = CreateEntity(); + auto transform = AddComponent(TankTest, "Transform"); + transform->Position = glm::vec3(1.5f, 0.7f, 5.f); + + auto model = AddComponent(TankTest, "Model"); + model->ModelFile = "Models/Placeholders/tank/Chassi.obj"; + CommitEntity(TankTest); + } +>>>>>>> 3412fa4... Jeep entity setup. + + for (int i = 0; i < 1; i++) { auto car = CreateEntity(); auto transform = AddComponent(car, "Transform"); - transform->Position = glm::vec3(0, 5, 0); + transform->Position = glm::vec3(0, (i+1)*5, 0); transform->Scale = glm::vec3(3, 1, 5); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(car, "Model"); @@ -58,107 +117,103 @@ void GameWorld::Initialize() box->Height = 0.5f; box->Depth = 2.5f; auto vehicle = AddComponent(car, "Vehicle"); + vehicle->TopSpeed = 500.f; + vehicle->MaxTorque = 1000.f; AddComponent(car, "Input"); { // Front Right Wheel auto ent = CreateEntity(car); auto transform = AddComponent(ent, "Transform"); - transform->Position = glm::vec3(1.1f, -0.5f, -1.3f); + transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); + transform->Position = glm::vec3(1.1f, -1.5f, -1.3f); auto Wheel = AddComponent(ent, "Wheel"); Wheel->Hardpoint = glm::vec3(1.1f, 0.f, -1.3f);// HACK: make into component Wheel->AxleID = 0; Wheel->Mass = 10; - Wheel->Radius = 0.6f; + Wheel->Radius = 0.5f; Wheel->Steering = true; + Wheel->SuspensionStrength = 20.f; + auto model = AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + CommitEntity(ent); } { // Front Left Wheel auto ent = CreateEntity(car); auto transform = AddComponent(ent, "Transform"); - transform->Position = glm::vec3(-1.1f, -0.5f, -1.3f); + transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); + transform->Position = glm::vec3(-1.1f, -1.5f, -1.3f); auto Wheel = AddComponent(ent, "Wheel"); Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, -1.3f); Wheel->AxleID = 0; Wheel->Mass = 10; - Wheel->Radius = 0.6f; + Wheel->Radius = 0.5f; Wheel->Steering = true; + Wheel->SuspensionStrength = 20.f; + auto model = AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + CommitEntity(ent); } { // Back Right Wheel auto ent = CreateEntity(car); auto transform = AddComponent(ent, "Transform"); - transform->Position = glm::vec3(1.1f, -0.5f, 1.3f); + transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); + transform->Position = glm::vec3(1.1f, -1.5f, 1.3f); auto Wheel = AddComponent(ent, "Wheel"); Wheel->Hardpoint = glm::vec3(1.1f, 0.f, 1.3f); Wheel->AxleID = 1; Wheel->Mass = 10; - Wheel->Radius = 0.6f; + Wheel->Radius = 0.5f; Wheel->Steering = false; + Wheel->ConnectedToHandbrake = true; + Wheel->SuspensionStrength = 20.f; + auto model = AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + CommitEntity(ent); } { // Back Left Wheel auto ent = CreateEntity(car); auto transform = AddComponent(ent, "Transform"); - transform->Position = glm::vec3(-1.1f, -0.5f, 1.3f); + transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); + transform->Position = glm::vec3(-1.1f, -1.5f, 1.3f); auto Wheel = AddComponent(ent, "Wheel"); Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, 1.3f); Wheel->AxleID = 1; Wheel->Mass = 10; - Wheel->Radius = 0.6f; + Wheel->Radius = 0.5f; Wheel->Steering = false; + Wheel->ConnectedToHandbrake = true; + Wheel->SuspensionStrength = 20.f; + auto model = AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + CommitEntity(ent); } -<<<<<<< HEAD + CommitEntity(car); } -======= - auto model = AddComponent(TankTest, "Model"); - model->ModelFile = "Models/Placeholders/tank/Chassi.obj"; - CommitEntity(TankTest); - } - for(int i = 0; i < 83; i++) + + for(int i = 0; i < 10; i++) { - auto light = CreateEntity(); - auto transform = AddComponent(light, "Transform"); - transform->Position = glm::vec3((float)(2*i)*glm::sin((float)i), 3, (float)(2*i)*glm::cos((float)i)); - - auto pointLight = AddComponent(light, "PointLight"); - pointLight->Specular = glm::vec3(0.1f, 0.1f, 0.1f); - pointLight->Diffuse = glm::vec3(0.05f, 0.36f, 1.f); - pointLight->constantAttenuation = 0.03f; - pointLight->linearAttenuation = 0.009f; - pointLight->quadraticAttenuation = 0.07f; - pointLight->spotExponent = 0.0f; - - auto model = AddComponent(light, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; - CommitEntity(light); - } ->>>>>>> 84d6911... Barebones entity component commit events - - - for(int i = 0; i < 50; i++) - { - auto ball = CreateEntity(); - auto transform = AddComponent(ball, "Transform"); - transform->Position = glm::vec3(243, 10 + i*10, 0); - transform->Scale = glm::vec3(10); + auto cube = CreateEntity(); + auto transform = AddComponent(cube, "Transform"); + transform->Position = glm::vec3(20, 10 + i*2, 0); + transform->Scale = glm::vec3(1); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); - auto model = AddComponent(ball, "Model"); + auto model = AddComponent(cube, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - auto physics = AddComponent(ball, "Physics"); -<<<<<<< HEAD + + auto physics = AddComponent(cube, "Physics"); physics->Mass = 100; - auto box = AddComponent(ball, "Box"); - box->Width = 5.f; - box->Height = 5.f; - box->Depth = 5.f; -======= - physics->Mass = 1; - CommitEntity(ball); ->>>>>>> 84d6911... Barebones entity component commit events + auto box = AddComponent(cube, "Box"); + box->Width = 0.5f; + box->Height = 0.5f; + box->Depth = 0.5f; + CommitEntity(cube); } { @@ -168,6 +223,7 @@ void GameWorld::Initialize() emitter->Path = "Sounds/korvring.wav"; emitter->Loop = true; GetSystem("SoundSystem")->PlaySound(emitter); + CommitEntity(entity); } } diff --git a/src/Shaders/Fragment.glsl b/src/Shaders/Fragment.glsl index 11a43ab..1909e84 100755 --- a/src/Shaders/Fragment.glsl +++ b/src/Shaders/Fragment.glsl @@ -52,7 +52,7 @@ void main() //float bias = 0.001 * tan(acos(cosTheta)); // cosTheta is dot( n,l ), clamped between 0 and 1 //bias = clamp(bias, 0.0, 0.01); float visibility = 1.0; - if (Input.ShadowCoord.x >= 0.0 && Input.ShadowCoord.x <= 1.0 && Input.ShadowCoord.y >= 0.0 && Input.ShadowCoord.y <= 1.0) + /*if (Input.ShadowCoord.x >= 0.0 && Input.ShadowCoord.x <= 1.0 && Input.ShadowCoord.y >= 0.0 && Input.ShadowCoord.y <= 1.0) { float bias = 0.00005; vec4 shadowMapValue = texture(shadowMap, Input.ShadowCoord.xy); @@ -60,7 +60,7 @@ void main() { visibility = 0.3; } - } + }*/ vec3 totalLighting = La * Ka * visibility; diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index 837ed5a..9fc476d 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -123,7 +123,7 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p hkQuaternion steeringOrientation = m_Vehicles[car]->m_wheelsInfo[wheelComponent->ID].m_steeringOrientationChassisSpace; hkReal spinAngle = -m_Vehicles[car]->m_wheelsInfo[wheelComponent->ID].m_spinAngle; glm::quat orientation = glm::quat(steeringOrientation(3), steeringOrientation(0), steeringOrientation(1), steeringOrientation(2)) * glm::angleAxis(spinAngle, glm::vec3(1, 0, 0)); - transformComponent->Orientation = orientation; + transformComponent->Orientation = orientation * wheelComponent->OriginalOrientation; } } else @@ -164,6 +164,7 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) if (wheelComponent) { wheelComponent->ID = m_Wheels.size(); + wheelComponent->OriginalOrientation = transformComponent->Orientation; m_Wheels.push_back(entity); } @@ -179,7 +180,6 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) hkpRigidBodyCinfo rigidBodyInfo; hkMassProperties massProperties; - if (sphereComponent) { shape = new hkpSphereShape(sphereComponent->Radius); From 0fbce570ff1bc535c0e85fb6649876e108ef7802 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 24 Apr 2014 02:36:31 +0200 Subject: [PATCH 19/37] Extended Model to support specular and normal maps --- src/Model.cpp | 10 +++++++++- src/Model.h | 4 +++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/Model.cpp b/src/Model.cpp index a2f42e9..547e940 100755 --- a/src/Model.cpp +++ b/src/Model.cpp @@ -17,11 +17,19 @@ Model::Model(OBJ &obj, ResourceManager* rm) if (face.Material != currentMaterial) { currentMaterial = face.Material; + // Load texture auto texture = std::shared_ptr(rm->Load("Texture", currentMaterial->DiffuseTexture.FileName)); + // TODO: Load normal map + std::shared_ptr normalMap = nullptr; + // Load specular map + std::shared_ptr specularMap = nullptr; + if (!currentMaterial->SpecularMap.FileName.empty()) + specularMap = std::shared_ptr(rm->Load("Texture", currentMaterial->SpecularMap.FileName)); + // TODO: Load material parameters // Create new texture group (start index of new group is upcoming index) - TextureGroup texGroup = { texture, index, index }; + TextureGroup texGroup = { texture, normalMap, specularMap, index, index }; TextureGroups.push_back(texGroup); currentTexGroup = &TextureGroups.back(); } diff --git a/src/Model.h b/src/Model.h index e1d7fa6..8d94a7d 100755 --- a/src/Model.h +++ b/src/Model.h @@ -21,7 +21,9 @@ public: struct TextureGroup { - std::shared_ptr Texture; + std::shared_ptr<::Texture> Texture; + std::shared_ptr<::Texture> NormalMap; + std::shared_ptr<::Texture> SpecularMap; unsigned int StartIndex; unsigned int EndIndex; }; From 613610d5b1676a5da8aaf5a67f262de2f530233a Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Thu, 24 Apr 2014 19:49:14 +0200 Subject: [PATCH 20/37] Fixed camera view matrix. --- src/Camera.cpp | 2 +- src/Systems/RenderSystem.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Camera.cpp b/src/Camera.cpp index 2db69de..1256e64 100755 --- a/src/Camera.cpp +++ b/src/Camera.cpp @@ -77,7 +77,7 @@ void Camera::UpdateProjectionMatrix() void Camera::UpdateViewMatrix() { - m_ViewMatrix = glm::translate(glm::toMat4(m_Orientation), -m_Position); + m_ViewMatrix = glm::toMat4(glm::inverse(m_Orientation)) * glm::translate(-m_Position); } void Camera::FOV(float val) diff --git a/src/Systems/RenderSystem.cpp b/src/Systems/RenderSystem.cpp index e296023..2748eda 100755 --- a/src/Systems/RenderSystem.cpp +++ b/src/Systems/RenderSystem.cpp @@ -49,8 +49,8 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa auto cameraComponent = m_World->GetComponent(entity, "Camera"); if (cameraComponent != nullptr) { - m_Renderer->GetCamera()->Position(transformComponent->Position); - m_Renderer->GetCamera()->Orientation(transformComponent->Orientation); + m_Renderer->GetCamera()->Position(m_TransformSystem->AbsolutePosition(entity)); + m_Renderer->GetCamera()->Orientation(m_TransformSystem->AbsoluteOrientation(entity)); m_Renderer->GetCamera()->FOV(cameraComponent->FOV); m_Renderer->GetCamera()->NearClip(cameraComponent->NearClip); From 824b31ff6b0b19820dd21ba78f411c3130c3a466 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Thu, 24 Apr 2014 20:09:46 +0200 Subject: [PATCH 21/37] FreeSteering fixed --- src/Systems/FreeSteeringSystem.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Systems/FreeSteeringSystem.cpp b/src/Systems/FreeSteeringSystem.cpp index 341f01c..57f057e 100755 --- a/src/Systems/FreeSteeringSystem.cpp +++ b/src/Systems/FreeSteeringSystem.cpp @@ -20,8 +20,8 @@ void Systems::FreeSteeringSystem::UpdateEntity(double dt, EntityID entity, Entit { auto transform = m_World->GetComponent(entity, "Transform"); - glm::vec3 Camera_Right = glm::vec3(glm::vec4(1, 0, 0, 0) * transform->Orientation); - glm::vec3 Camera_Forward = glm::vec3(glm::vec4(0, 0, 1, 0) * transform->Orientation); + glm::vec3 Camera_Right = glm::vec3(transform->Orientation * glm::vec4(1, 0, 0, 0)); + glm::vec3 Camera_Forward = glm::vec3(transform->Orientation * glm::vec4(0, 0, -1, 0)); float speed = steering->Speed; if (input->KeyState[GLFW_KEY_LEFT_SHIFT]) @@ -42,11 +42,11 @@ void Systems::FreeSteeringSystem::UpdateEntity(double dt, EntityID entity, Entit } if (input->KeyState[GLFW_KEY_W]) { - transform->Position -= Camera_Forward * (float)dt * speed; + transform->Position += Camera_Forward * (float)dt * speed; } if (input->KeyState[GLFW_KEY_S]) { - transform->Position += Camera_Forward * (float)dt * speed; + transform->Position -= Camera_Forward * (float)dt * speed; } if (input->KeyState[GLFW_KEY_SPACE]) { @@ -61,9 +61,9 @@ void Systems::FreeSteeringSystem::UpdateEntity(double dt, EntityID entity, Entit { // TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS // spelling tobias :3 //--------------------------------------------------------------------- - transform->Orientation = glm::angleAxis(input->dY / 300.f, glm::vec3(1, 0, 0)) * transform->Orientation; + transform->Orientation = glm::angleAxis(input->dX / 300.f, glm::vec3(0, -1, 0)) * transform->Orientation; + transform->Orientation = transform->Orientation * glm::angleAxis(input->dY / 300.f, glm::vec3(-1, 0, 0)); - transform->Orientation = transform->Orientation * glm::angleAxis(input->dX / 300.f, glm::vec3(0, 1, 0)); //--------------------------------------------------------------------- // TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS } From 8facd9dc9a3d44f6561a3627efcc1260d74e362e Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Thu, 24 Apr 2014 23:10:59 +0200 Subject: [PATCH 22/37] Rigidbody physics fixed. --- src/Components/Wheel.h | 7 ------ src/GameWorld.cpp | 43 +++++++++++++++++++---------------- src/Systems/PhysicsSystem.cpp | 23 +++++++++++-------- 3 files changed, 37 insertions(+), 36 deletions(-) diff --git a/src/Components/Wheel.h b/src/Components/Wheel.h index 5c005c7..d4917db 100644 --- a/src/Components/Wheel.h +++ b/src/Components/Wheel.h @@ -38,10 +38,3 @@ private: } #endif // Components_Wheel_h__ - -/* -m_currentSuspensionLength -m_suspension -m_steeringOrientationChassisSpace -m_spinAngle -*/ \ No newline at end of file diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 06b965f..72ca4a6 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -6,18 +6,7 @@ void GameWorld::Initialize() World::Initialize(); - { - auto camera = CreateEntity(); - auto transform = AddComponent(camera, "Transform"); - transform->Position.z = 20.f; - transform->Position.y = 20.f; - transform->Orientation = glm::quat(glm::vec3(glm::pi() / 8.f, 0.f, 0.f)); - auto cameraComp = AddComponent(camera, "Camera"); - cameraComp->FarClip = 2000.f; - AddComponent(camera, "Input"); - auto freeSteering = AddComponent(camera, "FreeSteering"); - CommitEntity(camera); - } + { @@ -53,16 +42,30 @@ void GameWorld::Initialize() box->Height = 0.727f; box->Depth = 2.594f; auto vehicle = AddComponent(jeep, "Vehicle"); - vehicle->TopSpeed = 500.f; - vehicle->MaxTorque = 1000.f; + AddComponent(jeep, "Input"); + + { + auto camera = CreateEntity(); + auto transform = AddComponent(camera, "Transform"); + transform->Position.z = 20.f; + transform->Position.y = 10.f; + transform->Orientation = glm::quat(glm::vec3(-glm::pi() / 8.f, 0.f, 0.f)); + auto cameraComp = AddComponent(camera, "Camera"); + cameraComp->FarClip = 2000.f; + AddComponent(camera, "Input"); + auto freeSteering = AddComponent(camera, "FreeSteering"); + CommitEntity(camera); + } + { auto chassis = CreateEntity(jeep); auto transform = AddComponent(chassis, "Transform"); transform->Position = glm::vec3(0, -0.6577f, 0); auto model = AddComponent(chassis, "Model"); model->ModelFile = "Models/JeepV2/Chassi/chassi.OBJ"; + } { @@ -75,10 +78,10 @@ void GameWorld::Initialize() auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); Wheel->AxleID = 0; - Wheel->Mass = 10; + Wheel->Mass = 50; Wheel->Radius = 0.837f; Wheel->Steering = true; - Wheel->SuspensionStrength = 50.f; + Wheel->SuspensionStrength = 40.f; Wheel->Friction = 4.0f; Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); @@ -95,10 +98,10 @@ void GameWorld::Initialize() auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); Wheel->AxleID = 0; - Wheel->Mass = 10; + Wheel->Mass = 50; Wheel->Radius = 0.837f; Wheel->Steering = true; - Wheel->SuspensionStrength = 50.f; + Wheel->SuspensionStrength = 40.f; Wheel->Friction = 4.0f; Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); @@ -239,7 +242,7 @@ void GameWorld::Initialize() CommitEntity(cube); } - { + /*{ auto entity = CreateEntity(); AddComponent(entity, "Transform"); auto emitter = AddComponent(entity, "SoundEmitter"); @@ -247,7 +250,7 @@ void GameWorld::Initialize() emitter->Loop = true; GetSystem("SoundSystem")->PlaySound(emitter); CommitEntity(entity); - } + }*/ } void GameWorld::Update(double dt) diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index 9fc476d..702233d 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -126,17 +126,22 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p transformComponent->Orientation = orientation * wheelComponent->OriginalOrientation; } } - else + else if(m_Vehicles.find(entity) != m_Vehicles.end()) { - if(m_Vehicles.find(entity) != m_Vehicles.end()) + hkVector4 position = m_RigidBodies[entity]->getPosition(); + transformComponent->Position = glm::vec3(position(0), position(1), position(2)); + hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); + transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); + + } + else if(m_RigidBodies.find(entity) != m_RigidBodies.end()) + { + if(m_RigidBodies[entity]->isActive()) { - if(m_RigidBodies[entity]->isActive()) - { - hkVector4 position = m_RigidBodies[entity]->getPosition(); - transformComponent->Position = glm::vec3(position(0), position(1), position(2)); - hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); - transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); - } + hkVector4 position = m_RigidBodies[entity]->getPosition(); + transformComponent->Position = glm::vec3(position(0), position(1), position(2)); + hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); + transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); } } From 7da030d8cdd2488e69ea6e19ed563c90aab7336f Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 25 Apr 2014 00:23:49 +0200 Subject: [PATCH 23/37] Bloody .orig files! --- .gitignore | 1 + src/GameWorld.cpp.orig | 413 ---------------------------- src/Systems/PhysicsSystem.cpp.orig | 426 ----------------------------- src/Systems/PhysicsSystem.h.orig | 91 ------ 4 files changed, 1 insertion(+), 930 deletions(-) delete mode 100644 src/GameWorld.cpp.orig delete mode 100644 src/Systems/PhysicsSystem.cpp.orig delete mode 100644 src/Systems/PhysicsSystem.h.orig diff --git a/.gitignore b/.gitignore index 4f30c2a..3b5dc2e 100755 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,7 @@ ipch/ [Dd]ebug*/ [Rr]elease*/ Ankh.NoLoad +*.orig assets/ !libs/*.lib \ No newline at end of file diff --git a/src/GameWorld.cpp.orig b/src/GameWorld.cpp.orig deleted file mode 100644 index 1203b42..0000000 --- a/src/GameWorld.cpp.orig +++ /dev/null @@ -1,413 +0,0 @@ -#include "PrecompiledHeader.h" -#include "GameWorld.h" - -void GameWorld::Initialize() -{ - World::Initialize(); - -<<<<<<< HEAD - m_ResourceManager.Preload("Model", "Models/Placeholders/PhysicsTest/Plane.obj"); - m_ResourceManager.Preload("Model", "Models/Placeholders/PhysicsTest/ArrowCube.obj"); - - RegisterComponents(); -======= ->>>>>>> havok - - { - auto camera = CreateEntity(); - auto transform = AddComponent(camera, "Transform"); - transform->Position.z = 20.f; - transform->Position.y = 20.f; - transform->Orientation = glm::quat(glm::vec3(glm::pi() / 8.f, 0.f, 0.f)); - auto cameraComp = AddComponent(camera, "Camera"); - cameraComp->FarClip = 2000.f; - AddComponent(camera, "Input"); - auto freeSteering = AddComponent(camera, "FreeSteering"); - CommitEntity(camera); - } - - - { - auto ground = CreateEntity(); - auto transform = AddComponent(ground, "Transform"); - transform->Position = glm::vec3(0, -5, 0); - transform->Scale = glm::vec3(400.0f, 10.0f, 400.0f); - transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); - auto model = AddComponent(ground, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube.obj"; - auto box = AddComponent(ground, "Box"); - box->Width = 200; - box->Height = 5; - box->Depth = 200; - - auto physics = AddComponent(ground, "Physics"); - physics->Mass = 10; -<<<<<<< HEAD - CommitEntity(ground); - } - - { - auto jeep = CreateEntity(); - auto transform = AddComponent(jeep, "Transform"); - transform->Position = glm::vec3(0, 1, 0); - - auto model = AddComponent(jeep, "Model"); - model->ModelFile = "Models/JeepV2/Chassi/chassi.OBJ"; - CommitEntity(jeep); - - { - auto wheel = CreateEntity(jeep); - auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(1.4f, 0.5546f, -0.9242f); - auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; - CommitEntity(wheel); - } - - { - auto wheel = CreateEntity(jeep); - auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(-1.4f, 0.5546f, -0.9242f); - transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); - auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; - CommitEntity(wheel); - } - - { - auto wheel = CreateEntity(jeep); - auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(0.2726f, 0.2805f, 1.9307f); - auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; - CommitEntity(wheel); - } - - { - auto wheel = CreateEntity(jeep); - auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(-0.2726f, 0.2805f, 1.9307f); - transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); - auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; - CommitEntity(wheel); - } - } - - { - auto TankTest = CreateEntity(); - auto transform = AddComponent(TankTest, "Transform"); - transform->Position = glm::vec3(1.5f, 0.7f, 5.f); - - auto model = AddComponent(TankTest, "Model"); - model->ModelFile = "Models/Placeholders/tank/Chassi.obj"; - CommitEntity(TankTest); - } - - for(int i = 0; i < 83; i++) - { - auto light = CreateEntity(); - auto transform = AddComponent(light, "Transform"); - transform->Position = glm::vec3((float)(2*i)*glm::sin((float)i), 3, (float)(2*i)*glm::cos((float)i)); - - auto pointLight = AddComponent(light, "PointLight"); - pointLight->Specular = glm::vec3(0.1f, 0.1f, 0.1f); - pointLight->Diffuse = glm::vec3(0.05f, 0.36f, 1.f); - pointLight->constantAttenuation = 0.03f; - pointLight->linearAttenuation = 0.009f; - pointLight->quadraticAttenuation = 0.07f; - pointLight->spotExponent = 0.0f; - - auto model = AddComponent(light, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; - CommitEntity(light); - } - - for(int i = 0; i < 500; i++) - { - auto ball = CreateEntity(); - auto transform = AddComponent(ball, "Transform"); - transform->Position = glm::vec3(i/5.f, 5 + i*2, i/5.f); - transform->Scale = glm::vec3(1.0f, 1.0f, 1.0f); - transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); - auto model = AddComponent(ball, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Sphere.obj"; - auto sphere = AddComponent(ball, "Sphere"); - sphere->Radius = 0.5; - auto physics = AddComponent(ball, "Physics"); - physics->Mass = 1; - CommitEntity(ball); -======= - physics->Static = true; - - CommitEntity(ground); - } - - - { - auto jeep = CreateEntity(); - auto transform = AddComponent(jeep, "Transform"); - transform->Position = glm::vec3(0, 2, 0); - - auto physics = AddComponent(jeep, "Physics"); - physics->Mass = 1200; - auto box = AddComponent(jeep, "Box"); - box->Width = 1.487f; - box->Height = 0.727f; - box->Depth = 2.594f; - auto vehicle = AddComponent(jeep, "Vehicle"); - vehicle->TopSpeed = 500.f; - vehicle->MaxTorque = 1000.f; - AddComponent(jeep, "Input"); - - { - auto chassis = CreateEntity(jeep); - auto transform = AddComponent(chassis, "Transform"); - transform->Position = glm::vec3(0, -0.6577f, 0); - auto model = AddComponent(chassis, "Model"); - model->ModelFile = "Models/JeepV2/Chassi/chassi.OBJ"; - } - - { - auto wheel = CreateEntity(jeep); - auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(1.4f, 0.5546f - 0.6577f - 0.2, -0.9242f); - transform->Scale = glm::vec3(1.0f); - auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; - auto Wheel = AddComponent(wheel, "Wheel"); - Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); - Wheel->AxleID = 0; - Wheel->Mass = 10; - Wheel->Radius = 0.837f; - Wheel->Steering = true; - Wheel->SuspensionStrength = 50.f; - Wheel->Friction = 4.0f; - Wheel->ConnectedToHandbrake = true; - CommitEntity(wheel); - } - - { - auto wheel = CreateEntity(jeep); - auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(-1.4f, 0.5546f - 0.6577f - 0.2, -0.9242f); - transform->Scale = glm::vec3(1.0f); - transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); - auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; - auto Wheel = AddComponent(wheel, "Wheel"); - Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); - Wheel->AxleID = 0; - Wheel->Mass = 10; - Wheel->Radius = 0.837f; - Wheel->Steering = true; - Wheel->SuspensionStrength = 50.f; - Wheel->Friction = 4.0f; - Wheel->ConnectedToHandbrake = true; - CommitEntity(wheel); - } - - { - auto wheel = CreateEntity(jeep); - auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(0.2726f, 0.2805f - 0.6577f, 1.9307f); - auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; - auto Wheel = AddComponent(wheel, "Wheel"); - Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); - Wheel->AxleID = 1; - Wheel->Mass = 10; - Wheel->Radius = 0.737f; - Wheel->Steering = false; - Wheel->SuspensionStrength = 50.f; - Wheel->Friction = 4.0f; - CommitEntity(wheel); - } - - { - auto wheel = CreateEntity(jeep); - auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(-0.2726f, 0.2805f - 0.6577f, 1.9307f); - transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); - auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; - auto Wheel = AddComponent(wheel, "Wheel"); - Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); - Wheel->AxleID = 1; - Wheel->Mass = 10; - Wheel->Radius = 0.737f; - Wheel->Steering = false; - Wheel->SuspensionStrength = 50.f; - Wheel->Friction = 4.0f; - CommitEntity(wheel); - } - CommitEntity(jeep); - } - -/* - - { - // Front Right Wheel - auto ent = CreateEntity(car); - auto transform = AddComponent(ent, "Transform"); - transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(1.1f, -1.5f, -1.3f); - auto Wheel = AddComponent(ent, "Wheel"); - Wheel->Hardpoint = glm::vec3(1.1f, 0.f, -1.3f);// HACK: make into component - Wheel->AxleID = 0; - Wheel->Mass = 10; - Wheel->Radius = 0.5f; - Wheel->Steering = true; - Wheel->SuspensionStrength = 20.f; - auto model = AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - CommitEntity(ent); - } - { - // Front Left Wheel - auto ent = CreateEntity(car); - auto transform = AddComponent(ent, "Transform"); - transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(-1.1f, -1.5f, -1.3f); - auto Wheel = AddComponent(ent, "Wheel"); - Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, -1.3f); - Wheel->AxleID = 0; - Wheel->Mass = 10; - Wheel->Radius = 0.5f; - Wheel->Steering = true; - Wheel->SuspensionStrength = 20.f; - auto model = AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - CommitEntity(ent); - } - { - // Back Right Wheel - auto ent = CreateEntity(car); - auto transform = AddComponent(ent, "Transform"); - transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(1.1f, -1.5f, 1.3f); - auto Wheel = AddComponent(ent, "Wheel"); - Wheel->Hardpoint = glm::vec3(1.1f, 0.f, 1.3f); - Wheel->AxleID = 1; - Wheel->Mass = 10; - Wheel->Radius = 0.5f; - Wheel->Steering = false; - Wheel->ConnectedToHandbrake = true; - Wheel->SuspensionStrength = 20.f; - auto model = AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - CommitEntity(ent); - } - { - // Back Left Wheel - auto ent = CreateEntity(car); - auto transform = AddComponent(ent, "Transform"); - transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(-1.1f, -1.5f, 1.3f); - auto Wheel = AddComponent(ent, "Wheel"); - Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, 1.3f); - Wheel->AxleID = 1; - Wheel->Mass = 10; - Wheel->Radius = 0.5f; - Wheel->Steering = false; - Wheel->ConnectedToHandbrake = true; - Wheel->SuspensionStrength = 20.f; - auto model = AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - CommitEntity(ent); - } - - CommitEntity(car); - } -*/ - - - - for(int i = 0; i < 10; i++) - { - auto cube = CreateEntity(); - auto transform = AddComponent(cube, "Transform"); - transform->Position = glm::vec3(20, 10 + i*2, 0); - transform->Scale = glm::vec3(1); - transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); - auto model = AddComponent(cube, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - - auto physics = AddComponent(cube, "Physics"); - physics->Mass = 100; - auto box = AddComponent(cube, "Box"); - box->Width = 0.5f; - box->Height = 0.5f; - box->Depth = 0.5f; - CommitEntity(cube); ->>>>>>> havok - } - - { - auto entity = CreateEntity(); - AddComponent(entity, "Transform"); - auto emitter = AddComponent(entity, "SoundEmitter"); - emitter->Path = "Sounds/korvring.wav"; - emitter->Loop = true; - GetSystem("SoundSystem")->PlaySound(emitter); - CommitEntity(entity); - } -} - -void GameWorld::Update(double dt) -{ - World::Update(dt); -} - -void GameWorld::RegisterComponents() -{ -<<<<<<< HEAD - m_ComponentFactory.Register("Transform", []() { return new Components::Transform(); }); - m_ComponentFactory.Register("Template", []() { return new Components::Template(); }); -======= - m_ComponentFactory.Register("Camera", []() { return new Components::Camera(); }); - m_ComponentFactory.Register("DirectionalLight", []() { return new Components::DirectionalLight(); }); - m_ComponentFactory.Register("Input", []() { return new Components::Input(); }); - m_ComponentFactory.Register("Model", []() { return new Components::Model(); }); - m_ComponentFactory.Register("ParticleEmitter", []() { return new Components::ParticleEmitter(); }); - m_ComponentFactory.Register("PointLight", []() { return new Components::PointLight(); }); - m_ComponentFactory.Register("SoundEmitter", []() { return new Components::SoundEmitter(); }); - m_ComponentFactory.Register("Sprite", []() { return new Components::Sprite(); }); - m_ComponentFactory.Register("Template", []() { return new Components::Template(); }); - m_ComponentFactory.Register("Transform", []() { return new Components::Transform(); }); - m_ComponentFactory.Register("FreeSteering", []() { return new Components::FreeSteering(); }); - m_ComponentFactory.Register("Physics", []() { return new Components::Physics(); }); ->>>>>>> havok - m_ComponentFactory.Register("Sphere", []() { return new Components::Sphere(); }); - m_ComponentFactory.Register("Box", []() { return new Components::Box (); }); - m_ComponentFactory.Register("Vehicle", []() { return new Components::Vehicle(); }); - m_ComponentFactory.Register("Wheel", []() { return new Components::Wheel(); }); -} - -void GameWorld::RegisterSystems() -{ - m_SystemFactory.Register("TransformSystem", [this]() { return new Systems::TransformSystem(this); }); - //m_SystemFactory.Register("LevelGenerationSystem", [this]() { return new Systems::LevelGenerationSystem(this); }); - m_SystemFactory.Register("InputSystem", [this]() { return new Systems::InputSystem(this, m_Renderer); }); - //m_SystemFactory.Register("CollisionSystem", [this]() { return new Systems::CollisionSystem(this); }); - ////m_SystemFactory.Register("ParticleSystem", [this]() { return new Systems::ParticleSystem(this); }); - //m_SystemFactory.Register("PlayerSystem", [this]() { return new Systems::PlayerSystem(this); }); - m_SystemFactory.Register("FreeSteeringSystem", [this]() { return new Systems::FreeSteeringSystem(this); }); - m_SystemFactory.Register("SoundSystem", [this]() { return new Systems::SoundSystem(this); }); - m_SystemFactory.Register("PhysicsSystem", [this]() { return new Systems::PhysicsSystem(this); }); - m_SystemFactory.Register("RenderSystem", [this]() { return new Systems::RenderSystem(this, m_Renderer); }); -} - -void GameWorld::AddSystems() -{ - AddSystem("TransformSystem"); - //AddSystem("LevelGenerationSystem"); - AddSystem("InputSystem"); - //AddSystem("CollisionSystem"); - ////AddSystem("ParticleSystem"); - //AddSystem("PlayerSystem"); - AddSystem("FreeSteeringSystem"); - AddSystem("SoundSystem"); - AddSystem("PhysicsSystem"); - AddSystem("RenderSystem"); -} \ No newline at end of file diff --git a/src/Systems/PhysicsSystem.cpp.orig b/src/Systems/PhysicsSystem.cpp.orig deleted file mode 100644 index 1f3913f..0000000 --- a/src/Systems/PhysicsSystem.cpp.orig +++ /dev/null @@ -1,426 +0,0 @@ -#include "PrecompiledHeader.h" - -// We’re not using anything product specific yet. We undef these so we don’t get the usual -// product initialization for the products. -#undef HK_FEATURE_PRODUCT_AI -#undef HK_FEATURE_PRODUCT_ANIMATION -#undef HK_FEATURE_PRODUCT_CLOTH -#undef HK_FEATURE_PRODUCT_DESTRUCTION_2012 -#undef HK_FEATURE_PRODUCT_DESTRUCTION -#undef HK_FEATURE_PRODUCT_BEHAVIOR -#undef HK_FEATURE_PRODUCT_PHYSICS_2012 -//#undef HK_FEATURE_PRODUCT_PHYSICS -// Also we’re not using any serialization/versioning so we don’t need any of these. -#define HK_EXCLUDE_FEATURE_SerializeDeprecatedPre700 -#define HK_EXCLUDE_FEATURE_RegisterVersionPatches -#define HK_EXCLUDE_FEATURE_RegisterReflectedClasses -#define HK_EXCLUDE_FEATURE_MemoryTracker -#define HK_CLASSES_FILE "Common/Serialize/classlist/hkClasses.h" -#include "Common/Serialize/Util/hkBuiltinTypeRegistry.cxx" -#define HK_COMPAT_FILE "Common/Compat/hkCompatVersions.h" -// This include generates an initialization function based on the products -// and the excluded features. -#include -#include -#include "PhysicsSystem.h" -#include "World.h" - - - -Systems::PhysicsSystem::PhysicsSystem(World* world) : System(world) -{ - m_Accumulator = 0; - { - hkMemorySystem::FrameInfo finfo(500 * 1024); // Allocate 500KB of Physics solver buffer - hkMemoryRouter* memoryRouter = hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, finfo); - hkBaseSystem::init(memoryRouter, HavokErrorReport); - - - hkpWorldCinfo worldInfo; - worldInfo.setupSolverInfo(hkpWorldCinfo::SOLVER_TYPE_4ITERS_MEDIUM); - worldInfo.m_gravity = hkVector4(0.0f, -9.8f, 0.0f); - worldInfo.m_broadPhaseBorderBehaviour = hkpWorldCinfo::BROADPHASE_BORDER_FIX_ENTITY; // just fix the entity if the object falls off too far - - // You must specify the size of the broad phase - objects should not be simulated outside this region - worldInfo.setBroadPhaseWorldSize(10000.0f); - m_PhysicsWorld = new hkpWorld(worldInfo); - } - // Register all collision agents, even though only box - box will be used in this particular example. - // It's important to register collision agents before adding any entities to the world. - hkpAgentRegisterUtil::registerAllAgents(m_PhysicsWorld->getCollisionDispatcher()); - - // - // Initialize the visual debugger so we can connect remotely to the simulation - // The context must exist beyond the use of the VDB instance, and you can make - // whatever contexts you like for your own viewer types. - // - hkpPhysicsContext* context = new hkpPhysicsContext; - hkpPhysicsContext::registerAllPhysicsProcesses(); // all the physics viewers - context->addWorld(m_PhysicsWorld); // add the physics world so the viewers can see it - SetupVisualDebugger(context); - - //SetupPhysics(m_PhysicsWorld); -} - -void Systems::PhysicsSystem::RegisterComponents(ComponentFactory* cf) -{ - cf->Register("Physics", []() { return new Components::Physics(); }); -} - -void Systems::PhysicsSystem::Update(double dt) -{ -<<<<<<< HEAD - static const double timestep = 1 / 60.0; -======= - for (auto pair : *m_World->GetEntities()) - { - EntityID entity = pair.first; - - if (m_RigidBodies.find(entity) == m_RigidBodies.end()) - continue; - - auto transformComponent = m_World->GetComponent(entity, "Transform"); - if (!transformComponent) - continue; - - - if(m_RigidBodies[entity]->isActive()) - { - hkVector4 position(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); - hkQuaternion rotation(transformComponent->Orientation.x, transformComponent->Orientation.y, transformComponent->Orientation.z, transformComponent->Orientation.w); - m_RigidBodies[entity]->setPositionAndRotation(position, rotation); - } - - } - - - - - static const double timestep = 1 / 30.0; ->>>>>>> havok - m_Accumulator += dt; - while (m_Accumulator >= timestep) - { - m_PhysicsWorld->stepDeltaTime(timestep); - m_Accumulator -= timestep; - } - - // Step the visual debugger - StepVisualDebugger(); -} - -void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) -{ - auto transformComponent = m_World->GetComponent(entity, "Transform"); - if (!transformComponent) - return; - - auto wheelComponent = m_World->GetComponent(entity, "Wheel"); - if (wheelComponent) - { - EntityID car = m_World->GetEntityParent(entity); - if(m_Vehicles.find(car) != m_Vehicles.end()) - { - m_Vehicles[car]->getChassis()->activate(); - - hkVector4 hardPoint = m_Vehicles[car]->m_suspension->m_wheelParams[wheelComponent->ID].m_hardpointChassisSpace; - hkVector4 suspensionDirection = m_Vehicles[car]->m_suspension->m_wheelParams[wheelComponent->ID].m_directionChassisSpace; - hkReal suspensionLength = m_Vehicles[car]->m_wheelsInfo[wheelComponent->ID].m_currentSuspensionLength; - glm::vec3 position = glm::vec3(hardPoint(0) + (suspensionDirection(0) * suspensionLength), hardPoint(1) + (suspensionDirection(1) * suspensionLength), hardPoint(2) + (suspensionDirection(2) * suspensionLength)); - transformComponent->Position = position; - - hkQuaternion steeringOrientation = m_Vehicles[car]->m_wheelsInfo[wheelComponent->ID].m_steeringOrientationChassisSpace; - hkReal spinAngle = -m_Vehicles[car]->m_wheelsInfo[wheelComponent->ID].m_spinAngle; - glm::quat orientation = glm::quat(steeringOrientation(3), steeringOrientation(0), steeringOrientation(1), steeringOrientation(2)) * glm::angleAxis(spinAngle, glm::vec3(1, 0, 0)); - transformComponent->Orientation = orientation * wheelComponent->OriginalOrientation; - } - } - else - { - if(m_Vehicles.find(entity) != m_Vehicles.end()) - { - if(m_RigidBodies[entity]->isActive()) - { - hkVector4 position = m_RigidBodies[entity]->getPosition(); - transformComponent->Position = glm::vec3(position(0), position(1), position(2)); - hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); - transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); - } - } - } - - - // HACK: Vehicle test-controls - auto vehicleComponent = m_World->GetComponent(entity, "Vehicle"); - auto inputComponent = m_World->GetComponent(entity, "Input"); - if (vehicleComponent && inputComponent) - { - hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)m_Vehicles[entity]->m_deviceStatus; - deviceStatus->m_positionY = inputComponent->KeyState[GLFW_KEY_UP] * -1 + inputComponent->KeyState[GLFW_KEY_DOWN] * 1; - deviceStatus->m_positionX = inputComponent->KeyState[GLFW_KEY_LEFT] * -1 + inputComponent->KeyState[GLFW_KEY_RIGHT] * 1; - deviceStatus->m_handbrakeButtonPressed = inputComponent->KeyState[GLFW_KEY_RIGHT_CONTROL]; - } -} - -void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) -{ - auto transformComponent = m_World->GetComponent(entity, "Transform"); - if (!transformComponent) - return; - - - auto wheelComponent = m_World->GetComponent(entity, "Wheel"); - if (wheelComponent) - { - wheelComponent->ID = m_Wheels.size(); - wheelComponent->OriginalOrientation = transformComponent->Orientation; - m_Wheels.push_back(entity); - } - - auto physicsComponent = m_World->GetComponent(entity, "Physics"); - if (!physicsComponent) - return; - - auto sphereComponent = m_World->GetComponent(entity, "Sphere"); - auto boxComponent = m_World->GetComponent(entity, "Box"); - - - hkpConvexShape* shape; - hkpRigidBodyCinfo rigidBodyInfo; - hkMassProperties massProperties; - - if (sphereComponent) - { - shape = new hkpSphereShape(sphereComponent->Radius); - rigidBodyInfo.m_shape = shape; - - if (physicsComponent->Static) - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; - } - else - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_SPHERE_INERTIA; - } - - hkpInertiaTensorComputer::computeSphereVolumeMassProperties(sphereComponent->Radius, physicsComponent->Mass, massProperties); - - } - else if (boxComponent) - { - hkReal thickness = 0.05; - shape = new hkpBoxShape(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness)); - rigidBodyInfo.m_shape = shape; - if (physicsComponent->Static) - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; - } - else - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_BOX_INERTIA; - } - hkpInertiaTensorComputer::computeBoxSurfaceMassProperties(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness), physicsComponent->Mass, thickness, massProperties); - } - else - { - return; - } - - rigidBodyInfo.m_position.set(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); - rigidBodyInfo.m_inertiaTensor = massProperties.m_inertiaTensor; - rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass; - rigidBodyInfo.m_mass = massProperties.m_mass; - - // Create RigidBody - hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo); - - - auto vehicleComponent = m_World->GetComponent(entity, "Vehicle"); - if (vehicleComponent && m_Vehicles.find(entity) == m_Vehicles.end()) - { - for (int i = 0; i < m_Wheels.size(); i++) - { - if(m_World->GetEntityParent(m_Wheels[i]) != entity) - { - m_Wheels.erase(m_Wheels.begin() + i); - i--; - } - } - VehicleSetup vehicleSetup; - - // Create the basic vehicle. - m_Vehicles[entity] = new hkpVehicleInstance(rigidBody); - vehicleSetup.buildVehicle(m_World, m_PhysicsWorld, *m_Vehicles[entity], entity, m_Wheels); - // Add the vehicle's entities and phantoms to the world - m_Vehicles[entity]->addToWorld(m_PhysicsWorld); - - m_RigidBodies[entity] = rigidBody; - - // The vehicle is an action - m_PhysicsWorld->addAction(m_Vehicles[entity]); - - //m_Vehicles[entity]->m_rpm = 0.0f; // Not sure why this one should be here - m_Wheels.clear(); - shape->removeReference(); - rigidBody->removeReference(); - } - else - { - m_PhysicsWorld->addEntity(rigidBody); - m_RigidBodies[entity] = rigidBody; - shape->removeReference(); - rigidBody->removeReference(); - } -} -/* - -void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent) -{ - auto transformComponent = m_World->GetComponent(entity, "Transform"); - if (!transformComponent) - return; - - auto physicsComponent = m_World->GetComponent(entity, "Physics"); - if (!physicsComponent) - return; - - auto sphereComponent = m_World->GetComponent(entity, "Sphere"); - auto boxComponent = m_World->GetComponent(entity, "Box"); - - - hkpConvexShape* shape; - hkpRigidBodyCinfo rigidBodyInfo; - hkMassProperties massProperties; - - - if (sphereComponent) - { - shape = new hkpSphereShape(sphereComponent->Radius); - rigidBodyInfo.m_shape = shape; - - if (physicsComponent->Static) - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; - } - else - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_SPHERE_INERTIA; - } - - hkpInertiaTensorComputer::computeSphereVolumeMassProperties(sphereComponent->Radius, physicsComponent->Mass, massProperties); - - } - else if (boxComponent) - { - hkReal thickness = 0.05; - shape = new hkpBoxShape(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness)); - rigidBodyInfo.m_shape = shape; - if (physicsComponent->Static) - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; - } - else - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_BOX_INERTIA; - } - hkpInertiaTensorComputer::computeBoxSurfaceMassProperties(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness), physicsComponent->Mass, thickness, massProperties); - } - else - { - return; - } - - rigidBodyInfo.m_position.set(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); - rigidBodyInfo.m_inertiaTensor = massProperties.m_inertiaTensor; - rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass; - rigidBodyInfo.m_mass = massProperties.m_mass; - - // Create RigidBody - hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo); - - - auto vehicleComponent = m_World->GetComponent(entity, "Vehicle"); - if (vehicleComponent && m_Vehicles.find(entity) == m_Vehicles.end()) - { - VehicleSetup vehicleSetup; - - // Create the basic vehicle. - m_Vehicles[entity] = new hkpVehicleInstance(rigidBody); - vehicleSetup.buildVehicle(m_PhysicsWorld, *m_Vehicles[entity]); - // Add the vehicle's entities and phantoms to the world - m_Vehicles[entity]->addToWorld(m_PhysicsWorld); - - m_RigidBodies[entity] = rigidBody; - - // The vehicle is an action - m_PhysicsWorld->addAction(m_Vehicles[entity]); - - //m_Vehicles[entity]->m_rpm = 0.0f; // Not sure why this one should be here - - shape->removeReference(); - rigidBody->removeReference(); - } - else - { - m_PhysicsWorld->addEntity(rigidBody); - m_RigidBodies[entity] = rigidBody; - shape->removeReference(); - rigidBody->removeReference(); - } -} -*/ - - - - -void Systems::PhysicsSystem::TearDownPhysicsState(EntityID entity, EntityID parent) -{ - -} - -void Systems::PhysicsSystem::OnComponentCreated(std::string type, std::shared_ptr component) -{ - -} - -void Systems::PhysicsSystem::OnComponentRemoved(std::string type, Component* component) -{ - -} - - -void Systems::PhysicsSystem::SetupVisualDebugger(hkpPhysicsContext* worlds) -{ - // Setup the visual debugger - hkArray contexts; - contexts.pushBack(worlds); - - m_VisualDebugger = new hkVisualDebugger(contexts); - m_VisualDebugger->serve(); - - // Allocate memory for internal profiling information - // You can discard this if you do not want Havok profiling information - hkMonitorStream& stream = hkMonitorStream::getInstance(); - stream.resize(500 * 1024); // 500K for timer info - stream.reset(); - -} - -void Systems::PhysicsSystem::StepVisualDebugger() -{ - // Step the debugger - m_VisualDebugger->step(); - - // Reset internal profiling info for next frame - hkMonitorStream::getInstance().reset(); -} - -void HK_CALL Systems::PhysicsSystem::HavokErrorReport(const char* msg, void*) -{ - LOG_INFO("%s", msg); -} -<<<<<<< HEAD -======= - - ->>>>>>> havok diff --git a/src/Systems/PhysicsSystem.h.orig b/src/Systems/PhysicsSystem.h.orig deleted file mode 100644 index 5e00aa1..0000000 --- a/src/Systems/PhysicsSystem.h.orig +++ /dev/null @@ -1,91 +0,0 @@ -#ifndef PhysicsSystem_h__ -#define PhysicsSystem_h__ - - - - - -#include "System.h" -#include "Components/Transform.h" -#include "Components/Physics.h" -#include "Components/Sphere.h" -#include "Components/Box.h" -#include "Components/Vehicle.h" -#include "Components/Input.h" - -// Math and base include - -#include -#include -#include -#include -#include -#include -#include -#include - -// Dynamics includes -#include -#include -#include -#include -#include - - - -#include -#include -#include - -// Visual Debugger includes -#include -#include - - - -#include "Physics/VehicleSetup.h" - - -#include -namespace Systems -{ - -class PhysicsSystem : public System -{ -public: - PhysicsSystem(World* world); - void RegisterComponents(ComponentFactory* cf) override; - - void Update(double dt) override; - void UpdateEntity(double dt, EntityID entity, EntityID parent) override; - void OnComponentCreated(std::string type, std::shared_ptr component) override; - void OnComponentRemoved(std::string type, Component* component) override; - void OnEntityCommit(EntityID entity) override; - -private: -<<<<<<< HEAD - -======= ->>>>>>> havok - double m_Accumulator; - hkpWorld* m_PhysicsWorld; - - void SetUpPhysicsState(EntityID entity, EntityID parent); - void TearDownPhysicsState(EntityID entity, EntityID parent); - - hkVisualDebugger* m_VisualDebugger; - void SetupVisualDebugger(hkpPhysicsContext* worlds); - void StepVisualDebugger(); - static void HK_CALL HavokErrorReport(const char* msg, void*); - void SetupPhysics(hkpWorld* physicsWorld); - - std::unordered_map m_RigidBodies; - std::unordered_map m_Vehicles; - std::vector m_Wheels; - - hkpVehicleInstance* Systems::PhysicsSystem::createVehicle(VehicleSetup& vehicleSetup, hkpRigidBody* chassis); -}; - -} - -#endif // PhysicsSystem_h__ From 22138a36aa5d73f2edb50466e401830d197a8793 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Mon, 28 Apr 2014 06:03:45 +0200 Subject: [PATCH 24/37] MessageRelay renamed to EventRelay --- src/{MessageRelay.h => EventRelay.h} | 10 +++++----- vs11/Returngeance/Returngeance.vcxproj | 2 +- vs11/Returngeance/Returngeance.vcxproj.filters | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) rename src/{MessageRelay.h => EventRelay.h} (79%) diff --git a/src/MessageRelay.h b/src/EventRelay.h similarity index 79% rename from src/MessageRelay.h rename to src/EventRelay.h index 692f8a7..a7629af 100644 --- a/src/MessageRelay.h +++ b/src/EventRelay.h @@ -5,17 +5,17 @@ #include #include -struct Message +struct Event { protected: - Message() { } + Event() { } }; -class MessageRelay +class EventRelay { private: typedef std::string MessageType_t; - typedef std::function MessageCallback_t; + typedef std::function MessageCallback_t; public: void Subscribe(std::string messageType, MessageCallback_t callback) @@ -23,7 +23,7 @@ public: m_Callbacks[messageType].push_back(callback); } - void Raise(std::string messageType, Message message) + void Raise(std::string messageType, Event message) { auto callbackIt = m_Callbacks.find(messageType); if (callbackIt == m_Callbacks.end()) diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index f2e85c8..64aea48 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -140,7 +140,7 @@ - + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 67c8abe..e716742 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -220,10 +220,10 @@ GUI - Util + From 5870a4d7bfb751a338f8f35b25ecf5a52bffd739 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Mon, 28 Apr 2014 09:28:18 +0200 Subject: [PATCH 25/37] Working event system! --- src/EventBroker.cpp | 26 ++++++ src/EventBroker.h | 92 +++++++++++++++++++ src/EventRelay.h | 43 --------- src/main.cpp | 28 ++++++ vs11/Returngeance/Returngeance.vcxproj | 3 +- .../Returngeance/Returngeance.vcxproj.filters | 3 +- 6 files changed, 150 insertions(+), 45 deletions(-) create mode 100644 src/EventBroker.cpp create mode 100644 src/EventBroker.h delete mode 100644 src/EventRelay.h diff --git a/src/EventBroker.cpp b/src/EventBroker.cpp new file mode 100644 index 0000000..f0b085a --- /dev/null +++ b/src/EventBroker.cpp @@ -0,0 +1,26 @@ +#include "PrecompiledHeader.h" +#include "EventBroker.h" + +BaseEventRelay::~BaseEventRelay() +{ + m_Broker->Unsubscribe(*this); +} + +void EventBroker::Unsubscribe(BaseEventRelay &relay) // ? +{ + auto itpair = m_Subscribers.equal_range(relay.m_TypeName); + for (auto it = itpair.first; it != itpair.second; ++it) + { + if (it->second == &relay) + { + m_Subscribers.erase(it); + break; + } + } +} + +void EventBroker::Subscribe(BaseEventRelay &relay) +{ + relay.m_Broker = this; + m_Subscribers.insert(std::make_pair(relay.m_TypeName, &relay)); +} \ No newline at end of file diff --git a/src/EventBroker.h b/src/EventBroker.h new file mode 100644 index 0000000..df84fd9 --- /dev/null +++ b/src/EventBroker.h @@ -0,0 +1,92 @@ +#ifndef MessageRelay_h__ +#define MessageRelay_h__ + +#include +#include +#include +#include + +struct Event +{ +protected: + Event() { } +}; + +class EventBroker; + +class BaseEventRelay +{ +friend class EventBroker; + +protected: + BaseEventRelay(std::string typeName) + : m_TypeName(typeName) { } + ~BaseEventRelay(); + +public: + virtual bool Receive(const Event &event) = 0; + +protected: + std::string m_TypeName; + EventBroker* m_Broker; +}; + +template +class EventRelay : public BaseEventRelay +{ +public: + typedef std::function CallbackType; + + EventRelay() + : m_Callback(nullptr) + , BaseEventRelay(typeid(EventType).name()) { } + EventRelay(CallbackType callback) + : m_Callback(callback) + , BaseEventRelay(typeid(EventType).name()) { } + +protected: + bool Receive(const Event &event) override; + +private: + CallbackType m_Callback; +}; + +template +bool EventRelay::Receive(const Event &event) +{ + if (m_Callback != nullptr) + { + return m_Callback(static_cast(event)); + } + else + { + return false; + } +} + +class EventBroker +{ +template friend class EventRelay; + +public: + template + void Publish(const EventType &event); + void Subscribe(BaseEventRelay &relay); + void Unsubscribe(BaseEventRelay &relay); + +private: + std::unordered_multimap m_Subscribers; +}; + + +template +void EventBroker::Publish(const EventType &event) +{ + auto itpair = m_Subscribers.equal_range(typeid(EventType).name()); + for (auto it = itpair.first; it != itpair.second; ++it) + { + it->second->Receive(event); + } +} + +#endif // MessageRelay_h__ diff --git a/src/EventRelay.h b/src/EventRelay.h deleted file mode 100644 index a7629af..0000000 --- a/src/EventRelay.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef MessageRelay_h__ -#define MessageRelay_h__ - -#include -#include -#include - -struct Event -{ -protected: - Event() { } -}; - -class EventRelay -{ -private: - typedef std::string MessageType_t; - typedef std::function MessageCallback_t; - -public: - void Subscribe(std::string messageType, MessageCallback_t callback) - { - m_Callbacks[messageType].push_back(callback); - } - - void Raise(std::string messageType, Event message) - { - auto callbackIt = m_Callbacks.find(messageType); - if (callbackIt == m_Callbacks.end()) - return; - - for (auto &callback : callbackIt->second) - { - callback(message); - } - } - -private: - std::unordered_map> m_Callbacks; - -}; - -#endif // MessageRelay_h__ diff --git a/src/main.cpp b/src/main.cpp index 03b63b4..29f3c96 100755 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,8 +1,36 @@ #include "PrecompiledHeader.h" #include "Engine.h" +#include "EventBroker.h" + +struct TestEvent : Event +{ + std::string Hello; +}; + +bool OnTestEvent(const TestEvent &event) +{ + std::cout << "TestEvent.Hello = " << event.Hello << std::endl; + return true; +} int main(int argc, char* argv[]) { + EventBroker broker; + + TestEvent e; + e.Hello = "Hello world"; + + { + EventRelay testRelay = &OnTestEvent; + broker.Subscribe(testRelay); + + broker.Publish(e); + } + + broker.Publish(e); + + return 0; + Engine engine(argc, argv); while (engine.Running()) engine.Tick(); diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 64aea48..52a5283 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -96,6 +96,7 @@ + @@ -140,7 +141,7 @@ - + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index e716742..0527db8 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -50,6 +50,7 @@ + @@ -223,7 +224,7 @@ Util - + From 6ba50c2d1e0e5838a29c56e0183a251efa044c06 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Mon, 28 Apr 2014 16:16:03 +0200 Subject: [PATCH 26/37] Fixed GetComponent bug which would create invalid components if the entity didn't have the requested component --- src/World.h | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/World.h b/src/World.h index 255ef1b..ffe887d 100755 --- a/src/World.h +++ b/src/World.h @@ -138,7 +138,16 @@ std::shared_ptr World::AddComponent(EntityID entity, std::string componentTyp template T* World::GetComponent(EntityID entity, std::string componentType) { - return (T*)m_EntityComponents[entity][componentType].get(); + auto components = m_EntityComponents[entity]; + auto it = components.find(componentType); + if (it != components.end()) + { + return static_cast(it->second.get()); + } + else + { + return nullptr; + } } #endif // World_h__ \ No newline at end of file From 57d29d0db7644f0778064380d04916d5e028a3a3 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Mon, 28 Apr 2014 19:55:31 +0200 Subject: [PATCH 27/37] Started implementation of events for InputSystem and SoundSystem --- src/Engine.h | 6 +++- src/EventBroker.cpp | 5 +++- src/EventBroker.h | 2 +- src/Events/KeyDown.h | 16 +++++++++++ src/Events/KeyUp.h | 16 +++++++++++ src/Events/PlaySound.h | 17 +++++++++++ src/GameWorld.cpp | 20 +++++++------ src/GameWorld.h | 5 ++-- src/System.h | 6 +++- src/Systems/DebugSystem.cpp | 27 ++++++++++++++++++ src/Systems/DebugSystem.h | 12 ++++++-- src/Systems/FreeSteeringSystem.h | 5 ++-- src/Systems/InputSystem.cpp | 16 +++++++++++ src/Systems/InputSystem.h | 8 ++++-- src/Systems/PhysicsSystem.cpp | 2 +- src/Systems/PhysicsSystem.h | 5 +++- src/Systems/RenderSystem.h | 5 ++-- src/Systems/SoundSystem.cpp | 19 +++++++++++-- src/Systems/SoundSystem.h | 10 ++++++- src/Systems/TransformSystem.h | 5 ++-- src/World.cpp | 10 ------- src/World.h | 9 ++++-- src/main.cpp | 28 ------------------- vs11/Returngeance/Returngeance.vcxproj | 3 ++ .../Returngeance/Returngeance.vcxproj.filters | 15 ++++++++++ 25 files changed, 201 insertions(+), 71 deletions(-) create mode 100644 src/Events/KeyDown.h create mode 100644 src/Events/KeyUp.h create mode 100644 src/Events/PlaySound.h diff --git a/src/Engine.h b/src/Engine.h index 4093d20..02fb93c 100755 --- a/src/Engine.h +++ b/src/Engine.h @@ -1,6 +1,7 @@ #include #include +#include "EventBroker.h" #include "Renderer.h" #include "GameWorld.h" @@ -9,10 +10,12 @@ class Engine public: Engine(int argc, char* argv[]) { + m_EventBroker = std::make_shared(); + m_Renderer = std::make_shared(); m_Renderer->Initialize(); - m_World = std::make_shared(m_Renderer); + m_World = std::make_shared(m_EventBroker, m_Renderer); m_World->Initialize(); m_LastTime = glfwGetTime(); @@ -33,6 +36,7 @@ public: } private: + std::shared_ptr m_EventBroker; std::shared_ptr m_Renderer; // TODO: This should ultimately live in GameFrame std::shared_ptr m_World; diff --git a/src/EventBroker.cpp b/src/EventBroker.cpp index f0b085a..68354c9 100644 --- a/src/EventBroker.cpp +++ b/src/EventBroker.cpp @@ -3,7 +3,10 @@ BaseEventRelay::~BaseEventRelay() { - m_Broker->Unsubscribe(*this); + if (m_Broker != nullptr) + { + m_Broker->Unsubscribe(*this); + } } void EventBroker::Unsubscribe(BaseEventRelay &relay) // ? diff --git a/src/EventBroker.h b/src/EventBroker.h index df84fd9..c11fe4a 100644 --- a/src/EventBroker.h +++ b/src/EventBroker.h @@ -20,7 +20,7 @@ friend class EventBroker; protected: BaseEventRelay(std::string typeName) - : m_TypeName(typeName) { } + : m_TypeName(typeName), m_Broker(nullptr) { } ~BaseEventRelay(); public: diff --git a/src/Events/KeyDown.h b/src/Events/KeyDown.h new file mode 100644 index 0000000..f2da381 --- /dev/null +++ b/src/Events/KeyDown.h @@ -0,0 +1,16 @@ +#ifndef Event_KeyDown_h__ +#define Event_KeyDown_h__ + +#include "EventBroker.h" + +namespace Events +{ + +struct KeyDown : Event +{ + int KeyCode; +}; + +} + +#endif // Event_KeyDown_h__ diff --git a/src/Events/KeyUp.h b/src/Events/KeyUp.h new file mode 100644 index 0000000..0770767 --- /dev/null +++ b/src/Events/KeyUp.h @@ -0,0 +1,16 @@ +#ifndef Event_KeyUp_h__ +#define Event_KeyUp_h__ + +#include "EventBroker.h" + +namespace Events +{ + +struct KeyUp : Event +{ + int KeyCode; +}; + +} + +#endif // Event_KeyUp_h__ \ No newline at end of file diff --git a/src/Events/PlaySound.h b/src/Events/PlaySound.h new file mode 100644 index 0000000..e00ef73 --- /dev/null +++ b/src/Events/PlaySound.h @@ -0,0 +1,17 @@ +#ifndef Event_PlaySound_h__ +#define Event_PlaySound_h__ + +#include "EventBroker.h" + +namespace Events +{ + +struct PlaySound : Event +{ + EntityID Emitter; + std::string Resource; +}; + +} + +#endif // Event_PlaySound_h__ diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index d3b9aad..c92f868 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -87,14 +87,14 @@ void GameWorld::Initialize() CommitEntity(ball); } - /*{ + { auto entity = CreateEntity(); AddComponent(entity, "Transform"); auto emitter = AddComponent(entity, "SoundEmitter"); emitter->Path = "Sounds/korvring.wav"; emitter->Loop = true; - GetSystem("SoundSystem")->PlaySound(emitter); - }*/ + //GetSystem("SoundSystem")->PlaySound(emitter); + } } void GameWorld::Update(double dt) @@ -112,16 +112,17 @@ void GameWorld::RegisterComponents() void GameWorld::RegisterSystems() { - m_SystemFactory.Register("TransformSystem", [this]() { return new Systems::TransformSystem(this); }); + m_SystemFactory.Register("TransformSystem", [this]() { return new Systems::TransformSystem(this, m_EventBroker); }); //m_SystemFactory.Register("LevelGenerationSystem", [this]() { return new Systems::LevelGenerationSystem(this); }); - m_SystemFactory.Register("InputSystem", [this]() { return new Systems::InputSystem(this, m_Renderer); }); + m_SystemFactory.Register("InputSystem", [this]() { return new Systems::InputSystem(this, m_EventBroker, m_Renderer); }); + m_SystemFactory.Register("DebugSystem", [this]() { return new Systems::DebugSystem(this, m_EventBroker); }); //m_SystemFactory.Register("CollisionSystem", [this]() { return new Systems::CollisionSystem(this); }); ////m_SystemFactory.Register("ParticleSystem", [this]() { return new Systems::ParticleSystem(this); }); //m_SystemFactory.Register("PlayerSystem", [this]() { return new Systems::PlayerSystem(this); }); - m_SystemFactory.Register("FreeSteeringSystem", [this]() { return new Systems::FreeSteeringSystem(this); }); - m_SystemFactory.Register("SoundSystem", [this]() { return new Systems::SoundSystem(this); }); - m_SystemFactory.Register("PhysicsSystem", [this]() { return new Systems::PhysicsSystem(this); }); - m_SystemFactory.Register("RenderSystem", [this]() { return new Systems::RenderSystem(this, m_Renderer); }); + m_SystemFactory.Register("FreeSteeringSystem", [this]() { return new Systems::FreeSteeringSystem(this, m_EventBroker); }); + m_SystemFactory.Register("SoundSystem", [this]() { return new Systems::SoundSystem(this, m_EventBroker); }); + m_SystemFactory.Register("PhysicsSystem", [this]() { return new Systems::PhysicsSystem(this, m_EventBroker); }); + m_SystemFactory.Register("RenderSystem", [this]() { return new Systems::RenderSystem(this, m_EventBroker, m_Renderer); }); } void GameWorld::AddSystems() @@ -129,6 +130,7 @@ void GameWorld::AddSystems() AddSystem("TransformSystem"); //AddSystem("LevelGenerationSystem"); AddSystem("InputSystem"); + AddSystem("DebugSystem"); //AddSystem("CollisionSystem"); ////AddSystem("ParticleSystem"); //AddSystem("PlayerSystem"); diff --git a/src/GameWorld.h b/src/GameWorld.h index 05ca584..17901c3 100755 --- a/src/GameWorld.h +++ b/src/GameWorld.h @@ -7,6 +7,7 @@ #include "Systems/TransformSystem.h" //#include "Systems/CollisionSystem.h" #include "Systems/InputSystem.h" +#include "Systems/DebugSystem.h" //#include "Systems/LevelGenerationSystem.h" //#include "Systems/ParticleSystem.h" //#include "Systems/PlayerSystem.h" @@ -33,8 +34,8 @@ class GameWorld : public World { public: - GameWorld(std::shared_ptr renderer) - : m_Renderer(renderer), World() { } + GameWorld(std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr renderer) + : World(eventBroker), m_Renderer(renderer) { } void Initialize(); diff --git a/src/System.h b/src/System.h index ff76450..b40bdef 100755 --- a/src/System.h +++ b/src/System.h @@ -4,6 +4,7 @@ #include "Factory.h" #include "Entity.h" #include "Component.h" +#include "EventBroker.h" #include "ResourceManager.h" class World; @@ -11,7 +12,9 @@ class World; class System { public: - System(World* world) : m_World(world) { } + System(World* world, std::shared_ptr eventBroker) + : m_World(world) + , EventBroker(eventBroker) { } virtual ~System() { } virtual void RegisterComponents(ComponentFactory* cf) { } @@ -33,6 +36,7 @@ public: protected: World* m_World; + std::shared_ptr EventBroker; }; class SystemFactory : public Factory { }; diff --git a/src/Systems/DebugSystem.cpp b/src/Systems/DebugSystem.cpp index 964aa9f..f076664 100644 --- a/src/Systems/DebugSystem.cpp +++ b/src/Systems/DebugSystem.cpp @@ -2,3 +2,30 @@ #include "DebugSystem.h" #include "World.h" + +void Systems::DebugSystem::Initialize() +{ + // Subscribe to events + m_EKeyDown = decltype(m_EKeyDown)(std::bind(&Systems::DebugSystem::OnKeyDown, this, std::placeholders::_1)); + EventBroker->Subscribe(m_EKeyDown); +} + +void Systems::DebugSystem::Update(double dt) +{ + +} + +bool Systems::DebugSystem::OnKeyDown(const Events::KeyDown &event) +{ + if (event.KeyCode == GLFW_KEY_ENTER) + { + Events::PlaySound e; + e.Emitter = 0; + e.Resource = "Sounds/korvring.wav"; + EventBroker->Publish(e); + + return true; + } + + return false; +} diff --git a/src/Systems/DebugSystem.h b/src/Systems/DebugSystem.h index accaa8c..9db4de6 100644 --- a/src/Systems/DebugSystem.h +++ b/src/Systems/DebugSystem.h @@ -3,6 +3,8 @@ #include "System.h" #include "Components/Transform.h" +#include "Events/KeyDown.h" +#include "Events/PlaySound.h" namespace Systems { @@ -10,10 +12,16 @@ namespace Systems class DebugSystem : public System { public: - DebugSystem(World* world) - : System(world) { } + DebugSystem(World* world, std::shared_ptr<::EventBroker> eventBroker) + : System(world, eventBroker) { } + + void Initialize() override; void Update(double dt) override; + + EventRelay m_EKeyDown; + bool OnKeyDown(const Events::KeyDown &event); + //void UpdateEntity(double dt, EntityID entity, EntityID parent) override; }; diff --git a/src/Systems/FreeSteeringSystem.h b/src/Systems/FreeSteeringSystem.h index 11b86ae..49a65d9 100755 --- a/src/Systems/FreeSteeringSystem.h +++ b/src/Systems/FreeSteeringSystem.h @@ -10,8 +10,9 @@ namespace Systems class FreeSteeringSystem : public System { public: - FreeSteeringSystem(World* world) - : System(world) { } + FreeSteeringSystem(World* world, std::shared_ptr<::EventBroker> eventBroker) + : System(world, eventBroker) { } + void RegisterComponents(ComponentFactory* cf) override; void Update(double dt) override; diff --git a/src/Systems/InputSystem.cpp b/src/Systems/InputSystem.cpp index b64bc03..11d4b91 100755 --- a/src/Systems/InputSystem.cpp +++ b/src/Systems/InputSystem.cpp @@ -16,6 +16,22 @@ void Systems::InputSystem::Update(double dt) for (int i = 0; i <= GLFW_KEY_LAST; ++i) { m_CurrentKeyState[i] = glfwGetKey(m_Renderer->GetWindow(), i); + if (m_CurrentKeyState[i] != m_LastKeyState[i]) + { + // Publish key events + if (m_CurrentKeyState[i]) + { + Events::KeyDown e; + e.KeyCode = i; + EventBroker->Publish(e); + } + else + { + Events::KeyUp e; + e.KeyCode = i; + EventBroker->Publish(e); + } + } } // Mouse buttons diff --git a/src/Systems/InputSystem.h b/src/Systems/InputSystem.h index abceb77..6107c2b 100755 --- a/src/Systems/InputSystem.h +++ b/src/Systems/InputSystem.h @@ -6,6 +6,8 @@ #include "System.h" #include "Renderer.h" #include "Components/Input.h" +#include "Events/KeyUp.h" +#include "Events/KeyDown.h" namespace Systems { @@ -13,8 +15,10 @@ namespace Systems class InputSystem : public System { public: - InputSystem(World* world, std::shared_ptr renderer) - : System(world), m_Renderer(renderer) { } + InputSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr renderer) + : System(world, eventBroker) + , m_Renderer(renderer) { } + void RegisterComponents(ComponentFactory* cf) override; void Update(double dt) override; diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index 6ec3b45..ff3607c 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -27,7 +27,7 @@ -Systems::PhysicsSystem::PhysicsSystem(World* world) : System(world) +void Systems::PhysicsSystem::Initialize() { { hkMemorySystem::FrameInfo finfo(500 * 1024); // Allocate 500KB of Physics solver buffer diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index 626bbcd..0544b13 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -46,8 +46,11 @@ namespace Systems class PhysicsSystem : public System { public: - PhysicsSystem(World* world); + PhysicsSystem(World* world, std::shared_ptr<::EventBroker> eventBroker) + : System(world, eventBroker) { } + void RegisterComponents(ComponentFactory* cf) override; + void Initialize() override; void Update(double dt) override; void UpdateEntity(double dt, EntityID entity, EntityID parent) override; diff --git a/src/Systems/RenderSystem.h b/src/Systems/RenderSystem.h index 4df8658..c3cd09a 100755 --- a/src/Systems/RenderSystem.h +++ b/src/Systems/RenderSystem.h @@ -24,8 +24,9 @@ namespace Systems class RenderSystem : public System { public: - RenderSystem(World* world, std::shared_ptr renderer) - : System(world), m_Renderer(renderer) { } + RenderSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr renderer) + : System(world, eventBroker) + , m_Renderer(renderer) { } void RegisterComponents(ComponentFactory* cf) override; void RegisterResourceTypes(ResourceManager* rm) override; diff --git a/src/Systems/SoundSystem.cpp b/src/Systems/SoundSystem.cpp index ffb9b06..02a665e 100755 --- a/src/Systems/SoundSystem.cpp +++ b/src/Systems/SoundSystem.cpp @@ -2,8 +2,7 @@ #include "SoundSystem.h" #include "World.h" -Systems::SoundSystem::SoundSystem(World* world) - : System(world) +void Systems::SoundSystem::Initialize() { //initialize OpenAL ALCdevice* Device = alcOpenDevice(NULL); @@ -22,6 +21,10 @@ Systems::SoundSystem::SoundSystem(World* world) alSpeedOfSound(340.29f); // Speed of sound alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED); + + // Subscribe to events + m_EPlaySound = decltype(m_EPlaySound)(std::bind(&Systems::SoundSystem::OnPlaySound, this, std::placeholders::_1)); + EventBroker->Subscribe(m_EPlaySound); } void Systems::SoundSystem::RegisterComponents(ComponentFactory* cf) @@ -143,3 +146,15 @@ ALuint Systems::SoundSystem::CreateSource() return source; } + +bool Systems::SoundSystem::OnPlaySound(const Events::PlaySound &event) +{ + LOG_DEBUG("Events::PlaySound.Resource = %s", event.Resource.c_str()); + + ALuint buffer = *m_World->GetResourceManager()->Load("Sound", event.Resource); + ALuint source = m_Sources.begin()->second; + alSourcei(source, AL_BUFFER, buffer); + alSourcePlay(source); + + return true; +} diff --git a/src/Systems/SoundSystem.h b/src/Systems/SoundSystem.h index 85ee4fa..7fbc5aa 100755 --- a/src/Systems/SoundSystem.h +++ b/src/Systems/SoundSystem.h @@ -7,6 +7,7 @@ #include "System.h" #include "Components/Transform.h" #include "Components/SoundEmitter.h" +#include "Events/PlaySound.h" #include "Sound.h" namespace Systems @@ -15,9 +16,12 @@ namespace Systems class SoundSystem : public System { public: - SoundSystem(World* world); + SoundSystem(World* world, std::shared_ptr<::EventBroker> eventBroker) + : System(world, eventBroker) { } + void RegisterComponents(ComponentFactory* cf) override; void RegisterResourceTypes(ResourceManager* rm) override; + void Initialize() override; void Update(double dt) override; void UpdateEntity(double dt, EntityID entity, EntityID parent) override; @@ -39,6 +43,10 @@ private: //short bytesPerSample, bitsPerSample; //unsigned long dataSize; + // Events + EventRelay m_EPlaySound; + bool OnPlaySound(const Events::PlaySound &event); + std::map m_Sources; std::map m_BufferCache; // string = fileName }; diff --git a/src/Systems/TransformSystem.h b/src/Systems/TransformSystem.h index 542000d..f4e6f48 100755 --- a/src/Systems/TransformSystem.h +++ b/src/Systems/TransformSystem.h @@ -10,9 +10,8 @@ namespace Systems class TransformSystem : public System { public: - TransformSystem(World* world) - : System(world) { } - + TransformSystem(World* world, std::shared_ptr<::EventBroker> eventBroker) + : System(world, eventBroker) { } //void Update(double dt) override; //void UpdateEntity(double dt, EntityID entity, EntityID parent) override; diff --git a/src/World.cpp b/src/World.cpp index 0b6a245..44bc45e 100755 --- a/src/World.cpp +++ b/src/World.cpp @@ -120,16 +120,6 @@ EntityID World::CreateEntity(EntityID parent /*= 0*/) return newEntity; } -World::~World() -{ - -} - -World::World() -{ - m_LastEntityID = 0; -} - void World::Initialize() { RegisterSystems(); diff --git a/src/World.h b/src/World.h index 255ef1b..fd496cd 100755 --- a/src/World.h +++ b/src/World.h @@ -14,13 +14,16 @@ #include "Entity.h" #include "Component.h" #include "System.h" +#include "EventBroker.h" #include "ResourceManager.h" class World { public: - World(); - ~World(); + World(std::shared_ptr<::EventBroker> eventBroker) + : m_EventBroker(eventBroker) + , m_LastEntityID(0) { } + ~World() { } virtual void Initialize(); @@ -75,8 +78,10 @@ public: std::unordered_map* GetEntities() { return &m_EntityParents; } ResourceManager* GetResourceManager() { return &m_ResourceManager; } + std::shared_ptr<::EventBroker> EventBroker() { return m_EventBroker; } protected: + std::shared_ptr<::EventBroker> m_EventBroker; SystemFactory m_SystemFactory; ComponentFactory m_ComponentFactory; ResourceManager m_ResourceManager; diff --git a/src/main.cpp b/src/main.cpp index 29f3c96..03b63b4 100755 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,36 +1,8 @@ #include "PrecompiledHeader.h" #include "Engine.h" -#include "EventBroker.h" - -struct TestEvent : Event -{ - std::string Hello; -}; - -bool OnTestEvent(const TestEvent &event) -{ - std::cout << "TestEvent.Hello = " << event.Hello << std::endl; - return true; -} int main(int argc, char* argv[]) { - EventBroker broker; - - TestEvent e; - e.Hello = "Hello world"; - - { - EventRelay testRelay = &OnTestEvent; - broker.Subscribe(testRelay); - - broker.Publish(e); - } - - broker.Publish(e); - - return 0; - Engine engine(argc, argv); while (engine.Running()) engine.Tick(); diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 52a5283..17327db 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -138,6 +138,9 @@ + + + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 0527db8..febf3eb 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -116,6 +116,12 @@ {6e633434-4aed-453d-b2f9-8c51ca7f78db} + + {85692f3a-5241-4780-a3ca-f4d8a2851392} + + + {ee125b77-b275-4841-abc9-374957a89916} + @@ -225,6 +231,15 @@ Util + + Audio\Events + + + Input\Events + + + Input\Events + From d0211ef8d6f96902c014194a632d0115b7c04c51 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 29 Apr 2014 13:58:27 +0200 Subject: [PATCH 28/37] Encapsulated Renderer WIDTH and HEIGHT variables. --- src/Renderer.cpp | 12 ++++++------ src/Renderer.h | 7 ++++--- src/Systems/InputSystem.cpp | 4 ++-- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/Renderer.cpp b/src/Renderer.cpp index e7dfed6..9479b55 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -31,11 +31,11 @@ void Renderer::Initialize() } // Create a window - WIDTH = 1280; - HEIGHT = 720; + m_Width = 1280; + m_Height = 720; // Antialiasing //glfwWindowHint(GLFW_SAMPLES, 16); - m_Window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL", nullptr, nullptr); + m_Window = glfwCreateWindow(m_Width, m_Height, "OpenGL", nullptr, nullptr); if (!m_Window) { LOG_ERROR("GLFW: Failed to create window"); @@ -63,7 +63,7 @@ void Renderer::Initialize() } // Create Camera - m_Camera = std::make_shared(45.f, (float)WIDTH / HEIGHT, 0.01f, 1000.f); + m_Camera = std::make_shared(45.f, (float)m_Width / m_Height, 0.01f, 1000.f); m_Camera->Position(glm::vec3(0.0f, 0.0f, 2.f)); glfwSwapInterval(m_VSync); @@ -187,7 +187,7 @@ void Renderer::Draw(double dt) void Renderer::DrawSkybox() { glBindFramebuffer(GL_FRAMEBUFFER, 0); - glViewport(0, 0, WIDTH, HEIGHT); + glViewport(0, 0, m_Width, m_Height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_ShaderProgramSkybox.Bind(); @@ -200,7 +200,7 @@ void Renderer::DrawSkybox() void Renderer::DrawScene() { glBindFramebuffer(GL_FRAMEBUFFER, 0); - glViewport(0, 0, WIDTH, HEIGHT); + glViewport(0, 0, m_Width, m_Height); glClear(GL_DEPTH_BUFFER_BIT); //glClearColor(1.0f, 1.0f, 0.0f, 1.0f); diff --git a/src/Renderer.h b/src/Renderer.h index 8d0da1f..3c2d957 100755 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -20,7 +20,9 @@ public: glm::mat4 viewMatrix; glm::mat4 projectionMatrix; - int HEIGHT, WIDTH; + + int Width() const { return m_Width; } + int Height() const { return m_Height; } std::list> ModelsToRender; int Lights; @@ -65,9 +67,8 @@ public: void DrawBounds(bool val) { m_DrawBounds = val; } void DrawSkybox(); - - private: + int m_Width, m_Height; GLFWwindow* m_Window; GLint m_glVersion[2]; GLchar* m_glVendor; diff --git a/src/Systems/InputSystem.cpp b/src/Systems/InputSystem.cpp index 11d4b91..3f16de9 100755 --- a/src/Systems/InputSystem.cpp +++ b/src/Systems/InputSystem.cpp @@ -51,8 +51,8 @@ void Systems::InputSystem::Update(double dt) // Lock mouse while holding LMB if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT]) { - m_LastMouseX = m_Renderer->WIDTH / 2.f; // xpos; - m_LastMouseY = m_Renderer->HEIGHT / 2.f; // ypos; + m_LastMouseX = m_Renderer->Width() / 2.f; // xpos; + m_LastMouseY = m_Renderer->Height() / 2.f; // ypos; glfwSetCursorPos(m_Renderer->GetWindow(), m_LastMouseX, m_LastMouseY); } // Hide/show cursor with LMB From 9e8c3161e0b263a424d8b2b453c961fd43f1031c Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 29 Apr 2014 13:58:37 +0200 Subject: [PATCH 29/37] WIP Frame --- src/Engine.h | 4 ++++ src/GUI/Frame.h | 28 ++++++++++++++++++++++------ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/Engine.h b/src/Engine.h index 02fb93c..91fed1c 100755 --- a/src/Engine.h +++ b/src/Engine.h @@ -2,6 +2,7 @@ #include #include "EventBroker.h" +#include "GUI/Frame.h" #include "Renderer.h" #include "GameWorld.h" @@ -15,6 +16,8 @@ public: m_Renderer = std::make_shared(); m_Renderer->Initialize(); + m_UIParent = std::make_shared(0, 0, m_Renderer->Width(), m_Renderer->Height()); + m_World = std::make_shared(m_EventBroker, m_Renderer); m_World->Initialize(); @@ -38,6 +41,7 @@ public: private: std::shared_ptr m_EventBroker; std::shared_ptr m_Renderer; + std::shared_ptr m_UIParent; // TODO: This should ultimately live in GameFrame std::shared_ptr m_World; diff --git a/src/GUI/Frame.h b/src/GUI/Frame.h index f77d29f..19f534a 100644 --- a/src/GUI/Frame.h +++ b/src/GUI/Frame.h @@ -4,6 +4,7 @@ #include #include "Util/Rectangle.h" +#include "EventBroker.h" namespace GUI { @@ -19,13 +20,28 @@ public: Bottom }; - Frame() { } - - Frame(const Frame &parent) - : Rectangle(static_cast(parent)) - , Parent(std::shared_ptr(&parent)) { } + // Set up a base frame with an event broker + Frame(std::shared_ptr<::EventBroker> eventBroker) + : EventBroker(eventBroker) + , Rectangle() + { Initialize(); } + // Create a frame as a child + Frame(std::shared_ptr parent) + : Rectangle(static_cast(*parent)) // Clone parent rectangle using copy constructor + { SetParent(parent); Initialize(); } - std::shared_ptr Parent; + virtual void Initialize() { } + std::shared_ptr Parent() const { return m_Parent; } + void SetParent(std::shared_ptr parent) + { + m_Parent = parent; + EventBroker = parent->EventBroker; + } + virtual void Update(double dt) { } + +protected: + std::shared_ptr<::EventBroker> EventBroker; + std::shared_ptr m_Parent; }; } From 330a212830849d4a518dec312aa022860f70f293 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Mon, 5 May 2014 07:15:47 +0200 Subject: [PATCH 30/37] Rectangle comparison fixed --- src/Util/Rectangle.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Util/Rectangle.h b/src/Util/Rectangle.h index 7e55659..0d0db32 100644 --- a/src/Util/Rectangle.h +++ b/src/Util/Rectangle.h @@ -66,9 +66,9 @@ inline bool operator!=(const Rectangle &lhs, const Rectangle &rhs) return !(lhs == rhs); } -inline bool operator<(const Rectangle &lhs, const Rectangle &lhs) +inline bool operator<(const Rectangle &lhs, const Rectangle &rhs) { - return (lhs.Width < lhs.Width) && (lhs.Height < lhs.Height); + return (lhs.Width < rhs.Width) && (lhs.Height < rhs.Height); } inline bool operator>(const Rectangle &lhs, const Rectangle &rhs) From 5e7537b903cb1d081121c5a8f2ffa03768d37e07 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Mon, 5 May 2014 07:16:45 +0200 Subject: [PATCH 31/37] Input events moved from InputSystem to new InputManager --- src/Engine.h | 9 +- src/Events/KeyDown.h | 6 +- src/Events/KeyUp.h | 6 +- src/Events/MouseMove.h | 17 +++ src/Events/MousePress.h | 16 +++ src/Events/MouseRelease.h | 16 +++ src/InputManager.cpp | 92 ++++++++++++++ src/InputManager.h | 33 +++++ src/Systems/InputSystem.cpp | 115 ++++-------------- src/Systems/InputSystem.h | 11 +- vs11/Returngeance/Returngeance.vcxproj | 5 + .../Returngeance/Returngeance.vcxproj.filters | 13 ++ 12 files changed, 236 insertions(+), 103 deletions(-) create mode 100644 src/Events/MouseMove.h create mode 100644 src/Events/MousePress.h create mode 100644 src/Events/MouseRelease.h create mode 100644 src/InputManager.cpp create mode 100644 src/InputManager.h diff --git a/src/Engine.h b/src/Engine.h index 91fed1c..25337c4 100755 --- a/src/Engine.h +++ b/src/Engine.h @@ -2,8 +2,9 @@ #include #include "EventBroker.h" -#include "GUI/Frame.h" #include "Renderer.h" +#include "InputManager.h" +#include "GUI/Frame.h" #include "GameWorld.h" class Engine @@ -16,7 +17,9 @@ public: m_Renderer = std::make_shared(); m_Renderer->Initialize(); - m_UIParent = std::make_shared(0, 0, m_Renderer->Width(), m_Renderer->Height()); + m_InputManager = std::make_shared(m_Renderer->GetWindow(), m_EventBroker); + + m_UIParent = std::make_shared(m_EventBroker); m_World = std::make_shared(m_EventBroker, m_Renderer); m_World->Initialize(); @@ -32,6 +35,7 @@ public: double dt = currentTime - m_LastTime; m_LastTime = currentTime; + m_InputManager->Update(dt); m_World->Update(dt); m_Renderer->Draw(dt); @@ -41,6 +45,7 @@ public: private: std::shared_ptr m_EventBroker; std::shared_ptr m_Renderer; + std::shared_ptr m_InputManager; std::shared_ptr m_UIParent; // TODO: This should ultimately live in GameFrame std::shared_ptr m_World; diff --git a/src/Events/KeyDown.h b/src/Events/KeyDown.h index f2da381..0864862 100644 --- a/src/Events/KeyDown.h +++ b/src/Events/KeyDown.h @@ -1,5 +1,5 @@ -#ifndef Event_KeyDown_h__ -#define Event_KeyDown_h__ +#ifndef Events_KeyDown_h__ +#define Events_KeyDown_h__ #include "EventBroker.h" @@ -13,4 +13,4 @@ struct KeyDown : Event } -#endif // Event_KeyDown_h__ +#endif // Events_KeyDown_h__ \ No newline at end of file diff --git a/src/Events/KeyUp.h b/src/Events/KeyUp.h index 0770767..9fcbf83 100644 --- a/src/Events/KeyUp.h +++ b/src/Events/KeyUp.h @@ -1,5 +1,5 @@ -#ifndef Event_KeyUp_h__ -#define Event_KeyUp_h__ +#ifndef Events_KeyUp_h__ +#define Events_KeyUp_h__ #include "EventBroker.h" @@ -13,4 +13,4 @@ struct KeyUp : Event } -#endif // Event_KeyUp_h__ \ No newline at end of file +#endif // Events_KeyUp_h__ \ No newline at end of file diff --git a/src/Events/MouseMove.h b/src/Events/MouseMove.h new file mode 100644 index 0000000..2d668a1 --- /dev/null +++ b/src/Events/MouseMove.h @@ -0,0 +1,17 @@ +#ifndef Events_MouseMove_h__ +#define Events_MouseMove_h__ + +#include "EventBroker.h" + +namespace Events +{ + +struct MouseMove : Event +{ + double X, Y; + double DeltaX, DeltaY; +}; + +} + +#endif // Events_MouseMove_h__ \ No newline at end of file diff --git a/src/Events/MousePress.h b/src/Events/MousePress.h new file mode 100644 index 0000000..3116edb --- /dev/null +++ b/src/Events/MousePress.h @@ -0,0 +1,16 @@ +#ifndef Events_MousePress_h__ +#define Events_MousePress_h__ + +#include "EventBroker.h" + +namespace Events +{ + +struct MousePress : Event +{ + int Button; +}; + +} + +#endif // Events_MousePress_h__ \ No newline at end of file diff --git a/src/Events/MouseRelease.h b/src/Events/MouseRelease.h new file mode 100644 index 0000000..7249dcd --- /dev/null +++ b/src/Events/MouseRelease.h @@ -0,0 +1,16 @@ +#ifndef Events_MouseRelease_h__ +#define Events_MouseRelease_h__ + +#include "EventBroker.h" + +namespace Events +{ + +struct MouseRelease : Event +{ + int Button; +}; + +} + +#endif // Events_MouseRelease_h__ \ No newline at end of file diff --git a/src/InputManager.cpp b/src/InputManager.cpp new file mode 100644 index 0000000..18d8d92 --- /dev/null +++ b/src/InputManager.cpp @@ -0,0 +1,92 @@ +#include "PrecompiledHeader.h" +#include "InputManager.h" + +InputManager::InputManager(GLFWwindow* window, std::shared_ptr eventBroker) : m_GLFWWindow(window) + , m_EventBroker(eventBroker) +{ + +} + +void InputManager::Update(double dt) +{ + m_LastKeyState = m_CurrentKeyState; + m_LastMouseState = m_CurrentMouseState; + m_LastMouseX = m_CurrentMouseX; + m_LastMouseY = m_CurrentMouseY; + + // Keyboard input + for (int i = 0; i <= GLFW_KEY_LAST; ++i) + { + m_CurrentKeyState[i] = glfwGetKey(m_GLFWWindow, i); + if (m_CurrentKeyState[i] != m_LastKeyState[i]) + { + // Publish key events + if (m_CurrentKeyState[i]) + { + Events::KeyDown e; + e.KeyCode = i; + m_EventBroker->Publish(e); + } + else + { + Events::KeyUp e; + e.KeyCode = i; + m_EventBroker->Publish(e); + } + } + } + + // Mouse buttons + for (int i = 0; i <= GLFW_MOUSE_BUTTON_LAST; ++i) + { + m_CurrentMouseState[i] = glfwGetMouseButton(m_GLFWWindow, i); + if (m_CurrentMouseState[i] != m_LastMouseState[i]) + { + // Publish mouse button events + if (m_CurrentKeyState[i]) + { + Events::MousePress e; + e.Button = i; + m_EventBroker->Publish(e); + } + else + { + Events::MouseRelease e; + e.Button = i; + m_EventBroker->Publish(e); + } + } + } + + // Cursor position + glfwGetCursorPos(m_GLFWWindow, &m_CurrentMouseX, &m_CurrentMouseY); + m_CurrentMouseDeltaX = m_CurrentMouseX - m_LastMouseX; + m_CurrentMouseDeltaY = m_CurrentMouseY - m_LastMouseY; + if (m_CurrentMouseDeltaX != 0 || m_CurrentMouseDeltaY != 0) + { + // Publish mouse move events + Events::MouseMove e; + e.X = m_CurrentMouseX; + e.Y = m_CurrentMouseY; + e.DeltaX = m_CurrentMouseDeltaX; + e.DeltaY = m_CurrentMouseDeltaY; + m_EventBroker->Publish(e); + } + + // // Lock mouse while holding LMB + // if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT]) + // { + // m_LastMouseX = m_Renderer->Width() / 2.f; // xpos; + // m_LastMouseY = m_Renderer->Height() / 2.f; // ypos; + // glfwSetCursorPos(m_GLFWWindow, m_LastMouseX, m_LastMouseY); + // } + // // Hide/show cursor with LMB + // if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && !m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT]) + // { + // glfwSetInputMode(m_GLFWWindow, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); + // } + // if (!m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT]) + // { + // glfwSetInputMode(m_GLFWWindow, GLFW_CURSOR, GLFW_CURSOR_NORMAL); + // } +} diff --git a/src/InputManager.h b/src/InputManager.h new file mode 100644 index 0000000..d7545e4 --- /dev/null +++ b/src/InputManager.h @@ -0,0 +1,33 @@ +#ifndef InputManager_h__ +#define InputManager_h__ + +#include + +#include "EventBroker.h" +#include "Events/KeyDown.h" +#include "Events/KeyUp.h" +#include "Events/MousePress.h" +#include "Events/MouseRelease.h" +#include "Events/MouseMove.h" + +class InputManager +{ +public: + InputManager(GLFWwindow* window, std::shared_ptr eventBroker); + + void Update(double dt); + +private: + GLFWwindow* m_GLFWWindow; + std::shared_ptr m_EventBroker; + + std::array m_CurrentKeyState; + std::array m_LastKeyState; + std::array m_CurrentMouseState; + std::array m_LastMouseState; + double m_CurrentMouseX, m_CurrentMouseY; + double m_LastMouseX, m_LastMouseY; + double m_CurrentMouseDeltaX, m_CurrentMouseDeltaY; +}; + +#endif // InputManager_h__ diff --git a/src/Systems/InputSystem.cpp b/src/Systems/InputSystem.cpp index 3f16de9..70cb927 100755 --- a/src/Systems/InputSystem.cpp +++ b/src/Systems/InputSystem.cpp @@ -7,96 +7,35 @@ void Systems::InputSystem::RegisterComponents(ComponentFactory* cf) cf->Register("Input", []() { return new Components::Input(); }); } +void Systems::InputSystem::Initialize() +{ + // Subscribe to events + m_EKeyDown = decltype(m_EKeyDown)(std::bind(&Systems::InputSystem::OnKeyDown, this, std::placeholders::_1)); + EventBroker->Subscribe(m_EKeyDown); +} + void Systems::InputSystem::Update(double dt) { - m_LastKeyState = m_CurrentKeyState; - m_LastMouseState = m_CurrentMouseState; - - // Keyboard input - for (int i = 0; i <= GLFW_KEY_LAST; ++i) - { - m_CurrentKeyState[i] = glfwGetKey(m_Renderer->GetWindow(), i); - if (m_CurrentKeyState[i] != m_LastKeyState[i]) - { - // Publish key events - if (m_CurrentKeyState[i]) - { - Events::KeyDown e; - e.KeyCode = i; - EventBroker->Publish(e); - } - else - { - Events::KeyUp e; - e.KeyCode = i; - EventBroker->Publish(e); - } - } - } - - // Mouse buttons - for (int i = 0; i <= GLFW_MOUSE_BUTTON_LAST; ++i) - { - m_CurrentMouseState[i] = glfwGetMouseButton(m_Renderer->GetWindow(), i); - } - - // Cursor position - double xpos, ypos; - glfwGetCursorPos(m_Renderer->GetWindow(), &xpos, &ypos); - m_CurrentMouseDeltaX = xpos - m_LastMouseX; - m_CurrentMouseDeltaY = ypos - m_LastMouseY; - m_LastMouseX = xpos; - m_LastMouseY = ypos; - - // Lock mouse while holding LMB - if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT]) - { - m_LastMouseX = m_Renderer->Width() / 2.f; // xpos; - m_LastMouseY = m_Renderer->Height() / 2.f; // ypos; - glfwSetCursorPos(m_Renderer->GetWindow(), m_LastMouseX, m_LastMouseY); - } - // Hide/show cursor with LMB - if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && !m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT]) - { - glfwSetInputMode(m_Renderer->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN); - } - if (!m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT]) - { - glfwSetInputMode(m_Renderer->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL); - } - -#ifdef DEBUG - // Wireframe - if (m_CurrentKeyState[GLFW_KEY_F1] && !m_LastKeyState[GLFW_KEY_F1]) - { - m_Renderer->DrawWireframe(!m_Renderer->DrawWireframe()); - } - // Normals - if (m_CurrentKeyState[GLFW_KEY_F2] && !m_LastKeyState[GLFW_KEY_F2]) - { - m_Renderer->DrawNormals(!m_Renderer->DrawNormals()); - } - // Bounds - if (m_CurrentKeyState[GLFW_KEY_F3] && !m_LastKeyState[GLFW_KEY_F3]) - { - m_Renderer->DrawBounds(!m_Renderer->DrawBounds()); - } -#endif +// #ifdef DEBUG +// // Wireframe +// if (m_CurrentKeyState[GLFW_KEY_F1] && !m_LastKeyState[GLFW_KEY_F1]) +// { +// m_Renderer->DrawWireframe(!m_Renderer->DrawWireframe()); +// } +// // Normals +// if (m_CurrentKeyState[GLFW_KEY_F2] && !m_LastKeyState[GLFW_KEY_F2]) +// { +// m_Renderer->DrawNormals(!m_Renderer->DrawNormals()); +// } +// // Bounds +// if (m_CurrentKeyState[GLFW_KEY_F3] && !m_LastKeyState[GLFW_KEY_F3]) +// { +// m_Renderer->DrawBounds(!m_Renderer->DrawBounds()); +// } +// #endif } -void Systems::InputSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) +bool Systems::InputSystem::OnKeyDown(const Events::KeyDown &event) { - auto input = m_World->GetComponent(entity, "Input"); - if (input == nullptr) - return; - - input->KeyState = m_CurrentKeyState; - input->LastKeyState = m_LastKeyState; - input->MouseState = m_CurrentMouseState; - input->LastMouseState = m_LastMouseState; - input->dX = m_CurrentMouseDeltaX; - input->dY = m_CurrentMouseDeltaY; -} - -std::array Systems::InputSystem::m_CurrentKeyState; -std::array Systems::InputSystem::m_LastKeyState; + return true; +} \ No newline at end of file diff --git a/src/Systems/InputSystem.h b/src/Systems/InputSystem.h index 6107c2b..b38bf96 100755 --- a/src/Systems/InputSystem.h +++ b/src/Systems/InputSystem.h @@ -20,19 +20,16 @@ public: , m_Renderer(renderer) { } void RegisterComponents(ComponentFactory* cf) override; + void Initialize() override; void Update(double dt) override; - void UpdateEntity(double dt, EntityID entity, EntityID parent) override; private: std::shared_ptr m_Renderer; - static std::array m_CurrentKeyState; - static std::array m_LastKeyState; - std::array m_CurrentMouseState; - std::array m_LastMouseState; - float m_CurrentMouseDeltaX, m_CurrentMouseDeltaY; - float m_LastMouseX, m_LastMouseY; + // Events + EventRelay m_EKeyDown; + bool OnKeyDown(const Events::KeyDown &event); }; } diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 17327db..d894ab5 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -98,6 +98,7 @@ + @@ -140,11 +141,15 @@ + + + + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index febf3eb..532c16e 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -51,6 +51,7 @@ + @@ -240,6 +241,18 @@ Input\Events + + Input + + + Input\Events + + + Input\Events + + + Input\Events + From 0e068be77b999c338d04351d68ce5c2ebb3c4fc2 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Mon, 5 May 2014 09:17:58 +0200 Subject: [PATCH 32/37] Basic input binding and command publishing system --- src/Events/BindKey.h | 17 +++ src/Events/BindMouseButton.h | 17 +++ src/Events/InputCommand.h | 17 +++ src/Events/InputCommandValue.h | 18 +++ src/InputManager.cpp | 8 +- src/InputManager.h | 11 +- src/Systems/InputSystem.cpp | 110 +++++++++++++++++- src/Systems/InputSystem.h | 26 ++++- vs11/Returngeance/Returngeance.vcxproj | 4 + .../Returngeance/Returngeance.vcxproj.filters | 16 ++- 10 files changed, 233 insertions(+), 11 deletions(-) create mode 100644 src/Events/BindKey.h create mode 100644 src/Events/BindMouseButton.h create mode 100644 src/Events/InputCommand.h create mode 100644 src/Events/InputCommandValue.h diff --git a/src/Events/BindKey.h b/src/Events/BindKey.h new file mode 100644 index 0000000..a774942 --- /dev/null +++ b/src/Events/BindKey.h @@ -0,0 +1,17 @@ +#ifndef Events_BindKey_h__ +#define Events_BindKey_h__ + +#include "EventBroker.h" + +namespace Events +{ + +struct BindKey : Event +{ + int KeyCode; + std::string Command; +}; + +} + +#endif // Events_BindKey_h__ \ No newline at end of file diff --git a/src/Events/BindMouseButton.h b/src/Events/BindMouseButton.h new file mode 100644 index 0000000..1f46647 --- /dev/null +++ b/src/Events/BindMouseButton.h @@ -0,0 +1,17 @@ +#ifndef Events_BindMouseButton_h__ +#define Events_BindMouseButton_h__ + +#include "EventBroker.h" + +namespace Events +{ + +struct BindMouseButton : Event +{ + int Button; + std::string Command; +}; + +} + +#endif // Events_BindMouseButton_h__ \ No newline at end of file diff --git a/src/Events/InputCommand.h b/src/Events/InputCommand.h new file mode 100644 index 0000000..34a22c9 --- /dev/null +++ b/src/Events/InputCommand.h @@ -0,0 +1,17 @@ +#ifndef Events_InputCommand_h__ +#define Events_InputCommand_h__ + +#include "EventBroker.h" + +namespace Events +{ + +struct InputCommand : Event +{ + unsigned int PlayerID; + std::string Command; +}; + +} + +#endif // Events_InputCommand_h__ \ No newline at end of file diff --git a/src/Events/InputCommandValue.h b/src/Events/InputCommandValue.h new file mode 100644 index 0000000..87e3702 --- /dev/null +++ b/src/Events/InputCommandValue.h @@ -0,0 +1,18 @@ +#ifndef Events_InputCommandValue_h__ +#define Events_InputCommandValue_h__ + +#include "EventBroker.h" +#include "Events/InputCommand.h" + +namespace Events +{ + +template +struct InputCommandValue : public InputCommand +{ + T Value; +}; + +} + +#endif // Events_InputCommandValue_h__ \ No newline at end of file diff --git a/src/InputManager.cpp b/src/InputManager.cpp index 18d8d92..9f09b1c 100644 --- a/src/InputManager.cpp +++ b/src/InputManager.cpp @@ -1,12 +1,6 @@ #include "PrecompiledHeader.h" #include "InputManager.h" -InputManager::InputManager(GLFWwindow* window, std::shared_ptr eventBroker) : m_GLFWWindow(window) - , m_EventBroker(eventBroker) -{ - -} - void InputManager::Update(double dt) { m_LastKeyState = m_CurrentKeyState; @@ -43,7 +37,7 @@ void InputManager::Update(double dt) if (m_CurrentMouseState[i] != m_LastMouseState[i]) { // Publish mouse button events - if (m_CurrentKeyState[i]) + if (m_CurrentMouseState[i]) { Events::MousePress e; e.Button = i; diff --git a/src/InputManager.h b/src/InputManager.h index d7545e4..5acaaa2 100644 --- a/src/InputManager.h +++ b/src/InputManager.h @@ -13,7 +13,16 @@ class InputManager { public: - InputManager(GLFWwindow* window, std::shared_ptr eventBroker); + InputManager(GLFWwindow* window, std::shared_ptr eventBroker) + : m_GLFWWindow(window) + , m_EventBroker(eventBroker) + , m_CurrentKeyState() + , m_LastKeyState() + , m_CurrentMouseState() + , m_LastMouseState() + , m_CurrentMouseX(0), m_CurrentMouseY(0) + , m_LastMouseX(0), m_LastMouseY(0) + , m_CurrentMouseDeltaX(0), m_CurrentMouseDeltaY(0) { } void Update(double dt); diff --git a/src/Systems/InputSystem.cpp b/src/Systems/InputSystem.cpp index 70cb927..f8b1d59 100755 --- a/src/Systems/InputSystem.cpp +++ b/src/Systems/InputSystem.cpp @@ -12,6 +12,30 @@ void Systems::InputSystem::Initialize() // Subscribe to events m_EKeyDown = decltype(m_EKeyDown)(std::bind(&Systems::InputSystem::OnKeyDown, this, std::placeholders::_1)); EventBroker->Subscribe(m_EKeyDown); + m_EKeyUp = decltype(m_EKeyUp)(std::bind(&Systems::InputSystem::OnKeyUp, this, std::placeholders::_1)); + EventBroker->Subscribe(m_EKeyUp); + m_EMousePress = decltype(m_EMousePress)(std::bind(&Systems::InputSystem::OnMousePress, this, std::placeholders::_1)); + EventBroker->Subscribe(m_EMousePress); + m_EMouseRelease = decltype(m_EMouseRelease)(std::bind(&Systems::InputSystem::OnMouseRelease, this, std::placeholders::_1)); + EventBroker->Subscribe(m_EMouseRelease); + m_EBindKey = decltype(m_EBindKey)(std::bind(&Systems::InputSystem::OnBindKey, this, std::placeholders::_1)); + EventBroker->Subscribe(m_EBindKey); + m_EBindMouseButton = decltype(m_EBindMouseButton)(std::bind(&Systems::InputSystem::OnBindMouseButton, this, std::placeholders::_1)); + EventBroker->Subscribe(m_EBindMouseButton); + + { + Events::BindKey e; + e.KeyCode = GLFW_KEY_W; + e.Command = "+forward"; + EventBroker->Publish(e); + } + + { + Events::BindMouseButton e; + e.Button = GLFW_MOUSE_BUTTON_1; + e.Command = "+attack"; + EventBroker->Publish(e); + } } void Systems::InputSystem::Update(double dt) @@ -37,5 +61,89 @@ void Systems::InputSystem::Update(double dt) bool Systems::InputSystem::OnKeyDown(const Events::KeyDown &event) { + auto bindingIt = m_KeyBindings.find(event.KeyCode); + if (bindingIt != m_KeyBindings.end()) + { + PublishCommand(0, bindingIt->second, false); + } + return true; -} \ No newline at end of file +} + +bool Systems::InputSystem::OnKeyUp(const Events::KeyUp &event) +{ + auto bindingIt = m_KeyBindings.find(event.KeyCode); + if (bindingIt != m_KeyBindings.end()) + { + PublishCommand(0, bindingIt->second, true); + } + + return true; +} + +bool Systems::InputSystem::OnMousePress(const Events::MousePress &event) +{ + auto bindingIt = m_MouseButtonBindings.find(event.Button); + if (bindingIt != m_MouseButtonBindings.end()) + { + PublishCommand(0, bindingIt->second, false); + } + + return true; +} + +bool Systems::InputSystem::OnMouseRelease(const Events::MouseRelease &event) +{ + auto bindingIt = m_MouseButtonBindings.find(event.Button); + if (bindingIt != m_MouseButtonBindings.end()) + { + PublishCommand(0, bindingIt->second, true); + } + + return true; +} + +bool Systems::InputSystem::OnBindKey(const Events::BindKey &event) +{ + if (event.Command.empty()) + { + m_KeyBindings.erase(event.KeyCode); + } + else + { + m_KeyBindings[event.KeyCode] = event.Command; + LOG_DEBUG("Input: Bound key %c to %s", (char)event.KeyCode, event.Command.c_str()); + } + + return true; +} + +bool Systems::InputSystem::OnBindMouseButton(const Events::BindMouseButton &event) +{ + if (event.Command.empty()) + { + m_MouseButtonBindings.erase(event.Button); + } + else + { + m_MouseButtonBindings[event.Button] = event.Command; + LOG_DEBUG("Input: Bound mouse button %i to %s", event.Button, event.Command.c_str()); + } + + return true; +} + +void Systems::InputSystem::PublishCommand(int playerID, std::string command, bool release /*= false*/) +{ + if (release && command.at(0) == '+') + { + command[0] = '-'; + } + + Events::InputCommand e; + e.PlayerID = playerID; + e.Command = command; + EventBroker->Publish(e); + + LOG_DEBUG("Input: Published command %s for player %i", e.Command.c_str(), playerID); +} diff --git a/src/Systems/InputSystem.h b/src/Systems/InputSystem.h index b38bf96..d0766e5 100755 --- a/src/Systems/InputSystem.h +++ b/src/Systems/InputSystem.h @@ -2,12 +2,19 @@ #define InputSystem_h__ #include +#include #include "System.h" #include "Renderer.h" #include "Components/Input.h" #include "Events/KeyUp.h" #include "Events/KeyDown.h" +#include "Events/MousePress.h" +#include "Events/MouseRelease.h" +#include "Events/BindKey.h" +#include "Events/BindMouseButton.h" +#include "Events/InputCommand.h" +#include "Events/InputCommandValue.h" namespace Systems { @@ -27,9 +34,26 @@ public: private: std::shared_ptr m_Renderer; - // Events + // Input binding tables + std::unordered_map m_KeyBindings; // GLFW_KEY... -> command string + std::unordered_map m_MouseButtonBindings; // GLFW_MOUSE_BUTTON... -> command string + + // Input events EventRelay m_EKeyDown; bool OnKeyDown(const Events::KeyDown &event); + EventRelay m_EKeyUp; + bool OnKeyUp(const Events::KeyUp &event); + EventRelay m_EMousePress; + bool OnMousePress(const Events::MousePress &event); + EventRelay m_EMouseRelease; + bool OnMouseRelease(const Events::MouseRelease &event); + // Input binding events + EventRelay m_EBindKey; + bool OnBindKey(const Events::BindKey &event); + EventRelay m_EBindMouseButton; + bool OnBindMouseButton(const Events::BindMouseButton &event); + + void PublishCommand(int playerID, std::string command, bool release = false); }; } diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index d894ab5..2b7c917 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -139,6 +139,10 @@ + + + + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 532c16e..4da5b38 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -51,7 +51,9 @@ - + + Input + @@ -253,6 +255,18 @@ Input\Events + + Input\Events + + + Input\Events + + + Input\Events + + + Input\Events + From 8c8edd0e8e4c62879f5f3a0f2bda39a9f9655c8b Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 6 May 2014 14:33:02 +0200 Subject: [PATCH 33/37] WIP InputController for easier command handling in systems --- src/EventBroker.h | 4 +++ src/Events/InputCommand.h | 3 ++ src/Events/InputCommandValue.h | 18 ----------- src/GameWorld.cpp | 30 +++++++++++++++-- src/GameWorld.h | 3 ++ src/InputController.h | 30 +++++++++++++++++ src/Systems/InputSystem.cpp | 32 ++++--------------- src/Systems/InputSystem.h | 1 - vs11/Returngeance/Returngeance.vcxproj | 2 +- .../Returngeance/Returngeance.vcxproj.filters | 6 ++-- 10 files changed, 77 insertions(+), 52 deletions(-) delete mode 100644 src/Events/InputCommandValue.h create mode 100644 src/InputController.h diff --git a/src/EventBroker.h b/src/EventBroker.h index c11fe4a..f8877e8 100644 --- a/src/EventBroker.h +++ b/src/EventBroker.h @@ -6,6 +6,10 @@ #include #include +#define EVENT_SUBSCRIBE_MEMBER(relay, handler) \ + relay = decltype(relay)(std::bind(handler, this, std::placeholders::_1)); \ + EventBroker->Subscribe(relay); + struct Event { protected: diff --git a/src/Events/InputCommand.h b/src/Events/InputCommand.h index 34a22c9..bd18f6a 100644 --- a/src/Events/InputCommand.h +++ b/src/Events/InputCommand.h @@ -1,6 +1,8 @@ #ifndef Events_InputCommand_h__ #define Events_InputCommand_h__ +#include + #include "EventBroker.h" namespace Events @@ -10,6 +12,7 @@ struct InputCommand : Event { unsigned int PlayerID; std::string Command; + boost::any Value; }; } diff --git a/src/Events/InputCommandValue.h b/src/Events/InputCommandValue.h deleted file mode 100644 index 87e3702..0000000 --- a/src/Events/InputCommandValue.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef Events_InputCommandValue_h__ -#define Events_InputCommandValue_h__ - -#include "EventBroker.h" -#include "Events/InputCommand.h" - -namespace Events -{ - -template -struct InputCommandValue : public InputCommand -{ - T Value; -}; - -} - -#endif // Events_InputCommandValue_h__ \ No newline at end of file diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index c92f868..b8dcf9d 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -8,6 +8,14 @@ void GameWorld::Initialize() m_ResourceManager.Preload("Model", "Models/Placeholders/PhysicsTest/Plane.obj"); m_ResourceManager.Preload("Model", "Models/Placeholders/PhysicsTest/ArrowCube.obj"); + BindKey(GLFW_KEY_W, "+forward"); + BindKey(GLFW_KEY_S, "+backward"); + BindKey(GLFW_KEY_A, "+left"); + BindKey(GLFW_KEY_D, "+right"); + BindMouseButton(GLFW_MOUSE_BUTTON_1, "+attack"); + BindMouseButton(GLFW_MOUSE_BUTTON_2, "+attack2"); + BindMouseButton(GLFW_MOUSE_BUTTON_3, "+attack3"); + RegisterComponents(); { @@ -42,7 +50,7 @@ void GameWorld::Initialize() CommitEntity(ground); } - { + /*{ auto TankTest = CreateEntity(); auto transform = AddComponent(TankTest, "Transform"); transform->Position = glm::vec3(1.5f, 0.7f, 5.f); @@ -85,7 +93,7 @@ void GameWorld::Initialize() auto physics = AddComponent(ball, "Physics"); physics->Mass = 1; CommitEntity(ball); - } + }*/ { auto entity = CreateEntity(); @@ -138,4 +146,20 @@ void GameWorld::AddSystems() AddSystem("SoundSystem"); AddSystem("PhysicsSystem"); AddSystem("RenderSystem"); -} \ No newline at end of file +} + +void GameWorld::BindKey(int keyCode, std::string command) +{ + Events::BindKey e; + e.KeyCode = keyCode; + e.Command = command; + m_EventBroker->Publish(e); +} + +void GameWorld::BindMouseButton(int button, std::string command) +{ + Events::BindMouseButton e; + e.Button = button; + e.Command = command; + m_EventBroker->Publish(e); +} diff --git a/src/GameWorld.h b/src/GameWorld.h index 17901c3..355c9b1 100755 --- a/src/GameWorld.h +++ b/src/GameWorld.h @@ -47,6 +47,9 @@ public: private: std::shared_ptr m_Renderer; + + void BindKey(int keyCode, std::string command); + void BindMouseButton(int button, std::string command); }; #endif // GameWorld_h__ diff --git a/src/InputController.h b/src/InputController.h new file mode 100644 index 0000000..535e4f4 --- /dev/null +++ b/src/InputController.h @@ -0,0 +1,30 @@ +#ifndef InputController_h__ +#define InputController_h__ + +#include + +#include "EventBroker.h" +#include "Events/InputCommand.h" + +class InputController +{ +public: + InputController(std::shared_ptr<::EventBroker> eventBroker) + : EventBroker(EventBroker) { Initialize(); } + + virtual void Initialize() + { + EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &InputController::OnCommand) + } + + virtual bool OnCommand(const Events::InputCommand &event) { } + +protected: + std::shared_ptr<::EventBroker> EventBroker; + +private: + EventRelay m_EInputCommand; + +}; + +#endif // InputController_h__ diff --git a/src/Systems/InputSystem.cpp b/src/Systems/InputSystem.cpp index f8b1d59..3c9fdfd 100755 --- a/src/Systems/InputSystem.cpp +++ b/src/Systems/InputSystem.cpp @@ -10,32 +10,12 @@ void Systems::InputSystem::RegisterComponents(ComponentFactory* cf) void Systems::InputSystem::Initialize() { // Subscribe to events - m_EKeyDown = decltype(m_EKeyDown)(std::bind(&Systems::InputSystem::OnKeyDown, this, std::placeholders::_1)); - EventBroker->Subscribe(m_EKeyDown); - m_EKeyUp = decltype(m_EKeyUp)(std::bind(&Systems::InputSystem::OnKeyUp, this, std::placeholders::_1)); - EventBroker->Subscribe(m_EKeyUp); - m_EMousePress = decltype(m_EMousePress)(std::bind(&Systems::InputSystem::OnMousePress, this, std::placeholders::_1)); - EventBroker->Subscribe(m_EMousePress); - m_EMouseRelease = decltype(m_EMouseRelease)(std::bind(&Systems::InputSystem::OnMouseRelease, this, std::placeholders::_1)); - EventBroker->Subscribe(m_EMouseRelease); - m_EBindKey = decltype(m_EBindKey)(std::bind(&Systems::InputSystem::OnBindKey, this, std::placeholders::_1)); - EventBroker->Subscribe(m_EBindKey); - m_EBindMouseButton = decltype(m_EBindMouseButton)(std::bind(&Systems::InputSystem::OnBindMouseButton, this, std::placeholders::_1)); - EventBroker->Subscribe(m_EBindMouseButton); - - { - Events::BindKey e; - e.KeyCode = GLFW_KEY_W; - e.Command = "+forward"; - EventBroker->Publish(e); - } - - { - Events::BindMouseButton e; - e.Button = GLFW_MOUSE_BUTTON_1; - e.Command = "+attack"; - EventBroker->Publish(e); - } + EVENT_SUBSCRIBE_MEMBER(m_EKeyDown, &Systems::InputSystem::OnKeyDown) + EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &Systems::InputSystem::OnKeyUp) + EVENT_SUBSCRIBE_MEMBER(m_EMousePress, &Systems::InputSystem::OnMousePress) + EVENT_SUBSCRIBE_MEMBER(m_EMouseRelease, &Systems::InputSystem::OnMouseRelease) + EVENT_SUBSCRIBE_MEMBER(m_EBindKey, &Systems::InputSystem::OnBindKey) + EVENT_SUBSCRIBE_MEMBER(m_EBindMouseButton, &Systems::InputSystem::OnBindMouseButton) } void Systems::InputSystem::Update(double dt) diff --git a/src/Systems/InputSystem.h b/src/Systems/InputSystem.h index d0766e5..bc1142a 100755 --- a/src/Systems/InputSystem.h +++ b/src/Systems/InputSystem.h @@ -14,7 +14,6 @@ #include "Events/BindKey.h" #include "Events/BindMouseButton.h" #include "Events/InputCommand.h" -#include "Events/InputCommandValue.h" namespace Systems { diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 2b7c917..88d37ff 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -142,7 +142,6 @@ - @@ -153,6 +152,7 @@ + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 4da5b38..f76cb42 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -261,12 +261,12 @@ Input\Events - - Input\Events - Input\Events + + Input + From a232559bb19775fb7820249b75d2a435f7f57d1e Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 6 May 2014 17:07:38 +0200 Subject: [PATCH 34/37] FreeSteeringSystem converted to take input commands --- src/GameWorld.cpp | 10 +- src/InputController.h | 11 +- src/Systems/FreeSteeringSystem.cpp | 162 ++++++++++++++++++++--------- src/Systems/FreeSteeringSystem.h | 28 ++++- src/Systems/InputSystem.h | 8 +- 5 files changed, 155 insertions(+), 64 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index b8dcf9d..48a65a5 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -12,6 +12,10 @@ void GameWorld::Initialize() BindKey(GLFW_KEY_S, "+backward"); BindKey(GLFW_KEY_A, "+left"); BindKey(GLFW_KEY_D, "+right"); + BindKey(GLFW_KEY_SPACE, "+up"); + BindKey(GLFW_KEY_LEFT_CONTROL, "+down"); + BindKey(GLFW_KEY_LEFT_ALT, "+slow"); + BindKey(GLFW_KEY_LEFT_SHIFT, "+fast"); BindMouseButton(GLFW_MOUSE_BUTTON_1, "+attack"); BindMouseButton(GLFW_MOUSE_BUTTON_2, "+attack2"); BindMouseButton(GLFW_MOUSE_BUTTON_3, "+attack3"); @@ -50,7 +54,7 @@ void GameWorld::Initialize() CommitEntity(ground); } - /*{ + { auto TankTest = CreateEntity(); auto transform = AddComponent(TankTest, "Transform"); transform->Position = glm::vec3(1.5f, 0.7f, 5.f); @@ -60,7 +64,7 @@ void GameWorld::Initialize() CommitEntity(TankTest); } - for(int i = 0; i < 83; i++) + /*for(int i = 0; i < 83; i++) { auto light = CreateEntity(); auto transform = AddComponent(light, "Transform"); @@ -122,7 +126,7 @@ void GameWorld::RegisterSystems() { m_SystemFactory.Register("TransformSystem", [this]() { return new Systems::TransformSystem(this, m_EventBroker); }); //m_SystemFactory.Register("LevelGenerationSystem", [this]() { return new Systems::LevelGenerationSystem(this); }); - m_SystemFactory.Register("InputSystem", [this]() { return new Systems::InputSystem(this, m_EventBroker, m_Renderer); }); + m_SystemFactory.Register("InputSystem", [this]() { return new Systems::InputSystem(this, m_EventBroker); }); m_SystemFactory.Register("DebugSystem", [this]() { return new Systems::DebugSystem(this, m_EventBroker); }); //m_SystemFactory.Register("CollisionSystem", [this]() { return new Systems::CollisionSystem(this); }); ////m_SystemFactory.Register("ParticleSystem", [this]() { return new Systems::ParticleSystem(this); }); diff --git a/src/InputController.h b/src/InputController.h index 535e4f4..7afd5d5 100644 --- a/src/InputController.h +++ b/src/InputController.h @@ -5,26 +5,29 @@ #include "EventBroker.h" #include "Events/InputCommand.h" +#include "Events/MouseMove.h" class InputController { public: InputController(std::shared_ptr<::EventBroker> eventBroker) - : EventBroker(EventBroker) { Initialize(); } + : EventBroker(eventBroker) { Initialize(); } virtual void Initialize() { - EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &InputController::OnCommand) + EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &InputController::OnCommand); + EVENT_SUBSCRIBE_MEMBER(m_EMouseMove, &InputController::OnMouseMove); } - virtual bool OnCommand(const Events::InputCommand &event) { } + virtual bool OnCommand(const Events::InputCommand &event) { return false; } + virtual bool OnMouseMove(const Events::MouseMove &event) { return false; } protected: std::shared_ptr<::EventBroker> EventBroker; private: EventRelay m_EInputCommand; - + EventRelay m_EMouseMove; }; #endif // InputController_h__ diff --git a/src/Systems/FreeSteeringSystem.cpp b/src/Systems/FreeSteeringSystem.cpp index 407200b..f1ed04e 100755 --- a/src/Systems/FreeSteeringSystem.cpp +++ b/src/Systems/FreeSteeringSystem.cpp @@ -7,65 +7,127 @@ void Systems::FreeSteeringSystem::RegisterComponents(ComponentFactory* cf) cf->Register("FreeSteering", []() { return new Components::FreeSteering(); }); } +void Systems::FreeSteeringSystem::Initialize() +{ + m_InputController = std::unique_ptr(new FreeSteeringInputController(EventBroker)); +} + void Systems::FreeSteeringSystem::Update(double dt) { - + } void Systems::FreeSteeringSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) { auto steering = m_World->GetComponent(entity, "FreeSteering"); - auto input = m_World->GetComponent(entity, "Input"); - if (steering && input) + if (steering) { auto transform = m_World->GetComponent(entity, "Transform"); - glm::vec3 Camera_Right = glm::vec3(glm::vec4(1, 0, 0, 0) * transform->Orientation); - glm::vec3 Camera_Forward = glm::vec3(glm::vec4(0, 0, 1, 0) * transform->Orientation); - - float speed = steering->Speed; - if (input->KeyState[GLFW_KEY_LEFT_SHIFT]) - { - speed *= 4.0f; - } - if (input->KeyState[GLFW_KEY_LEFT_ALT]) - { - speed /= 4.0f; - } - if (input->KeyState[GLFW_KEY_A]) - { - transform->Position -= Camera_Right * (float)dt * speed; - } - else if (input->KeyState[GLFW_KEY_D]) - { - transform->Position += Camera_Right * (float)dt * speed; - } - if (input->KeyState[GLFW_KEY_W]) - { - transform->Position -= Camera_Forward * (float)dt * speed; - } - if (input->KeyState[GLFW_KEY_S]) - { - transform->Position += Camera_Forward * (float)dt * speed; - } - if (input->KeyState[GLFW_KEY_SPACE]) - { - transform->Position += glm::vec3(0, 1, 0) * (float)dt * speed; - } - if (input->KeyState[GLFW_KEY_LEFT_CONTROL]) - { - transform->Position -= glm::vec3(0, 1, 0) * (float)dt * speed; - } - - if (input->MouseState[GLFW_MOUSE_BUTTON_LEFT]) - { - // TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS // spelling tobias :3 - //--------------------------------------------------------------------- - transform->Orientation = glm::angleAxis(input->dY / 300.f, glm::vec3(1, 0, 0)) * transform->Orientation; - - transform->Orientation = transform->Orientation * glm::angleAxis(input->dX / 300.f, glm::vec3(0, 1, 0)); - //--------------------------------------------------------------------- - // TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS - } + glm::vec3 cameraRight = glm::vec3(glm::vec4(1, 0, 0, 0) * m_InputController->Orientation); + glm::vec3 cameraForward = glm::vec3(glm::vec4(0, 0, -1, 0) * m_InputController->Orientation); + glm::vec3 movement; + movement += cameraRight * m_InputController->Movement.x; + movement.y += m_InputController->Movement.y; + movement += cameraForward * -m_InputController->Movement.z; + transform->Position += movement * steering->Speed * m_InputController->SpeedMultiplier * (float)dt; + transform->Orientation = m_InputController->Orientation; } } + +bool Systems::FreeSteeringSystem::FreeSteeringInputController::OnCommand(const Events::InputCommand &event) +{ + // Movement + if (event.Command == "+forward") + { + Movement.z += -1.f; + } + else if (event.Command == "-forward") + { + Movement.z -= -1.f; + } + else if (event.Command == "+backward") + { + Movement.z += 1.f; + } + else if (event.Command == "-backward") + { + Movement.z -= 1.f; + } + else if (event.Command == "+right") + { + Movement.x += 1.f; + } + else if (event.Command == "-right") + { + Movement.x -= 1.f; + } + else if (event.Command == "+left") + { + Movement.x += -1.f; + } + else if (event.Command == "-left") + { + Movement.x -= -1.f; + } + else if (event.Command == "+up") + { + Movement.y += 1.f; + } + else if (event.Command == "-up") + { + Movement.y -= 1.f; + } + else if (event.Command == "+down") + { + Movement.y += -1.f; + } + else if (event.Command == "-down") + { + Movement.y -= -1.f; + } + + // Speed + else if (event.Command == "+fast") + { + SpeedMultiplier *= 4.f; + } + else if (event.Command == "-fast") + { + SpeedMultiplier /= 4.f; + } + else if (event.Command == "+slow") + { + SpeedMultiplier /= 4.f; + } + else if (event.Command == "-slow") + { + SpeedMultiplier *= 4.f; + } + + // Mouse click + else if (event.Command == "+attack") + { + OrientationActive = true; + } + else if (event.Command == "-attack") + { + OrientationActive = false; + } + + return true; +} + +bool Systems::FreeSteeringSystem::FreeSteeringInputController::OnMouseMove(const Events::MouseMove &event) +{ + if (OrientationActive) + { + // TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS + //--------------------------------------------------------------------- + Orientation = glm::angleAxis(event.DeltaY / 300.f, glm::vec3(1, 0, 0)) * Orientation * glm::angleAxis(event.DeltaX / 300.f, glm::vec3(0, 1, 0)); + //--------------------------------------------------------------------- + // TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS + } + + return true; +} diff --git a/src/Systems/FreeSteeringSystem.h b/src/Systems/FreeSteeringSystem.h index 49a65d9..4535cbb 100755 --- a/src/Systems/FreeSteeringSystem.h +++ b/src/Systems/FreeSteeringSystem.h @@ -2,11 +2,12 @@ #include "System.h" #include "Components/Transform.h" -#include "Components/Input.h" #include "Components/FreeSteering.h" +#include "InputController.h" namespace Systems { + class FreeSteeringSystem : public System { public: @@ -14,8 +15,33 @@ public: : System(world, eventBroker) { } void RegisterComponents(ComponentFactory* cf) override; + void Initialize() override; void Update(double dt) override; void UpdateEntity(double dt, EntityID entity, EntityID parent) override; + +private: + class FreeSteeringInputController; + + std::unique_ptr m_InputController; }; + +class FreeSteeringSystem::FreeSteeringInputController : InputController +{ +public: + FreeSteeringInputController(std::shared_ptr<::EventBroker> eventBroker) + : InputController(eventBroker) + , SpeedMultiplier(1.f) + , OrientationActive(false) { } + + glm::vec3 Movement; + glm::quat Orientation; + float SpeedMultiplier; + bool OrientationActive; + +protected: + virtual bool OnCommand(const Events::InputCommand &event); + virtual bool OnMouseMove(const Events::MouseMove &event); +}; + } \ No newline at end of file diff --git a/src/Systems/InputSystem.h b/src/Systems/InputSystem.h index bc1142a..c56cccf 100755 --- a/src/Systems/InputSystem.h +++ b/src/Systems/InputSystem.h @@ -5,7 +5,6 @@ #include #include "System.h" -#include "Renderer.h" #include "Components/Input.h" #include "Events/KeyUp.h" #include "Events/KeyDown.h" @@ -21,9 +20,8 @@ namespace Systems class InputSystem : public System { public: - InputSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr renderer) - : System(world, eventBroker) - , m_Renderer(renderer) { } + InputSystem(World* world, std::shared_ptr<::EventBroker> eventBroker) + : System(world, eventBroker) { } void RegisterComponents(ComponentFactory* cf) override; void Initialize() override; @@ -31,8 +29,6 @@ public: void Update(double dt) override; private: - std::shared_ptr m_Renderer; - // Input binding tables std::unordered_map m_KeyBindings; // GLFW_KEY... -> command string std::unordered_map m_MouseButtonBindings; // GLFW_MOUSE_BUTTON... -> command string From c73da364f470f05d74dbfedb7244aedc8bfdad67 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 6 May 2014 18:08:13 +0200 Subject: [PATCH 35/37] Derpy skybox un-derped --- src/Renderer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Renderer.cpp b/src/Renderer.cpp index e7dfed6..6cc7dc2 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -191,7 +191,7 @@ void Renderer::DrawSkybox() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_ShaderProgramSkybox.Bind(); - glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * glm::toMat4(m_Camera->Orientation()); + glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * glm::toMat4(glm::inverse(m_Camera->Orientation())); glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgramSkybox.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(cameraMatrix)); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); m_Skybox->Draw(); From 6e6a115ac3ad18184b6bb8d5e0b87ade9e0cd39f Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Sat, 10 May 2014 19:13:41 +0200 Subject: [PATCH 36/37] Assets now as Git submodule! --- .gitignore | 1 - .gitmodules | 4 ++++ assets | 1 + 3 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 .gitmodules create mode 160000 assets diff --git a/.gitignore b/.gitignore index 3b5dc2e..5982b10 100755 --- a/.gitignore +++ b/.gitignore @@ -31,5 +31,4 @@ ipch/ Ankh.NoLoad *.orig -assets/ !libs/*.lib \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..185a1f9 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "assets"] + path = assets + url = returngeance@shard.imon.nu:Assets + branch = master diff --git a/assets b/assets new file mode 160000 index 0000000..672e8a2 --- /dev/null +++ b/assets @@ -0,0 +1 @@ +Subproject commit 672e8a2b11ecaafc95a5b0286b5ec310c62438ad From 41177581c63473a90a267f1bd5c85af3d516a173 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Sun, 11 May 2014 01:46:02 +0200 Subject: [PATCH 37/37] WIP Render Queue --- src/Components/Camera.h | 6 +- src/GUI/Viewport.h | 21 +++++++ src/RenderQueue.h | 62 +++++++++++++++++++ vs11/Returngeance/Returngeance.vcxproj | 2 + .../Returngeance/Returngeance.vcxproj.filters | 6 ++ 5 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 src/GUI/Viewport.h create mode 100644 src/RenderQueue.h diff --git a/src/Components/Camera.h b/src/Components/Camera.h index 2cd379d..d30c537 100755 --- a/src/Components/Camera.h +++ b/src/Components/Camera.h @@ -8,8 +8,12 @@ namespace Components struct Camera : Component { - Camera() : FOV(glm::radians(45.f)), NearClip(0.1f), FarClip(100.f) { } + Camera() + : FOV(glm::radians(45.f)) + , NearClip(0.1f) + , FarClip(100.f) { } + std::string Viewport; float FOV; float NearClip; float FarClip; diff --git a/src/GUI/Viewport.h b/src/GUI/Viewport.h new file mode 100644 index 0000000..b4568b5 --- /dev/null +++ b/src/GUI/Viewport.h @@ -0,0 +1,21 @@ +#ifndef GUI_Viewport_h__ +#define GUI_Viewport_h__ + +#include + +#include "GUI/Frame.h" + +namespace GUI +{ + +class Viewport : public Frame +{ +public: + // Create a frame as a child + Viewport(std::shared_ptr parent) + : Frame(parent) { } +}; + +} + +#endif // GUI_Viewport_h__ diff --git a/src/RenderQueue.h b/src/RenderQueue.h new file mode 100644 index 0000000..7439de2 --- /dev/null +++ b/src/RenderQueue.h @@ -0,0 +1,62 @@ +#ifndef RenderQueue_h__ +#define RenderQueue_h__ + +#include +#include + +#include "ResourceManager.h" +#include "Texture.h" +#include "Model.h" + +class RenderQueue; + +struct RenderJob +{ + friend class RenderQueue; + + unsigned int ViewportID; + unsigned int TextureID; + + GLuint DiffuseTexture; + GLuint NormalTexture; + GLuint SpecularTexture; + GLuint VAO; + unsigned int StartIndex; + unsigned int EndIndex; + glm::mat4 ModelMatrix; + +protected: + uint64_t Hash; + + void CalculateHash() + { + Hash = ViewportID << 58 // 6 bits + | TextureID << 42; // 16 bits + } + + bool operator<(const RenderJob& rhs) + { + return this->Hash < rhs.Hash; + } +}; + +class RenderQueue +{ +public: + void Add(RenderJob &job) + { + job.CalculateHash(); + m_Jobs.push_front(job); + m_Jobs.sort(); + } + + void Clear() + { + m_Jobs.clear(); + } + +private: + std::forward_list m_Jobs; +}; + +#endif // RenderQueue_h__ diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index f9a533a..1de7fd5 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -155,6 +155,7 @@ + @@ -162,6 +163,7 @@ + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index f0145be..51e5aa8 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -279,6 +279,12 @@ Input + + Rendering + + + GUI +