diff --git a/engine/src/terrain/com/jme3/terrain/geomipmap/TerrainPatch.java b/engine/src/terrain/com/jme3/terrain/geomipmap/TerrainPatch.java index 381f61fc7..4ac811e9f 100644 --- a/engine/src/terrain/com/jme3/terrain/geomipmap/TerrainPatch.java +++ b/engine/src/terrain/com/jme3/terrain/geomipmap/TerrainPatch.java @@ -982,5 +982,27 @@ public class TerrainPatch extends Geometry { return worldTranslationCached; } + /** + * Removes any references when the terrain is being removed. + */ + protected void clearCaches() { + if (leftNeighbour != null) { + leftNeighbour.rightNeighbour = null; + leftNeighbour = null; + } + if (rightNeighbour != null) { + rightNeighbour.leftNeighbour = null; + rightNeighbour = null; + } + if (topNeighbour != null) { + topNeighbour.bottomNeighbour = null; + topNeighbour = null; + } + if (bottomNeighbour != null) { + bottomNeighbour.topNeighbour = null; + bottomNeighbour = null; + } + } + } diff --git a/engine/src/terrain/com/jme3/terrain/geomipmap/TerrainQuad.java b/engine/src/terrain/com/jme3/terrain/geomipmap/TerrainQuad.java index e191bbd0c..8c9e0bc14 100644 --- a/engine/src/terrain/com/jme3/terrain/geomipmap/TerrainQuad.java +++ b/engine/src/terrain/com/jme3/terrain/geomipmap/TerrainQuad.java @@ -1806,6 +1806,34 @@ public class TerrainQuad extends Node implements Terrain { return quadClone; } + + @Override + protected void setParent(Node parent) { + super.setParent(parent); + if (parent == null) { + // if the terrain is being detached + clearCaches(); + } + } + + /** + * Removes any cached references this terrain is holding, in particular + * the TerrainPatch's neighbour references. + * This is called automatically when the root terrainQuad is detached from + * its parent or if setParent(null) is called. + */ + public void clearCaches() { + if (children != null) { + for (int i = children.size(); --i >= 0;) { + Spatial child = children.get(i); + if (child instanceof TerrainQuad) { + ((TerrainQuad) child).clearCaches(); + } else if (child instanceof TerrainPatch) { + ((TerrainPatch) child).clearCaches(); + } + } + } + } public int getMaxLod() { if (maxLod < 0)