From 00a07ffc6abc6e36cf790448e694155f021c7b9d Mon Sep 17 00:00:00 2001
From: =?utf8?q?C=C3=B4me=20Chilliet?= <come@chilliet.eu>
Date: Mon, 30 Jan 2017 19:13:08 +0100
Subject: [PATCH] This should fix the segfault from #89

---
 Source/Environment/Terrain.cpp | 20 ++++++++++++++++++++
 Source/Environment/Terrain.hpp |  1 +
 Source/Objects/Object.cpp      |  1 +
 3 files changed, 22 insertions(+)

diff --git a/Source/Environment/Terrain.cpp b/Source/Environment/Terrain.cpp
index 4874e33..2530f0a 100644
--- a/Source/Environment/Terrain.cpp
+++ b/Source/Environment/Terrain.cpp
@@ -1241,6 +1241,26 @@ void Terrain::AddObject(XYZ where, float radius, int id)
     }
 }
 
+void Terrain::DeleteObject(unsigned int id)
+{
+    for (int i = 0; i < subdivision; i++) {
+        for (int j = 0; j < subdivision; j++) {
+            for (unsigned int k = 0; k < patchobjects[i][j].size();) {
+                if (patchobjects[i][j][k] == id) {
+                    /* Remove all occurences of id (there should never be more than 1 though) */
+                    patchobjects[i][j].erase(patchobjects[i][j].begin() + k);
+                } else {
+                    /* Update id of other objects if needed */
+                    if (patchobjects[i][j][k] > id) {
+                        patchobjects[i][j][k]--;
+                    }
+                    k++;
+                }
+            }
+        }
+    }
+}
+
 void Terrain::DeleteDecal(int which)
 {
     if (decalstoggle) {
diff --git a/Source/Environment/Terrain.hpp b/Source/Environment/Terrain.hpp
index 6132c6a..f4876cf 100644
--- a/Source/Environment/Terrain.hpp
+++ b/Source/Environment/Terrain.hpp
@@ -87,6 +87,7 @@ public:
     std::vector<Decal> decals;
 
     void AddObject(XYZ where, float radius, int id);
+    void DeleteObject(unsigned int id);
     void DeleteDecal(int which);
     void MakeDecal(decal_type type, XYZ where, float size, float opacity, float rotation);
     void MakeDecalLock(decal_type type, XYZ where, int whichx, int whichy, float size, float opacity, float rotation);
diff --git a/Source/Objects/Object.cpp b/Source/Objects/Object.cpp
index a7d991d..84cc173 100644
--- a/Source/Objects/Object.cpp
+++ b/Source/Objects/Object.cpp
@@ -636,6 +636,7 @@ void Object::Draw()
 void Object::DeleteObject(int which)
 {
     objects.erase(objects.begin() + which);
+    terrain.DeleteObject(which);
 }
 
 void Object::MakeObject(int atype, XYZ where, float ayaw, float apitch, float ascale)
-- 
2.39.5