Browse Source

Replace new/delete with UniquePtr in simplest cases.

Eugene Kozlov 9 years ago
parent
commit
a69df6344a
32 changed files with 107 additions and 239 deletions
  1. 3 38
      Source/Urho3D/Container/Ptr.h
  2. 0 4
      Source/Urho3D/Input/Input.cpp
  3. 1 1
      Source/Urho3D/Input/Input.h
  4. 4 10
      Source/Urho3D/Navigation/DynamicNavigationMesh.cpp
  5. 3 3
      Source/Urho3D/Navigation/DynamicNavigationMesh.h
  6. 7 13
      Source/Urho3D/Navigation/NavigationMesh.cpp
  7. 2 2
      Source/Urho3D/Navigation/NavigationMesh.h
  8. 0 3
      Source/Urho3D/Network/Network.cpp
  9. 1 1
      Source/Urho3D/Network/Network.h
  10. 13 29
      Source/Urho3D/Physics/CollisionShape.cpp
  11. 5 5
      Source/Urho3D/Physics/CollisionShape.h
  12. 11 13
      Source/Urho3D/Physics/Constraint.cpp
  13. 2 2
      Source/Urho3D/Physics/Constraint.h
  14. 13 26
      Source/Urho3D/Physics/PhysicsWorld.cpp
  15. 5 5
      Source/Urho3D/Physics/PhysicsWorld.h
  16. 6 15
      Source/Urho3D/Physics/RigidBody.cpp
  17. 5 5
      Source/Urho3D/Physics/RigidBody.h
  18. 5 16
      Source/Urho3D/Resource/XMLElement.cpp
  19. 4 4
      Source/Urho3D/Resource/XMLElement.h
  20. 1 4
      Source/Urho3D/Resource/XMLFile.cpp
  21. 2 2
      Source/Urho3D/Resource/XMLFile.h
  22. 0 2
      Source/Urho3D/Scene/Node.cpp
  23. 1 1
      Source/Urho3D/Scene/Node.h
  24. 1 8
      Source/Urho3D/Scene/Serializable.cpp
  25. 3 3
      Source/Urho3D/Scene/Serializable.h
  26. 2 3
      Source/Urho3D/UI/FontFaceBitmap.cpp
  27. 1 6
      Source/Urho3D/Urho2D/AnimatedSprite2D.cpp
  28. 1 1
      Source/Urho3D/Urho2D/AnimatedSprite2D.h
  29. 1 6
      Source/Urho3D/Urho2D/AnimationSet2D.cpp
  30. 2 2
      Source/Urho3D/Urho2D/AnimationSet2D.h
  31. 0 4
      Source/Urho3D/Urho2D/PhysicsWorld2D.cpp
  32. 2 2
      Source/Urho3D/Urho2D/PhysicsWorld2D.h

+ 3 - 38
Source/Urho3D/Container/Ptr.h

@@ -578,6 +578,9 @@ public:
     template <class U>
     template <class U>
     bool operator !=(const UniquePtr<U>& rhs) const { return ptr_ != rhs.ptr_; }
     bool operator !=(const UniquePtr<U>& rhs) const { return ptr_ != rhs.ptr_; }
 
 
+    /// Cast pointer to bool.
+    operator bool() const { return !!ptr_; }
+
     /// Swap with another UniquePtr.
     /// Swap with another UniquePtr.
     void Swap(UniquePtr& up) { Swap(ptr_, up.ptr_); }
     void Swap(UniquePtr& up) { Swap(ptr_, up.ptr_); }
 
 
@@ -642,44 +645,6 @@ template <class T, class ... Args> SharedPtr<T> MakeShared(Args && ... args)
     return SharedPtr<T>(new T(std::forward<Args>(args)...));
     return SharedPtr<T>(new T(std::forward<Args>(args)...));
 }
 }
 
 
-#else
-
-/// Construct UniquePtr without arguments.
-template <class T> UniquePtr<T> MakeUnique()
-{
-    return UniquePtr<T>(new T());
-}
-
-/// Construct UniquePtr with one argument.
-template <class T, class U> UniquePtr<T> MakeUnique(U& arg)
-{
-    return UniquePtr<T>(new T(arg));
-}
-
-/// Construct UniquePtr with one argument.
-template <class T, class U> UniquePtr<T> MakeUnique(const U& arg)
-{
-    return UniquePtr<T>(new T(arg));
-}
-
-/// Construct SharedPtr without arguments.
-template <class T> SharedPtr<T> MakeShared()
-{
-    return SharedPtr<T>(new T());
-}
-
-/// Construct SharedPtr with one argument.
-template <class T, class U> SharedPtr<T> MakeShared(U& arg)
-{
-    return SharedPtr<T>(new T(arg));
-}
-
-/// Construct SharedPtr with one argument.
-template <class T, class U> SharedPtr<T> MakeShared(const U& arg)
-{
-    return SharedPtr<T>(new T(arg));
-}
-
 #endif
 #endif
 
 
 }
 }

+ 0 - 4
Source/Urho3D/Input/Input.cpp

@@ -366,10 +366,6 @@ Input::Input(Context* context) :
 
 
 Input::~Input()
 Input::~Input()
 {
 {
-#ifdef __EMSCRIPTEN__
-    delete emscriptenInput_;
-    emscriptenInput_ = 0;
-#endif
 }
 }
 
 
 void Input::Update()
 void Input::Update()

+ 1 - 1
Source/Urho3D/Input/Input.h

@@ -432,7 +432,7 @@ private:
 
 
 #ifdef __EMSCRIPTEN__
 #ifdef __EMSCRIPTEN__
     /// Emscripten Input glue instance.
     /// Emscripten Input glue instance.
-    EmscriptenInput* emscriptenInput_;
+    UniquePtr<EmscriptenInput> emscriptenInput_;
     /// Flag used to detect mouse jump when exiting pointer-lock.
     /// Flag used to detect mouse jump when exiting pointer-lock.
     bool emscriptenExitingPointerLock_;
     bool emscriptenExitingPointerLock_;
     /// Flag used to detect mouse jump on initial mouse click when entering pointer-lock.
     /// Flag used to detect mouse jump on initial mouse click when entering pointer-lock.

+ 4 - 10
Source/Urho3D/Navigation/DynamicNavigationMesh.cpp

@@ -226,12 +226,6 @@ DynamicNavigationMesh::DynamicNavigationMesh(Context* context) :
 DynamicNavigationMesh::~DynamicNavigationMesh()
 DynamicNavigationMesh::~DynamicNavigationMesh()
 {
 {
     ReleaseNavigationMesh();
     ReleaseNavigationMesh();
-    delete allocator_;
-    allocator_ = 0;
-    delete compressor_;
-    compressor_ = 0;
-    delete meshProcessor_;
-    meshProcessor_ = 0;
 }
 }
 
 
 void DynamicNavigationMesh::RegisterObject(Context* context)
 void DynamicNavigationMesh::RegisterObject(Context* context)
@@ -336,7 +330,7 @@ bool DynamicNavigationMesh::Build()
             return false;
             return false;
         }
         }
 
 
-        if (dtStatusFailed(tileCache_->init(&tileCacheParams, allocator_, compressor_, meshProcessor_)))
+        if (dtStatusFailed(tileCache_->init(&tileCacheParams, allocator_.Get(), compressor_.Get(), meshProcessor_.Get())))
         {
         {
             URHO3D_LOGERROR("Could not initialize tile cache");
             URHO3D_LOGERROR("Could not initialize tile cache");
             ReleaseNavigationMesh();
             ReleaseNavigationMesh();
@@ -595,7 +589,7 @@ void DynamicNavigationMesh::SetNavigationDataAttr(const PODVector<unsigned char>
         ReleaseNavigationMesh();
         ReleaseNavigationMesh();
         return;
         return;
     }
     }
-    if (dtStatusFailed(tileCache_->init(&tcParams, allocator_, compressor_, meshProcessor_)))
+    if (dtStatusFailed(tileCache_->init(&tcParams, allocator_.Get(), compressor_.Get(), meshProcessor_.Get())))
     {
     {
         URHO3D_LOGERROR("Could not initialize tile cache");
         URHO3D_LOGERROR("Could not initialize tile cache");
         ReleaseNavigationMesh();
         ReleaseNavigationMesh();
@@ -688,7 +682,7 @@ int DynamicNavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryLis
             boundingBox_.max_.y_,
             boundingBox_.max_.y_,
             boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)));
             boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)));
 
 
-    DynamicNavBuildData build(allocator_);
+    DynamicNavBuildData build(allocator_.Get());
 
 
     rcConfig cfg;
     rcConfig cfg;
     memset(&cfg, 0, sizeof cfg);
     memset(&cfg, 0, sizeof cfg);
@@ -835,7 +829,7 @@ int DynamicNavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryLis
         header.hmax = (unsigned short)layer->hmax;
         header.hmax = (unsigned short)layer->hmax;
 
 
         if (dtStatusFailed(
         if (dtStatusFailed(
-            dtBuildTileCacheLayer(compressor_/*compressor*/, &header, layer->heights, layer->areas/*areas*/, layer->cons,
+            dtBuildTileCacheLayer(compressor_.Get()/*compressor*/, &header, layer->heights, layer->areas/*areas*/, layer->cons,
                 &(tiles[retCt].data), &tiles[retCt].dataSize)))
                 &(tiles[retCt].data), &tiles[retCt].dataSize)))
         {
         {
             URHO3D_LOGERROR("Failed to build tile cache layers");
             URHO3D_LOGERROR("Failed to build tile cache layers");

+ 3 - 3
Source/Urho3D/Navigation/DynamicNavigationMesh.h

@@ -113,11 +113,11 @@ private:
     /// Detour tile cache instance that works with the nav mesh.
     /// Detour tile cache instance that works with the nav mesh.
     dtTileCache* tileCache_;
     dtTileCache* tileCache_;
     /// Used by dtTileCache to allocate blocks of memory.
     /// Used by dtTileCache to allocate blocks of memory.
-    dtTileCacheAlloc* allocator_;
+    UniquePtr<dtTileCacheAlloc> allocator_;
     /// Used by dtTileCache to compress the original tiles to use when reconstructing for changes.
     /// Used by dtTileCache to compress the original tiles to use when reconstructing for changes.
-    dtTileCacheCompressor* compressor_;
+    UniquePtr<dtTileCacheCompressor> compressor_;
     /// Mesh processer used by Detour, in this case a 'pass-through' processor.
     /// Mesh processer used by Detour, in this case a 'pass-through' processor.
-    dtTileCacheMeshProcess* meshProcessor_;
+    UniquePtr<dtTileCacheMeshProcess> meshProcessor_;
     /// Maximum number of obstacle objects allowed.
     /// Maximum number of obstacle objects allowed.
     unsigned maxObstacles_;
     unsigned maxObstacles_;
     /// Maximum number of layers that are allowed to be constructed.
     /// Maximum number of layers that are allowed to be constructed.

+ 7 - 13
Source/Urho3D/Navigation/NavigationMesh.cpp

@@ -129,12 +129,6 @@ NavigationMesh::NavigationMesh(Context* context) :
 NavigationMesh::~NavigationMesh()
 NavigationMesh::~NavigationMesh()
 {
 {
     ReleaseNavigationMesh();
     ReleaseNavigationMesh();
-
-    delete queryFilter_;
-    queryFilter_ = 0;
-
-    delete pathData_;
-    pathData_ = 0;
 }
 }
 
 
 void NavigationMesh::RegisterObject(Context* context)
 void NavigationMesh::RegisterObject(Context* context)
@@ -488,7 +482,7 @@ Vector3 NavigationMesh::FindNearestPoint(const Vector3& point, const Vector3& ex
     dtPolyRef pointRef;
     dtPolyRef pointRef;
     if (!nearestRef)
     if (!nearestRef)
         nearestRef = &pointRef;
         nearestRef = &pointRef;
-    navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, filter ? filter : queryFilter_, nearestRef, &nearestPoint.x_);
+    navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, filter ? filter : queryFilter_.Get(), nearestRef, &nearestPoint.x_);
     return *nearestRef ? transform * nearestPoint : point;
     return *nearestRef ? transform * nearestPoint : point;
 }
 }
 
 
@@ -504,7 +498,7 @@ Vector3 NavigationMesh::MoveAlongSurface(const Vector3& start, const Vector3& en
     Vector3 localStart = inverse * start;
     Vector3 localStart = inverse * start;
     Vector3 localEnd = inverse * end;
     Vector3 localEnd = inverse * end;
 
 
-    const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
+    const dtQueryFilter* queryFilter = filter ? filter : queryFilter_.Get();
     dtPolyRef startRef;
     dtPolyRef startRef;
     navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter, &startRef, 0);
     navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter, &startRef, 0);
     if (!startRef)
     if (!startRef)
@@ -546,7 +540,7 @@ void NavigationMesh::FindPath(PODVector<NavigationPathPoint>& dest, const Vector
     Vector3 localStart = inverse * start;
     Vector3 localStart = inverse * start;
     Vector3 localEnd = inverse * end;
     Vector3 localEnd = inverse * end;
 
 
-    const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
+    const dtQueryFilter* queryFilter = filter ? filter : queryFilter_.Get();
     dtPolyRef startRef;
     dtPolyRef startRef;
     dtPolyRef endRef;
     dtPolyRef endRef;
     navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter, &startRef, 0);
     navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter, &startRef, 0);
@@ -614,7 +608,7 @@ Vector3 NavigationMesh::GetRandomPoint(const dtQueryFilter* filter, dtPolyRef* r
     dtPolyRef polyRef;
     dtPolyRef polyRef;
     Vector3 point(Vector3::ZERO);
     Vector3 point(Vector3::ZERO);
 
 
-    navMeshQuery_->findRandomPoint(filter ? filter : queryFilter_, Random, randomRef ? randomRef : &polyRef, &point.x_);
+    navMeshQuery_->findRandomPoint(filter ? filter : queryFilter_.Get(), Random, randomRef ? randomRef : &polyRef, &point.x_);
 
 
     return node_->GetWorldTransform() * point;
     return node_->GetWorldTransform() * point;
 }
 }
@@ -632,7 +626,7 @@ Vector3 NavigationMesh::GetRandomPointInCircle(const Vector3& center, float radi
     Matrix3x4 inverse = transform.Inverse();
     Matrix3x4 inverse = transform.Inverse();
     Vector3 localCenter = inverse * center;
     Vector3 localCenter = inverse * center;
 
 
-    const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
+    const dtQueryFilter* queryFilter = filter ? filter : queryFilter_.Get();
     dtPolyRef startRef;
     dtPolyRef startRef;
     navMeshQuery_->findNearestPoly(&localCenter.x_, &extents.x_, queryFilter, &startRef, 0);
     navMeshQuery_->findNearestPoly(&localCenter.x_, &extents.x_, queryFilter, &startRef, 0);
     if (!startRef)
     if (!startRef)
@@ -663,7 +657,7 @@ float NavigationMesh::GetDistanceToWall(const Vector3& point, float radius, cons
     Matrix3x4 inverse = transform.Inverse();
     Matrix3x4 inverse = transform.Inverse();
     Vector3 localPoint = inverse * point;
     Vector3 localPoint = inverse * point;
 
 
-    const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
+    const dtQueryFilter* queryFilter = filter ? filter : queryFilter_.Get();
     dtPolyRef startRef;
     dtPolyRef startRef;
     navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, queryFilter, &startRef, 0);
     navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, queryFilter, &startRef, 0);
     if (!startRef)
     if (!startRef)
@@ -696,7 +690,7 @@ Vector3 NavigationMesh::Raycast(const Vector3& start, const Vector3& end, const
     Vector3 localStart = inverse * start;
     Vector3 localStart = inverse * start;
     Vector3 localEnd = inverse * end;
     Vector3 localEnd = inverse * end;
 
 
-    const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
+    const dtQueryFilter* queryFilter = filter ? filter : queryFilter_.Get();
     dtPolyRef startRef;
     dtPolyRef startRef;
     navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter, &startRef, 0);
     navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter, &startRef, 0);
     if (!startRef)
     if (!startRef)

+ 2 - 2
Source/Urho3D/Navigation/NavigationMesh.h

@@ -278,9 +278,9 @@ protected:
     /// Detour navigation mesh query.
     /// Detour navigation mesh query.
     dtNavMeshQuery* navMeshQuery_;
     dtNavMeshQuery* navMeshQuery_;
     /// Detour navigation mesh query filter.
     /// Detour navigation mesh query filter.
-    dtQueryFilter* queryFilter_;
+    UniquePtr<dtQueryFilter> queryFilter_;
     /// Temporary data for finding a path.
     /// Temporary data for finding a path.
-    FindPathData* pathData_;
+    UniquePtr<FindPathData> pathData_;
     /// Tile size.
     /// Tile size.
     int tileSize_;
     int tileSize_;
     /// Cell size.
     /// Cell size.

+ 0 - 3
Source/Urho3D/Network/Network.cpp

@@ -114,9 +114,6 @@ Network::~Network()
     serverConnection_.Reset();
     serverConnection_.Reset();
 
 
     clientConnections_.Clear();
     clientConnections_.Clear();
-
-    delete network_;
-    network_ = 0;
 }
 }
 
 
 void Network::HandleMessage(kNet::MessageConnection* source, kNet::packet_id_t packetId, kNet::message_id_t msgId, const char* data,
 void Network::HandleMessage(kNet::MessageConnection* source, kNet::packet_id_t packetId, kNet::message_id_t msgId, const char* data,

+ 1 - 1
Source/Urho3D/Network/Network.h

@@ -147,7 +147,7 @@ private:
     void ConfigureNetworkSimulator();
     void ConfigureNetworkSimulator();
 
 
     /// kNet instance.
     /// kNet instance.
-    kNet::Network* network_;
+    UniquePtr<kNet::Network> network_;
     /// Client's server connection.
     /// Client's server connection.
     SharedPtr<Connection> serverConnection_;
     SharedPtr<Connection> serverConnection_;
     /// Server's client connections.
     /// Server's client connections.

+ 13 - 29
Source/Urho3D/Physics/CollisionShape.cpp

@@ -194,40 +194,26 @@ private:
     Vector<SharedArrayPtr<unsigned char> > dataArrays_;
     Vector<SharedArrayPtr<unsigned char> > dataArrays_;
 };
 };
 
 
-TriangleMeshData::TriangleMeshData(Model* model, unsigned lodLevel) :
-    meshInterface_(0),
-    shape_(0),
-    infoMap_(0)
+TriangleMeshData::TriangleMeshData(Model* model, unsigned lodLevel)
 {
 {
     meshInterface_ = new TriangleMeshInterface(model, lodLevel);
     meshInterface_ = new TriangleMeshInterface(model, lodLevel);
-    shape_ = new btBvhTriangleMeshShape(meshInterface_, meshInterface_->useQuantize_, true);
+    shape_ = new btBvhTriangleMeshShape(meshInterface_.Get(), meshInterface_->useQuantize_, true);
 
 
     infoMap_ = new btTriangleInfoMap();
     infoMap_ = new btTriangleInfoMap();
-    btGenerateInternalEdgeInfo(shape_, infoMap_);
+    btGenerateInternalEdgeInfo(shape_.Get(), infoMap_.Get());
 }
 }
 
 
-TriangleMeshData::TriangleMeshData(CustomGeometry* custom) :
-    meshInterface_(0),
-    shape_(0),
-    infoMap_(0)
+TriangleMeshData::TriangleMeshData(CustomGeometry* custom)
 {
 {
     meshInterface_ = new TriangleMeshInterface(custom);
     meshInterface_ = new TriangleMeshInterface(custom);
-    shape_ = new btBvhTriangleMeshShape(meshInterface_, meshInterface_->useQuantize_, true);
+    shape_ = new btBvhTriangleMeshShape(meshInterface_.Get(), meshInterface_->useQuantize_, true);
 
 
     infoMap_ = new btTriangleInfoMap();
     infoMap_ = new btTriangleInfoMap();
-    btGenerateInternalEdgeInfo(shape_, infoMap_);
+    btGenerateInternalEdgeInfo(shape_.Get(), infoMap_.Get());
 }
 }
 
 
 TriangleMeshData::~TriangleMeshData()
 TriangleMeshData::~TriangleMeshData()
 {
 {
-    delete shape_;
-    shape_ = 0;
-
-    delete meshInterface_;
-    meshInterface_ = 0;
-
-    delete infoMap_;
-    infoMap_ = 0;
 }
 }
 
 
 ConvexData::ConvexData(Model* model, unsigned lodLevel)
 ConvexData::ConvexData(Model* model, unsigned lodLevel)
@@ -410,7 +396,6 @@ bool HasDynamicBuffers(Model* model, unsigned lodLevel)
 
 
 CollisionShape::CollisionShape(Context* context) :
 CollisionShape::CollisionShape(Context* context) :
     Component(context),
     Component(context),
-    shape_(0),
     shapeType_(SHAPE_BOX),
     shapeType_(SHAPE_BOX),
     position_(Vector3::ZERO),
     position_(Vector3::ZERO),
     rotation_(Quaternion::IDENTITY),
     rotation_(Quaternion::IDENTITY),
@@ -501,7 +486,7 @@ void CollisionShape::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
         Quaternion worldRotation(worldTransform.Rotation() * rotation_);
         Quaternion worldRotation(worldTransform.Rotation() * rotation_);
 
 
         btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
         btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
-        world->debugDrawObject(btTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition)), shape_, bodyActive ?
+        world->debugDrawObject(btTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition)), shape_.Get(), bodyActive ?
             WHITE : GREEN);
             WHITE : GREEN);
 
 
         physicsWorld_->SetDebugRenderer(0);
         physicsWorld_->SetDebugRenderer(0);
@@ -863,7 +848,7 @@ void CollisionShape::NotifyRigidBody(bool updateMass)
     if (node_ && shape_ && compound)
     if (node_ && shape_ && compound)
     {
     {
         // Remove the shape first to ensure it is not added twice
         // Remove the shape first to ensure it is not added twice
-        compound->removeChildShape(shape_);
+        compound->removeChildShape(shape_.Get());
 
 
         if (IsEnabledEffective())
         if (IsEnabledEffective())
         {
         {
@@ -879,7 +864,7 @@ void CollisionShape::NotifyRigidBody(bool updateMass)
             btTransform offset;
             btTransform offset;
             offset.setOrigin(ToBtVector3(node_->GetWorldScale() * position));
             offset.setOrigin(ToBtVector3(node_->GetWorldScale() * position));
             offset.setRotation(ToBtQuaternion(rotation_));
             offset.setRotation(ToBtQuaternion(rotation_));
-            compound->addChildShape(offset, shape_);
+            compound->addChildShape(offset, shape_.Get());
         }
         }
 
 
         // Finally tell the rigid body to update its mass
         // Finally tell the rigid body to update its mass
@@ -906,12 +891,11 @@ void CollisionShape::ReleaseShape()
     btCompoundShape* compound = GetParentCompoundShape();
     btCompoundShape* compound = GetParentCompoundShape();
     if (shape_ && compound)
     if (shape_ && compound)
     {
     {
-        compound->removeChildShape(shape_);
+        compound->removeChildShape(shape_.Get());
         rigidBody_->UpdateMass();
         rigidBody_->UpdateMass();
     }
     }
 
 
-    delete shape_;
-    shape_ = 0;
+    shape_.Reset();
 
 
     geometry_.Reset();
     geometry_.Reset();
 
 
@@ -1072,7 +1056,7 @@ void CollisionShape::UpdateShape()
                 {
                 {
                     geometry_ = new TriangleMeshData(custom);
                     geometry_ = new TriangleMeshData(custom);
                     TriangleMeshData* triMesh = static_cast<TriangleMeshData*>(geometry_.Get());
                     TriangleMeshData* triMesh = static_cast<TriangleMeshData*>(geometry_.Get());
-                    shape_ = new btScaledBvhTriangleMeshShape(triMesh->shape_, ToBtVector3(newWorldScale * size_));
+                    shape_ = new btScaledBvhTriangleMeshShape(triMesh->shape_.Get(), ToBtVector3(newWorldScale * size_));
                 }
                 }
                 else
                 else
                     URHO3D_LOGWARNING("Could not find custom geometry component ID " + String(customGeometryID_) +
                     URHO3D_LOGWARNING("Could not find custom geometry component ID " + String(customGeometryID_) +
@@ -1095,7 +1079,7 @@ void CollisionShape::UpdateShape()
                 }
                 }
 
 
                 TriangleMeshData* triMesh = static_cast<TriangleMeshData*>(geometry_.Get());
                 TriangleMeshData* triMesh = static_cast<TriangleMeshData*>(geometry_.Get());
-                shape_ = new btScaledBvhTriangleMeshShape(triMesh->shape_, ToBtVector3(newWorldScale * size_));
+                shape_ = new btScaledBvhTriangleMeshShape(triMesh->shape_.Get(), ToBtVector3(newWorldScale * size_));
                 // Watch for live reloads of the collision model to reload the geometry if necessary
                 // Watch for live reloads of the collision model to reload the geometry if necessary
                 SubscribeToEvent(model_, E_RELOADFINISHED, URHO3D_HANDLER(CollisionShape, HandleModelReloadFinished));
                 SubscribeToEvent(model_, E_RELOADFINISHED, URHO3D_HANDLER(CollisionShape, HandleModelReloadFinished));
             }
             }

+ 5 - 5
Source/Urho3D/Physics/CollisionShape.h

@@ -75,11 +75,11 @@ struct TriangleMeshData : public CollisionGeometryData
     ~TriangleMeshData();
     ~TriangleMeshData();
 
 
     /// Bullet triangle mesh interface.
     /// Bullet triangle mesh interface.
-    TriangleMeshInterface* meshInterface_;
+    UniquePtr<TriangleMeshInterface> meshInterface_;
     /// Bullet triangle mesh collision shape.
     /// Bullet triangle mesh collision shape.
-    btBvhTriangleMeshShape* shape_;
+    UniquePtr<btBvhTriangleMeshShape> shape_;
     /// Bullet triangle info map.
     /// Bullet triangle info map.
-    btTriangleInfoMap* infoMap_;
+    UniquePtr<btTriangleInfoMap> infoMap_;
 };
 };
 
 
 /// Convex hull geometry data.
 /// Convex hull geometry data.
@@ -196,7 +196,7 @@ public:
     void SetLodLevel(unsigned lodLevel);
     void SetLodLevel(unsigned lodLevel);
 
 
     /// Return Bullet collision shape.
     /// Return Bullet collision shape.
-    btCollisionShape* GetCollisionShape() const { return shape_; }
+    btCollisionShape* GetCollisionShape() const { return shape_.Get(); }
 
 
     /// Return the shared geometry data.
     /// Return the shared geometry data.
     CollisionGeometryData* GetGeometryData() const { return geometry_; }
     CollisionGeometryData* GetGeometryData() const { return geometry_; }
@@ -272,7 +272,7 @@ private:
     /// Shared geometry data.
     /// Shared geometry data.
     SharedPtr<CollisionGeometryData> geometry_;
     SharedPtr<CollisionGeometryData> geometry_;
     /// Bullet collision shape.
     /// Bullet collision shape.
-    btCollisionShape* shape_;
+    UniquePtr<btCollisionShape> shape_;
     /// Collision shape type.
     /// Collision shape type.
     ShapeType shapeType_;
     ShapeType shapeType_;
     /// Offset position.
     /// Offset position.

+ 11 - 13
Source/Urho3D/Physics/Constraint.cpp

@@ -54,7 +54,6 @@ extern const char* PHYSICS_CATEGORY;
 
 
 Constraint::Constraint(Context* context) :
 Constraint::Constraint(Context* context) :
     Component(context),
     Component(context),
-    constraint_(0),
     constraintType_(CONSTRAINT_POINT),
     constraintType_(CONSTRAINT_POINT),
     position_(Vector3::ZERO),
     position_(Vector3::ZERO),
     rotation_(Quaternion::IDENTITY),
     rotation_(Quaternion::IDENTITY),
@@ -167,7 +166,7 @@ void Constraint::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
     {
     {
         physicsWorld_->SetDebugRenderer(debug);
         physicsWorld_->SetDebugRenderer(debug);
         physicsWorld_->SetDebugDepthTest(depthTest);
         physicsWorld_->SetDebugDepthTest(depthTest);
-        physicsWorld_->GetWorld()->debugDrawConstraint(constraint_);
+        physicsWorld_->GetWorld()->debugDrawConstraint(constraint_.Get());
         physicsWorld_->SetDebugRenderer(0);
         physicsWorld_->SetDebugRenderer(0);
     }
     }
 }
 }
@@ -380,10 +379,9 @@ void Constraint::ReleaseConstraint()
             otherBody_->RemoveConstraint(this);
             otherBody_->RemoveConstraint(this);
 
 
         if (physicsWorld_)
         if (physicsWorld_)
-            physicsWorld_->GetWorld()->removeConstraint(constraint_);
+            physicsWorld_->GetWorld()->removeConstraint(constraint_.Get());
 
 
-        delete constraint_;
-        constraint_ = 0;
+        constraint_.Reset();
     }
     }
 }
 }
 
 
@@ -402,7 +400,7 @@ void Constraint::ApplyFrames()
     {
     {
     case POINT2POINT_CONSTRAINT_TYPE:
     case POINT2POINT_CONSTRAINT_TYPE:
         {
         {
-            btPoint2PointConstraint* pointConstraint = static_cast<btPoint2PointConstraint*>(constraint_);
+            btPoint2PointConstraint* pointConstraint = static_cast<btPoint2PointConstraint*>(constraint_.Get());
             pointConstraint->setPivotA(ToBtVector3(ownBodyScaledPosition));
             pointConstraint->setPivotA(ToBtVector3(ownBodyScaledPosition));
             pointConstraint->setPivotB(ToBtVector3(otherBodyScaledPosition));
             pointConstraint->setPivotB(ToBtVector3(otherBodyScaledPosition));
         }
         }
@@ -410,7 +408,7 @@ void Constraint::ApplyFrames()
 
 
     case HINGE_CONSTRAINT_TYPE:
     case HINGE_CONSTRAINT_TYPE:
         {
         {
-            btHingeConstraint* hingeConstraint = static_cast<btHingeConstraint*>(constraint_);
+            btHingeConstraint* hingeConstraint = static_cast<btHingeConstraint*>(constraint_.Get());
             btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
             btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
             btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
             btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
             hingeConstraint->setFrames(ownFrame, otherFrame);
             hingeConstraint->setFrames(ownFrame, otherFrame);
@@ -419,7 +417,7 @@ void Constraint::ApplyFrames()
 
 
     case SLIDER_CONSTRAINT_TYPE:
     case SLIDER_CONSTRAINT_TYPE:
         {
         {
-            btSliderConstraint* sliderConstraint = static_cast<btSliderConstraint*>(constraint_);
+            btSliderConstraint* sliderConstraint = static_cast<btSliderConstraint*>(constraint_.Get());
             btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
             btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
             btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
             btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
             sliderConstraint->setFrames(ownFrame, otherFrame);
             sliderConstraint->setFrames(ownFrame, otherFrame);
@@ -428,7 +426,7 @@ void Constraint::ApplyFrames()
 
 
     case CONETWIST_CONSTRAINT_TYPE:
     case CONETWIST_CONSTRAINT_TYPE:
         {
         {
-            btConeTwistConstraint* coneTwistConstraint = static_cast<btConeTwistConstraint*>(constraint_);
+            btConeTwistConstraint* coneTwistConstraint = static_cast<btConeTwistConstraint*>(constraint_.Get());
             btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
             btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
             btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
             btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
             coneTwistConstraint->setFrames(ownFrame, otherFrame);
             coneTwistConstraint->setFrames(ownFrame, otherFrame);
@@ -555,7 +553,7 @@ void Constraint::CreateConstraint()
 
 
         ApplyLimits();
         ApplyLimits();
 
 
-        physicsWorld_->GetWorld()->addConstraint(constraint_, disableCollision_);
+        physicsWorld_->GetWorld()->addConstraint(constraint_.Get(), disableCollision_);
     }
     }
 
 
     recreateConstraint_ = false;
     recreateConstraint_ = false;
@@ -572,14 +570,14 @@ void Constraint::ApplyLimits()
     {
     {
     case HINGE_CONSTRAINT_TYPE:
     case HINGE_CONSTRAINT_TYPE:
         {
         {
-            btHingeConstraint* hingeConstraint = static_cast<btHingeConstraint*>(constraint_);
+            btHingeConstraint* hingeConstraint = static_cast<btHingeConstraint*>(constraint_.Get());
             hingeConstraint->setLimit(lowLimit_.x_ * M_DEGTORAD, highLimit_.x_ * M_DEGTORAD);
             hingeConstraint->setLimit(lowLimit_.x_ * M_DEGTORAD, highLimit_.x_ * M_DEGTORAD);
         }
         }
         break;
         break;
 
 
     case SLIDER_CONSTRAINT_TYPE:
     case SLIDER_CONSTRAINT_TYPE:
         {
         {
-            btSliderConstraint* sliderConstraint = static_cast<btSliderConstraint*>(constraint_);
+            btSliderConstraint* sliderConstraint = static_cast<btSliderConstraint*>(constraint_.Get());
             sliderConstraint->setUpperLinLimit(highLimit_.x_);
             sliderConstraint->setUpperLinLimit(highLimit_.x_);
             sliderConstraint->setUpperAngLimit(highLimit_.y_ * M_DEGTORAD);
             sliderConstraint->setUpperAngLimit(highLimit_.y_ * M_DEGTORAD);
             sliderConstraint->setLowerLinLimit(lowLimit_.x_);
             sliderConstraint->setLowerLinLimit(lowLimit_.x_);
@@ -589,7 +587,7 @@ void Constraint::ApplyLimits()
 
 
     case CONETWIST_CONSTRAINT_TYPE:
     case CONETWIST_CONSTRAINT_TYPE:
         {
         {
-            btConeTwistConstraint* coneTwistConstraint = static_cast<btConeTwistConstraint*>(constraint_);
+            btConeTwistConstraint* coneTwistConstraint = static_cast<btConeTwistConstraint*>(constraint_.Get());
             coneTwistConstraint->setLimit(highLimit_.y_ * M_DEGTORAD, highLimit_.y_ * M_DEGTORAD, highLimit_.x_ * M_DEGTORAD);
             coneTwistConstraint->setLimit(highLimit_.y_ * M_DEGTORAD, highLimit_.y_ * M_DEGTORAD, highLimit_.x_ * M_DEGTORAD);
         }
         }
         break;
         break;

+ 2 - 2
Source/Urho3D/Physics/Constraint.h

@@ -101,7 +101,7 @@ public:
     PhysicsWorld* GetPhysicsWorld() const { return physicsWorld_; }
     PhysicsWorld* GetPhysicsWorld() const { return physicsWorld_; }
 
 
     /// Return Bullet constraint.
     /// Return Bullet constraint.
-    btTypedConstraint* GetConstraint() const { return constraint_; }
+    btTypedConstraint* GetConstraint() const { return constraint_.Get(); }
 
 
     /// Return constraint type.
     /// Return constraint type.
     ConstraintType GetConstraintType() const { return constraintType_; }
     ConstraintType GetConstraintType() const { return constraintType_; }
@@ -168,7 +168,7 @@ private:
     /// Other rigid body.
     /// Other rigid body.
     WeakPtr<RigidBody> otherBody_;
     WeakPtr<RigidBody> otherBody_;
     /// Bullet constraint.
     /// Bullet constraint.
-    btTypedConstraint* constraint_;
+    UniquePtr<btTypedConstraint> constraint_;
     /// Constraint type.
     /// Constraint type.
     ConstraintType constraintType_;
     ConstraintType constraintType_;
     /// Constraint position.
     /// Constraint position.

+ 13 - 26
Source/Urho3D/Physics/PhysicsWorld.cpp

@@ -120,10 +120,6 @@ struct PhysicsQueryCallback : public btCollisionWorld::ContactResultCallback
 PhysicsWorld::PhysicsWorld(Context* context) :
 PhysicsWorld::PhysicsWorld(Context* context) :
     Component(context),
     Component(context),
     collisionConfiguration_(0),
     collisionConfiguration_(0),
-    collisionDispatcher_(0),
-    broadphase_(0),
-    solver_(0),
-    world_(0),
     fps_(DEFAULT_FPS),
     fps_(DEFAULT_FPS),
     maxSubSteps_(0),
     maxSubSteps_(0),
     timeAcc_(0.0f),
     timeAcc_(0.0f),
@@ -146,7 +142,7 @@ PhysicsWorld::PhysicsWorld(Context* context) :
     collisionDispatcher_ = new btCollisionDispatcher(collisionConfiguration_);
     collisionDispatcher_ = new btCollisionDispatcher(collisionConfiguration_);
     broadphase_ = new btDbvtBroadphase();
     broadphase_ = new btDbvtBroadphase();
     solver_ = new btSequentialImpulseConstraintSolver();
     solver_ = new btSequentialImpulseConstraintSolver();
-    world_ = new btDiscreteDynamicsWorld(collisionDispatcher_, broadphase_, solver_, collisionConfiguration_);
+    world_ = new btDiscreteDynamicsWorld(collisionDispatcher_.Get(), broadphase_.Get(), solver_.Get(), collisionConfiguration_);
 
 
     world_->setGravity(ToBtVector3(DEFAULT_GRAVITY));
     world_->setGravity(ToBtVector3(DEFAULT_GRAVITY));
     world_->getDispatchInfo().m_useContinuous = true;
     world_->getDispatchInfo().m_useContinuous = true;
@@ -172,17 +168,10 @@ PhysicsWorld::~PhysicsWorld()
             (*i)->ReleaseShape();
             (*i)->ReleaseShape();
     }
     }
 
 
-    delete world_;
-    world_ = 0;
-
-    delete solver_;
-    solver_ = 0;
-
-    delete broadphase_;
-    broadphase_ = 0;
-
-    delete collisionDispatcher_;
-    collisionDispatcher_ = 0;
+    world_.Reset();
+    solver_.Reset();
+    broadphase_.Reset();
+    collisionDispatcher_.Reset();
 
 
     // Delete configuration only if it was the default created by PhysicsWorld
     // Delete configuration only if it was the default created by PhysicsWorld
     if (!PhysicsWorld::config.collisionConfig_)
     if (!PhysicsWorld::config.collisionConfig_)
@@ -623,17 +612,16 @@ void PhysicsWorld::GetRigidBodies(PODVector<RigidBody*>& result, const Sphere& s
     result.Clear();
     result.Clear();
 
 
     btSphereShape sphereShape(sphere.radius_);
     btSphereShape sphereShape(sphere.radius_);
-    btRigidBody* tempRigidBody = new btRigidBody(1.0f, 0, &sphereShape);
+    UniquePtr<btRigidBody> tempRigidBody(new btRigidBody(1.0f, 0, &sphereShape));
     tempRigidBody->setWorldTransform(btTransform(btQuaternion::getIdentity(), ToBtVector3(sphere.center_)));
     tempRigidBody->setWorldTransform(btTransform(btQuaternion::getIdentity(), ToBtVector3(sphere.center_)));
     // Need to activate the temporary rigid body to get reliable results from static, sleeping objects
     // Need to activate the temporary rigid body to get reliable results from static, sleeping objects
     tempRigidBody->activate();
     tempRigidBody->activate();
-    world_->addRigidBody(tempRigidBody);
+    world_->addRigidBody(tempRigidBody.Get());
 
 
     PhysicsQueryCallback callback(result, collisionMask);
     PhysicsQueryCallback callback(result, collisionMask);
-    world_->contactTest(tempRigidBody, callback);
+    world_->contactTest(tempRigidBody.Get(), callback);
 
 
-    world_->removeRigidBody(tempRigidBody);
-    delete tempRigidBody;
+    world_->removeRigidBody(tempRigidBody.Get());
 }
 }
 
 
 void PhysicsWorld::GetRigidBodies(PODVector<RigidBody*>& result, const BoundingBox& box, unsigned collisionMask)
 void PhysicsWorld::GetRigidBodies(PODVector<RigidBody*>& result, const BoundingBox& box, unsigned collisionMask)
@@ -643,16 +631,15 @@ void PhysicsWorld::GetRigidBodies(PODVector<RigidBody*>& result, const BoundingB
     result.Clear();
     result.Clear();
 
 
     btBoxShape boxShape(ToBtVector3(box.HalfSize()));
     btBoxShape boxShape(ToBtVector3(box.HalfSize()));
-    btRigidBody* tempRigidBody = new btRigidBody(1.0f, 0, &boxShape);
+    UniquePtr<btRigidBody> tempRigidBody(new btRigidBody(1.0f, 0, &boxShape));
     tempRigidBody->setWorldTransform(btTransform(btQuaternion::getIdentity(), ToBtVector3(box.Center())));
     tempRigidBody->setWorldTransform(btTransform(btQuaternion::getIdentity(), ToBtVector3(box.Center())));
     tempRigidBody->activate();
     tempRigidBody->activate();
-    world_->addRigidBody(tempRigidBody);
+    world_->addRigidBody(tempRigidBody.Get());
 
 
     PhysicsQueryCallback callback(result, collisionMask);
     PhysicsQueryCallback callback(result, collisionMask);
-    world_->contactTest(tempRigidBody, callback);
+    world_->contactTest(tempRigidBody.Get(), callback);
 
 
-    world_->removeRigidBody(tempRigidBody);
-    delete tempRigidBody;
+    world_->removeRigidBody(tempRigidBody.Get());
 }
 }
 
 
 void PhysicsWorld::GetRigidBodies(PODVector<RigidBody*>& result, const RigidBody* body)
 void PhysicsWorld::GetRigidBodies(PODVector<RigidBody*>& result, const RigidBody* body)

+ 5 - 5
Source/Urho3D/Physics/PhysicsWorld.h

@@ -261,7 +261,7 @@ public:
     void SetDebugDepthTest(bool enable);
     void SetDebugDepthTest(bool enable);
 
 
     /// Return the Bullet physics world.
     /// Return the Bullet physics world.
-    btDiscreteDynamicsWorld* GetWorld() { return world_; }
+    btDiscreteDynamicsWorld* GetWorld() { return world_.Get(); }
 
 
     /// Clean up the geometry cache.
     /// Clean up the geometry cache.
     void CleanupGeometryCache();
     void CleanupGeometryCache();
@@ -301,13 +301,13 @@ private:
     /// Bullet collision configuration.
     /// Bullet collision configuration.
     btCollisionConfiguration* collisionConfiguration_;
     btCollisionConfiguration* collisionConfiguration_;
     /// Bullet collision dispatcher.
     /// Bullet collision dispatcher.
-    btDispatcher* collisionDispatcher_;
+    UniquePtr<btDispatcher> collisionDispatcher_;
     /// Bullet collision broadphase.
     /// Bullet collision broadphase.
-    btBroadphaseInterface* broadphase_;
+    UniquePtr<btBroadphaseInterface> broadphase_;
     /// Bullet constraint solver.
     /// Bullet constraint solver.
-    btConstraintSolver* solver_;
+    UniquePtr<btConstraintSolver> solver_;
     /// Bullet physics world.
     /// Bullet physics world.
-    btDiscreteDynamicsWorld* world_;
+    UniquePtr<btDiscreteDynamicsWorld> world_;
     /// Extra weak pointer to scene to allow for cleanup in case the world is destroyed before other components.
     /// Extra weak pointer to scene to allow for cleanup in case the world is destroyed before other components.
     WeakPtr<Scene> scene_;
     WeakPtr<Scene> scene_;
     /// Rigid bodies in the world.
     /// Rigid bodies in the world.

+ 6 - 15
Source/Urho3D/Physics/RigidBody.cpp

@@ -63,9 +63,6 @@ extern const char* PHYSICS_CATEGORY;
 
 
 RigidBody::RigidBody(Context* context) :
 RigidBody::RigidBody(Context* context) :
     Component(context),
     Component(context),
-    body_(0),
-    compoundShape_(0),
-    shiftedCompoundShape_(0),
     gravityOverride_(Vector3::ZERO),
     gravityOverride_(Vector3::ZERO),
     centerOfMass_(Vector3::ZERO),
     centerOfMass_(Vector3::ZERO),
     mass_(DEFAULT_MASS),
     mass_(DEFAULT_MASS),
@@ -92,11 +89,6 @@ RigidBody::~RigidBody()
 
 
     if (physicsWorld_)
     if (physicsWorld_)
         physicsWorld_->RemoveRigidBody(this);
         physicsWorld_->RemoveRigidBody(this);
-
-    delete compoundShape_;
-    compoundShape_ = 0;
-    delete shiftedCompoundShape_;
-    shiftedCompoundShape_ = 0;
 }
 }
 
 
 void RigidBody::RegisterObject(Context* context)
 void RigidBody::RegisterObject(Context* context)
@@ -218,7 +210,7 @@ void RigidBody::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
         physicsWorld_->SetDebugDepthTest(depthTest);
         physicsWorld_->SetDebugDepthTest(depthTest);
 
 
         btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
         btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
-        world->debugDrawObject(body_->getWorldTransform(), shiftedCompoundShape_, IsActive() ? btVector3(1.0f, 1.0f, 1.0f) :
+        world->debugDrawObject(body_->getWorldTransform(), shiftedCompoundShape_.Get(), IsActive() ? btVector3(1.0f, 1.0f, 1.0f) :
             btVector3(0.0f, 1.0f, 0.0f));
             btVector3(0.0f, 1.0f, 0.0f));
 
 
         physicsWorld_->SetDebugRenderer(0);
         physicsWorld_->SetDebugRenderer(0);
@@ -794,7 +786,7 @@ void RigidBody::UpdateMass()
             !ToQuaternion(childTransform.getRotation()).Equals(Quaternion::IDENTITY))
             !ToQuaternion(childTransform.getRotation()).Equals(Quaternion::IDENTITY))
             useCompound = true;
             useCompound = true;
     }
     }
-    body_->setCollisionShape(useCompound ? shiftedCompoundShape_ : shiftedCompoundShape_->getChildShape(0));
+    body_->setCollisionShape(useCompound ? shiftedCompoundShape_.Get() : shiftedCompoundShape_->getChildShape(0));
 
 
     // If we have one shape and this is a triangle mesh, we use a custom material callback in order to adjust internal edges
     // If we have one shape and this is a triangle mesh, we use a custom material callback in order to adjust internal edges
     if (!useCompound && body_->getCollisionShape()->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE &&
     if (!useCompound && body_->getCollisionShape()->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE &&
@@ -888,8 +880,7 @@ void RigidBody::ReleaseBody()
 
 
         RemoveBodyFromWorld();
         RemoveBodyFromWorld();
 
 
-        delete body_;
-        body_ = 0;
+        body_.Reset();
     }
     }
 }
 }
 
 
@@ -970,7 +961,7 @@ void RigidBody::AddBodyToWorld()
     {
     {
         // Correct inertia will be calculated below
         // Correct inertia will be calculated below
         btVector3 localInertia(0.0f, 0.0f, 0.0f);
         btVector3 localInertia(0.0f, 0.0f, 0.0f);
-        body_ = new btRigidBody(mass_, this, shiftedCompoundShape_, localInertia);
+        body_ = new btRigidBody(mass_, this, shiftedCompoundShape_.Get(), localInertia);
         body_->setUserPointer(this);
         body_->setUserPointer(this);
 
 
         // Check for existence of the SmoothedTransform component, which should be created by now in network client mode.
         // Check for existence of the SmoothedTransform component, which should be created by now in network client mode.
@@ -1016,7 +1007,7 @@ void RigidBody::AddBodyToWorld()
         return;
         return;
 
 
     btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
     btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
-    world->addRigidBody(body_, (short)collisionLayer_, (short)collisionMask_);
+    world->addRigidBody(body_.Get(), (short)collisionLayer_, (short)collisionMask_);
     inWorld_ = true;
     inWorld_ = true;
     readdBody_ = false;
     readdBody_ = false;
     hasSimulated_ = false;
     hasSimulated_ = false;
@@ -1035,7 +1026,7 @@ void RigidBody::RemoveBodyFromWorld()
     if (physicsWorld_ && body_ && inWorld_)
     if (physicsWorld_ && body_ && inWorld_)
     {
     {
         btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
         btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
-        world->removeRigidBody(body_);
+        world->removeRigidBody(body_.Get());
         inWorld_ = false;
         inWorld_ = false;
     }
     }
 }
 }

+ 5 - 5
Source/Urho3D/Physics/RigidBody.h

@@ -153,10 +153,10 @@ public:
     PhysicsWorld* GetPhysicsWorld() const { return physicsWorld_; }
     PhysicsWorld* GetPhysicsWorld() const { return physicsWorld_; }
 
 
     /// Return Bullet rigid body.
     /// Return Bullet rigid body.
-    btRigidBody* GetBody() const { return body_; }
+    btRigidBody* GetBody() const { return body_.Get(); }
 
 
     /// Return Bullet compound collision shape.
     /// Return Bullet compound collision shape.
-    btCompoundShape* GetCompoundShape() const { return compoundShape_; }
+    btCompoundShape* GetCompoundShape() const { return compoundShape_.Get(); }
 
 
     /// Return mass.
     /// Return mass.
     float GetMass() const { return mass_; }
     float GetMass() const { return mass_; }
@@ -264,11 +264,11 @@ private:
     void HandleTargetRotation(StringHash eventType, VariantMap& eventData);
     void HandleTargetRotation(StringHash eventType, VariantMap& eventData);
 
 
     /// Bullet rigid body.
     /// Bullet rigid body.
-    btRigidBody* body_;
+    UniquePtr<btRigidBody> body_;
     /// Bullet compound collision shape.
     /// Bullet compound collision shape.
-    btCompoundShape* compoundShape_;
+    UniquePtr<btCompoundShape> compoundShape_;
     /// Compound collision shape with center of mass offset applied.
     /// Compound collision shape with center of mass offset applied.
-    btCompoundShape* shiftedCompoundShape_;
+    UniquePtr<btCompoundShape> shiftedCompoundShape_;
     /// Physics world.
     /// Physics world.
     WeakPtr<PhysicsWorld> physicsWorld_;
     WeakPtr<PhysicsWorld> physicsWorld_;
     /// Smoothed transform, if has one.
     /// Smoothed transform, if has one.

+ 5 - 16
Source/Urho3D/Resource/XMLElement.cpp

@@ -990,32 +990,23 @@ bool XPathResultSet::Empty() const
     return resultSet_ ? resultSet_->empty() : true;
     return resultSet_ ? resultSet_->empty() : true;
 }
 }
 
 
-XPathQuery::XPathQuery() :
-    query_(0),
-    variables_(0)
+XPathQuery::XPathQuery()
 {
 {
 }
 }
 
 
-XPathQuery::XPathQuery(const String& queryString, const String& variableString) :
-    query_(0),
-    variables_(0)
+XPathQuery::XPathQuery(const String& queryString, const String& variableString)
 {
 {
     SetQuery(queryString, variableString);
     SetQuery(queryString, variableString);
 }
 }
 
 
 XPathQuery::~XPathQuery()
 XPathQuery::~XPathQuery()
 {
 {
-    delete variables_;
-    variables_ = 0;
-    delete query_;
-    query_ = 0;
 }
 }
 
 
 void XPathQuery::Bind()
 void XPathQuery::Bind()
 {
 {
     // Delete previous query object and create a new one binding it with variable set
     // Delete previous query object and create a new one binding it with variable set
-    delete query_;
-    query_ = new pugi::xpath_query(queryString_.CString(), variables_);
+    query_ = new pugi::xpath_query(queryString_.CString(), variables_.Get());
 }
 }
 
 
 bool XPathQuery::SetVariable(const String& name, bool value)
 bool XPathQuery::SetVariable(const String& name, bool value)
@@ -1100,10 +1091,8 @@ void XPathQuery::Clear()
 {
 {
     queryString_.Clear();
     queryString_.Clear();
 
 
-    delete variables_;
-    variables_ = 0;
-    delete query_;
-    query_ = 0;
+    variables_.Reset();
+    query_.Reset();
 }
 }
 
 
 bool XPathQuery::EvaluateToBool(XMLElement element) const
 bool XPathQuery::EvaluateToBool(XMLElement element) const

+ 4 - 4
Source/Urho3D/Resource/XMLElement.h

@@ -370,18 +370,18 @@ public:
     String GetQuery() const { return queryString_; }
     String GetQuery() const { return queryString_; }
 
 
     /// Return pugixml xpath_query.
     /// Return pugixml xpath_query.
-    pugi::xpath_query* GetXPathQuery() const { return query_; }
+    pugi::xpath_query* GetXPathQuery() const { return query_.Get(); }
 
 
     /// Return pugixml xpath_variable_set.
     /// Return pugixml xpath_variable_set.
-    pugi::xpath_variable_set* GetXPathVariableSet() const { return variables_; }
+    pugi::xpath_variable_set* GetXPathVariableSet() const { return variables_.Get(); }
 
 
 private:
 private:
     /// XPath query string.
     /// XPath query string.
     String queryString_;
     String queryString_;
     /// Pugixml xpath_query.
     /// Pugixml xpath_query.
-    pugi::xpath_query* query_;
+    UniquePtr<pugi::xpath_query> query_;
     /// Pugixml xpath_variable_set.
     /// Pugixml xpath_variable_set.
-    pugi::xpath_variable_set* variables_;
+    UniquePtr<pugi::xpath_variable_set> variables_;
 };
 };
 
 
 }
 }

+ 1 - 4
Source/Urho3D/Resource/XMLFile.cpp

@@ -71,8 +71,6 @@ XMLFile::XMLFile(Context* context) :
 
 
 XMLFile::~XMLFile()
 XMLFile::~XMLFile()
 {
 {
-    delete document_;
-    document_ = 0;
 }
 }
 
 
 void XMLFile::RegisterObject(Context* context)
 void XMLFile::RegisterObject(Context* context)
@@ -116,11 +114,10 @@ bool XMLFile::BeginLoad(Deserializer& source)
         }
         }
 
 
         // Patch this XMLFile and leave the original inherited XMLFile as it is
         // Patch this XMLFile and leave the original inherited XMLFile as it is
-        pugi::xml_document* patchDocument = document_;
+        UniquePtr<pugi::xml_document> patchDocument(document_.Detach());
         document_ = new pugi::xml_document();
         document_ = new pugi::xml_document();
         document_->reset(*inheritedXMLFile->document_);
         document_->reset(*inheritedXMLFile->document_);
         Patch(rootElem);
         Patch(rootElem);
-        delete patchDocument;
 
 
         // Store resource dependencies so we know when to reload/repatch when the inherited resource changes
         // Store resource dependencies so we know when to reload/repatch when the inherited resource changes
         cache->StoreResourceDependency(this, inherit);
         cache->StoreResourceDependency(this, inherit);

+ 2 - 2
Source/Urho3D/Resource/XMLFile.h

@@ -66,7 +66,7 @@ public:
     XMLElement GetRoot(const String& name = String::EMPTY);
     XMLElement GetRoot(const String& name = String::EMPTY);
 
 
     /// Return the pugixml document.
     /// Return the pugixml document.
-    pugi::xml_document* GetDocument() const { return document_; }
+    pugi::xml_document* GetDocument() const { return document_.Get(); }
 
 
     /// Serialize the XML content to a string.
     /// Serialize the XML content to a string.
     String ToString(const String& indentation = "\t") const;
     String ToString(const String& indentation = "\t") const;
@@ -92,7 +92,7 @@ private:
     bool CombineText(const pugi::xml_node& patch, const pugi::xml_node& original, bool prepend) const;
     bool CombineText(const pugi::xml_node& patch, const pugi::xml_node& original, bool prepend) const;
 
 
     /// Pugixml document.
     /// Pugixml document.
-    pugi::xml_document* document_;
+    UniquePtr<pugi::xml_document> document_;
 };
 };
 
 
 }
 }

+ 0 - 2
Source/Urho3D/Scene/Node.cpp

@@ -72,8 +72,6 @@ Node::~Node()
     // Remove from the scene
     // Remove from the scene
     if (scene_)
     if (scene_)
         scene_->NodeRemoved(this);
         scene_->NodeRemoved(this);
-
-    delete impl_;
 }
 }
 
 
 void Node::RegisterObject(Context* context)
 void Node::RegisterObject(Context* context)

+ 1 - 1
Source/Urho3D/Scene/Node.h

@@ -678,7 +678,7 @@ private:
     /// Node listeners.
     /// Node listeners.
     Vector<WeakPtr<Component> > listeners_;
     Vector<WeakPtr<Component> > listeners_;
     /// Pointer to implementation.
     /// Pointer to implementation.
-    NodeImpl* impl_;
+    UniquePtr<NodeImpl> impl_;
 
 
 protected:
 protected:
     /// User variables.
     /// User variables.

+ 1 - 8
Source/Urho3D/Scene/Serializable.cpp

@@ -57,18 +57,12 @@ static unsigned RemapAttributeIndex(const Vector<AttributeInfo>* attributes, con
 
 
 Serializable::Serializable(Context* context) :
 Serializable::Serializable(Context* context) :
     Object(context),
     Object(context),
-    networkState_(0),
-    instanceDefaultValues_(0),
     temporary_(false)
     temporary_(false)
 {
 {
 }
 }
 
 
 Serializable::~Serializable()
 Serializable::~Serializable()
 {
 {
-    delete networkState_;
-    networkState_ = 0;
-    delete instanceDefaultValues_;
-    instanceDefaultValues_ = 0;
 }
 }
 
 
 void Serializable::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
 void Serializable::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
@@ -669,8 +663,7 @@ void Serializable::ResetToDefault()
 
 
 void Serializable::RemoveInstanceDefault()
 void Serializable::RemoveInstanceDefault()
 {
 {
-    delete instanceDefaultValues_;
-    instanceDefaultValues_ = 0;
+    instanceDefaultValues_.Reset();
 }
 }
 
 
 void Serializable::SetTemporary(bool enable)
 void Serializable::SetTemporary(bool enable)

+ 3 - 3
Source/Urho3D/Scene/Serializable.h

@@ -126,11 +126,11 @@ public:
     bool GetInterceptNetworkUpdate(const String& attributeName) const;
     bool GetInterceptNetworkUpdate(const String& attributeName) const;
 
 
     /// Return the network attribute state, if allocated.
     /// Return the network attribute state, if allocated.
-    NetworkState* GetNetworkState() const { return networkState_; }
+    NetworkState* GetNetworkState() const { return networkState_.Get(); }
 
 
 protected:
 protected:
     /// Network attribute state.
     /// Network attribute state.
-    NetworkState* networkState_;
+    UniquePtr<NetworkState> networkState_;
 
 
 private:
 private:
     /// Set instance-level default value. Allocate the internal data structure as necessary.
     /// Set instance-level default value. Allocate the internal data structure as necessary.
@@ -139,7 +139,7 @@ private:
     Variant GetInstanceDefault(const String& name) const;
     Variant GetInstanceDefault(const String& name) const;
 
 
     /// Attribute default value at each instance level.
     /// Attribute default value at each instance level.
-    VariantMap* instanceDefaultValues_;
+    UniquePtr<VariantMap> instanceDefaultValues_;
     /// Temporary flag.
     /// Temporary flag.
     bool temporary_;
     bool temporary_;
 };
 };

+ 2 - 3
Source/Urho3D/UI/FontFaceBitmap.cpp

@@ -355,15 +355,14 @@ unsigned FontFaceBitmap::ConvertFormatToNumComponents(unsigned format)
 
 
 SharedPtr<Image> FontFaceBitmap::SaveFaceTexture(Texture2D* texture)
 SharedPtr<Image> FontFaceBitmap::SaveFaceTexture(Texture2D* texture)
 {
 {
-    Image* image = new Image(font_->GetContext());
+    SharedPtr<Image> image(new Image(font_->GetContext()));
     image->SetSize(texture->GetWidth(), texture->GetHeight(), ConvertFormatToNumComponents(texture->GetFormat()));
     image->SetSize(texture->GetWidth(), texture->GetHeight(), ConvertFormatToNumComponents(texture->GetFormat()));
     if (!texture->GetData(0, image->GetData()))
     if (!texture->GetData(0, image->GetData()))
     {
     {
-        delete image;
         URHO3D_LOGERROR("Could not save texture to image resource");
         URHO3D_LOGERROR("Could not save texture to image resource");
         return SharedPtr<Image>();
         return SharedPtr<Image>();
     }
     }
-    return SharedPtr<Image>(image);
+    return image;
 }
 }
 
 
 bool FontFaceBitmap::SaveFaceTexture(Texture2D* texture, const String& fileName)
 bool FontFaceBitmap::SaveFaceTexture(Texture2D* texture, const String& fileName)

+ 1 - 6
Source/Urho3D/Urho2D/AnimatedSprite2D.cpp

@@ -59,7 +59,6 @@ AnimatedSprite2D::AnimatedSprite2D(Context* context) :
     animationStateData_(0),
     animationStateData_(0),
     animationState_(0),
     animationState_(0),
 #endif
 #endif
-    spriterInstance_(0),
     speed_(1.0f),
     speed_(1.0f),
     loopMode_(LM_DEFAULT)
     loopMode_(LM_DEFAULT)
 {
 {
@@ -527,11 +526,7 @@ void AnimatedSprite2D::Dispose()
         skeleton_ = 0;
         skeleton_ = 0;
     }
     }
 #endif
 #endif
-    if (spriterInstance_)
-    {
-        delete spriterInstance_;
-        spriterInstance_ = 0;
-    }
+    spriterInstance_.Reset();
 }
 }
 
 
 }
 }

+ 1 - 1
Source/Urho3D/Urho2D/AnimatedSprite2D.h

@@ -143,7 +143,7 @@ protected:
 #endif
 #endif
     
     
     /// Spriter instance.
     /// Spriter instance.
-    Spriter::SpriterInstance* spriterInstance_;
+    UniquePtr<Spriter::SpriterInstance> spriterInstance_;
 };
 };
 
 
 }
 }

+ 1 - 6
Source/Urho3D/Urho2D/AnimationSet2D.cpp

@@ -110,7 +110,6 @@ AnimationSet2D::AnimationSet2D(Context* context) :
     skeletonData_(0),
     skeletonData_(0),
     atlas_(0),
     atlas_(0),
 #endif
 #endif
-    spriterData_(0),
     hasSpriteSheet_(false)
     hasSpriteSheet_(false)
 {
 {
 }
 }
@@ -525,11 +524,7 @@ void AnimationSet2D::Dispose()
     }
     }
 #endif
 #endif
 
 
-    if (spriterData_)
-    {
-        delete spriterData_;
-        spriterData_ = 0;
-    }
+    spriterData_.Reset();
 
 
     sprite_.Reset();
     sprite_.Reset();
     spriteSheet_.Reset();
     spriteSheet_.Reset();

+ 2 - 2
Source/Urho3D/Urho2D/AnimationSet2D.h

@@ -76,7 +76,7 @@ public:
 #endif
 #endif
 
 
     /// Return spriter data.
     /// Return spriter data.
-    Spriter::SpriterData* GetSpriterData() const { return spriterData_; }
+    Spriter::SpriterData* GetSpriterData() const { return spriterData_.Get(); }
     /// Return spriter file sprite.
     /// Return spriter file sprite.
     Sprite2D* GetSpriterFileSprite(int folderId, int fileId) const;
     Sprite2D* GetSpriterFileSprite(int folderId, int fileId) const;
 
 
@@ -109,7 +109,7 @@ private:
 #endif
 #endif
     
     
     /// Spriter data.
     /// Spriter data.
-    Spriter::SpriterData* spriterData_;
+    UniquePtr<Spriter::SpriterData> spriterData_;
     /// Has sprite sheet.
     /// Has sprite sheet.
     bool hasSpriteSheet_;
     bool hasSpriteSheet_;
     /// Sprite sheet file path.
     /// Sprite sheet file path.

+ 0 - 4
Source/Urho3D/Urho2D/PhysicsWorld2D.cpp

@@ -47,7 +47,6 @@ static const int DEFAULT_POSITION_ITERATIONS = 3;
 
 
 PhysicsWorld2D::PhysicsWorld2D(Context* context) :
 PhysicsWorld2D::PhysicsWorld2D(Context* context) :
     Component(context),
     Component(context),
-    world_(0),
     gravity_(DEFAULT_GRAVITY),
     gravity_(DEFAULT_GRAVITY),
     velocityIterations_(DEFAULT_VELOCITY_ITERATIONS),
     velocityIterations_(DEFAULT_VELOCITY_ITERATIONS),
     positionIterations_(DEFAULT_POSITION_ITERATIONS),
     positionIterations_(DEFAULT_POSITION_ITERATIONS),
@@ -72,9 +71,6 @@ PhysicsWorld2D::~PhysicsWorld2D()
     for (unsigned i = 0; i < rigidBodies_.Size(); ++i)
     for (unsigned i = 0; i < rigidBodies_.Size(); ++i)
         if (rigidBodies_[i])
         if (rigidBodies_[i])
             rigidBodies_[i]->ReleaseBody();
             rigidBodies_[i]->ReleaseBody();
-
-    delete world_;
-    world_ = 0;
 }
 }
 
 
 void PhysicsWorld2D::RegisterObject(Context* context)
 void PhysicsWorld2D::RegisterObject(Context* context)

+ 2 - 2
Source/Urho3D/Urho2D/PhysicsWorld2D.h

@@ -197,7 +197,7 @@ public:
     int GetPositionIterations() const { return positionIterations_; }
     int GetPositionIterations() const { return positionIterations_; }
 
 
     /// Return the Box2D physics world.
     /// Return the Box2D physics world.
-    b2World* GetWorld() { return world_; }
+    b2World* GetWorld() { return world_.Get(); }
 
 
     /// Set node dirtying to be disregarded.
     /// Set node dirtying to be disregarded.
     void SetApplyingTransforms(bool enable) { applyingTransforms_ = enable; }
     void SetApplyingTransforms(bool enable) { applyingTransforms_ = enable; }
@@ -218,7 +218,7 @@ private:
     void SendEndContactEvents();
     void SendEndContactEvents();
 
 
     /// Box2D physics world.
     /// Box2D physics world.
-    b2World* world_;
+    UniquePtr<b2World> world_;
     /// Gravity.
     /// Gravity.
     Vector2 gravity_;
     Vector2 gravity_;
     /// Velocity iterations.
     /// Velocity iterations.