def __init__(self, path, preload=False, download=False):
        """Add the file to downloadables if download is True.

        :param str path:
            Path to file to use.
        :param bool preload:
            If ``True`` the file will be pre-loaded.
        :param bool download:
            If ``True`` the file will be added to the ``downloadables`` string
            table.
        """
        # Save the path that should be precached
        self._path = path

        # Save whether the the file should be preloaded
        self._preload = preload

        # Is the map loaded?
        if global_vars.map_name:

            # Precache the instance
            self._precache()

        # Register the server_spawn event to precache every map change
        event_manager.register_for_event('server_spawn', self._server_spawn)

        # Should the path be added to the downloadables?
        if download:

            # Add the path to the downloadables
            self._downloads = Downloadables()
            self._downloads.add(self._path)
예제 #2
0
    def __init__(
            self, sample, index=SOUND_FROM_WORLD, volume=VOL_NORM,
            attenuation=Attenuation.NONE, channel=Channel.AUTO,
            flags=SoundFlags.NO_FLAGS, pitch=Pitch.NORMAL,
            origin=NULL_VECTOR, direction=NULL_VECTOR, origins=(),
            update_positions=True, sound_time=0.0,
            speaker_entity=INVALID_ENTITY_INDEX, download=False):
        """Store all the given attributes and set the module for unloading."""
        # Set sample as a private attribute, since it should never change
        # Added replacing \ with / in paths for comformity
        self._sample = sample.replace('\\', '/')

        # Set all the base attributes
        self.index = index
        self.volume = volume
        self.attenuation = attenuation
        self.channel = channel
        self.flags = flags
        self.pitch = pitch
        self.origin = origin
        self.direction = direction
        self.origins = origins
        self.update_positions = update_positions
        self.sound_time = sound_time
        self.speaker_entity = speaker_entity

        # Should the sample be downloaded by clients?
        if download:

            # Add the sample to Downloadables
            self._downloads = Downloadables()
            self._downloads.add('sound/{0}'.format(self.sample))
예제 #3
0
def setDL():
    downloadables = Downloadables()
    with open(DOWNLOADLIST_PATH) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            downloadables.add(line)
예제 #4
0
def load_downloadables(filepath):
    downloadables = Downloadables()

    with open(filepath) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            downloadables.add(line)

    return downloadables
예제 #5
0
class downloads:
	def __init__(self, db):
		self.db = db
		self.downloads = Downloadables()

	def add(self, file):
		self.downloads.add(file)
		msg('INFO', 'added download {}'.format(file))

### list of available callbacks
## player_is_spawned
# When a player is definately read to spawn (e.G. after choosing class, weapon, ... and is ready to play) needed for make sure that a player choose a weapon and class before starts to play / getting attacked
예제 #6
0
def load_downloadables(file_name):
    file_path = DOWNLOADLISTS_PATH / file_name
    downloadables = Downloadables()

    with open(file_path) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            downloadables.add(line)

    return downloadables
예제 #7
0
    def __init__(self, path, preload=False, download=False):
        """Add the file to downloadables if download is True."""
        # Save the path that should be precached
        self._path = path

        # Save whether the the file should be preloaded
        self._preload = preload

        # Get the calling module
        caller = getmodule(stack()[1][0])

        # Set the _calling_module attribute for the instance
        self._calling_module = caller.__name__

        # Is the map loaded?
        if global_vars.map_name:
            # Precache the instance
            self._precache()

        # Register the server_spawn event to precache every map change
        event_manager.register_for_event('server_spawn', self._server_spawn)

        # Should the path be added to the downloadables?
        if download:

            # Add the path to the downloadables
            self._downloads = Downloadables()
            self._downloads.add(self._path)
예제 #8
0
    def __init__(
            self, sample, index=SOUND_FROM_WORLD, volume=VOL_NORM,
            attenuation=Attenuation.NONE, channel=Channel.AUTO,
            flags=SoundFlags.NO_FLAGS, pitch=Pitch.NORMAL,
            origin=NULL_VECTOR, direction=NULL_VECTOR, origins=(),
            update_positions=True, sound_time=0.0,
            speaker_entity=INVALID_ENTITY_INDEX, download=False):
        """Store all the given attributes and set the module for unloading."""
        # Set sample as a private attribute, since it should never change
        # Added replacing \ with / in paths for comformity
        self._sample = sample.replace('\\', '/')

        # Set all the base attributes
        self.index = index
        self.volume = volume
        self.attenuation = attenuation
        self.channel = channel
        self.flags = flags
        self.pitch = pitch
        self.origin = origin
        self.direction = direction
        self.origins = origins
        self.update_positions = update_positions
        self.sound_time = sound_time
        self.speaker_entity = speaker_entity

        # Should the sample be downloaded by clients?
        if download:

            # Add the sample to Downloadables
            self._downloads = Downloadables()
            self._downloads.add('sound/{0}'.format(self.sample))
    def __init__(self, path, preload=False, download=False):
        """Add the file to downloadables if download is True.

        :param str path:
            Path to file to use.
        :param bool preload:
            If ``True`` the file will be pre-loaded.
        :param bool download:
            If ``True`` the file will be added to the ``downloadables`` string
            table.
        """
        # Save the path that should be precached
        self._path = path

        # Save whether the the file should be preloaded
        self._preload = preload

        # Is the map loaded?
        if global_vars.map_name:

            # Precache the instance
            self._precache()

        # Register the server_spawn event to precache every map change
        event_manager.register_for_event('server_spawn', self._server_spawn)

        # Should the path be added to the downloadables?
        if download:

            # Add the path to the downloadables
            self._downloads = Downloadables()
            self._downloads.add(self._path)
예제 #10
0
# Current mc_timelimit value will be multiplied by this fallback value
# and then applied to mc_scheduled_vote_time.
# Take a look at schedule_vote()
INVALID_SCHEDULED_VOTE_TIME_FALLBACK_VALUE = 0.33

# We will add extra seconds after vote ends to prevent
# instant level changing when the vote ends
EXTRA_SECONDS_AFTER_VOTE = 5.0


cvar_mapcyclefile = ConVar('mapcyclefile')
cvar_mp_timelimit = ConVar('mp_timelimit')

# While sound cvars may be changed in real time, we only detect
# files to upload to players on plugin load
downloadables = Downloadables()

with open(str(DOWNLOADLIST)) as f:   # TODO: Do we need str() here?
    for line in f:
        line = line.strip()
        if not line:
            continue
        downloadables.add(line)

log = LogManager(info.basename, cvar_logging_level, cvar_logging_areas)


class CorruptJSONFile(Exception):
    """Raised when mapcycle.json doesn't contain a list."""
    pass
예제 #11
0
## IMPORTS

from engines.precache import Model
from stringtables.downloads import Downloadables
from vmchanger import viewmodel_manager, worldmodel_manager

## GLOBALS

downloadables = Downloadables()
downloadables.add_directory('models/weapons/futuristicgrenades')

decoy_view_model = Model('models/weapons/futuristicgrenades/v_eq_decoy.mdl')
decoy_world_model = Model('models/weapons/futuristicgrenades/w_eq_decoy.mdl')

##

def load():
	viewmodel_manager.add_weapon_remodel('weapon_decoy', decoy_view_model)
	worldmodel_manager.add_weapon_remodel('decoy_projectile', decoy_world_model)
	viewmodel_manager.add_weapon_remodel('weapon_flashbang', decoy_view_model)
	worldmodel_manager.add_weapon_remodel('flashbang_projectile', decoy_world_model)

def unload():
	del viewmodel_manager['weapon_decoy']
	del worldmodel_manager['decoy_projectile']
	del viewmodel_manager['weapon_flashbang']
	del worldmodel_manager['flashbang_projectile']
class _PrecacheBase(AutoUnload):
    """Base precache class used to interact with a specific object."""

    # Set the base _downloads attribute to know whether
    #   or not the path was added to the downloadables
    _downloads = None

    def __init__(self, path, preload=False, download=False):
        """Add the file to downloadables if download is True.

        :param str path:
            Path to file to use.
        :param bool preload:
            If ``True`` the file will be pre-loaded.
        :param bool download:
            If ``True`` the file will be added to the ``downloadables`` string
            table.
        """
        # Save the path that should be precached
        self._path = path

        # Save whether the the file should be preloaded
        self._preload = preload

        # Is the map loaded?
        if global_vars.map_name:

            # Precache the instance
            self._precache()

        # Register the server_spawn event to precache every map change
        event_manager.register_for_event('server_spawn', self._server_spawn)

        # Should the path be added to the downloadables?
        if download:

            # Add the path to the downloadables
            self._downloads = Downloadables()
            self._downloads.add(self._path)

    @property
    def index(self):
        """Return the precached index of the object.

        :rtype: int
        """
        # Get the index of the object in its precache table
        index = string_tables[self.precache_table][self._path]

        # Is the object precached?
        if index != INVALID_STRING_INDEX:

            # Return the precache index
            return index

        # If the object was not precached, raise an error
        raise PrecacheError(
            '"{0}" was not able to be precached due to the "{1}" table '
            'reaching its limit.'.format(self._path, self.precache_table))

    @property
    def path(self):
        """Return the path.

        :rtype: str
        """
        return self._path

    def _precache(self):
        """Precache the file."""
        raise NotImplementedError('Must be implemented by a subclass.')

    def _server_spawn(self, game_event):
        """Precache the object on map change."""
        self._precache()

    def _unload_instance(self):
        """Remove from the downloads list and unregister server_spawn."""
        # Remove the path from the downloads list
        with suppress(AttributeError):
            self._downloads._unload_instance()

        # Unregister the server_spawn event
        event_manager.unregister_for_event('server_spawn', self._server_spawn)

    @property
    def precache_table(self):
        """Return the name of the precache table.

        :rtype: str
        """
        raise NotImplementedError('No precache_table defined for class.')
def set_download() -> None:
    downloadable = Downloadables()
    for sound in DOWNLOAD_TABLE:
        downloadable.add(sound)
예제 #14
0
class Sound(AutoUnload):

    """Class used to interact with a specific sound file."""

    # Set the base _downloads attribute to know whether
    #   or not the sample was added to the downloadables
    _downloads = None

    def __init__(
            self, recipients, index, sample, volume=VOL_NORM,
            attenuation=Attenuations.NONE, channel=Channels.AUTO,
            flags=0, pitch=PitchTypes.NORMAL, origin=NULL_VECTOR,
            direction=NULL_VECTOR, origins=(), update_positions=True,
            sound_time=0.0, speaker_entity=-1, download=False):
        """Store all the given attributes and set the module for unloading."""
        # Set sample as a private attribute, since it should never change
        # Added replacing \ with / in paths for comformity
        self._sample = sample.replace('\\', '/')

        # Set all the base attributes
        self.recipients = recipients
        self.index = index
        self.volume = volume
        self.attenuation = attenuation
        self.channel = channel
        self.flags = flags
        self.pitch = pitch
        self.origin = origin
        self.direction = direction
        self.origins = origins
        self.update_positions = update_positions
        self.sound_time = sound_time
        self.speaker_entity = speaker_entity

        # Should the sample be downloaded by clients?
        if download:

            # Add the sample to Downloadables
            self._downloads = Downloadables()
            self._downloads.add('sound/{0}'.format(self.sample))

    def play(self, *recipients):
        """Play the sound."""
        # Get the recipients to play the sound to
        recipients = RecipientFilter(*(recipients or self.recipients))

        # Is the sound precached?
        if not self.is_precached:

            # Precache the sound
            self.precache()

        # Play the sound
        engine_sound.emit_sound(
            recipients, self.index, self.channel, self.sample,
            self.volume, self.attenuation, self.flags, self.pitch,
            self.origin, self.direction, self.origins,
            self.update_positions, self.sound_time, self.speaker_entity)

    def stop(self, index=None, channel=None):
        """Stop a sound from being played."""
        # Was an index passed in?
        if index is None:

            # Use the instance's index
            index = self.index

        # Was a channel passed in?
        if channel is None:

            # Use the instance's index
            channel = self.channel

        # Stop the sound
        engine_sound.stop_sound(index, channel, self.sample)

    def precache(self):
        """Precache the sample."""
        engine_sound.precache_sound(self.sample)

    @property
    def is_precached(self):
        """Return whether or not the sample is precached."""
        return self.sample in string_tables.soundprecache

    @property
    def sample(self):
        """Return the filename of the Sound instance."""
        return self._sample

    @property
    def duration(self):
        """Return the duration of the sample."""
        return engine_sound.get_sound_duration(self.sample)

    def _unload_instance(self):
        """Remove the sample from the downloads list."""
        if self._downloads is not None:
            self._downloads._unload_instance()
예제 #15
0
    def __init__(self,
                 sample,
                 index=SOUND_FROM_WORLD,
                 volume=VOL_NORM,
                 attenuation=Attenuation.NONE,
                 channel=Channel.AUTO,
                 flags=SoundFlags.NO_FLAGS,
                 pitch=Pitch.NORMAL,
                 origin=NULL_VECTOR,
                 direction=NULL_VECTOR,
                 origins=(),
                 update_positions=True,
                 sound_time=0.0,
                 speaker_entity=INVALID_ENTITY_INDEX,
                 download=False):
        """Store all the given attributes and set the module for unloading.

        :param str sample:
            Path to the sound file.
        :param int index:
            An entity index to play the sound from. Use
            :data:`SOUND_FROM_WORLD` if you want to play the sound from the
            world.
        :param float volume:
            Volume to play the sound with.
        :param Attenuation attenuation:
            Define how the sound attenuates.
        :param Channel channel:
            Channel to use when playing the sound.
        :param SoundFlags flags:
        :param Pitch pitch:
            Pitch of the sound.
        :param Vector origin:
            Location to play the sound from.
        :param Vector direction:
            Direction to play the sound.
        :param tuple origins:
            Locations to play the sound from.
        :param bool update_positions:
        :param float sound_time:
        :param int speaker_entity:
        :param bool download:
            If ``True`` the sound file will be added to the ``downloadables``
            list.
        """
        # Set sample as a private attribute, since it should never change
        # Added replacing \ with / in paths for comformity
        self._sample = sample.replace('\\', '/')

        self._duration = None

        # Set all the base attributes
        self.index = index
        self.volume = volume
        self.attenuation = attenuation
        self.channel = channel
        self.flags = flags
        self.pitch = pitch
        self.origin = origin
        self.direction = direction
        self.origins = origins
        self.update_positions = update_positions
        self.sound_time = sound_time
        self.speaker_entity = speaker_entity

        # Should the sample be downloaded by clients?
        if download:

            # Add the sample to Downloadables
            self._downloads = Downloadables()
            self._downloads.add(self.relative_path)
예제 #16
0
class _BaseSound(AutoUnload):
    """Base class for sound classes."""

    # Set the base _downloads attribute to know whether
    #   or not the sample was added to the downloadables
    _downloads = None

    def __init__(
            self, sample, index=SOUND_FROM_WORLD, volume=VOL_NORM,
            attenuation=Attenuation.NONE, channel=Channel.AUTO,
            flags=SoundFlags.NO_FLAGS, pitch=Pitch.NORMAL,
            origin=NULL_VECTOR, direction=NULL_VECTOR, origins=(),
            update_positions=True, sound_time=0.0,
            speaker_entity=INVALID_ENTITY_INDEX, download=False):
        """Store all the given attributes and set the module for unloading."""
        # Set sample as a private attribute, since it should never change
        # Added replacing \ with / in paths for comformity
        self._sample = sample.replace('\\', '/')

        # Set all the base attributes
        self.index = index
        self.volume = volume
        self.attenuation = attenuation
        self.channel = channel
        self.flags = flags
        self.pitch = pitch
        self.origin = origin
        self.direction = direction
        self.origins = origins
        self.update_positions = update_positions
        self.sound_time = sound_time
        self.speaker_entity = speaker_entity

        # Should the sample be downloaded by clients?
        if download:

            # Add the sample to Downloadables
            self._downloads = Downloadables()
            self._downloads.add('sound/{0}'.format(self.sample))

    def play(self, *recipients):
        """Play the sound."""
        # Get the recipients to play the sound to
        recipients = RecipientFilter(*recipients)

        # Is the sound precached?
        if not self.is_precached:

            # Precache the sound
            self.precache()

        # Play the sound
        self._play(recipients)

    def stop(self, index=None, channel=None):
        """Stop a sound from being played."""
        # Was an index passed in?
        if index is None:

            # Use the instance's index
            index = self.index

        # Was a channel passed in?
        if channel is None:

            # Use the instance's index
            channel = self.channel

        # Stop the sound
        self._stop(index, channel)

    def _play(self, recipients):
        """Play the sound (internal)."""
        raise NotImplementedError

    def _stop(self, index, channel):
        """Stop a sound from being played (internal)."""
        raise NotImplementedError

    def precache(self):
        """Precache the sample."""
        raise NotImplementedError

    @property
    def is_precached(self):
        """Return whether or not the sample is precached."""
        raise NotImplementedError

    @property
    def sample(self):
        """Return the filename of the Sound instance."""
        return self._sample

    @property
    def duration(self):
        """Return the duration of the sample."""
        return engine_sound.get_sound_duration(self.sample)

    def _unload_instance(self):
        """Remove the sample from the downloads list."""
        if self._downloads is not None:
            self._downloads._unload_instance()
예제 #17
0
from stringtables.downloads import Downloadables
from paths import GAME_PATH
from os import listdir
from os.path import isfile, join, isdir
from engines.precache import Model

downloads = Downloadables()

paths_to_add = [
    GAME_PATH + '/materials/sprites', GAME_PATH + '/materials/particle',
    GAME_PATH + '/materials/effects', GAME_PATH + '/sound/wcs'
]

for mypath in paths_to_add:
    if isdir(mypath):
        downloads.add_directory(mypath)
        for mypath in paths_to_add:
            if isdir(mypath):
                files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
                for x in files:
                    Model(x, True)
예제 #18
0
class Sound(AutoUnload):
    """Class used to interact with a specific sound file."""

    # Set the base _downloads attribute to know whether
    #   or not the sample was added to the downloadables
    _downloads = None

    def __init__(
            self, sample, index=SOUND_FROM_WORLD, volume=VOL_NORM,
            attenuation=Attenuation.NONE, channel=Channel.AUTO,
            flags=SoundFlags.NO_FLAGS, pitch=Pitch.NORMAL,
            origin=NULL_VECTOR, direction=NULL_VECTOR, origins=(),
            update_positions=True, sound_time=0.0,
            speaker_entity=INVALID_ENTITY_INDEX, download=False):
        """Store all the given attributes and set the module for unloading."""
        # Set sample as a private attribute, since it should never change
        # Added replacing \ with / in paths for comformity
        self._sample = sample.replace('\\', '/')

        # Set all the base attributes
        self.index = index
        self.volume = volume
        self.attenuation = attenuation
        self.channel = channel
        self.flags = flags
        self.pitch = pitch
        self.origin = origin
        self.direction = direction
        self.origins = origins
        self.update_positions = update_positions
        self.sound_time = sound_time
        self.speaker_entity = speaker_entity

        # Should the sample be downloaded by clients?
        if download:

            # Add the sample to Downloadables
            self._downloads = Downloadables()
            self._downloads.add('sound/{0}'.format(self.sample))

    def play(self, *recipients):
        """Play the sound."""
        # Get the recipients to play the sound to
        recipients = RecipientFilter(*recipients)

        # Is the sound precached?
        if not self.is_precached:

            # Precache the sound
            self.precache()

        # Play the sound
        engine_sound.emit_sound(
            recipients, self.index, self.channel, self.sample,
            self.volume, self.attenuation, self.flags, self.pitch,
            self.origin, self.direction, self.origins,
            self.update_positions, self.sound_time, self.speaker_entity)

    def stop(self, index=None, channel=None):
        """Stop a sound from being played."""
        # Was an index passed in?
        if index is None:

            # Use the instance's index
            index = self.index

        # Was a channel passed in?
        if channel is None:

            # Use the instance's index
            channel = self.channel

        # Stop the sound
        engine_sound.stop_sound(index, channel, self.sample)

    def precache(self):
        """Precache the sample."""
        engine_sound.precache_sound(self.sample)

    @property
    def is_precached(self):
        """Return whether or not the sample is precached."""
        return self.sample in string_tables.soundprecache

    @property
    def sample(self):
        """Return the filename of the Sound instance."""
        return self._sample

    @property
    def duration(self):
        """Return the duration of the sample."""
        return engine_tool.get_sound_duration_by_path(self.sample)

    def _unload_instance(self):
        """Remove the sample from the downloads list."""
        if self._downloads is not None:
            self._downloads._unload_instance()
예제 #19
0
class _BaseSound(WeakAutoUnload):
    """Base class for sound classes."""

    # Set the base _downloads attribute to know whether
    #   or not the sample was added to the downloadables
    _downloads = None

    def __init__(self,
                 sample,
                 index=SOUND_FROM_WORLD,
                 volume=VOL_NORM,
                 attenuation=Attenuation.NONE,
                 channel=Channel.AUTO,
                 flags=SoundFlags.NO_FLAGS,
                 pitch=Pitch.NORMAL,
                 origin=NULL_VECTOR,
                 direction=NULL_VECTOR,
                 origins=(),
                 update_positions=True,
                 sound_time=0.0,
                 speaker_entity=INVALID_ENTITY_INDEX,
                 download=False):
        """Store all the given attributes and set the module for unloading.

        :param str sample:
            Path to the sound file.
        :param int index:
            An entity index to play the sound from. Use
            :data:`SOUND_FROM_WORLD` if you want to play the sound from the
            world.
        :param float volume:
            Volume to play the sound with.
        :param Attenuation attenuation:
            Define how the sound attenuates.
        :param Channel channel:
            Channel to use when playing the sound.
        :param SoundFlags flags:
        :param Pitch pitch:
            Pitch of the sound.
        :param Vector origin:
            Location to play the sound from.
        :param Vector direction:
            Direction to play the sound.
        :param tuple origins:
            Locations to play the sound from.
        :param bool update_positions:
        :param float sound_time:
        :param int speaker_entity:
        :param bool download:
            If ``True`` the sound file will be added to the ``downloadables``
            list.
        """
        # Set sample as a private attribute, since it should never change
        # Added replacing \ with / in paths for comformity
        self._sample = sample.replace('\\', '/')

        self._duration = None

        # Set all the base attributes
        self.index = index
        self.volume = volume
        self.attenuation = attenuation
        self.channel = channel
        self.flags = flags
        self.pitch = pitch
        self.origin = origin
        self.direction = direction
        self.origins = origins
        self.update_positions = update_positions
        self.sound_time = sound_time
        self.speaker_entity = speaker_entity

        # Should the sample be downloaded by clients?
        if download:

            # Add the sample to Downloadables
            self._downloads = Downloadables()
            self._downloads.add(self.relative_path)

    def play(self, *recipients):
        """Play the sound.

        :param recipients:
            Players who will hear the sound.
        """
        # Done here to fix a cyclic import...
        from filters.recipients import RecipientFilter

        # Get the recipients to play the sound to
        recipients = RecipientFilter(*recipients)

        # Is the sound precached?
        if not self.is_precached:

            # Precache the sound
            self.precache()

        # Play the sound
        self._play(recipients)

    def stop(self, index=None, channel=None):
        """Stop a sound from being played."""
        # Was an index passed in?
        if index is None:

            # Use the instance's index
            index = self.index

        # Was a channel passed in?
        if channel is None:

            # Use the instance's index
            channel = self.channel

        # Stop the sound
        self._stop(index, channel)

    def _play(self, recipients):
        """Play the sound (internal)."""
        raise NotImplementedError

    def _stop(self, index, channel):
        """Stop a sound from being played (internal)."""
        raise NotImplementedError

    def precache(self):
        """Precache the sample."""
        raise NotImplementedError

    @property
    def is_precached(self):
        """Return whether or not the sample is precached."""
        raise NotImplementedError

    @property
    def sample(self):
        """Return the filename of the Sound instance.

        :rtype: str
        """
        return self._sample

    @property
    def extension(self):
        """Return the type of sound.

        :rtype: str
        """
        return self.full_path.ext[1:]

    @property
    def full_path(self):
        """Return the full path to the file.

        :rtype: path.Path
        """
        return GAME_PATH / 'sound' / self.sample

    @property
    def relative_path(self):
        """Return the relative path to the file.

        :rtype: str
        """
        return 'sound' + os.sep + self.sample

    @property
    def duration(self):
        """Return the duration of the sample.

        :rtype: float
        """
        if self._duration is not None:
            return self._duration

        with closing(SourceFile.open(self.relative_path, 'rb')) as f:
            if self.extension == 'ogg':
                value = oggvorbis.Open(f).info.length
            elif self.extension == 'mp3':
                value = mp3.Open(f).info.length
            elif self.extension == 'wav':
                with closing(wave.open(f)) as open_file:
                    value = open_file.getnframes() / open_file.getframerate()
            else:
                raise NotImplementedError(
                    'Sound extension "{extension}" is not supported.'.format(
                        extension=self.extension, ))

        self._duration = value
        return value

    def _unload_instance(self):
        """Remove the sample from the downloads list."""
        if self._downloads is not None:
            self._downloads._unload_instance()
예제 #20
0
    def __init__(
            self, sample, index=SOUND_FROM_WORLD, volume=VOL_NORM,
            attenuation=Attenuation.NONE, channel=Channel.AUTO,
            flags=SoundFlags.NO_FLAGS, pitch=Pitch.NORMAL,
            origin=NULL_VECTOR, direction=NULL_VECTOR, origins=(),
            update_positions=True, sound_time=0.0,
            speaker_entity=INVALID_ENTITY_INDEX, download=False):
        """Store all the given attributes and set the module for unloading.

        :param str sample:
            Path to the sound file.
        :param int index:
            An entity index to play the sound from. Use
            :data:`SOUND_FROM_WORLD` if you want to play the sound from the
            world.
        :param float volume:
            Volume to play the sound with.
        :param Attenuation attenuation:
            Define how the sound attenuates.
        :param Channel channel:
            Channel to use when playing the sound.
        :param SoundFlags flags:
        :param Pitch pitch:
            Pitch of the sound.
        :param Vector origin:
            Location to play the sound from.
        :param Vector direction:
            Direction to play the sound.
        :param tuple origins:
            Locations to play the sound from.
        :param bool update_positions:
        :param float sound_time:
        :param int speaker_entity:
        :param bool download:
            If ``True`` the sound file will be added to the ``downloadables``
            list.
        """
        # Set sample as a private attribute, since it should never change
        # Added replacing \ with / in paths for comformity
        self._sample = sample.replace('\\', '/')

        self._duration = None

        # Set all the base attributes
        self.index = index
        self.volume = volume
        self.attenuation = attenuation
        self.channel = channel
        self.flags = flags
        self.pitch = pitch
        self.origin = origin
        self.direction = direction
        self.origins = origins
        self.update_positions = update_positions
        self.sound_time = sound_time
        self.speaker_entity = speaker_entity

        # Should the sample be downloaded by clients?
        if download:

            # Add the sample to Downloadables
            self._downloads = Downloadables()
            self._downloads.add(self.relative_path)
예제 #21
0
class _BaseSound(AutoUnload):
    """Base class for sound classes."""

    # Set the base _downloads attribute to know whether
    #   or not the sample was added to the downloadables
    _downloads = None

    def __init__(
            self, sample, index=SOUND_FROM_WORLD, volume=VOL_NORM,
            attenuation=Attenuation.NONE, channel=Channel.AUTO,
            flags=SoundFlags.NO_FLAGS, pitch=Pitch.NORMAL,
            origin=NULL_VECTOR, direction=NULL_VECTOR, origins=(),
            update_positions=True, sound_time=0.0,
            speaker_entity=INVALID_ENTITY_INDEX, download=False):
        """Store all the given attributes and set the module for unloading.

        :param str sample:
            Path to the sound file.
        :param int index:
            An entity index to play the sound from. Use
            :data:`SOUND_FROM_WORLD` if you want to play the sound from the
            world.
        :param float volume:
            Volume to play the sound with.
        :param Attenuation attenuation:
            Define how the sound attenuates.
        :param Channel channel:
            Channel to use when playing the sound.
        :param SoundFlags flags:
        :param Pitch pitch:
            Pitch of the sound.
        :param Vector origin:
            Location to play the sound from.
        :param Vector direction:
            Direction to play the sound.
        :param tuple origins:
            Locations to play the sound from.
        :param bool update_positions:
        :param float sound_time:
        :param int speaker_entity:
        :param bool download:
            If ``True`` the sound file will be added to the ``downloadables``
            list.
        """
        # Set sample as a private attribute, since it should never change
        # Added replacing \ with / in paths for comformity
        self._sample = sample.replace('\\', '/')

        self._duration = None

        # Set all the base attributes
        self.index = index
        self.volume = volume
        self.attenuation = attenuation
        self.channel = channel
        self.flags = flags
        self.pitch = pitch
        self.origin = origin
        self.direction = direction
        self.origins = origins
        self.update_positions = update_positions
        self.sound_time = sound_time
        self.speaker_entity = speaker_entity

        # Should the sample be downloaded by clients?
        if download:

            # Add the sample to Downloadables
            self._downloads = Downloadables()
            self._downloads.add(self.relative_path)

    def play(self, *recipients):
        """Play the sound.

        :param recipients:
            Players who will hear the sound.
        """
        # Done here to fix a cyclic import...
        from filters.recipients import RecipientFilter

        # Get the recipients to play the sound to
        recipients = RecipientFilter(*recipients)

        # Is the sound precached?
        if not self.is_precached:

            # Precache the sound
            self.precache()

        # Play the sound
        self._play(recipients)

    def stop(self, index=None, channel=None):
        """Stop a sound from being played."""
        # Was an index passed in?
        if index is None:

            # Use the instance's index
            index = self.index

        # Was a channel passed in?
        if channel is None:

            # Use the instance's index
            channel = self.channel

        # Stop the sound
        self._stop(index, channel)

    def _play(self, recipients):
        """Play the sound (internal)."""
        raise NotImplementedError

    def _stop(self, index, channel):
        """Stop a sound from being played (internal)."""
        raise NotImplementedError

    def precache(self):
        """Precache the sample."""
        raise NotImplementedError

    @property
    def is_precached(self):
        """Return whether or not the sample is precached."""
        raise NotImplementedError

    @property
    def sample(self):
        """Return the filename of the Sound instance.

        :rtype: str
        """
        return self._sample

    @property
    def extension(self):
        """Return the type of sound.

        :rtype: str
        """
        return self.full_path.ext[1:]

    @property
    def full_path(self):
        """Return the full path to the file.

        :rtype: path.Path
        """
        return GAME_PATH / 'sound' / self.sample

    @property
    def relative_path(self):
        """Return the relative path to the file.

        :rtype: str
        """
        return 'sound' + os.sep + self.sample

    @property
    def duration(self):
        """Return the duration of the sample.

        :rtype: float
        """
        if self._duration is not None:
            return self._duration

        with closing(SourceFile.open(self.relative_path, 'rb')) as f:
            if self.extension == 'ogg':
                value = oggvorbis.Open(f).info.length
            elif self.extension == 'mp3':
                value = mp3.Open(f).info.length
            elif self.extension == 'wav':
                with closing(wave.open(f)) as open_file:
                    value = open_file.getnframes() / open_file.getframerate()
            else:
                raise NotImplementedError(
                    'Sound extension "{extension}" is not supported.'.format(
                        extension=self.extension,
                    )
                )

        self._duration = value
        return value

    def _unload_instance(self):
        """Remove the sample from the downloads list."""
        if self._downloads is not None:
            self._downloads._unload_instance()
class _PrecacheBase(AutoUnload):
    """Base precache class used to interact with a specific object."""

    # Set the base _downloads attribute to know whether
    #   or not the path was added to the downloadables
    _downloads = None

    def __init__(self, path, preload=False, download=False):
        """Add the file to downloadables if download is True.

        :param str path:
            Path to file to use.
        :param bool preload:
            If ``True`` the file will be pre-loaded.
        :param bool download:
            If ``True`` the file will be added to the ``downloadables`` string
            table.
        """
        # Save the path that should be precached
        self._path = path

        # Save whether the the file should be preloaded
        self._preload = preload

        # Is the map loaded?
        if global_vars.map_name:

            # Precache the instance
            self._precache()

        # Register the server_spawn event to precache every map change
        event_manager.register_for_event('server_spawn', self._server_spawn)

        # Should the path be added to the downloadables?
        if download:

            # Add the path to the downloadables
            self._downloads = Downloadables()
            self._downloads.add(self._path)

    @property
    def index(self):
        """Return the precached index of the object.

        :rtype: int
        """
        # Get the index of the object in its precache table
        index = string_tables[self.precache_table][self._path]

        # Is the object precached?
        if index != INVALID_STRING_INDEX:

            # Return the precache index
            return index

        # If the object was not precached, raise an error
        raise PrecacheError(
            '"{0}" was not able to be precached due to the "{1}" table '
            'reaching its limit.'.format(self._path, self.precache_table))

    @property
    def path(self):
        """Return the path.

        :rtype: str
        """
        return self._path

    def _precache(self):
        """Precache the file."""
        raise NotImplementedError('Must be implemented by a subclass.')

    def _server_spawn(self, game_event):
        """Precache the object on map change."""
        self._precache()

    def _unload_instance(self):
        """Remove from the downloads list and unregister server_spawn."""
        # Remove the path from the downloads list
        try:
            self._downloads._unload_instance()
        except AttributeError:
            pass

        # Unregister the server_spawn event
        event_manager.unregister_for_event('server_spawn', self._server_spawn)

    @property
    def precache_table(self):
        """Return the name of the precache table.

        :rtype: str
        """
        raise NotImplementedError('No precache_table defined for class.')
예제 #23
0
파일: ctf.py 프로젝트: KirillMysnik/SP-CTF
    0: 9,  # Round draw
    2: 8,  # Terrorists win
    3: 7,  # Counter-Terrorists win
}

# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
_flags = {}
_team_points = {}
_round_end = False

_ecx_storage_start_touch_flags = {}
_ecx_storage_start_touch_zones = {}

downloadables = Downloadables()
with open(DOWNLOADLIST_PATH) as f:
    for line in f:
        line = line.strip()
        if not line:
            continue

        downloadables.add(line)


# =============================================================================
# >> CLASSES
# =============================================================================
class CTFPlayerDictionary(PlayerDictionary):
    def on_automatically_removed(self, index):
        ctfplayer = self[index]
예제 #24
0
class _PrecacheBase(AutoUnload):

    """Base precache class used to interact with a specific object."""

    # Set the base _downloads attribute to know whether
    #   or not the path was added to the downloadables
    _downloads = None

    def __init__(self, path, download=False):
        """Add the file to downloadables if download is True."""
        # Save the path that should be precached
        self._path = path

        # Get the calling module
        caller = getmodule(stack()[1][0])

        # Set the _calling_module attribute for the instance
        self._calling_module = caller.__name__

        # Is the map loaded?
        if global_vars.map_name:
            # Precache the instance
            self._precache()

        # Register the server_spawn event to precache every map change
        event_manager.register_for_event('server_spawn', self._server_spawn)

        # Should the path be added to the downloadables?
        if download:

            # Add the path to the downloadables
            self._downloads = Downloadables()
            self._downloads.add(self._path)

    @property
    def index(self):
        """Return the precached index of the object."""
        # Get the index of the object in its precache table
        index = string_tables[self._precache_table][self._path]

        # Is the object precached?
        if index != INVALID_STRING_INDEX:

            # Return the precache index
            return index

        # If the object was not precached, raise an error
        raise PrecacheError(
            '"{0}" was not able to be precached due to the "{1}" table '
            'reaching its limit.'.format(self._path, self._precache_table))

    @property
    def path(self):
        """Return the path."""
        return self._path

    def _precache(self):
        """Precache the path."""
        self._precache_method(self._path)

    def _server_spawn(self, game_event):
        """Precache the object on map change."""
        self._precache()

    def _unload_instance(self):
        """Remove from the downloads list and unregister server_spawn."""
        # Remove the path from the downloads list
        with suppress(AttributeError):
            self._downloads._unload_instance()

        # Unregister the server_spawn event
        event_manager.unregister_for_event('server_spawn', self._server_spawn)

    @property
    def _precache_table(self):
        """Should define the name of the precache table."""
        raise NotImplementedError('No _precache_table defined for class.')

    @property
    def _precache_method(self):
        """Should define the method to be used to precache the path."""
        raise NotImplementedError('No _precache_method defined for class.')
예제 #25
0
	def __init__(self, db):
		self.db = db
		self.downloads = Downloadables()
예제 #26
0
from listeners import OnClientActive
from path import Path
from core import echo_console
from engines.server import global_vars
from stringtables.downloads import Downloadables
from engines.precache import Decal
from commands.server import ServerCommand
from plugins.info import PluginInfo

base_path = Path(__file__).parent

MODNAME = base_path.namebase
DECALPATH = base_path.joinpath('decallist.json')
COORDSDIR = base_path.joinpath('coords')

dl = Downloadables()

class FifoDict(MutableMapping):
	def __init__(self, *args, **kwargs):
		self._maxlen = None
		self._data = OrderedDict(*args, **kwargs)
	def __setitem__(self, key, value):
		if self._maxlen and len(self) >= self._maxlen:
			self.popitem()
		self._data[key] = value
	def __delitem__(self, key):
		del self._data[key]
	def __iter__(self):
		return iter(self._data)
	def __len__(self):
		return len(self._data)
예제 #27
0
def setDL():
    dl = Downloadables()
    dl.add_directory('sound/round_end_sound')