def on_update(self):
     super().on_update()
     if self._countdown <= 0:
         services.current_zone().on_hit_their_marks()
         return _ZoneSpinUpStateResult.DONE
     services.game_clock_service().advance_for_hitting_their_marks()
     return _ZoneSpinUpStateResult.WAITING
 def on_enter(self):
     super().on_enter()
     services.current_zone().lot.publish_shared_inventory_items()
     active_household_id = services.active_household_id()
     for script_object in services.object_manager().get_all():
         script_object.finalize(active_household_id=active_household_id)
     return _ZoneSpinUpStateResult.DONE
def set_venue(venue_type, _connection=None):
    venue_tuning = services.venue_manager().get(venue_type)
    if venue_tuning is None:
        sims4.commands.output('Requesting an unknown venue type: {0}'.format(venue_type), _connection)
        return False
    services.current_zone().venue_service.set_venue_and_schedule_events(venue_tuning)
    return True
 def on_add(self):
     if self._relationship_based_state_change_tuning is None:
         return
     self._state_changes = self._relationship_based_state_change_tuning.state_changes
     self._default_state = self._relationship_based_state_change_tuning.default_state
     services.current_zone().register_callback(zone_types.ZoneState.CLIENT_CONNECTED, self._register_active_sim_change)
     services.current_zone().register_callback(zone_types.ZoneState.HOUSEHOLDS_AND_SIM_INFOS_LOADED, self._publish_relationship_data)
Esempio n. 5
0
def create_object(definition_or_id, obj_id=0, init=None, post_add=None, loc_type=None, **kwargs):
    from objects.components.inventory_item import ItemLocation
    from objects.base_object import BaseObject
    added_to_object_manager = False
    obj = None
    if loc_type is None:
        loc_type = ItemLocation.ON_LOT
    try:
        obj = create_script_object(definition_or_id, **kwargs)
        if obj is None:
            return
        if not isinstance(obj, BaseObject):
            logger.error('Type {0} is not a valid managed object.  It is not a subclass of BaseObject.', type(obj))
            return
        if init is not None:
            init(obj)
        if loc_type == ItemLocation.FROM_WORLD_FILE:
            obj.persistence_group = PersistenceGroups.IN_OPEN_STREET
        obj.item_location = ItemLocation(loc_type) if loc_type is not None else ItemLocation.INVALID_LOCATION
        obj.id = obj_id
        if loc_type == ItemLocation.ON_LOT or loc_type == ItemLocation.FROM_WORLD_FILE or loc_type == ItemLocation.FROM_OPEN_STREET:
            obj.object_manager_for_create.add(obj)
        elif loc_type == ItemLocation.SIM_INVENTORY or loc_type == ItemLocation.OBJECT_INVENTORY:
            services.current_zone().inventory_manager.add(obj)
        else:
            logger.error('Unsupported loc_type passed to create_script_object.  We likely need to update this code path.', owner='mduke')
        added_to_object_manager = True
        if post_add is not None:
            post_add(obj)
        return obj
    finally:
        if not added_to_object_manager and obj is not None:
            import _weakrefutils
            _weakrefutils.clear_weak_refs(obj)
def broadcasters_add(broadcaster_type, broadcasting_object:OptionalTargetParam=None, _connection=None):
    broadcasting_object = get_optional_target(broadcasting_object, _connection)
    if broadcasting_object is None:
        return False
    broadcaster = broadcaster_type(broadcasting_object=broadcasting_object)
    services.current_zone().broadcaster_service.add_broadcaster(broadcaster)
    return True
 def add(self, obj, *args, **kwargs):
     super().add(obj, *args, **kwargs)
     if obj.objectage_component is None:
         services.current_zone().increment_object_count(obj)
         household_manager = services.household_manager()
         if household_manager is not None:
             household_manager.increment_household_object_count(obj.get_household_owner_id())
Esempio n. 8
0
 def get_save_lot_coords_and_level(self):
     lot_coord_msg = LotCoord()
     parent = self.parent
     if parent is not None and parent.is_sim:
         parent.force_update_routing_location()
         starting_position = parent.position + parent.forward
         search_flags = CarryingObject.SNAP_TO_GOOD_LOCATION_SEARCH_FLAGS
         (trans, orient) = placement.find_good_location(placement.FindGoodLocationContext(starting_position=starting_position, starting_orientation=parent.orientation, starting_routing_surface=self.location.world_routing_surface, object_footprints=(self.footprint,), object_id=self.id, search_flags=search_flags))
         if trans is None:
             logger.warn('Unable to find good location to save object{}, which is parented to sim {} and cannot go into an inventory. Defaulting to location of sim.', self, parent)
             transform = parent.transform
         else:
             transform = sims4.math.Transform(trans, orient)
         transform = services.current_zone().lot.convert_to_lot_coordinates(transform)
     elif self.persistence_group == PersistenceGroups.OBJECT:
         transform = services.current_zone().lot.convert_to_lot_coordinates(self.transform)
     else:
         transform = self.transform
     lot_coord_msg.x = transform.translation.x
     lot_coord_msg.y = transform.translation.y
     lot_coord_msg.z = transform.translation.z
     lot_coord_msg.rot_x = transform.orientation.x
     lot_coord_msg.rot_y = transform.orientation.y
     lot_coord_msg.rot_z = transform.orientation.z
     lot_coord_msg.rot_w = transform.orientation.w
     if self.location.world_routing_surface is not None:
         level = self.location.level
     else:
         level = 0
     return (lot_coord_msg, level)
 def _on_leaving_situation(self, end_work_reason):
     service_npc_type = self._service_npc_type
     household = self._hiring_household
     try:
         now = services.time_service().sim_now
         time_worked = now - self._service_start_time
         time_worked_in_hours = time_worked.in_hours()
         if self._had_preroll_work:
             cost = service_npc_type.get_cost(time_worked_in_hours)
         else:
             cost = 0
         if cost > 0:
             (paid_amount, billed_amount) = service_npc_type.try_charge_for_service(household, cost)
             end_work_reason = ServiceNpcEndWorkReason.NOT_PAID
         else:
             paid_amount = 0
             billed_amount = 0
         self._send_end_work_notification(end_work_reason, paid_amount, billed_amount)
         service_record = household.get_service_npc_record(service_npc_type.guid64)
         service_record.time_last_finished_service = now
         if end_work_reason == ServiceNpcEndWorkReason.FIRED:
             service_sim = self.service_sim()
             if service_record is not None:
                 service_record.add_fired_sim(service_sim.id)
                 service_record.remove_preferred_sim(service_sim.id)
         while end_work_reason in ServiceNpcSituation.CANCEL_SERVICE_LEAVING_REASONS:
             services.current_zone().service_npc_service.cancel_service(household, service_npc_type)
     except Exception as e:
         logger.exception('Exception while executing _on_leaving_situation for situation {}', self, exc=e)
     finally:
         if not self._is_recurring:
             services.current_zone().service_npc_service.cancel_service(household, service_npc_type)
     return end_work_reason
 def _run_interaction_gen(self, timeline):
     sim = self.sim
     end_time = services.time_service().sim_now + create_time_span(hours=8)
     fake_alarm_data = AlarmData(None, end_time, None, False)
     default_user_specified_data_id = self._service_tuning.get_default_user_specified_data_id()
     creation_data = ServiceNpcSituationCreationParams(sim.household, self._service_tuning, user_specified_data_id=default_user_specified_data_id, is_recurring=False)
     services.current_zone().service_npc_service._send_service_npc(None, fake_alarm_data, creation_data)
     return True
 def on_enter(self):
     super().on_enter()
     situation_manager = services.get_zone_situation_manager()
     situation_manager.create_situations_during_zone_spin_up()
     services.current_zone(
     ).venue_service.initialize_venue_background_schedule()
     situation_manager.on_all_situations_created_during_zone_spin_up()
     return _ZoneSpinUpStateResult.DONE
Esempio n. 12
0
 def get_jog_waypoint_constraints(cls, context):
     sim = context.sim
     if context.pick is not None:
         pick_position = context.pick.location
         pick_vector = pick_position - sim.position
         pick_vector /= pick_vector.magnitude()
     else:
         pick_vector = sim.forward
     zone = services.current_zone()
     active_lot = zone.lot
     lot_corners = active_lot.corners
     sim_poly = sims4.geometry.CompoundPolygon(sims4.geometry.Polygon([sim.position]))
     lot_poly = sims4.geometry.CompoundPolygon(sims4.geometry.Polygon([corner for corner in lot_corners]))
     intersection = lot_poly.intersect(sim_poly)
     sim_on_lot = len(intersection) >= 1
     if sim_on_lot:
         spawn_point = zone.get_spawn_point(lot_id=active_lot.lot_id, sim_spawner_tags=SimInfoSpawnerTags.SIM_SPAWNER_TAGS)
         origin_position = spawn_point.center
         routing_surface = routing.SurfaceIdentifier(zone.id, 0, routing.SURFACETYPE_WORLD)
         except_lot_id = active_lot.lot_id
     else:
         origin_position = sim.position
         routing_surface = sim.routing_surface
         except_lot_id = None
     interaction_constraint = Circle(origin_position, cls.CONSTRAINT_RADIUS, routing_surface=routing_surface, los_reference_point=None)
     jog_waypoint_constraints = []
     zone = services.current_zone()
     active_lot = zone.lot
     constraint_set = zone.get_spawn_points_constraint(except_lot_id=except_lot_id)
     constraints_weighted = []
     min_score = sims4.math.MAX_FLOAT
     for constraint in constraint_set:
         spawn_point_vector = constraint.average_position - sim.position
         score = sims4.math.vector_dot_2d(pick_vector, spawn_point_vector)
         if score < min_score:
             min_score = score
         constraints_weighted.append((score, constraint))
     constraints_weighted = [(score - min_score, constraint) for (score, constraint) in constraints_weighted]
     constraints_weighted = sorted(constraints_weighted, key=lambda i: i[0])
     first_constraint = constraints_weighted[-1][1]
     del constraints_weighted[-1]
     first_constraint_circle = Circle(first_constraint.average_position, cls.CONSTRAINT_RADIUS, routing_surface=first_constraint.routing_surface)
     jog_waypoint_constraints.append(first_constraint_circle)
     last_waypoint_position = first_constraint.average_position
     for _ in range(cls.NUM_JOG_POINTS - 1):
         constraints_weighted_next = []
         for (_, constraint) in constraints_weighted:
             average_position = constraint.average_position
             distance_last = (average_position - last_waypoint_position).magnitude_2d()
             distance_home = (average_position - origin_position).magnitude_2d()
             constraints_weighted_next.append((distance_last + distance_home, constraint))
         next_constraint = pop_weighted(constraints_weighted_next)
         next_constraint_circle = Circle(next_constraint.average_position, cls.CONSTRAINT_RADIUS, routing_surface=next_constraint.routing_surface)
         jog_waypoint_constraints.append(next_constraint_circle)
         constraints_weighted = constraints_weighted_next
         last_waypoint_position = next_constraint.average_position
     jog_waypoint_constraints.append(interaction_constraint)
     return (interaction_constraint, jog_waypoint_constraints)
def cancel_service(service_npc_type, max_duration:int=240, _connection=None):
    service_npc_tuning = services.service_npc_manager().get(service_npc_type)
    if service_npc_tuning is not None:
        tgt_client = services.client_manager().get(_connection)
        if tgt_client is None:
            return False
        household = tgt_client.household
        services.current_zone().service_npc_service.cancel_service(household, service_npc_tuning)
        return True
    return False
 def stop(self):
     if self._alarm_handle is not None:
         cancel_alarm(self._alarm_handle)
         self._alarm_handle = None
     if self._processing_task is not None:
         self._processing_task.stop()
         self._processing_task = None
     object_manager = services.object_manager()
     object_manager.unregister_callback(CallbackTypes.ON_OBJECT_LOCATION_CHANGED, self._update_object_cache)
     object_manager.unregister_callback(CallbackTypes.ON_OBJECT_ADD, self._update_object_cache)
     services.current_zone().wall_contour_update_callbacks.remove(self._update_object_cache)
 def on_enter(self):
     super().on_enter()
     zone = services.current_zone()
     client = zone.zone_spin_up_service._client_connect_data.client
     destroy_unentitled_craftables()
     GlobalLotTuningAndCleanup.cleanup_objects(lot=zone.lot)
     zone.service_manager.on_cleanup_zone_objects(client)
     services.current_zone(
     ).posture_graph_service.build_during_zone_spin_up()
     pythonutils.try_highwater_gc()
     return _ZoneSpinUpStateResult.DONE
def create_situation_for_venue_type(situation_type, venue_type, opt_sim:OptionalTargetParam=None, _connection=None):
    sim = get_optional_target(opt_sim, _connection)
    if not services.current_zone().venue_service.has_zone_for_venue_type((venue_type,)):
        sims4.commands.output('There are no zones that support the venue type provided, {}.'.format(venue_type), _connection)
        return False
    situation_manager = services.get_zone_situation_manager()
    (zone_id, _) = services.current_zone().venue_service.get_zone_and_venue_type_for_venue_types((venue_type,))
    guest_list = SituationGuestList(False, sim.id)
    situation_id = situation_manager.create_situation(situation_type, guest_list=guest_list, user_facing=True, zone_id=zone_id)
    if situation_id is None:
        sims4.commands.output('Insufficient funds to create situation', _connection)
    else:
        sims4.commands.output('Successfully created situation: {}.'.format(situation_id), _connection)
Esempio n. 17
0
def c_api_buildbuy_session_begin(zone_id, account_id):
    with sims4.zone_utils.global_zone_lock(zone_id):
        posture_graph_service = services.current_zone().posture_graph_service
        posture_graph_service.on_enter_buildbuy()
        services.current_zone().on_build_buy_enter()
        indexed_manager.IndexedManager.add_gc_collect_disable_reason(
            BUILD_BUY_OBJECT_LEAK_DISABLED)
        resource_keys = []
        current_zone = services.current_zone()
        household = current_zone.get_active_lot_owner_household()
        if household is not None:
            for unlock in household.build_buy_unlocks:
                resource_keys.append(unlock)
        update_gameplay_unlocked_products(resource_keys, zone_id, account_id)
    return True
Esempio n. 18
0
 def on_cleanup_zone_objects(self, client):
     zone = services.current_zone()
     if client.household_id != zone.lot.owner_household_id:
         time_elapsed = services.game_clock_service().time_elapsed_since_last_save()
         if time_elapsed.in_minutes() > self.ELAPSED_TIME_SINCE_LAST_VISIT_FOR_CLEANUP:
             cleanup = VenueService.VENUE_CLEANUP_ACTIONS()
             cleanup.modify_objects_on_active_lot()
def get_hide_from_lot_picker(_connection=None):
    current_zone = services.current_zone()
    world_desc_id = services.get_world_description_id(current_zone.world_id)
    lot = current_zone.lot
    b = services.get_hide_from_lot_picker(lot.lot_id, world_desc_id)
    output = sims4.commands.Output(_connection)
    output('c_api returned {} for lot {} and world {}'.format(b, lot.lot_id, current_zone.world_id))
Esempio n. 20
0
def c_api_navmesh_fence_callback(fence_id):
    zone = services.current_zone()
    if zone.is_zone_running:
        build_buy.buildbuy_session_end(zone.id)
    from objects.components.spawner_component import SpawnerInitializerSingleton
    if SpawnerInitializerSingleton is not None:
        SpawnerInitializerSingleton.spawner_spawn_objects_post_nav_mesh_load(zone.id)
Esempio n. 21
0
 def _update(self, force_create=False):
     if services.get_super_speed_three_service().in_or_has_requested_super_speed_three():
         gsi_handlers.ambient_handlers.archive_ambient_data('In super speed 3 mode')
         return
     if not self._sources:
         return
     if gsi_handlers.ambient_handlers.archiver.enabled:
         gsi_description = self.get_gsi_description()
     else:
         gsi_description = None
     sources_and_priorities = [(source, source.get_priority()) for source in self._sources]
     sources_and_priorities.sort(key=lambda source: source[1], reverse=True)
     situation_id = None
     source = sources_and_priorities[0][0]
     priority = sources_and_priorities[0][1]
     if priority > 0:
         situation_id = source.start_appropriate_situation()
     elif force_create:
         for (source, _) in sources_and_priorities:
             situation_id = source.start_appropriate_situation()
             while situation_id is not None:
                 break
     if gsi_handlers.ambient_handlers.archiver.enabled:
         if situation_id is not None:
             situation = services.current_zone().situation_manager.get(situation_id)
             gsi_description += '    Created {}'.format(situation)
         gsi_handlers.ambient_handlers.archive_ambient_data(gsi_description)
     return situation_id
    def _complete_pregnancy_gen(self, timeline, pregnancy_tracker):
        is_off_lot_birth = False
        for offspring_data in pregnancy_tracker.get_offspring_data_gen():
            sim_info = pregnancy_tracker.create_sim_info(offspring_data)
            current_zone = services.current_zone()
            if current_zone.id == sim_info.zone_id:
                create_and_place_baby(sim_info, ignore_daycare=True)
            else:
                is_off_lot_birth = True
        offspring_count = pregnancy_tracker.offspring_count
        pregnancy_tracker.complete_pregnancy()
        pregnancy_tracker.clear_pregnancy()
        if is_off_lot_birth:
            travel_liability = TravelSimLiability(self, self.sim.sim_info, self.sim.sim_info.household.home_zone_id, expecting_dialog_response=True)
            self.add_liability(TRAVEL_SIM_LIABILITY, travel_liability)

            def on_travel_dialog_response(dialog):
                if dialog.accepted:
                    save_lock_liability = self.get_liability(SaveLockLiability.LIABILITY_TOKEN)
                    if save_lock_liability is not None:
                        save_lock_liability.release()
                    travel_liability.travel_dialog_response(dialog)

            travel_dialog_element = UiDialogElement(self.sim, self.get_resolver(), dialog=self.off_lot_birth_dialog, on_response=on_travel_dialog_response, additional_tokens=(offspring_count,))
            result = yield element_utils.run_child(timeline, travel_dialog_element)
            return result
        return True
 def _start_broadcaster(self):
     if not self.should_broadcast:
         return
     broadcaster_service = services.current_zone().broadcaster_service
     if broadcaster_service is not None and self._broadcaster is None:
         self._broadcaster = EnvironmentScoreTuning.ENVIRONMENT_SCORE_BROADCASTER(broadcasting_object=self.owner)
         broadcaster_service.add_broadcaster(self._broadcaster)
 def get_spawn_point_string_gen(self):
     zone = services.current_zone()
     for spawn_point in zone.spawn_points_gen():
         spawn_point_string = 'Spawn Point {}:'.format(spawn_point.get_name())
         spawn_point_string += '\nPosition: {}'.format(spawn_point.center)
         spawn_point_string += '\nTags: {}'.format(spawn_point.get_tags())
         yield spawn_point_string
Esempio n. 25
0
 def _start_specific_situation(self, situation_type):
     situation_manager = services.current_zone().situation_manager
     guest_list = self.create_standard_ambient_guest_list(situation_type)
     situation_id = situation_manager.create_situation(situation_type, guest_list=guest_list, user_facing=False)
     if situation_id is not None:
         self._running_situation_ids.append(situation_id)
     return situation_id
    def save_and_destroy_sim(self, on_reset, sim_info):
        if services.current_zone().is_zone_shutting_down:
            return
        from_zone_id = self.from_zone_id
        to_zone_id = self.to_zone_id
        callback = self.on_complete_callback
        context = self.on_complete_context

        def notify_travel_service():
            if services.travel_service().has_pending_travel(sim_info.account):
                travel_service.on_travel_interaction_succeeded(sim_info, from_zone_id, to_zone_id, callback, context)
            if not sim_info.is_npc:
                services.client_manager().get_first_client().send_selectable_sims_update()

        try:
            logger.debug('Saving sim during TravelInteraction for {}', sim_info)
            sim_info.inject_into_inactive_zone(self.to_zone_id)
            save_success = sim_info.save_sim()
            while not save_success:
                logger.error('Failure saving during TravelInteraction for {}', sim_info)
        finally:
            logger.debug('Destroying sim {}', sim_info)
            self.force_save_and_destroy_sim = False
            if on_reset:
                if self.sim is not None:
                    services.object_manager().remove(self.sim)
                notify_travel_service()
            elif self.sim is not None:
                self.sim.schedule_destroy_asap(source=self, cause='Destroying sim on travel.')
Esempio n. 27
0
def generate_summary_report(skip_atomic, reverse_entries):
    labeled_roots = []
    from objects.definition_manager import DefinitionManager
    from sims4.tuning.instance_manager import InstanceManager
    from indexed_manager import IndexedManager
    from postures.posture_graph import PostureGraphService
    SERVICE_GROUPS = [(DefinitionManager, 'DefinitionManager'), (InstanceManager, 'TuningManager'), (IndexedManager, 'IndexedManager'), (PostureGraphService, 'PostureGraph'), (object, 'Other')]
    direction_iter = reversed if reverse_entries else iter
    zone = services.current_zone()
    service_sources = []
    zone_services = [source for service in zone.service_manager.services for source in service.get_buckets_for_memory_tracking()]
    service_sources.append((zone_services, 'ZoneService/'))
    core_services = [source for service in sims4.core_services.service_manager.services for source in service.get_buckets_for_memory_tracking()]
    service_sources.append((core_services, 'CoreService/'))
    for (source, source_name) in service_sources:
        for service in direction_iter(source):
            group = source_name + _first_applicable_match(service, SERVICE_GROUPS)
            labeled_roots.append(('{1}/{0}'.format(service, group), [service]))
    for (name, module) in direction_iter(sorted(sys.modules.items())):
        path_root = 'Other'
        if hasattr(module, '__file__'):
            matching_paths = [path for path in sys.path if module.__file__.startswith(path)]
            if matching_paths:
                path_root = os.path.split(next(iter(matching_paths)))[-1]
                path_root = path_root.capitalize()
        group = 'Module/{}'.format(path_root)
        labeled_roots.append(('{1}/{0}'.format(name, group), [module]))
    report = sizeof.report(labeled_roots, skip_atomic=skip_atomic)
    return report
Esempio n. 28
0
 def callback(file):
     zone = services.current_zone()
     tick_data = zone.tick_data
     zone.stop_gathering_tick_metrics()
     file.write('ABSOLUTE TICKS,SIM NOW READABLE, SIM NOW TICKS,CLOCK SPEED ENUM,CLOCK SPEED MULTIPLIER,GAME TIME READABLE,GAME TIME TICKS,MULTIPLIER TYPE\n')
     for data in tick_data:
         file.write('{},{},{},{},{},{},{},{}\n'.format(data.absolute_ticks, data.sim_now, data.sim_now.absolute_ticks(), data.clock_speed, data.clock_speed_multiplier, data.game_time, data.game_time.absolute_ticks(), data.multiplier_type))
Esempio n. 29
0
 def get_inventory(self):
     if self.is_in_inventory():
         if self._last_inventory_owner is not None:
             return self._last_inventory_owner.inventory_component
         if self.is_in_sim_inventory():
             logger.error('Object exists but owning Sim does not!  This means we leaked the inventory item when the Sim was deleted.', owner='jpollak/mduke')
         return services.current_zone().lot.get_object_inventory(self._current_inventory_type)
def get_valid_situation_locations(sim_id, situation_type, *guests, _connection=None):
    sim = get_optional_target(sim_id, _connection)
    if not sim:
        sims4.commands.output('Invalid Sim ID: {}'.format(sim_id), _connection)
        return
    sim_info = sim.sim_info
    possible_zones = []
    possible_zones.append(sim_info.household.home_zone_id)
    for guest_id in guests:
        guest_id = int(guest_id)
        guest_info = services.sim_info_manager().get(guest_id)
        while guest_info is not None:
            guest_zone_id = guest_info.household.home_zone_id
            if guest_zone_id is not None and guest_zone_id and guest_zone_id not in possible_zones:
                possible_zones.append(guest_zone_id)
    venue_service = services.current_zone().venue_service
    for venue_type in situation_type.venue_types:
        possible_zones.extend(venue_service.get_zones_for_venue_type(venue_type))
    venue_manager = services.get_instance_manager(sims4.resources.Types.VENUE)
    persistence_service = services.get_persistence_service()
    locations_msg = Situations_pb2.SituationLocations()
    cas_zones_msg = InteractionOps_pb2.CASAvailableZonesInfo()
    world_info_msg = cas_zones_msg.zones.add()
    for zone_id in possible_zones:
        zone_data = persistence_service.get_zone_proto_buff(zone_id)
        if zone_data is None:
            pass
        neighborhood_data = persistence_service.get_neighborhood_proto_buff(zone_data.neighborhood_id)
        if neighborhood_data is None:
            pass
        lot_data = None
        for lot_owner_data in neighborhood_data.lots:
            while zone_id == lot_owner_data.zone_instance_id:
                lot_data = lot_owner_data
                break
        while zone_data is not None and lot_data is not None:
            location_data = Dialog_pb2.LotInfoItem()
            location_data.zone_id = zone_data.zone_id
            location_data.name = zone_data.name
            location_data.world_id = zone_data.world_id
            location_data.lot_template_id = zone_data.lot_template_id
            location_data.lot_description_id = zone_data.lot_description_id
            venue_type_id = build_buy.get_current_venue(zone_id)
            venue_instance = venue_manager.get(venue_type_id)
            if venue_instance is not None:
                location_data.venue_type_name = venue_instance.display_name
            if lot_data.lot_owner:
                household_id = lot_data.lot_owner[0].household_id
                household = services.household_manager().get(household_id)
                if household is not None:
                    location_data.household_name = household.name
            locations_msg.situation_locations.append(location_data)
            with ProtocolBufferRollback(world_info_msg.zones) as zone_info_msg:
                zone_info_msg.id = zone_data.zone_id
                zone_info_msg.name = zone_data.name
                zone_info_msg.world_id = zone_data.world_id
                zone_info_msg.lot_template_id = zone_data.lot_template_id
                zone_info_msg.lot_description_id = zone_data.lot_description_id
    shared_messages.add_object_message_for_sim_id(sim.id, Consts_pb2.MSG_NS_AVAILABLE_ZONES_INFO, cas_zones_msg)
    shared_messages.add_object_message_for_sim_id(sim.id, Consts_pb2.MSG_SITUATION_LOCATIONS, locations_msg)
Esempio n. 31
0
def live_drag_end(object_source_id,
                  object_target_id,
                  end_system,
                  _connection=None):
    current_zone = services.current_zone()
    source_object = current_zone.find_object(object_source_id)
    target_object = None
    if object_target_id:
        target_object = current_zone.find_object(object_target_id)
    if gsi_handlers.live_drag_handlers.live_drag_archiver.enabled:
        gsi_handlers.live_drag_handlers.archive_live_drag(
            'End',
            'Command',
            end_system,
            LiveDragLocation.GAMEPLAY_SCRIPT,
            live_drag_object=source_object,
            live_drag_object_id=object_source_id,
            live_drag_target=target_object)
    if source_object is None:
        logger.error(
            'Ending Live Drag with an object that does not exist. object_id: {}'
            .format(object_source_id),
            owner='rmccord')
        sims4.commands.output(
            'Live Drag object with id: {} does not exist.'.format(
                object_source_id), _connection)
        return
    if target_object is None and object_target_id:
        logger.error(
            'Ending Live Drag with a drop target that does not exist. object_id: {}'
            .format(object_target_id),
            owner='rmccord')
        sims4.commands.output(
            'Live Drag target object with id: {} does not exist.'.format(
                object_target_id), _connection)
        return
    client = services.client_manager().get_first_client()
    if client is None:
        logger.error('Client is not connected', owner='rmccord')
        sims4.commands.output('Client is not connected.', _connection)
        return
    client.end_live_drag(source_object, target_object, end_system)
Esempio n. 32
0
 def _run_gen(self, timeline):
     if not self._arb_element_sequence:
         return True
         yield
     duration_must_run = 0
     for arb_element in self._arb_element_sequence:
         (arb_duration_total, arb_duration_must_run, arb_duration_repeat) = arb_element.arb.get_timing()
         arb_duration_interrupt = arb_duration_total - arb_duration_must_run
         duration_must_run += arb_duration_must_run
         arb_element.distribute()
     duration_interrupt = arb_duration_interrupt
     duration_repeat = arb_duration_repeat
     if ArbAccumulatorService.MAXIMUM_TIME_DEBT > 0:
         actors = _get_actors_for_arb_element_sequence(self._arb_element_sequence, main_timeline_only=True)
         arb_accumulator = services.current_zone().arb_accumulator_service
         time_debt_max = arb_accumulator.get_time_debt(actors)
         shave_time_actual = arb_accumulator.get_shave_time_given_duration_and_debt(duration_must_run, time_debt_max)
         duration_must_run -= shave_time_actual
         if shave_time_actual:
             for actor in actors:
                 time_debt = arb_accumulator.get_time_debt((actor,))
                 time_debt += shave_time_actual
                 arb_accumulator.set_time_debt((actor,), time_debt)
         else:
             last_arb = self._arb_element_sequence[-1].arb
             if all(last_arb._normal_timeline_ends_in_looping_content(actor.id) for actor in actors):
                 duration_must_run += time_debt_max
                 arb_accumulator.set_time_debt(actors, 0)
     arbs = tuple(animation_element.arb for animation_element in self._arb_element_sequence)
     animation_sleep_element = AnimationSleepElement(duration_must_run, duration_interrupt, duration_repeat, arbs=arbs)
     if not self._animate_instantly:
         yield from element_utils.run_child(timeline, animation_sleep_element)
     optional_time_elapsed = animation_sleep_element.optional_time_elapsed
     if ArbAccumulatorService.MAXIMUM_TIME_DEBT > 0:
         if optional_time_elapsed > 0:
             for actor in actors:
                 time_debt = arb_accumulator.get_time_debt((actor,))
                 new_time_debt = time_debt - optional_time_elapsed
                 new_time_debt = max(new_time_debt, 0)
                 arb_accumulator.set_time_debt((actor,), new_time_debt)
     return True
     yield
Esempio n. 33
0
 def _get_role_state_overrides(self, sim, job_type, role_state_type,
                               role_affordance_target):
     if self.owner._crafted_object_id != 0:
         target = services.current_zone().inventory_manager.get(
             self.owner._crafted_object_id)
     else:
         recipe = services.recipe_manager().get(
             self.owner._object_definition_to_craft)
         if recipe is None:
             raise ValueError('No recipe for {}'.format(self))
         target = DebugCreateCraftableInteraction.create_craftable(
             recipe,
             self.owner._service_npc,
             owning_household_id_override=self.owner._hiring_household.id,
             place_in_crafter_inventory=True)
         if target is None:
             raise ValueError('No craftable created for {} on {}'.format(
                 recipe, self))
         self.owner._crafted_object_id = target.id
     return (role_state_type, target)
Esempio n. 34
0
 def do_responses(_):
     arb_accumulator = services.current_zone().arb_accumulator_service
     with arb_accumulator.parallelize():
         for sim in sims_ordered:
             best_participant_type = interaction.get_participant_type(sim, restrict_to_participant_types=participant_types)
             response_animation = animations.get(best_participant_type)
             if response_animation is None:
                 pass
             if sim is not interaction.sim or setup_asm_override is DEFAULT:
                 setup_asm = generate_setup_asm(sim, response_animation.factory.actor_name)
             else:
                 setup_asm = setup_asm_override
             arb = animation.arb.Arb()
             response = response_animation(interaction, setup_asm_override=setup_asm, use_asm_cache=False, **kwargs)
             response_asm = response.get_asm()
             response.append_to_arb(response_asm, arb)
             posture_idle = sim.posture.idle_animation(sim.posture.source_interaction)
             posture_asm = posture_idle.get_asm()
             posture_idle.append_to_arb(posture_asm, arb)
             arb_accumulator.add_arb(arb)
Esempio n. 35
0
 def on_remove(self):
     zone = services.current_zone()
     if zone is not None and not zone.is_zone_shutting_down:
         services.get_event_manager().process_event(test_events.TestEvent.ObjectDestroyed, obj=self)
     super().on_remove()
     if not zone.is_zone_shutting_down:
         self._remove_from_world()
         self.unregister_on_location_changed(self._location_changed)
         if self.is_fire_related_object:
             fire_service = services.get_fire_service()
             if fire_service is not None:
                 self.unregister_on_location_changed(fire_service.flammable_object_location_changed)
         posture_graph_service = services.posture_graph_service()
         if self.provided_mobile_posture_affordances:
             posture_graph_service.remove_mobile_posture_provider(self)
         if posture_graph.is_object_mobile_posture_compatible(self):
             posture_graph_service.remove_object_from_mobile_posture_quadtree(self)
             self.unregister_on_location_changed(posture_graph_service.mobile_posture_object_location_changed)
     else:
         self._on_location_changed_callbacks = None
Esempio n. 36
0
 def on_cleanup_zone_objects(self):
     super().on_cleanup_zone_objects()
     current_zone = services.current_zone()
     if current_zone.time_has_passed_in_world_since_zone_save():
         if self.object_commodities_to_fixup_on_load:
             time_of_last_zone_save = current_zone.time_of_last_save()
             for obj in list(services.object_manager().values()):
                 if not obj.is_on_active_lot():
                     continue
                 for commodity_fixup in self.object_commodities_to_fixup_on_load:
                     if not commodity_fixup.object_test(objects=(obj, )):
                         continue
                     fixup_commodity = obj.get_stat_instance(
                         commodity_fixup.commodity)
                     if fixup_commodity is not None:
                         fixup_commodity.update_commodity_to_time(
                             time_of_last_zone_save, update_callbacks=True)
     if self._should_reset_progress_on_load():
         self._revealed_plex = 0
     self._update_locks_and_visibility()
 def get_npc_greeted_status_during_zone_fixup(self, sim_info):
     if not services.current_zone(
     ).venue_service.venue.requires_visitation_rights:
         return GreetedStatus.NOT_APPLICABLE
     if sim_info.lives_here:
         return GreetedStatus.NOT_APPLICABLE
     cur_status = GreetedStatus.NOT_APPLICABLE
     for seed in self._zone_seeds_for_zone_spinup:
         status = seed.get_npc_greeted_status(sim_info)
         logger.debug('NPC:{} :{} :{}',
                      sim_info,
                      status,
                      seed.situation_type,
                      owner='sscholl')
         if status == GreetedStatus.GREETED:
             cur_status = status
             break
         while status == GreetedStatus.WAITING_TO_BE_GREETED:
             cur_status = status
     return cur_status
 def _verify_buy_state_interactions(self):
     object_to_buy = None
     should_restart = False
     if self.object_id is not None:
         current_zone = services.current_zone()
         object_to_buy = current_zone.find_object(self.object_id)
         if not (object_to_buy is None or not any(
                 interaction.sim is self.owner._customer
                 for interaction in list(object_to_buy.interaction_refs))):
             should_restart = True
     if should_restart:
         new_buy_state = _BuyState()
         new_buy_state.object_id = self.object_id
         self._change_state(new_buy_state)
     else:
         self._create_or_load_alarm(
             _BuyState.BUY_STATE_VERIFICATION,
             _BuyState.BUY_STATE_VERIFICATION_TIME,
             lambda _: self._verify_buy_state_interactions(),
             should_persist=False)
Esempio n. 39
0
def print_object_transform(obj_id: int = None, _connection=None):
    if obj_id is None:
        sims4.commands.output(
            'Usage: objects.print_object_transform <obj_id>: No obj_id provided',
            _connection)
        return False
    current_zone = services.current_zone()
    selected_obj = current_zone.find_object(obj_id)
    if selected_obj is None:
        sims4.commands.output(
            'Usage: objects.get_users <obj_id>: obj_id is not in the object manager or inventory manager.',
            _connection)
        return False
    sims4.commands.output(str(selected_obj.transform), _connection)
    if not selected_obj.parts:
        return
    for part in selected_obj.parts:
        sims4.commands.output(
            'Part[{}]: {}'.format(part.part_suffix, part.transform),
            _connection)
Esempio n. 40
0
 def on_client_connect(self, client):
     zone = services.current_zone()
     active_venue_key = get_current_venue(zone.id)
     logger.assert_raise(active_venue_key is not None,
                         ' Venue Type is None for zone id:{}',
                         zone.id,
                         owner='shouse')
     raw_active_venue_key = get_current_venue(zone.id,
                                              allow_ineligible=True)
     logger.assert_raise(raw_active_venue_key is not None,
                         ' Raw Venue Type is None for zone id:{}',
                         zone.id,
                         owner='shouse')
     if not active_venue_key is None and not raw_active_venue_key is None:
         active_venue_type = services.venue_manager().get(active_venue_key)
         raw_active_venue_type = services.venue_manager().get(
             raw_active_venue_key)
         source_venue_type = VenueService.get_variable_venue_source_venue(
             raw_active_venue_type)
         self._set_venue(active_venue_type, source_venue_type)
def generate_summary_report(skip_atomic, reverse_entries):
    labeled_roots = []
    from objects.definition_manager import DefinitionManager
    from sims4.tuning.instance_manager import InstanceManager
    from indexed_manager import IndexedManager
    from postures.posture_graph import PostureGraphService
    SERVICE_GROUPS = [(DefinitionManager, 'DefinitionManager'),
                      (InstanceManager, 'TuningManager'),
                      (IndexedManager, 'IndexedManager'),
                      (PostureGraphService, 'PostureGraph'), (object, 'Other')]
    direction_iter = reversed if reverse_entries else iter
    zone = services.current_zone()
    service_sources = []
    zone_services = [
        source for service in zone.service_manager.services
        for source in service.get_buckets_for_memory_tracking()
    ]
    service_sources.append((zone_services, 'ZoneService/'))
    core_services = [
        source for service in sims4.core_services.service_manager.services
        for source in service.get_buckets_for_memory_tracking()
    ]
    service_sources.append((core_services, 'CoreService/'))
    for (source, source_name) in service_sources:
        for service in direction_iter(source):
            group = source_name + _first_applicable_match(
                service, SERVICE_GROUPS)
            labeled_roots.append(('{1}/{0}'.format(service, group), [service]))
    for (name, module) in direction_iter(sorted(sys.modules.items())):
        path_root = 'Other'
        if hasattr(module, '__file__'):
            matching_paths = [
                path for path in sys.path if module.__file__.startswith(path)
            ]
            if matching_paths:
                path_root = os.path.split(next(iter(matching_paths)))[-1]
                path_root = path_root.capitalize()
        group = 'Module/{}'.format(path_root)
        labeled_roots.append(('{1}/{0}'.format(name, group), [module]))
    report = sizeof.report(labeled_roots, skip_atomic=skip_atomic)
    return report
Esempio n. 42
0
 def _run_gen(self, timeline=None):
     if not self.arb.is_valid():
         return False
         yield
     actors = self._actors()
     if not actors and not self._objects_to_reset:
         return True
         yield
     animation_sleep_element = None
     with distributor.system.Distributor.instance().dependent_block():
         self.attach(*actors)
         if self.event_records is None:
             (self.event_records, sleep) = self.handle_events()
         else:
             sleep = True
         self._log_event_records(dump_logger.error, True)
         for actor in actors:
             actor.update_reference_arb(self.arb)
         if sleep:
             if timeline is not None:
                 (self._duration_total, self._duration_must_run,
                  self._duration_repeat) = self.arb.get_timing()
                 self._duration_interrupt = self._duration_total - self._duration_must_run
                 if self._duration_must_run or self._duration_repeat:
                     animation_sleep_element = AnimationSleepElement(
                         self._duration_must_run,
                         self._duration_interrupt,
                         self._duration_repeat,
                         enable_optional_sleep_time=self.
                         enable_optional_sleep_time,
                         arbs=(self.arb, ))
         if gsi_handlers.animation_archive_handlers.archiver.enabled:
             gsi_handlers.animation_archive_handlers.archive_animation_request(
                 self.arb)
     if animation_sleep_element is not None and not services.current_zone(
     ).animate_instantly:
         yield from element_utils.run_child(timeline,
                                            animation_sleep_element)
     self.detach(*self._attached_actors)
     return True
     yield
Esempio n. 43
0
def get_object_use_list(obj_id: int = None, _connection=None):
    if obj_id is None:
        sims4.commands.output(
            'Usage: objects.get_users <obj_id>: No obj_id provided',
            _connection)
        return False
    current_zone = services.current_zone()
    selected_obj = current_zone.find_object(obj_id)
    if selected_obj is None:
        sims4.commands.output(
            'Usage: objects.get_users <obj_id>: obj_id is not in the object manager or inventory manager.',
            _connection)
        return False
    object_users = selected_obj.get_users(sims_only=True)
    user_strs = []
    for (index, reserver) in enumerate(object_users):
        user_strs.append('SimId{}:{}'.format(index, reserver.id))
    use_list_str = 'ObjectUserList; ObjectId:{}, NumUsers:{}, {}'.format(
        obj_id, len(object_users), ', '.join(user_strs))
    sims4.commands.automation_output(use_list_str, _connection)
    sims4.commands.output(use_list_str, _connection)
Esempio n. 44
0
 def save(self, zone_data=None, open_street_data=None, **kwargs):
     owning_household = services.current_zone(
     ).get_active_lot_owner_household()
     situation_manager = services.get_zone_situation_manager()
     for sim_info in self.get_all():
         while sim_info.account_id is not None:
             sim = sim_info.get_sim_instance(
                 allow_hidden_flags=ALL_HIDDEN_REASONS)
             if sim is not None:
                 if sim.is_selectable or owning_household is not None and sim_info in owning_household:
                     if sim.is_on_active_lot() or sim.has_hidden_flags(
                             HiddenReasonFlag.RABBIT_HOLE):
                         sim_info._serialization_option = sims.sim_info_types.SimSerializationOption.LOT
                     else:
                         sim_info._serialization_option = sims.sim_info_types.SimSerializationOption.OPEN_STREETS
                         sim_info._serialization_option = situation_manager.get_sim_serialization_option(
                             sim)
                 else:
                     sim_info._serialization_option = situation_manager.get_sim_serialization_option(
                         sim)
             sim_info.save_sim()
Esempio n. 45
0
def toggle_initial_story_progression(enable: bool = None, _connection=None):
    current_zone = services.current_zone()
    if current_zone is None:
        return False
    story_progression_service = current_zone.story_progression_service
    if story_progression_service is None:
        return False
    if enable is None:
        enable = not story_progression_service.is_story_progression_flag_enabled(
            story_progression.StoryProgressionFlags.ALLOW_INITIAL_POPULATION)
    if enable:
        story_progression_service.enable_story_progression_flag(
            story_progression.StoryProgressionFlags.ALLOW_INITIAL_POPULATION)
        sims4.commands.output('Initial Population has been enabled',
                              _connection)
    else:
        story_progression_service.disable_story_progression_flag(
            story_progression.StoryProgressionFlags.ALLOW_INITIAL_POPULATION)
        sims4.commands.output('Initial Population has been disabled',
                              _connection)
    return True
Esempio n. 46
0
def ShowPresetConfirmDialog(
        callback: typing.Callable[[ui_dialog.UiDialog], None]) -> None:
    if services.current_zone() is None:
        Debug.Log("Tried to show setting dialog before a zone was loaded.\n" +
                  str.join("", traceback.format_stack()),
                  This.Mod.Namespace,
                  Debug.LogLevels.Warning,
                  group=This.Mod.Namespace,
                  owner=__name__)
        return

    dialogArguments = {
        "title": PresetConfirmDialogTitle.GetCallableLocalizationString(),
        "text": PresetConfirmDialogText.GetCallableLocalizationString(),
        "text_ok":
        PresetConfirmDialogYesButton.GetCallableLocalizationString(),
        "text_cancel":
        PresetConfirmDialogNoButton.GetCallableLocalizationString()
    }

    Dialogs.ShowOkCancelDialog(callback=callback, **dialogArguments)
 def load(self, message):
     data = message.Extensions[protocols.PersistableInventoryItemComponent.persistable_data]
     if data.owner_id != 0:
         self._last_inventory_owner = services.object_manager().get(data.owner_id)
     else:
         self._last_inventory_owner = None
     if data.inventory_type == 0:
         return
     if data.inventory_type in InventoryType.values:
         self._current_inventory_type = InventoryType(data.inventory_type)
         if self._current_inventory_type in UNIQUE_OBJECT_INVENTORY_TYPES:
             inv = self._last_inventory_owner.inventory_component if self._last_inventory_owner is not None else None
             logger.assert_log(inv is not None, 'Loading object {} in a unique object inventory but missing inventory owner object.', self.owner, owner='tingyul')
         else:
             lot = services.current_zone().lot
             inv = lot.get_object_inventory(self._current_inventory_type)
             if inv is None:
                 inv = lot.create_object_inventory(self._current_inventory_type)
             inv._insert_item(self.owner, use_overflow=False, call_add=False, object_with_inventory=self._last_inventory_owner, try_find_matching_item=False)
         self._apply_inventory_effects(inv)
     self._stack_count = data.stack_count
Esempio n. 48
0
 def _try_to_be_invited_in(self):
     owner_household = services.household_manager().get(services.current_zone().lot.owner_household_id)
     resolver = self.get_resolver()
     if owner_household is None:
         dialog = self._nobody_home_failure_notification(self.sim, resolver)
         dialog.show_dialog()
         return
     owner_household_sims = tuple(owner_household.instanced_sims_gen())
     if not owner_household_sims:
         dialog = self._nobody_home_failure_notification(self.sim, resolver)
         dialog.show_dialog()
         return
     for target_sim in owner_household_sims:
         relationship_resolver = DoubleSimResolver(self.sim.sim_info, target_sim.sim_info)
         while relationship_resolver(self._relationship_test):
             dialog = self._success_notification(self.sim, resolver)
             dialog.show_dialog()
             services.get_zone_situation_manager().make_waiting_player_greeted(self.sim)
             return
     dialog = self._bad_relationship_failure_notification(self.sim, resolver)
     dialog.show_dialog()
Esempio n. 49
0
 def get_lot_tuning(cls):
     current_zone = services.current_zone()
     lot = current_zone.lot
     if lot is None:
         logger.warn('Attempting to get LotTuning when the current zone does not have a lot.', owner='manus')
         return
     (world_description_id, lot_description_id) = services.get_world_and_lot_description_id_from_zone_id(current_zone.id)
     lot_tuning = cls.LOT_TO_LOTTUNING_MAP.get(lot_description_id)
     if lot_tuning is not None:
         return lot_tuning
     lot_tuning = cls.STREET_TO_LOTTUNING_MAP.get(world_description_id, None)
     if lot_tuning is not None:
         return lot_tuning
     neighborhood_id = current_zone.neighborhood_id
     if neighborhood_id == 0:
         logger.warn('Attempting to get LotTuning when the current zone does not have a neighborhood.', owner='manus')
         return
     neighborhood_proto_buff = services.get_persistence_service().get_neighborhood_proto_buff(neighborhood_id)
     region_id = neighborhood_proto_buff.region_id
     lot_tuning = cls.REGION_TO_LOTTUNING_MAP.get(region_id, None)
     return lot_tuning
Esempio n. 50
0
 def on_enter(self):
     super().on_enter()
     zone = services.current_zone()
     zone_spin_up_service = zone.zone_spin_up_service
     zone.venue_service.setup_special_event_alarm()
     zone.ambient_service.begin_walkbys()
     client = zone_spin_up_service._client_connect_data.client
     if client is not None:
         with telemetry_helper.begin_hook(
                 zone_telemetry_writer,
                 TELEMETRY_HOOK_ZONE_LOAD,
                 household=client.household) as hook:
             (player_sims, npc_sims
              ) = services.sim_info_manager().get_player_npc_sim_count()
             hook.write_int(TELEMETRY_FIELD_PLAYER_COUNT, player_sims)
             hook.write_int(TELEMETRY_FIELD_NPC_COUNT, npc_sims)
     services.get_persistence_service().try_send_once_per_session_telemetry(
     )
     client.household.telemetry_tracker.initialize_alarms()
     zone_spin_up_service.apply_save_lock()
     return _ZoneSpinUpStateResult.DONE
Esempio n. 51
0
 def _test(cls, target, context, **kwargs):
     sim = context.sim
     test_result = super()._test(target, context, **kwargs)
     if not test_result:
         return test_result
     if target is not None and target is not sim:
         return TestResult(False,
                           'Self Interactions cannot target other Sims.')
     if sim.sim_info.is_npc or context.source == InteractionContext.SOURCE_AUTONOMY:
         return TestResult(False,
                           'Selectable Sims cannot go home autonomously.')
     test_result = cls.travel_test(context)
     if not test_result:
         return test_result
     zone = services.current_zone()
     home_zone_id = sim.household.home_zone_id
     if zone.id == home_zone_id and sim.intended_position_on_active_lot:
         return TestResult(
             False,
             'Selectable Sims cannot go home if they are already at home.')
     return TestResult.TRUE
Esempio n. 52
0
 def __init__(self,
              interaction,
              participant_type,
              distance_to_participant,
              tag_set,
              lot_id,
              zone_id,
              routing_surface=None):
     super().__init__(lot_id, zone_id, routing_surface=routing_surface)
     self.interaction = interaction
     self.participant_type = participant_type
     self.distance_to_participant = distance_to_participant
     self.obj_def_guid = 0
     self.spawn_point_id = DynamicInteractionSpawnPoint.get_next_id()
     self._tags = tag_set
     if routing_surface is None:
         self._routing_surface = routing.SurfaceIdentifier(
             services.current_zone().id, 0, routing.SURFACETYPE_WORLD)
     self.location = None
     self.spawn_index = 0
     self._valid_slots = 1
Esempio n. 53
0
 def _gather_route_events(self, path, **kwargs):
     owner = self.owner
     if owner.is_sim:
         interaction = owner.transition_controller.interaction if owner.transition_controller is not None else None
         if interaction is not None and interaction.is_super:
             interaction.provide_route_events(self._route_event_context, owner, path, **kwargs)
         owner.Buffs.provide_route_events_from_buffs(self._route_event_context, owner, path, **kwargs)
     broadcaster_service = services.current_zone().broadcaster_service
     broadcaster_service.provide_route_events(self._route_event_context, owner, path, **kwargs)
     if owner.weather_aware_component is not None:
         owner.weather_aware_component.provide_route_events(self._route_event_context, owner, path, **kwargs)
     if self._route_event_provider_requests is not None:
         for request in self._route_event_provider_requests:
             request.provide_route_events(self._route_event_context, owner, path, **kwargs)
     object_manager = services.object_manager(owner.zone_id)
     if object_manager is not None:
         for node in path.nodes:
             if node.portal_object_id != 0:
                 portal_object = object_manager.get(node.portal_object_id)
                 if portal_object is not None:
                     portal_object.provide_route_events(node.portal_id, self._route_event_context, owner, path, node=node, **kwargs)
def archive_live_drag(op_or_command,
                      message_type,
                      location_from,
                      location_to,
                      live_drag_object=None,
                      live_drag_object_id: int = 0,
                      live_drag_target=None):
    definition_id = 0
    stack_id = 0
    stack_count = 1
    can_live_drag = False
    current_inventory = None
    if live_drag_object is None:
        live_drag_object = services.current_zone().find_object(
            live_drag_object_id)
    if live_drag_object is not None:
        definition_id = live_drag_object.definition.id
        live_drag_component = live_drag_object.live_drag_component
        can_live_drag = live_drag_component.can_live_drag
        inventoryitem_component = live_drag_object.inventoryitem_component
        stack_count = live_drag_object.stack_count()
        if inventoryitem_component is not None:
            stack_id = inventoryitem_component.get_stack_id()
            current_inventory = inventoryitem_component.get_inventory()
    entry = {
        'live_drag_id': _live_drag_index(),
        'live_drag_operation': str(op_or_command),
        'live_drag_message_type': message_type,
        'live_drag_from_where': str(location_from),
        'live_drag_to_where': str(location_to),
        'live_drag_object': gsi_utils.format_object_name(live_drag_object),
        'live_drag_object_id': live_drag_object_id,
        'live_drag_definition_id': definition_id,
        'live_drag_target': gsi_utils.format_object_name(live_drag_target),
        'live_drag_status': str(can_live_drag),
        'live_drag_object_inventory': str(current_inventory),
        'live_drag_stack_id': stack_id,
        'live_drag_stack_count': stack_count
    }
    live_drag_archiver.archive(data=entry)
Esempio n. 55
0
def _check_send_baby_to_day_care(household, travel_sim_infos, from_zone_id):
    if household.is_npc_household:
        return
    if not household.number_of_babies:
        return
    message_owner_info = None
    curent_zone = services.current_zone()
    for sim_info in household.teen_or_older_info_gen():
        while sim_info.zone_id == household.home_zone_id:
            if sim_info.zone_id != curent_zone.id:
                if not sim_info.career_tracker.currently_at_work:
                    return
                    sim = sim_info.get_sim_instance()
                    if sim is not None and not sim.is_hidden():
                        return
            else:
                sim = sim_info.get_sim_instance()
                if sim is not None and not sim.is_hidden():
                    return
    if curent_zone.id == from_zone_id:
        client = services.client_manager().get_client_by_household(household)
        if client is not None:
            message_owner_info = client.active_sim.sim_info
        obj_mgr = services.object_manager(curent_zone.id)
        for baby_info in household.baby_info_gen():
            bassinet = obj_mgr.get(baby_info.sim_id)
            while bassinet is not None:
                bassinet.empty_baby_state()
    else:
        message_owner_info = sim_info
    if message_owner_info is None:
        return
    if household.number_of_babies == 1:
        dialog = Baby.SEND_BABY_TO_DAYCARE_NOTIFICATION_SINGLE_BABY(
            message_owner_info,
            SingleSimResolver(next(household.baby_info_gen())))
    else:
        dialog = Baby.SEND_BABY_TO_DAYCARE_NOTIFICATION_MULTIPLE_BABIES(
            message_owner_info, SingleSimResolver(message_owner_info))
    dialog.show_dialog()
 def distribute_neighborhood_update(self):
     street_service = services.street_service()
     street = street_service.get_street(
         self) if street_service is not None else None
     if street is None:
         return
     (neighborhood_proto,
      street_info_data) = street_service.get_neighborhood_proto(street)
     if neighborhood_proto is None or street_info_data is None:
         return
     current_zone = services.current_zone()
     if current_zone is None:
         return
     persistence_service = services.get_persistence_service()
     lot_data = persistence_service.get_lot_proto_buff(
         current_zone.lot.lot_id)
     lot = services.active_lot()
     lot_footprint_value = lot.commodity_tracker.get_value(
         EcoFootprintTunables.LOT_FOOTPRINT)
     lot_data.eco_footprint_state = EcoFootprintTunables.eco_footprint_value_to_state(
         lot_footprint_value)
     street_footprint_stat = self.get_street_footprint()
     street_footprint_value = street_footprint_stat.get_value()
     street_info_data.eco_footprint_delta = street_footprint_stat.convergence_value - street_footprint_value
     street_info_data.eco_footprint_state = self._curr_state_type
     if self._curr_state_type == EcoFootprintStateType.GREEN:
         min = street_footprint_stat.min_value
         max = EcoFootprintTunables.ECO_FOOTPRINT_STATE_DATA.green_threshold
     elif self._curr_state_type == EcoFootprintStateType.NEUTRAL:
         min = EcoFootprintTunables.ECO_FOOTPRINT_STATE_DATA.green_threshold
         max = EcoFootprintTunables.ECO_FOOTPRINT_STATE_DATA.industrial_threshold
     else:
         min = EcoFootprintTunables.ECO_FOOTPRINT_STATE_DATA.industrial_threshold
         max = street_footprint_stat.max_value
     if max - min is not 0:
         street_info_data.normalized_eco_footprint_state_progress = (
             street_footprint_value - min) / (max - min)
     distributor = Distributor.instance()
     distributor.add_event(Consts_pb2.MSG_NS_NEIGHBORHOOD_UPDATE,
                           neighborhood_proto)
Esempio n. 57
0
 def push_guest_take_seat_interaction(self, guest, zone_director):
     (seat_id, _) = zone_director.get_sims_seat(guest)
     if seat_id is None:
         log_host_action(
             'During Show To Table Seat',
             "Failed - couldn't find a seat for the Sim {}.".format(guest))
         return
     seat = services.current_zone().object_manager.get(seat_id)
     if seat is None:
         log_host_action(
             'During Show To Table Seat',
             "Failed - couldn't find a seat for the Sim {}.".format(guest))
         return
     context = InteractionContext(guest, InteractionContext.SOURCE_SCRIPT,
                                  Priority.High)
     if not guest.push_super_affordance(self.guest_take_seat_interaction,
                                        seat, context):
         log_host_action('During Show To Table State',
                         'Failed to Push Guest Interaction')
     else:
         log_host_action('During Show To Table State',
                         'Push Guest Interaction on {}'.format(guest))
Esempio n. 58
0
def gsi_create_object(def_id,
                      x_pos: float = None,
                      y_pos: float = None,
                      z_pos: float = None,
                      _connection=None):
    obj = objects.system.create_object(def_id)
    if x_pos is None or y_pos is None or z_pos is None:
        start_pos = services.current_zone().lot.center
    else:
        start_pos = sims4.math.Vector3(x_pos, y_pos, z_pos)
    if obj is not None:
        search_flags = placement.FGLSearchFlagsDefault
        fgl_context = placement.FindGoodLocationContext(
            starting_position=start_pos,
            object_id=obj.id,
            max_distance=100,
            search_flags=search_flags,
            object_footprints=(obj.get_footprint(), ))
        (position, orientation) = placement.find_good_location(fgl_context)
        obj.transform = sims4.math.Transform(position, orientation)
        return True
    return False
def street_civic_policy_show_community_board(
        current_street: bool = True,
        opt_sim: OptionalSimInfoParam = None,
        opt_target_id: int = 0,
        _connection=None):
    street_service = services.street_service()
    if street_service is None:
        sims4.commands.automation_output('Pack not loaded', _connection)
        sims4.commands.cheat_output('Pack not loaded', _connection)
        return False
    sim_info = get_optional_target(opt_sim,
                                   _connection,
                                   target_type=OptionalSimInfoParam)
    if current_street:
        street = services.current_zone().street
    else:
        world_id = sim_info.household.get_home_world_id()
        street = world.street.get_street_instance_from_world_id(world_id)
    provider = street_service.get_provider(street)
    if provider is not None:
        op = CommunityBoardDialog(provider, sim_info, opt_target_id)
        Distributor.instance().add_op_with_no_owner(op)
Esempio n. 60
0
 def update_zone_object_locators(self):
     current_zone = services.current_zone()
     current_zone_id = services.current_zone_id()
     object_manager = current_zone.object_manager
     current_open_street_id = current_zone.open_street_id
     for locator in list(self._object_locators):
         if locator.zone_id != current_zone_id:
             continue
         obj = object_manager.get(locator.object_id)
         if obj is not None:
             locator.open_street_id = ObjectLostAndFoundService.STREET_UNKNOWN if current_zone.lot.is_position_on_lot(
                 obj.position) else current_open_street_id
             object_list = FileSerialization_pb2.ObjectList()
             open_street_object_locators = FileSerialization_pb2.ObjectList(
             )
             locator.object_data = ObjectManager.save_game_object(
                 obj, object_list, open_street_object_locators)
             if locator.object_data is None:
                 self.remove_object(locator.object_id)
                 self.remove_object(locator.object_id)
         else:
             self.remove_object(locator.object_id)