From 6a52767fe15fa65c508e8733a9d7429b793647c7 Mon Sep 17 00:00:00 2001
From: Matthieu Schaller <schaller@strw.leidenuniv.nl>
Date: Tue, 16 Jun 2020 09:44:49 +0200
Subject: [PATCH] More sensible abort condition in cell_add_gpart()
 cell_add_spart(). Add check to prevent users from running with SF but no
 spare stars

---
 src/cell.c  | 16 ++++++++++------
 src/space.c |  7 +++++++
 2 files changed, 17 insertions(+), 6 deletions(-)

diff --git a/src/cell.c b/src/cell.c
index 802ce7dbf6..88c8b84e00 100644
--- a/src/cell.c
+++ b/src/cell.c
@@ -5615,12 +5615,14 @@ struct spart *cell_add_spart(struct engine *e, struct cell *const c) {
   lock_lock(&top->stars.star_formation_lock);
 
   /* Are there any extra particles left? */
-  if (top->stars.count >= top->stars.count_total - 1) {
+  if (top->stars.count == top->stars.count_total) {
+
+    message("We ran out of free star particles!");
+
     /* Release the local lock before exiting. */
     if (lock_unlock(&top->stars.star_formation_lock) != 0)
       error("Failed to unlock the top-level cell.");
-    if (top->stars.count == top->stars.count_total - 1)
-      message("We ran out of star particles!");
+
     atomic_inc(&e->forcerebuild);
     return NULL;
   }
@@ -5748,12 +5750,14 @@ struct gpart *cell_add_gpart(struct engine *e, struct cell *c) {
   lock_lock(&top->grav.star_formation_lock);
 
   /* Are there any extra particles left? */
-  if (top->grav.count >= top->grav.count_total - 1) {
+  if (top->grav.count == top->grav.count_total) {
+
+    message("We ran out of free gravity particles!");
+
     /* Release the local lock before exiting. */
     if (lock_unlock(&top->grav.star_formation_lock) != 0)
       error("Failed to unlock the top-level cell.");
-    if (top->grav.count == top->grav.count_total - 1)
-      message("We ran out of gravity particles!");
+
     atomic_inc(&e->forcerebuild);
     return NULL;
   }
diff --git a/src/space.c b/src/space.c
index a5be979156..5bdf075f40 100644
--- a/src/space.c
+++ b/src/space.c
@@ -5125,6 +5125,13 @@ void space_init(struct space *s, struct swift_params *params,
     space_extra_sparts = 0;
   }
 
+  if (star_formation && swift_star_formation_model_creates_stars &&
+      space_extra_sparts == 0) {
+    error(
+        "Running with star formation but without spare star particles. "
+        "Increase 'Scheduler:cell_extra_sparts'.");
+  }
+
   /* Build the cells recursively. */
   if (!dry_run) space_regrid(s, verbose);
 
-- 
GitLab