Ejemplo n.º 1
0
def toggle_debug_view(particle):
    if particle is None:
        return
    try:
        particle.debug_view = not particle.debug_view
    except:
        Logger.log_warning("Can't toggle debug view of selected entity.")
Ejemplo n.º 2
0
def load_from_json(sim, fname="sim"):
    """ Loads a simulation state. """

    fname = get_file_path(fname, "json")

    if not os.path.exists(fname):
        Logger.log_error("File not found: '{}'. Can't load.".format(fname))
        return

    data = dict()
    with open(fname, 'r') as savefile:
        data = json.load(savefile)

    # Clear previous state
    sim.entities.clear()

    # Construct sim state
    sim.lifetime = data["lifetime"]

    for e in data["particles"]:

        p = particle_factory.create_particle(e)
        if p is not None:
            sim.add_entity(p)
        else:
            Logger.log_warning("Loading particle failed.")
Ejemplo n.º 3
0
def save_to_json(sim, fname="sim"):
    """ Saves a simulation's state as a .json file. """

    fname = get_file_path(fname, "json")

    with open(fname, 'w') as savefile:

        # Collect all data to be saved
        data = {"lifetime": sim.lifetime, "particles": list()}

        # Go over each entity and save its properties
        for e in sim.entities:

            if issubclass(type(e), particle.ForceParticle):
                try:
                    p_data = dict()
                    p_data["type"] = str(type(e))
                    p_data["pos"] = e.pos
                    p_data["velocity"] = e.velocity
                    p_data["mass"] = e.mass
                    p_data["size"] = e.size
                    p_data["can_move"] = e._can_move
                    p_data["paused"] = e.paused
                    data["particles"].append(p_data)
                except AttributeError as e:
                    Logger.log_warning(
                        "Corrupt particle. Can't save particle.")
                    Logger.log_exception(e)
                    continue

        # Dump data to json
        json.dump(data, savefile)
Ejemplo n.º 4
0
def set_global_particle_velocity(sim, v):

    for e in sim.entities:
        try:
            e.velocity = [v, v]
        except AttributeError:
            Logger.log_warning("Can't set velocity of entity {}".format(e))
    Logger.log_custom("control",
                      "Set global particle velocity to {}.".format(v))
Ejemplo n.º 5
0
def set_global_particle_radius(sim, r):
    """ Sets all PrimordialParticle's radii. Note: This is rather costly """

    for e in sim.entities:
        try:
            e.radius = r
        except AttributeError:
            Logger.log_warning("Can't set radius of entity: {}".format(e))
    Logger.log_custom("control", "Set global particle radius to {}.".format(r))
Ejemplo n.º 6
0
def toggle_trail(particle):
    if particle is None:
        return
    try:
        particle.draw_trail_points = not particle.draw_trail_points
        if particle.draw_trail_points:
            # Clear previous trail if turning it back on
            particle.trail_points.clear()
    except AttributeError:
        Logger.log_warning("Can't draw trail of selected entity.")
Ejemplo n.º 7
0
 def add_state(self, s, ix=None):
     if s not in self.S:
         if ix is None:
             self.S.append(s)
         else:
             try:
                 self.S.insert(ix, s)
             except:
                 Logger.log_warning(
                     "Can't insert state at position {}.".format(ix))
Ejemplo n.º 8
0
def cycle_trail_length(particle, increase=False):

    if particle is None:
        return

    try:
        old = particle.trail_points.limit
        inc = -1 * (int(math.log10(old)) + 1)
        if increase:
            inc *= -1  # Make increment positive
            particle.trail_points.set_limit(old + inc)
    except AttributeError:
        Logger.log_warning("Cannot change trail length of selected entity.")
Ejemplo n.º 9
0
def cycle_trail_density(particle, increase=False):
    if particle is None:
        return

    inc = -1
    if increase:
        inc = 1

    try:
        new = particle.trail_points_interval + inc
        if new > 0:
            particle.trail_points_interval = new
    except:
        Logger.log_warning("Can't adjust trail density of selected entity.")
Ejemplo n.º 10
0
    def calculate_type_mod(self, e):

        result = 0
        e_type = type(e)

        try:
            result = self.interacting_types[e_type]
        except KeyError:
            # This shouldn't be reachable, but let's be safe
            Logger.log_warning(
                "Trying to calculate mod for unknown type '{}'.".format(
                    e_type))

        return result
Ejemplo n.º 11
0
def change_particle_velocity(symbol, particle):
    # Changes a particle's velocity based on the key pressed

    if particle is None:
        return

    speedmod = 0.1
    mod = 1
    if symbol == key.W:
        # Slow down, fella
        mod = (1 - speedmod)
    elif symbol == key.C:
        # Hurry up, buster
        mod = (1 + speedmod)
    elif symbol == key.X:
        # It's time to stop
        mod = 0

    speed_incr = (0, 0)
    step = 0.0001
    if symbol == key.LEFT:
        speed_incr = (-step, 0)
    elif symbol == key.RIGHT:
        speed_incr = (step, 0)
    elif symbol == key.UP:
        speed_incr = (0, step)
    elif symbol == key.DOWN:
        speed_incr = (0, -step)

    try:
        v_old = particle.velocity
        particle.velocity = ((v_old[0] * mod) + speed_incr[0],
                             (v_old[1] * mod) + speed_incr[1])
    except AttributeError:
        Logger.log_warning(
            "Selected entity is not a particle. Can't change velocity.")
Ejemplo n.º 12
0
def create_particle(data):
    """ Accepts data and creates particle according to it. """

    # Get particle type
    type_raw = None
    try:
        type_raw = data["type"]
    except KeyError as ke:
        Logger.log_warning("No particle type data. Can't spawn particle.")
        Logger.log_exception(ke)
        return None

    t = type_raw
    if type(type_raw) is str:
        # Get actual class reference
        t = get_particle_type(type_raw)

    if t is None:
        Logger.log_warning("Unrecognized particle type. Can't spawn particle.")
        return None

    # Construct particle
    p = None
    try:
        pos = data["pos"]
        p = t(pos[0], pos[1])
    except KeyError as ke:
        Logger.log_warning("Incomplete particle data. Can't spawn particle.")
        Logger.log_exception(ke)
        return None

    # Set particle attributes
    try:
        p.mass = data["mass"]
        p.velocity = data["velocity"]
        p.size = data["size"]
        p._can_move = data["can_move"]
        p.paused = data["paused"]
    except KeyError as ke:
        Logger.log_info("Missing particle data.")
        Logger.log_exception(ke)

    return p
Ejemplo n.º 13
0
def toggle_particle_movable(particle):

    try:
        particle._can_move = not particle._can_move
    except AttributeError:
        Logger.log_warning("Can't toggle movability of '{}.'".format(particle))