struct planet *move_planet(struct planet *p, const double time)
{
- struct vector tmp;
+ struct vector tmp, new_pos;
struct quadtree *tree_parent;
+ struct planet_search_iterator it;
vector_scale(&p->speed, time, &tmp);
- vector_add(&p->pos, &tmp, &p->pos);
+ vector_add(&p->pos, &tmp, &new_pos);
vector_scale(&p->speed, pow(0.99, time), &p->speed);
- tree_parent = quadtree_del(&p->tree, planet_spatial_compare);
- quadtree_add(tree_parent, &p->tree, planet_spatial_compare);
- return tree_to_planet(tree_parent);
+ /*
+ * Update the quadtree if there are any planets between the
+ * old and new position. If there is nothing between the old
+ * and new location, there is no need to modify the tree at
+ * all.
+ */
+ it.limit[0] = p->pos;
+ it.limit[1] = new_pos;
+ it.qt_iterator.head = quadtree_find_parent(&p->tree);
+
+ if (walk_quadtree(&it.qt_iterator)) {
+ tree_parent = quadtree_del(&p->tree, planet_spatial_compare);
+ quadtree_add(tree_parent, &p->tree, planet_spatial_compare);
+ return tree_to_planet(tree_parent);
+ }
+
+ return tree_to_planet(it.qt_iterator.head);
}
void print_planet(const struct planet *p)