From 4e106f075e1521dbe22f1d2ff358d5cbc2c0074e Mon Sep 17 00:00:00 2001
From: Pedro Gonnet <gonnet@google.com>
Date: Sat, 11 Mar 2017 18:42:52 +0100
Subject: [PATCH] remember at which step the cell was last sorted, enforce
 during drift that no sort is older than its sub-cell sorts.

---
 src/cell.c | 8 ++++++--
 src/cell.h | 3 +++
 2 files changed, 9 insertions(+), 2 deletions(-)

diff --git a/src/cell.c b/src/cell.c
index ead1d7a49e..bbab79d73f 100644
--- a/src/cell.c
+++ b/src/cell.c
@@ -1097,7 +1097,7 @@ void cell_drift(struct cell *c, const struct engine *e) {
   /* Drift from the last time the cell was drifted to the current time */
   const double dt = (ti_current - ti_old) * timeBase;
   float dx_max = 0.f, dx2_max = 0.f;
-  float dx_max_sort = c->dx_max_sort, dx2_max_sort = 0.f;
+  float dx_max_sort = 0.0f, dx2_max_sort = 0.f;
   float h_max = 0.f;
 
   /* Check that we are actually going to move forward. */
@@ -1114,6 +1114,10 @@ void cell_drift(struct cell *c, const struct engine *e) {
         dx_max = max(dx_max, cp->dx_max);
         dx_max_sort = max(dx_max_sort, cp->dx_max_sort);
         h_max = max(h_max, cp->h_max);
+        if (cp->ti_sort > c->ti_sort)
+          c->sorted = 0;
+        else
+          c->sorted &= cp->sorted;
       }
 
   } else if (ti_current > ti_old) {
@@ -1162,7 +1166,7 @@ void cell_drift(struct cell *c, const struct engine *e) {
 
     /* Now, get the maximal particle motion from its square */
     dx_max = sqrtf(dx2_max);
-    dx_max_sort = max(dx_max_sort, sqrtf(dx2_max_sort));
+    dx_max_sort = sqrtf(dx2_max_sort);
 
   } else {
 
diff --git a/src/cell.h b/src/cell.h
index eed72bfa64..c9a3513af2 100644
--- a/src/cell.h
+++ b/src/cell.h
@@ -227,6 +227,9 @@ struct cell {
   /*! Last (integer) time the cell's content was drifted forward in time. */
   integertime_t ti_old;
 
+  /*! Last (integer) time the cell's sort arrays were updated. */
+  integertime_t ti_sort;
+
   /*! Minimum dimension, i.e. smallest edge of this cell (min(width)). */
   float dmin;
 
-- 
GitLab