Subversion Repository Public Repository

Divide-Framework

This repository has no backups
This repository's network speed is throttled to 100KB/sec

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#include "Headers/PhysX.h"
#include "Headers/PhysXSceneInterface.h"
#include "Core/Headers/ParamHandler.h"
#include "Core/Math/Headers/Transform.h"
#include "Graphs/Headers/SceneGraphNode.h"
#include "Geometry/Shapes/Headers/Object3D.h"
#include "Geometry/Shapes/Headers/Mesh.h"
#include "Geometry/Shapes/Headers/SubMesh.h"
#include "Hardware/Video/Buffers/VertexBuffer/Headers/VertexBuffer.h"

#include <Samples/PxToolkit/include/PxToolkit.h>
#include <Samples/PxToolkit/include/PxTkNamespaceMangle.h>
#include <PsFile.h>

using namespace physx;

namespace Divide {

physx::PxDefaultAllocator     PhysX::_gDefaultAllocatorCallback;
physx::PxDefaultErrorCallback PhysX::_gDefaultErrorCallback;

physx::PxProfileZone* PhysX::getOrCreateProfileZone(PxFoundation& inFoundation) { 	
#ifdef PHYSX_PROFILE_SDK
    if (_profileZone == nullptr) {
        _profileZone = &physx::PxProfileZone::createProfileZone( &inFoundation, "SampleProfileZone", gProfileNameProvider );
    }
#endif
    return _profileZone;
}

PhysX::PhysX() : _gPhysicsSDK(nullptr),
                 _foundation(nullptr),
                 _zoneManager(nullptr),
                 _cooking(nullptr),
                 _profileZone(nullptr),
                 _pvdConnection(nullptr),
                 _targetScene(nullptr),
                 _accumulator(0.0f),
                 _timeStepFactor(0.0f),
                 _timeStep(0.0f)
{
}

ErrorCode PhysX::initPhysicsApi(U8 targetFrameRate) {
    PRINT_FN(Locale::get("START_PHYSX_API"));

    // create foundation object with default error and allocator callbacks.
    _foundation = PxCreateFoundation(PX_PHYSICS_VERSION, _gDefaultAllocatorCallback, _gDefaultErrorCallback);
    assert(_foundation != nullptr);
    
    bool recordMemoryAllocations = false;

#ifdef _DEBUG
    recordMemoryAllocations = true;
    _zoneManager = &PxProfileZoneManager::createProfileZoneManager(_foundation);
    assert(_zoneManager != nullptr);
#endif

    _gPhysicsSDK = PxCreatePhysics(PX_PHYSICS_VERSION, *_foundation, PxTolerancesScale(), recordMemoryAllocations, _zoneManager);

    if (_gPhysicsSDK == nullptr) {
        ERROR_FN(Locale::get("ERROR_START_PHYSX_API"));
        return PHYSX_INIT_ERROR;
    }
  
#ifdef _DEBUG
    if (getOrCreateProfileZone(*_foundation)) {
        _zoneManager->addProfileZone(*_profileZone);
    }

    _pvdConnection = _gPhysicsSDK->getPvdConnectionManager();
    _gPhysicsSDK->getPvdConnectionManager()->addHandler(*this);

    if (_pvdConnection != nullptr) {
        if(PxVisualDebuggerExt::createConnection(_pvdConnection, "localhost", 5425, 10000) != nullptr) {
             D_PRINT_FN(Locale::get("CONNECT_PVD_OK"));
        }
    }
#endif

    if (!PxInitExtensions(*_gPhysicsSDK)) {
        ERROR_FN(Locale::get("ERROR_EXTENSION_PHYSX_API"));
        return PHYSX_EXTENSION_ERROR;
    }
    
    if (!_cooking) {
        PxCookingParams* cookparams = MemoryManager_NEW PxCookingParams(PxTolerancesScale());
        cookparams->targetPlatform = PxPlatform::ePC;
        _cooking = PxCreateCooking(PX_PHYSICS_VERSION, *_foundation, *cookparams);
        MemoryManager::DELETE( cookparams );
    }

    updateTimeStep(targetFrameRate);
    PRINT_FN(Locale::get("START_PHYSX_API_OK"));

    return NO_ERR;
}

bool PhysX::closePhysicsApi() {
    if (!_gPhysicsSDK) {
        return false;
    }
    
    PRINT_FN(Locale::get("STOP_PHYSX_API"));
	
	DIVIDE_ASSERT(_targetScene == nullptr, 
                  "PhysX error: target scene not destroyed before calling closePhysicsApi." 
                  "Call \"setPhysicsScene( nullptr )\" first" );

    if (_cooking) {
        _cooking->release();
    }
    PxCloseExtensions();
	if (_zoneManager) {
		//_zoneManager->release();
	}
    _gPhysicsSDK->release();
    _foundation->release();

    return true;
}

inline void PhysX::updateTimeStep(U8 timeStepFactor) {
    CLAMP<U8>(timeStepFactor,1,timeStepFactor);
    _timeStepFactor = timeStepFactor;
    _timeStep = 1.0f / _timeStepFactor;
    _timeStep *= ParamHandler::getInstance().getParam<F32>("simSpeed");
}

///Process results
void PhysX::process(const U64 deltaTime) {
    if (_targetScene && _timeStep > 0.0f) {
        _accumulator  += static_cast<physx::PxReal>(getUsToMs(deltaTime));
        
        if(_accumulator < _timeStep) {
            return;
        }

        _accumulator -= _timeStep;
        _targetScene->process(_timeStep);
    }
}

///Update actors
void PhysX::update(const U64 deltaTime){
    if (_targetScene) {
        _targetScene->update(deltaTime);
    }
}

void PhysX::idle(){
    if (_targetScene) {
        _targetScene->idle();
    }
}

PhysicsSceneInterface* PhysX::NewSceneInterface(Scene* scene) {
    return MemoryManager_NEW PhysXSceneInterface(scene);
}

void PhysX::setPhysicsScene( PhysicsSceneInterface* const targetScene ) {
	if ( _targetScene ) {
        MemoryManager::DELETE( _targetScene );
	}
	_targetScene = targetScene;
}

void PhysX::initScene() {
	DIVIDE_ASSERT( _targetScene != nullptr, "PhysX error: no target scene specified before a call to initScene()" );
    _targetScene->init();
}

bool PhysX::createActor(SceneGraphNode* const node, 
                        const stringImpl& sceneName, 
                        PhysicsActorMask mask, 
                        PhysicsCollisionGroup group) {
    assert(node != nullptr);
    assert(_targetScene != nullptr);

    Object3D* sNode = node->getNode<Object3D>();

    //Load cached version from file first
    stringImpl nodeName("XML/Scenes/" + sceneName + "/collisionMeshes/node_[_" + sNode->getName() + "_]");
    nodeName.append(".cm");

    FILE* fp = fopen(nodeName.c_str(), "rb");
    bool ok = false;
    if(fp) {
        fseek(fp, 0, SEEK_END);
        PxU32 filesize=ftell(fp);
        fclose(fp);
        ok = (filesize != 0);
    }

    if (group == GROUP_NON_COLLIDABLE) {
        //return true;
    }

    if (!ok) {
    
        sNode->computeTriangleList();
        const vectorImpl<vec3<U32> >& triangles = sNode->getTriangles();

        if (sNode->getTriangles().empty()) {
            return false;
        }

        VertexBuffer* nodeVB = sNode->getGeometryVB();
        if (sNode->getObjectType() == Object3D::SUBMESH) {
            nodeVB = node->getParent()->getNode<Object3D>()->getGeometryVB();
        }

        PxDefaultFileOutputStream stream(nodeName.c_str());
        
        PxTriangleMeshDesc meshDesc;
        meshDesc.points.count     = (PxU32)nodeVB->getPosition().size();
        meshDesc.points.stride    = sizeof(vec3<F32>);
        meshDesc.points.data      = &nodeVB->getPosition()[0];
        meshDesc.triangles.count  = (PxU32)triangles.size();
        meshDesc.triangles.stride = 3*sizeof(U32);
        meshDesc.triangles.data   = triangles.data();
        if (!nodeVB->usesLargeIndices()) {
            //meshDesc.flags = PxMeshFlag::e16_BIT_INDICES;
        }

        if (!_cooking->cookTriangleMesh(meshDesc, stream)) {
            ERROR_FN(Locale::get("ERROR_COOK_TRIANGLE_MESH"));
            return false;
        }
        
    } else {
        PRINT_FN(Locale::get("COLLISION_MESH_LOADED_FROM_FILE"), nodeName.c_str());
    }
    
    PhysXSceneInterface* targetScene = dynamic_cast<PhysXSceneInterface* >(_targetScene);
    PhysicsComponent* nodePhysics = sNode->getObjectType() == Object3D::SUBMESH ? 
                                     node->getParent()->getComponent<PhysicsComponent>() :
                                     node->getComponent<PhysicsComponent>();

	PhysXActor* tempActor = targetScene->getOrCreateRigidActor( node->getName() );
	assert( tempActor != nullptr );
    tempActor->setParent(nodePhysics);

    if (!tempActor->_actor) {
        const vec3<F32>& position = nodePhysics->getPosition();
        const vec4<F32>& orientation = nodePhysics->getOrientation().asVec4();

        physx::PxTransform posePxTransform(PxVec3(position.x, position.y, position.z),
                                           PxQuat(orientation.x,orientation.y,orientation.z,orientation.w).getConjugate());

        if (mask != MASK_RIGID_DYNAMIC) {
            tempActor->_actor = _gPhysicsSDK->createRigidStatic(posePxTransform);
        } else {
            tempActor->_actor = _gPhysicsSDK->createRigidDynamic(posePxTransform);
            tempActor->_isDynamic = true;
        }

        if (!tempActor->_actor) {
            MemoryManager::DELETE( tempActor );
            return false;
        }

        tempActor->_type = PxGeometryType::eTRIANGLEMESH;
		// If we got here, the new actor was just created (didn't exist previously in the scene), so add it
        targetScene->addRigidActor(tempActor, false);
    }
    
    assert(tempActor->_actor);

    PxDefaultFileInputData stream(nodeName.c_str());
    physx::PxTriangleMesh* triangleMesh = _gPhysicsSDK->createTriangleMesh(stream);

    if (!triangleMesh) {
        ERROR_FN(Locale::get("ERROR_CREATE_TRIANGLE_MESH"));
        return false;
    }

    const vec3<F32>& scale = tempActor->getComponent()->getScale();
    PxTriangleMeshGeometry triangleGeometry(triangleMesh, PxMeshScale(PxVec3(scale.x,scale.y,scale.z), PxQuat(PxIdentity)));
	tempActor->_actor->createShape(triangleGeometry, *_gPhysicsSDK->createMaterial( 0.7f, 0.7f, 1.0f ) );

    return true;
};

};

Commits for Divide-Framework/trunk/Source Code/Dynamics/Physics/PhysX/PhysX.cpp

Diff revisions: vs.
Revision Author Commited Message
331 Diff Diff IonutCava picture IonutCava Sat 06 Dec, 2014 20:53:45 +0000

[Ionut]
- Limited line length to 132 characters to improve readability and diff-comparisons
- Refactored memory allocation/deallocation functions
- Fixed a few compatibility issues with HashMap.h
- Fixed a bug in GPU Skinning shaders (cast a float to int)

326 Diff Diff IonutCava picture IonutCava Tue 30 Sep, 2014 21:11:32 +0000

[Ionut]
- Fixed more memory leaks
- Simplified Task interface and timing System
- Improved compatibility between Boost, STL and EASTL with random combinations of vectors, strings and maps
- Simplified Light class by removing the “slot” member
- Random optimizations

325 Diff Diff IonutCava picture IonutCava Wed 17 Sep, 2014 20:06:13 +0000

[Ionut]
- Reworked transform system:
— Parent transform chain system moved from Transform class to the PhysicsComponent
— PhysicsComponent now returns all transform values needed both global and local (still needs heavy optimization and caching)

- Reworked SceneGraph node management:
— Proper ref counting of SceneNodes and proper removing of resource (ResourceCache is now empty on destruction, as it should be)
— Removed parent transform tracking as that’s the PhysicsComponent’s responsibility
— Only nodes loaded via the ResourceCache are allowed to be added to the SceneGraph (added proper loaders for Impostors, Sky, etc)

- Optimized some of the math classes (mat4, mat3)

324 Diff Diff IonutCava picture IonutCava Sun 14 Sep, 2014 14:01:39 +0000

[Ionut]
- New memory management system (no custom allocators in this commit)
— Memory tracer to detect memory leaks on shutdown (from: https://www.relisoft.com/book/tech/9new.html)
— SAFE_DELETE_XYZ are now inline template functions not macros
— ASSERTION system now supports logging and message boxes and continue on error configurable for each build type
— Fixed a lot of memory leaks detected by the new system (some still remain)

- Added SRGB support (part 1)
— Albedo textures are loaded as SRGB (make sure resources are SRGB)
— Shaders output gamma corrected colors
— Moved terrain textures back to 2 array system (albedo and normal maps, albedo maps using a SRGB sampler)

- Sky is now loaded via the ResourceCache system
- Added include safeguards in shader atoms

321 Diff Diff IonutCava picture IonutCava Wed 03 Sep, 2014 22:05:15 +0000

[Ionut]
- Added support (and enabled by default) for the EASTL library (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html / https://github.com/paulhodge/EASTL)
— Strings, vectors and hash_maps can be combined from EASTL, STL and Boost (not all combinations work. e.g. EASTL strings with STL/Boost containers due to the lack of a proper hash function)

318 Diff Diff IonutCava picture IonutCava Sat 30 Aug, 2014 17:35:53 +0000

[Ionut]
- Wrapped the entire code in a “Divide” namespace
- VertexBuffers now call “shrink_to_fit” on all internal data storage
- Improved some vector performance by preferring “emplace_back” instead of “push_back” + proepr usage of reserve / resize
- Wrapped OIS specific types and classes in Divide::Input namespace
- Added the messageBox.layout file (forgot it in the previous few commits)

314 Diff Diff IonutCava picture IonutCava Sun 24 Aug, 2014 19:54:33 +0000

[Ionut]
- More AI work
- Added some needed audio dlls

308 Diff Diff IonutCava picture IonutCava Sat 16 Aug, 2014 19:49:31 +0000

[Ionut]
- Moved Transform from SceneGraphNode to PhysicsComponent and modified BoundingBox update system based on transform update
- Added PhysicsAsset to PhysicsComponent for interfacing with PshysicsAPIs (e.g. PhysXActor inherits PhysicsAsset)
- PhysicsAsset keeps track of the parent PhysicsComponent to have direct access to a node’s transform
- Rewrote GUIConsole to only print items when visible, and use a single circular buffer for entries.
- Updated GUI input system to match the interface that both Kernel and SceneManager share (should probably abstract all the input methods in a class and have Kernel, SceneManager, Scene and GUI inherit from that. In next commit.)
- Updated CEGUI to probably match the OIS states(mouse, keyboard, etc) and properly inject time inputs.

302 Diff Diff IonutCava picture IonutCava Wed 06 Aug, 2014 22:09:55 +0000

[Ionut]
- GenericVertexData buffer size (for read/write buffering) is now configurable instead of a fixed 3x and also applies to non-persistently mapped buffers
- Moved OpenGL enum tables to Divide::GLUtil::GL_ENUM_TABLE
- More code cleanups (glResources, glError, glVertexArray, glGenericVertexData, glIMPrimitive)

298 k1ngp1n picture k1ngp1n Sun 03 Aug, 2014 17:46:29 +0000

[Ionut]
- Final nVidia compatibility commit