Example #1
0
 public void Play(SoundList sound)
 {
     if (Options.Entries["SoundEffects"]) {
         switch(sound)
         {
         case SoundList.Bombs:
             audio.PlayOneShot(bombSound, 0.7F);
             break;
         case SoundList.Explosions:
             audio.PlayOneShot(explosionSound, 0.7F);
             break;
         case SoundList.GameOvers:
             audio.PlayOneShot(gameOverSound, 1F);
             break;
         case SoundList.Lasers:
             audio.PlayOneShot(laserSound, 0.7F);
             break;
         case SoundList.Transitions:
             audio.PlayOneShot(transitionSound, 0.7F);
             break;
         }
     }
 }
Example #2
0
    void PlaySound(bool initial, int index, BeatmapObject objectData)
    {
        // bongo cat
        bongocat.triggerArm(objectData as BeatmapNote, container);

        //actual ding stuff
        if (objectData._time == lastCheckedTime || !NoteTypeToDing[(objectData as BeatmapNote)._type])
        {
            return;
        }

        /*
         * As for why we are not using "initial", it is so notes that are not supposed to ding do not prevent notes at
         * the same time that are supposed to ding from triggering the sound effects.
         */
        lastCheckedTime = objectData._time;
        SoundList list     = soundLists[soundListToUse];
        bool      shortCut = false;

        if (index - DensityCheckOffset < 0 || index + DensityCheckOffset >= container.LoadedContainers.Count)
        {
            return;
        }
        BeatmapObject first  = container.LoadedContainers[index + DensityCheckOffset]?.objectData;
        BeatmapObject second = container.LoadedContainers[index - DensityCheckOffset]?.objectData;

        if (first != null && second != null)
        {
            if (first._time - objectData._time <= ThresholdInNoteTime &&
                objectData._time - second._time <= ThresholdInNoteTime)
            {
                shortCut = true;
            }
        }

        audioUtil.PlayOneShotSound(list.GetRandomClip(shortCut), 0.5f);
    }
Example #3
0
    public void PlaySound(SoundList soundToPlay)
    {
        switch (soundToPlay)
        {
        case SoundList.BEEP:
            onshotSource.PlayOneShot(beep);
            break;

        case SoundList.GOSOUND:
            onshotSource.PlayOneShot(goSound);
            break;

        case SoundList.SPINOUT:
            onshotSource.PlayOneShot(spinOut);
            break;

        case SoundList.PERFECTTURN:
            onshotSource.PlayOneShot(perfectTurn);
            break;

        case SoundList.FIREWORK:
            fireworkSource.Play();
            break;

        case SoundList.CHEER:
            onShotHighSource.PlayOneShot(cheers);
            break;

        case SoundList.MUAHAHA:
            onshotSource.PlayOneShot(muahaha);
            break;

        default:
            Debug.Log("Couldn't find the sound. Blame Alex.");
            break;
        }
    }
Example #4
0
    private AudioClip GetAudioClip(SoundList soundList, AudioSource audioSource, out bool loop)
    {
        foreach (SoundAudioClipList soundAudioClipList in similarSounds)
        {
            if (soundAudioClipList.soundList == soundList)
            {
                int       randomIndex     = Random.Range(0, soundAudioClipList.audioClips.Count);
                AudioClip randomAudioClip = soundAudioClipList.audioClips[randomIndex];

                audioSource.outputAudioMixerGroup = soundAudioClipList.output;

                audioSource.dopplerLevel = 0f;
                audioSource.rolloffMode  = AudioRolloffMode.Linear;

                audioSource.loop = soundAudioClipList.loop;
                loop             = soundAudioClipList.loop;

                audioSource.ignoreListenerPause = soundAudioClipList.ignoreListenerPause;

                float volumeRandomness = Random.Range(-soundAudioClipList.volumeRandomness / 2f, soundAudioClipList.volumeRandomness / 2f);
                audioSource.volume = soundAudioClipList.volume * (1f + volumeRandomness);

                float pitchRandomness = Random.Range(-soundAudioClipList.pitchRandomness / 2f, soundAudioClipList.pitchRandomness / 2f);
                audioSource.pitch = soundAudioClipList.pitch * (1f + pitchRandomness);

                audioSource.maxDistance  = soundAudioClipList.maxDistance;
                audioSource.spatialBlend = soundAudioClipList.spatialBlend;

                return(randomAudioClip);
            }
        }

        Debug.LogError($"Sound list {soundList} not found");
        loop = false;
        return(null);
    }
Example #5
0
    public void PlaySound(SoundList sound, AudioMixerGroup group, float timeToLoop = 0.0f, bool infiniteLoop = false)
    {
        AudioSource emitterAvailable = null;

        if (sound == SoundList.TRASH_IMPACT)
        {
            foreach (AudioSource emitter in trashEmitters)
            {
                if (!emitter.isPlaying)
                {
                    emitterAvailable = emitter;
                }
            }

            if (emitterAvailable != null)
            {
                emitterAvailable.loop = false;
                emitterAvailable.clip = trashImpactClip[Random.Range(0, trashImpactClip.Length - 1)];
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Environment")[0];
                emitterAvailable.Play();
            }

            return;
        }

        foreach (AudioSource emitter in emitters)
        {
            if (!emitter.isPlaying)
            {
                emitterAvailable = emitter;
            }
        }

        if (emitterAvailable != null)
        {
            emitterAvailable.loop = false;
            switch (sound)
            {
            case SoundList.RUN:
                emitterAvailable.clip = runClips[Random.Range(0, runClips.Length - 1)];
                break;

            case SoundList.FIRE:
                emitterAvailable.clip = fireClip;
                break;

            case SoundList.WOOD_IMPACT:
                emitterAvailable.clip = woodImpactClip[Random.Range(0, woodImpactClip.Length - 1)];
                break;

            case SoundList.STEEL_IMPACT:
                emitterAvailable.clip = steelImpactClip[Random.Range(0, steelImpactClip.Length - 1)];
                break;

            case SoundList.CONVEYORBELT:
                emitterAvailable.clip = conveyorBeltclip;
                break;

            case SoundList.GENE_DAMAGE:
                emitterAvailable.clip = geneDamageClip;
                break;

            case SoundList.GENE_DESTROY:
                emitterAvailable.clip = geneDestroyClip;
                break;

            case SoundList.POWER_UP:
                emitterAvailable.clip = powerUpClip;
                break;

            case SoundList.PICK_UP:
                emitterAvailable.clip = pickupClip;
                break;

            case SoundList.WOOD_DESTROY:
                emitterAvailable.clip = woodDestroyClip;
                break;

            case SoundList.DEATH:
                emitterAvailable.clip = deathClips[Random.Range(0, deathClips.Length - 1)];
                break;

            case SoundList.MENU_SELECTION:
                emitterAvailable.clip = menuSelection;
                break;

            case SoundList.MENU_VALIDATION:
                emitterAvailable.clip = menuValidation;
                break;

            case SoundList.WIN_MUSIC:
                musicEmitter.clip = winMusicClip;
                musicEmitter.Play();
                break;

            case SoundList.LOSE_MUSIC:
                musicEmitter.clip = loseMusicClip;
                musicEmitter.Play();
                break;
            }

            if (timeToLoop > 0.0f)
            {
                emitterAvailable.loop = true;

                if (!infiniteLoop)
                {
                    LoopedSound newLoopSound = new LoopedSound
                    {
                        audioSource   = emitterAvailable,
                        timeUntilStop = Utilities.StartTimer(timeToLoop)
                    };
                    loopedSoundList.Add(newLoopSound);
                }
            }

            switch (group)
            {
            case AudioMixerGroup.PLAYER:
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Player")[0];
                break;

            case AudioMixerGroup.ENVIRONMENT:
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Environment")[0];
                break;

            case AudioMixerGroup.CONSTANT_NOISE:
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("ConstantNoise")[0];
                break;
            }

            emitterAvailable.Play();
        }
        else
        {
            Debug.Log("no emitter available");
        }
    }
Example #6
0
        private void LoadSoundNames()
        {
            var soundList = SoundPlayerUtilities.Instance.GetSoundList();

            soundList.ToList().ForEach(s => SoundList.Add(s));
        }
Example #7
0
        public void makesDic(ProfilProperties eingabe)
        {
            //Wichtig: Casten in das jeweilige Format

            #region Clear
            GrafikList.Clear();
            SoundList.Clear();
            SteuerungList.Clear();
            SpielereinstellungenList.Clear();

            GrafikDat.Clear();
            SoundDat.Clear();
            SteuerungDat.Clear();
            SpielereinstellungenDat.Clear();
            NamenKeysSound.Clear();
            NamenKeysGrafik.Clear();
            NamenKeysSteuerung.Clear();
            NamenKeysSpielereinstellungen.Clear();

            #endregion

            //Zuweisen der Werte
            #region Grafik
            NamenKeysGrafik.Add("Resolution");
            NamenKeysGrafik.Add("Shadow");
            NamenKeysGrafik.Add("Fog");
            NamenKeysGrafik.Add("Detail");
            NamenKeysGrafik.Add("Fullscreen");
            NamenKeysGrafik.Add("Anti Aliasing");

            GrafikDat.Add("Resolution", "string");
            GrafikDat.Add("Shadow", "bool");
            GrafikDat.Add("Fog", "bool");
            GrafikDat.Add("Detail", "float");
            GrafikDat.Add("Fullscreen", "bool");
            GrafikDat.Add("Anti Aliasing", "string");

            GrafikList.Add("Resolution", CurrentProfil.Resolution);
            GrafikList.Add("Shadow", CurrentProfil.Shadow);
            GrafikList.Add("Fog", CurrentProfil.Fog);
            GrafikList.Add("Detail", CurrentProfil.Detail);
            GrafikList.Add("Fullscreen", CurrentProfil.Fullscreen);
            GrafikList.Add("Anti Aliasing", CurrentProfil.AntiAliasing);
            #endregion

            #region Sound
            NamenKeysSound.Add("Music");
            NamenKeysSound.Add("Effect");
            NamenKeysSound.Add("Sound");

            SoundDat.Add("Music", "float");
            SoundDat.Add("Effect", "float");
            SoundDat.Add("Sound", "bool");

            SoundList.Add("Music", CurrentProfil.Music);
            SoundList.Add("Effect", CurrentProfil.Effect);
            SoundList.Add("Sound", CurrentProfil.Sound);
            #endregion

            #region Steuerung

            NamenKeysSteuerung.Add("Translation");
            NamenKeysSteuerung.Add("Acceleration Level");
            NamenKeysSteuerung.Add("Brake");
            NamenKeysSteuerung.Add("Banking");
            NamenKeysSteuerung.Add("Drift");
            NamenKeysSteuerung.Add("Auto Level");
            NamenKeysSteuerung.Add("Rolling");
            NamenKeysSteuerung.Add("Mouse Intensity");
            NamenKeysSteuerung.Add("Primary Fire");
            NamenKeysSteuerung.Add("Secondary Fire");
            NamenKeysSteuerung.Add("Left Drift");
            NamenKeysSteuerung.Add("Right Drift");
            NamenKeysSteuerung.Add("Brakes");
            NamenKeysSteuerung.Add("Acceleration");
            NamenKeysSteuerung.Add("Boost");
            NamenKeysSteuerung.Add("Primary Weapon 1");
            NamenKeysSteuerung.Add("Primary Weapon 2");
            NamenKeysSteuerung.Add("Secondary Weapon 1");
            NamenKeysSteuerung.Add("Secondary Weapon 2");

            SteuerungDat.Add("Translation", "float");
            SteuerungDat.Add("Acceleration Level", "float");
            SteuerungDat.Add("Brake", "float");
            SteuerungDat.Add("Banking", "float");
            SteuerungDat.Add("Drift", "float");
            SteuerungDat.Add("Auto Level", "float");
            SteuerungDat.Add("Rolling", "float");
            SteuerungDat.Add("Mouse Intensity", "float");
            SteuerungDat.Add("Primary Fire", "MouseButton");
            SteuerungDat.Add("Secondary Fire", "MouseButton");
            SteuerungDat.Add("Left Drift", "Keys");
            SteuerungDat.Add("Right Drift", "Keys");
            SteuerungDat.Add("Brakes", "Keys");
            SteuerungDat.Add("Acceleration", "Keys");
            SteuerungDat.Add("Boost", "Keys");
            SteuerungDat.Add("Primary Weapon 1", "Keys");
            SteuerungDat.Add("Primary Weapon 2", "Keys");
            SteuerungDat.Add("Secondary Weapon 1", "Keys");
            SteuerungDat.Add("Secondary Weapon 2", "Keys");

            SteuerungList.Add("Translation", CurrentProfil.Translation);
            SteuerungList.Add("Acceleration Level", CurrentProfil.Acceleration);
            SteuerungList.Add("Brake", CurrentProfil.Brake);
            SteuerungList.Add("Banking", CurrentProfil.Banking);
            SteuerungList.Add("Drift", CurrentProfil.Drift);
            SteuerungList.Add("Auto Level", CurrentProfil.AutoLevel);
            SteuerungList.Add("Rolling", CurrentProfil.Rolling);
            SteuerungList.Add("Mouse Intensity", CurrentProfil.mouseIntensity);
            SteuerungList.Add("Primary Fire", CurrentProfil.PlayerFirePrim);
            SteuerungList.Add("Secondary Fire", CurrentProfil.PlayerFireSek);
            SteuerungList.Add("Left Drift", CurrentProfil.PlayerLeftDrift);
            SteuerungList.Add("Right Drift", CurrentProfil.PlayerRightDrift);
            SteuerungList.Add("Brakes", CurrentProfil.PlayerBrake);
            SteuerungList.Add("Acceleration", CurrentProfil.PlayerAcceleration);
            SteuerungList.Add("Boost", CurrentProfil.PlayerBoost);
            SteuerungList.Add("Primary Weapon 1", CurrentProfil.PlayerPrimWeapon1);
            SteuerungList.Add("Primary Weapon 2", CurrentProfil.PlayerPrimWeapon2);
            SteuerungList.Add("Secondary Weapon 1", CurrentProfil.PlayerSekWeapon1);
            SteuerungList.Add("Secondary Weapon 2", CurrentProfil.PlayerSekWeapon2);
            #endregion

            #region Spielereinstellungen
            NamenKeysSpielereinstellungen.Add("Difficult");
            NamenKeysSpielereinstellungen.Add("Playername");

            SpielereinstellungenDat.Add("Difficult", "int");
            SpielereinstellungenDat.Add("Playernam", "string");

            SpielereinstellungenList.Add("Difficult", CurrentProfil.Difficult);
            SpielereinstellungenList.Add("Playername", CurrentProfil.Playername);
            #endregion
        }
Example #8
0
    public AudioSource PlaySound(SoundList sound, float timeToLoop = 0.0f)
    {
        //return null;
        AudioSource emitterAvailable = null;

        foreach (AudioSource emitter in emitters)
        {
            if (!emitter.isPlaying)
            {
                emitterAvailable = emitter;
            }
        }

        if (emitterAvailable != null)
        {
            emitterAvailable.loop = false;
            int index = 0;
            switch (sound)
            {
            case SoundList.WALK:
                index = Random.Range(0, listWalkSounds.Count);
                emitterAvailable.clip = listWalkSounds[index];
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Walk")[0];
                break;

            case SoundList.PUNCH:
                index = Random.Range(0, listPunchSounds.Count);
                emitterAvailable.clip = listPunchSounds[index];
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Punch")[0];
                break;

            case SoundList.IS_HIT:
                index = Random.Range(0, listHitSounds.Count);
                emitterAvailable.clip = listHitSounds[index];
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Effects")[0];
                break;

            case SoundList.HAND_MOVEMENT:
                emitterAvailable.clip = handMovementSoundClip;
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Effects")[0];
                break;

            case SoundList.FLAG_BACK:
                emitterAvailable.clip = flagBackSoundClip;
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("LittleMusics")[0];
                break;

            case SoundList.TAKE_FLAG:
                emitterAvailable.clip = takeFlagSoundClip;
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("LittleMusics")[0];
                break;

            case SoundList.WIN_SOUND:
                emitterAvailable.clip = winSoundClip;
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("LittleMusics")[0];
                break;

            case SoundList.LOSE_SOUND:
                emitterAvailable.clip = loseSoundClip;
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("LittleMusics")[0];
                break;
            }

            if (timeToLoop > 0.0f)
            {
                emitterAvailable.loop = true;
                LoopedSound newLoopSound = new LoopedSound
                {
                    audioSource   = emitterAvailable,
                    timeUntilStop = Utility.StartTimer(timeToLoop)
                };
                loopedSoundList.Add(newLoopSound);
            }

            emitterAvailable.Play();
            return(emitterAvailable);
        }
        else
        {
            Debug.Log("no emitter available");
            return(null);
        }
    }
Example #9
0
        static void Main(string[] args)
        {
            string[] arguments = Environment.GetCommandLineArgs();
            Game     game;
            string   filename;
            string   dir       = Environment.CurrentDirectory;
            bool     bigendian = false;

            if (args.Length == 0)
            {
                Console.WriteLine("USplit is a tool that lets you extract any data supported by SA Tools from any binary file.");
                Console.WriteLine("Usage: usplit <GAME> <FILENAME> <KEY> <TYPE> <ADDRESS> <PARAMETER1> <PARAMETER2> [-name <NAME>]\n");
                Console.WriteLine("Argument description:");
                Console.WriteLine("<GAME>: SA1, SADX, SA2, SA2B. Add '_b' (e.g. SADX_b) to switch to Big Endian.\n");
                Console.WriteLine("<FILENAME>: The name of the binary file, e.g. sonic.exe.\n");
                Console.WriteLine("<KEY>: Binary key, e.g. 400000 for sonic.exe or C900000 for SA1 STG file.\n");
                Console.WriteLine("<TYPE>: One of the following:\n" +
                                  "binary <length> [hex],\nlandtable, model, basicmodel, basicdxmodel, chunkmodel, gcmodel, action, animation <NJS_OBJECT address> [shortrot],\n" +
                                  "objlist, startpos, texlist, leveltexlist, triallevellist, bosslevellist, fieldstartpos, soundlist, soundtestlist,\nnextlevellist, " +
                                  "levelclearflags, deathzone, levelrankscores, levelranktimes, endpos, levelpathlist, pathlist,\nstagelightdatalist, weldlist" +
                                  "bmitemattrlist, creditstextlist, animindexlist, storysequence, musiclist <count>,\n" +
                                  "stringarray <count> [language], skyboxscale <count>, stageselectlist <count>, animationlist <count>,\n" +
                                  "masterstringlist <count>, cutscenetext <count>, recapscreen <count>, npctext <count>\n");
                Console.WriteLine("<ADDRESS>: The location of data in the file.\n");
                Console.WriteLine("<PARAMETER1>: length, count, secondary address etc. depending on data type\n");
                Console.WriteLine("<PARAMETER2>: 'hex' for binary to read length as hexadecimal, 'shortrot' for animation to read rotation as short\n");
                Console.WriteLine("<NAME>: Output file name (optional)\n");
                Console.WriteLine("Press ENTER to exit");
                Console.ReadLine();
                return;
            }
            //Args list: game, filename, key, type, address, [address2/count], [language], [name]
            switch (args[0])
            {
            case "SA1":
                game = Game.SA1;
                break;

            case "SA1_b":
                game      = Game.SA1;
                bigendian = true;
                break;

            case "SADX":
                game = Game.SADX;
                break;

            case "SADX_b":
                game      = Game.SADX;
                bigendian = true;
                break;

            case "SA2":
                game = Game.SA2;
                break;

            case "SA2_b":
                game      = Game.SA2;
                bigendian = true;
                break;

            case "SA2B":
                game = Game.SA2B;
                break;

            case "SA2B_b":
                game      = Game.SA2B;
                bigendian = true;
                break;

            default:
                return;
            }
            string model_extension     = ".sa1mdl";
            string landtable_extension = ".sa1lvl";

            ByteConverter.BigEndian = SonicRetro.SAModel.ByteConverter.BigEndian = bigendian;
            filename = args[1];
            byte[] datafile = File.ReadAllBytes(filename);
            if (Path.GetExtension(filename).ToLowerInvariant() == ".prs")
            {
                datafile = FraGag.Compression.Prs.Decompress(datafile);
            }
            Environment.CurrentDirectory = Path.Combine(Environment.CurrentDirectory, Path.GetDirectoryName(filename));
            uint            imageBase = uint.Parse(args[2], NumberStyles.AllowHexSpecifier);
            string          type      = args[3];
            int             address   = int.Parse(args[4], NumberStyles.AllowHexSpecifier);
            bool            SA2       = game == Game.SA2 | game == Game.SA2B;
            ModelFormat     modelfmt  = ModelFormat.BasicDX;
            LandTableFormat landfmt   = LandTableFormat.SADX;

            switch (game)
            {
            case Game.SA1:
                modelfmt            = ModelFormat.Basic;
                landfmt             = LandTableFormat.SA1;
                model_extension     = ".sa1mdl";
                landtable_extension = ".sa1lvl";
                break;

            case Game.SADX:
                modelfmt            = ModelFormat.BasicDX;
                landfmt             = LandTableFormat.SADX;
                model_extension     = ".sa1mdl";
                landtable_extension = ".sa1lvl";
                break;

            case Game.SA2:
                modelfmt            = ModelFormat.Chunk;
                landfmt             = LandTableFormat.SA2;
                model_extension     = ".sa2mdl";
                landtable_extension = ".sa2lvl";
                break;

            case Game.SA2B:
                modelfmt            = ModelFormat.Chunk;
                landfmt             = LandTableFormat.SA2B;
                model_extension     = ".sa2mdl";
                landtable_extension = ".sa2blvl";
                break;
            }
            Dictionary <string, MasterObjectListEntry>     masterobjlist = new Dictionary <string, MasterObjectListEntry>();
            Dictionary <string, Dictionary <string, int> > objnamecounts = new Dictionary <string, Dictionary <string, int> >();
            string fileOutputPath = dir + "\\" + address.ToString("X");

            Console.WriteLine("Game: {0}, file: {1}, key: 0x{2}, splitting {3} at 0x{4}", game.ToString(), filename, imageBase.ToString("X"), type, address.ToString("X"));
            if (args[args.Length - 2] == "-name")
            {
                fileOutputPath = dir + "\\" + args[args.Length - 1];
                Console.WriteLine("Name: {0}", args[args.Length - 1]);
            }
            switch (type)
            {
            case "landtable":
                new LandTable(datafile, address, imageBase, landfmt).SaveToFile(fileOutputPath + landtable_extension, landfmt);
                break;

            case "model":
            {
                NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, modelfmt, new Dictionary <int, Attach>());
                ModelFile.CreateFile(fileOutputPath + model_extension, mdl, null, null, null, null, modelfmt);
            }
            break;

            case "basicmodel":
            {
                NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.Basic, new Dictionary <int, Attach>());
                ModelFile.CreateFile(fileOutputPath + ".sa1mdl", mdl, null, null, null, null, ModelFormat.Basic);
            }
            break;

            case "basicdxmodel":
            {
                NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.BasicDX, new Dictionary <int, Attach>());
                ModelFile.CreateFile(fileOutputPath + ".sa1mdl", mdl, null, null, null, null, ModelFormat.BasicDX);
            }
            break;

            case "chunkmodel":
            {
                NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.Chunk, new Dictionary <int, Attach>());
                ModelFile.CreateFile(fileOutputPath + ".sa2mdl", mdl, null, null, null, null, ModelFormat.Chunk);
            }
            break;

            case "gcmodel":
            {
                NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.GC, new Dictionary <int, Attach>());
                ModelFile.CreateFile(fileOutputPath + ".sa2mdl", mdl, null, null, null, null, ModelFormat.GC);
            }
            break;

            case "action":
            {
                NJS_ACTION ani = new NJS_ACTION(datafile, address, imageBase, modelfmt, new Dictionary <int, Attach>());
                ani.Animation.Save(fileOutputPath + ".saanim");
                string[]   mdlanis = new string[0];
                NJS_OBJECT mdl     = ani.Model;
                mdlanis = (fileOutputPath + ".saanim").Split(',');
                ModelFile.CreateFile(fileOutputPath + "_model" + model_extension, mdl, mdlanis, null, null, null, modelfmt);
            }
            break;

            case "animation":
            {
                bool shortrot_enabled = false;
                if (args.Length > 6 && args[6] == "shortrot")
                {
                    shortrot_enabled = true;
                }
                NJS_OBJECT mdl = new NJS_OBJECT(datafile, int.Parse(args[5], NumberStyles.AllowHexSpecifier), imageBase, modelfmt, new Dictionary <int, Attach>());
                new NJS_MOTION(datafile, address, imageBase, mdl.CountAnimated(), shortrot: shortrot_enabled).Save(fileOutputPath + ".saanim");
                string[] mdlanis = new string[0];
                mdlanis = (fileOutputPath + ".saanim").Split(',');
                ModelFile.CreateFile(fileOutputPath + "_model" + model_extension, mdl, mdlanis, null, null, null, modelfmt);
            }
            break;

            case "objlist":
            {
                ObjectListEntry[] objs = ObjectList.Load(datafile, address, imageBase, SA2);
                foreach (ObjectListEntry obj in objs)
                {
                    if (!masterobjlist.ContainsKey(obj.CodeString))
                    {
                        masterobjlist.Add(obj.CodeString, new MasterObjectListEntry(obj));
                    }
                    if (!objnamecounts.ContainsKey(obj.CodeString))
                    {
                        objnamecounts.Add(obj.CodeString, new Dictionary <string, int>()
                            {
                                { obj.Name, 1 }
                            });
                    }
                    else if (!objnamecounts[obj.CodeString].ContainsKey(obj.Name))
                    {
                        objnamecounts[obj.CodeString].Add(obj.Name, 1);
                    }
                    else
                    {
                        objnamecounts[obj.CodeString][obj.Name]++;
                    }
                }
                objs.Save(fileOutputPath + ".ini");
            }
            break;

            case "startpos":
                if (SA2)
                {
                    SA2StartPosList.Load(datafile, address).Save(fileOutputPath + ".ini");
                }
                else
                {
                    SA1StartPosList.Load(datafile, address).Save(fileOutputPath + ".ini");
                }
                break;

            case "texlist":
                TextureList.Load(datafile, address, imageBase).Save(fileOutputPath + ".ini");
                break;

            case "leveltexlist":
                new LevelTextureList(datafile, address, imageBase).Save(fileOutputPath + ".ini");
                break;

            case "triallevellist":
                TrialLevelList.Save(TrialLevelList.Load(datafile, address, imageBase), fileOutputPath + ".ini");
                break;

            case "bosslevellist":
                BossLevelList.Save(BossLevelList.Load(datafile, address), fileOutputPath + ".ini");
                break;

            case "fieldstartpos":
                FieldStartPosList.Load(datafile, address).Save(fileOutputPath + ".ini");
                break;

            case "soundtestlist":
                SoundTestList.Load(datafile, address, imageBase).Save(fileOutputPath + ".ini");
                break;

            case "musiclist":
            {
                int muscnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                MusicList.Load(datafile, address, imageBase, muscnt).Save(fileOutputPath + ".ini");
            }
            break;

            case "soundlist":
                SoundList.Load(datafile, address, imageBase).Save(fileOutputPath + ".ini");
                break;

            case "stringarray":
            {
                int       cnt  = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                Languages lang = Languages.Japanese;
                if (args.Length > 6)
                {
                    lang = (Languages)Enum.Parse(typeof(Languages), args[6], true);
                }
                StringArray.Load(datafile, address, imageBase, cnt, lang).Save(fileOutputPath + ".txt");
            }
            break;

            case "nextlevellist":
                NextLevelList.Load(datafile, address).Save(fileOutputPath + ".ini");
                break;

            case "cutscenetext":
            {
                int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                new CutsceneText(datafile, address, imageBase, cnt).Save(fileOutputPath + ".txt", out string[] hashes);
            }
            break;

            case "recapscreen":
            {
                int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                RecapScreenList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath + ".txt", out string[][] hashes);
            }
            break;

            case "npctext":
            {
                int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                NPCTextList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath + ".txt", out string[][] hashes);
            }
            break;

            case "levelclearflags":
                LevelClearFlagList.Save(LevelClearFlagList.Load(datafile, address), fileOutputPath + ".ini");
                break;

            case "deathzone":
            {
                List <DeathZoneFlags> flags = new List <DeathZoneFlags>();
                string        path          = Path.GetDirectoryName(fileOutputPath);
                List <string> hashes        = new List <string>();
                int           num           = 0;
                while (ByteConverter.ToUInt32(datafile, address + 4) != 0)
                {
                    flags.Add(new DeathZoneFlags(datafile, address));
                    string file = Path.Combine(path, num++.ToString(NumberFormatInfo.InvariantInfo) + (modelfmt == ModelFormat.Chunk ? ".sa2mdl" : ".sa1mdl"));
                    ModelFile.CreateFile(file, new NJS_OBJECT(datafile, datafile.GetPointer(address + 4, imageBase), imageBase, modelfmt, new Dictionary <int, Attach>()), null, null, null, null, modelfmt);
                    address += 8;
                }
                flags.ToArray().Save(fileOutputPath + ".ini");
            }
            break;

            case "skyboxscale":
            {
                int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                SkyboxScaleList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath + ".ini");
            }
            break;

            case "stageselectlist":
            {
                int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                StageSelectLevelList.Load(datafile, address, cnt).Save(fileOutputPath + ".ini");
            }
            break;

            case "levelrankscores":
                LevelRankScoresList.Load(datafile, address).Save(fileOutputPath + ".ini");
                break;

            case "levelranktimes":
                LevelRankTimesList.Load(datafile, address).Save(fileOutputPath + ".ini");
                break;

            case "endpos":
                SA2EndPosList.Load(datafile, address).Save(fileOutputPath + ".ini");
                break;

            case "animationlist":
            {
                int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                SA2AnimationInfoList.Load(datafile, address, cnt).Save(fileOutputPath + ".ini");
            }
            break;

            case "levelpathlist":
            {
                ushort lvlnum = (ushort)ByteConverter.ToUInt32(datafile, address);
                while (lvlnum != 0xFFFF)
                {
                    int ptr = ByteConverter.ToInt32(datafile, address + 4);
                    if (ptr != 0)
                    {
                        ptr = (int)((uint)ptr - imageBase);
                        SA1LevelAct level  = new SA1LevelAct(lvlnum);
                        string      lvldir = Path.Combine(fileOutputPath, level.ToString());
                        PathList.Load(datafile, ptr, imageBase).Save(lvldir, out string[] lvlhashes);
                    }
                    address += 8;
                    lvlnum   = (ushort)ByteConverter.ToUInt32(datafile, address);
                }
            }
            break;

            case "pathlist":
            {
                PathList.Load(datafile, address, imageBase).Save(fileOutputPath, out string[] hashes);
            }
            break;

            case "stagelightdatalist":
                SA1StageLightDataList.Load(datafile, address).Save(fileOutputPath);
                break;

            case "weldlist":
                WeldList.Load(datafile, address, imageBase).Save(fileOutputPath);
                break;

            case "bmitemattrlist":
                BlackMarketItemAttributesList.Load(datafile, address, imageBase).Save(fileOutputPath);
                break;

            case "creditstextlist":
                CreditsTextList.Load(datafile, address, imageBase).Save(fileOutputPath);
                break;

            case "animindexlist":
            {
                Directory.CreateDirectory(fileOutputPath);
                List <string> hashes = new List <string>();
                int           i      = ByteConverter.ToInt16(datafile, address);
                while (i != -1)
                {
                    new NJS_MOTION(datafile, datafile.GetPointer(address + 4, imageBase), imageBase, ByteConverter.ToInt16(datafile, address + 2))
                    .Save(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim");
                    hashes.Add(i.ToString(NumberFormatInfo.InvariantInfo) + ":" + HelperFunctions.FileHash(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim"));
                    address += 8;
                    i        = ByteConverter.ToInt16(datafile, address);
                }
            }
            break;

            case "storysequence":
                SA2StoryList.Load(datafile, address).Save(fileOutputPath);
                break;

            case "masterstringlist":
            {
                int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                for (int l = 0; l < 5; l++)
                {
                    Languages            lng = (Languages)l;
                    System.Text.Encoding enc = HelperFunctions.GetEncoding(game, lng);
                    string ld = Path.Combine(fileOutputPath, lng.ToString());
                    Directory.CreateDirectory(ld);
                    int ptr = datafile.GetPointer(address, imageBase);
                    for (int i = 0; i < cnt; i++)
                    {
                        int ptr2 = datafile.GetPointer(ptr, imageBase);
                        if (ptr2 != 0)
                        {
                            string fn = Path.Combine(ld, $"{i}.txt");
                            File.WriteAllText(fn, datafile.GetCString(ptr2, enc).Replace("\n", "\r\n"));
                        }
                        ptr += 4;
                    }
                    address += 4;
                }
            }
            break;

            case "binary":
            {
                int length;
                if (args.Length > 6 && args[6] == "hex")
                {
                    length = int.Parse(args[5], NumberStyles.AllowHexSpecifier);
                }
                else
                {
                    length = int.Parse(args[5]);
                }
                byte[] bin = new byte[length];
                Array.Copy(datafile, address, bin, 0, bin.Length);
                File.WriteAllBytes(fileOutputPath + ".bin", bin);
                Console.WriteLine("Length: {0} (0x{1}) bytes", length.ToString(), length.ToString("X"));
            }
            break;

            default:
                break;
            }
        }
Example #10
0
        public static int SplitFile(string datafilename, string inifilename, string projectFolderName)
        {
            try
            {
                byte[]  datafile = File.ReadAllBytes(datafilename);
                IniData inifile  = IniSerializer.Deserialize <IniData>(inifilename);
                if (inifile.MD5 != null && inifile.MD5.Count > 0)
                {
                    string datahash = HelperFunctions.FileHash(datafile);
                    if (!inifile.MD5.Any(h => h.Equals(datahash, StringComparison.OrdinalIgnoreCase)))
                    {
                        Console.WriteLine("The file {0} is not valid for use with the INI {1}.", datafilename, inifilename);
                        return((int)ERRORVALUE.InvalidDataMapping);
                    }
                }
                ByteConverter.BigEndian      = SonicRetro.SAModel.ByteConverter.BigEndian = inifile.BigEndian;
                Environment.CurrentDirectory = Path.Combine(Environment.CurrentDirectory, Path.GetDirectoryName(datafilename));
                if (inifile.Compressed)
                {
                    datafile = FraGag.Compression.Prs.Decompress(datafile);
                }
                uint imageBase = HelperFunctions.SetupEXE(ref datafile) ?? inifile.ImageBase.Value;
                if (Path.GetExtension(datafilename).Equals(".rel", StringComparison.OrdinalIgnoreCase))
                {
                    HelperFunctions.FixRELPointers(datafile);
                }
                bool            SA2      = inifile.Game == Game.SA2 | inifile.Game == Game.SA2B;
                ModelFormat     modelfmt = 0;
                LandTableFormat landfmt  = 0;
                switch (inifile.Game)
                {
                case Game.SA1:
                    modelfmt = ModelFormat.Basic;
                    landfmt  = LandTableFormat.SA1;
                    break;

                case Game.SADX:
                    modelfmt = ModelFormat.BasicDX;
                    landfmt  = LandTableFormat.SADX;
                    break;

                case Game.SA2:
                case Game.SA2B:
                    modelfmt = ModelFormat.Chunk;
                    landfmt  = LandTableFormat.SA2;
                    break;
                }
                int itemcount = 0;
                Dictionary <string, MasterObjectListEntry>     masterobjlist = new Dictionary <string, MasterObjectListEntry>();
                Dictionary <string, Dictionary <string, int> > objnamecounts = new Dictionary <string, Dictionary <string, int> >();
                Stopwatch timer = new Stopwatch();
                timer.Start();
                foreach (KeyValuePair <string, SA_Tools.FileInfo> item in inifile.Files)
                {
                    if (string.IsNullOrEmpty(item.Key))
                    {
                        continue;
                    }
                    string                      filedesc         = item.Key;
                    SA_Tools.FileInfo           data             = item.Value;
                    Dictionary <string, string> customProperties = data.CustomProperties;
                    string                      type             = data.Type;
                    int  address = data.Address;
                    bool nohash  = false;

                    string fileOutputPath = string.Concat(projectFolderName, data.Filename);
                    Console.WriteLine(item.Key + ": " + data.Address.ToString("X") + " → " + fileOutputPath);
                    Directory.CreateDirectory(Path.GetDirectoryName(fileOutputPath));
                    switch (type)
                    {
                    case "landtable":
                        new LandTable(datafile, address, imageBase, landfmt)
                        {
                            Description = item.Key
                        }.SaveToFile(fileOutputPath, landfmt);
                        break;

                    case "model":
                    {
                        NJS_OBJECT mdl     = new NJS_OBJECT(datafile, address, imageBase, modelfmt);
                        string[]   mdlanis = new string[0];
                        if (customProperties.ContainsKey("animations"))
                        {
                            mdlanis = customProperties["animations"].Split(',');
                        }
                        string[] mdlmorphs = new string[0];
                        if (customProperties.ContainsKey("morphs"))
                        {
                            mdlmorphs = customProperties["morphs"].Split(',');
                        }
                        ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, mdlmorphs, null, item.Key, null, modelfmt);
                    }
                    break;

                    case "basicmodel":
                    {
                        NJS_OBJECT mdl     = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.Basic);
                        string[]   mdlanis = new string[0];
                        if (customProperties.ContainsKey("animations"))
                        {
                            mdlanis = customProperties["animations"].Split(',');
                        }
                        string[] mdlmorphs = new string[0];
                        if (customProperties.ContainsKey("morphs"))
                        {
                            mdlmorphs = customProperties["morphs"].Split(',');
                        }
                        ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, mdlmorphs, null, item.Key, null, ModelFormat.Basic);
                    }
                    break;

                    case "basicdxmodel":
                    {
                        NJS_OBJECT mdl     = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.BasicDX);
                        string[]   mdlanis = new string[0];
                        if (customProperties.ContainsKey("animations"))
                        {
                            mdlanis = customProperties["animations"].Split(',');
                        }
                        string[] mdlmorphs = new string[0];
                        if (customProperties.ContainsKey("morphs"))
                        {
                            mdlmorphs = customProperties["morphs"].Split(',');
                        }
                        ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, mdlmorphs, null, item.Key, null, ModelFormat.BasicDX);
                    }
                    break;

                    case "chunkmodel":
                    {
                        NJS_OBJECT mdl     = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.Chunk);
                        string[]   mdlanis = new string[0];
                        if (customProperties.ContainsKey("animations"))
                        {
                            mdlanis = customProperties["animations"].Split(',');
                        }
                        string[] mdlmorphs = new string[0];
                        if (customProperties.ContainsKey("morphs"))
                        {
                            mdlmorphs = customProperties["morphs"].Split(',');
                        }
                        ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, mdlmorphs, null, item.Key, null, ModelFormat.Chunk);
                    }
                    break;

                    case "action":
                    {
                        NJS_ACTION ani = new NJS_ACTION(datafile, address, imageBase, modelfmt);
                        ani.Animation.Name = filedesc;
                        ani.Animation.Save(fileOutputPath);
                    }
                    break;

                    case "animation":
                        new NJS_MOTION(datafile, address, imageBase, int.Parse(customProperties["numparts"], NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo))
                        {
                            Name = filedesc
                        }
                        .Save(fileOutputPath);
                        break;

                    case "objlist":
                    {
                        ObjectListEntry[] objs = ObjectList.Load(datafile, address, imageBase, SA2);
                        if (inifile.MasterObjectList != null)
                        {
                            foreach (ObjectListEntry obj in objs)
                            {
                                if (!masterobjlist.ContainsKey(obj.CodeString))
                                {
                                    masterobjlist.Add(obj.CodeString, new MasterObjectListEntry(obj));
                                }
                                if (!objnamecounts.ContainsKey(obj.CodeString))
                                {
                                    objnamecounts.Add(obj.CodeString, new Dictionary <string, int>()
                                        {
                                            { obj.Name, 1 }
                                        });
                                }
                                else if (!objnamecounts[obj.CodeString].ContainsKey(obj.Name))
                                {
                                    objnamecounts[obj.CodeString].Add(obj.Name, 1);
                                }
                                else
                                {
                                    objnamecounts[obj.CodeString][obj.Name]++;
                                }
                            }
                        }
                        objs.Save(fileOutputPath);
                    }
                    break;

                    case "startpos":
                        if (SA2)
                        {
                            SA2StartPosList.Load(datafile, address).Save(fileOutputPath);
                        }
                        else
                        {
                            SA1StartPosList.Load(datafile, address).Save(fileOutputPath);
                        }
                        break;

                    case "texlist":
                        TextureList.Load(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "leveltexlist":
                        new LevelTextureList(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "triallevellist":
                        TrialLevelList.Save(TrialLevelList.Load(datafile, address, imageBase), fileOutputPath);
                        break;

                    case "bosslevellist":
                        BossLevelList.Save(BossLevelList.Load(datafile, address), fileOutputPath);
                        break;

                    case "fieldstartpos":
                        FieldStartPosList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    case "soundtestlist":
                        SoundTestList.Load(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "musiclist":
                    {
                        int muscnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        MusicList.Load(datafile, address, imageBase, muscnt).Save(fileOutputPath);
                    }
                    break;

                    case "soundlist":
                        SoundList.Load(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "stringarray":
                    {
                        int       cnt  = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        Languages lang = Languages.Japanese;
                        if (data.CustomProperties.ContainsKey("language"))
                        {
                            lang = (Languages)Enum.Parse(typeof(Languages), data.CustomProperties["language"], true);
                        }
                        StringArray.Load(datafile, address, imageBase, cnt, lang).Save(fileOutputPath);
                    }
                    break;

                    case "nextlevellist":
                        NextLevelList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    case "cutscenetext":
                    {
                        int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        new CutsceneText(datafile, address, imageBase, cnt).Save(fileOutputPath, out string[] hashes);
                        data.MD5Hash = string.Join(",", hashes);
                        nohash       = true;
                    }
                    break;

                    case "recapscreen":
                    {
                        int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        RecapScreenList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath, out string[][] hashes);
                        string[] hash2 = new string[hashes.Length];
                        for (int i = 0; i < hashes.Length; i++)
                        {
                            hash2[i] = string.Join(",", hashes[i]);
                        }
                        data.MD5Hash = string.Join(":", hash2);
                        nohash       = true;
                    }
                    break;

                    case "npctext":
                    {
                        int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        NPCTextList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath, out string[][] hashes);
                        string[] hash2 = new string[hashes.Length];
                        for (int i = 0; i < hashes.Length; i++)
                        {
                            hash2[i] = string.Join(",", hashes[i]);
                        }
                        data.MD5Hash = string.Join(":", hash2);
                        nohash       = true;
                    }
                    break;

                    case "levelclearflags":
                        LevelClearFlagList.Save(LevelClearFlagList.Load(datafile, address), fileOutputPath);
                        break;

                    case "deathzone":
                    {
                        List <DeathZoneFlags> flags = new List <DeathZoneFlags>();
                        string        path          = Path.GetDirectoryName(fileOutputPath);
                        List <string> hashes        = new List <string>();
                        int           num           = 0;
                        while (ByteConverter.ToUInt32(datafile, address + 4) != 0)
                        {
                            flags.Add(new DeathZoneFlags(datafile, address));
                            string file = Path.Combine(path, num++.ToString(NumberFormatInfo.InvariantInfo) + (modelfmt == ModelFormat.Chunk ? ".sa2mdl" : ".sa1mdl"));
                            ModelFile.CreateFile(file, new NJS_OBJECT(datafile, datafile.GetPointer(address + 4, imageBase), imageBase, modelfmt), null, null, null, null, null, modelfmt);
                            hashes.Add(HelperFunctions.FileHash(file));
                            address += 8;
                        }
                        flags.ToArray().Save(fileOutputPath);
                        hashes.Insert(0, HelperFunctions.FileHash(fileOutputPath));
                        data.MD5Hash = string.Join(",", hashes.ToArray());
                        nohash       = true;
                    }
                    break;

                    case "skyboxscale":
                    {
                        int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        SkyboxScaleList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath);
                    }
                    break;

                    case "stageselectlist":
                    {
                        int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        StageSelectLevelList.Load(datafile, address, cnt).Save(fileOutputPath);
                    }
                    break;

                    case "levelrankscores":
                        LevelRankScoresList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    case "levelranktimes":
                        LevelRankTimesList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    case "endpos":
                        SA2EndPosList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    case "animationlist":
                    {
                        int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        SA2AnimationInfoList.Load(datafile, address, cnt).Save(fileOutputPath);
                    }
                    break;

                    case "levelpathlist":
                    {
                        List <string> hashes = new List <string>();
                        ushort        lvlnum = (ushort)ByteConverter.ToUInt32(datafile, address);
                        while (lvlnum != 0xFFFF)
                        {
                            int ptr = ByteConverter.ToInt32(datafile, address + 4);
                            if (ptr != 0)
                            {
                                ptr = (int)((uint)ptr - imageBase);
                                SA1LevelAct level  = new SA1LevelAct(lvlnum);
                                string      lvldir = Path.Combine(fileOutputPath, level.ToString());
                                PathList.Load(datafile, ptr, imageBase).Save(lvldir, out string[] lvlhashes);
                                hashes.Add(level.ToString() + ":" + string.Join(",", lvlhashes));
                            }
                            address += 8;
                            lvlnum   = (ushort)ByteConverter.ToUInt32(datafile, address);
                        }
                        data.MD5Hash = string.Join("|", hashes.ToArray());
                        nohash       = true;
                    }
                    break;

                    case "pathlist":
                    {
                        PathList.Load(datafile, address, imageBase).Save(fileOutputPath, out string[] hashes);
                        data.MD5Hash = string.Join(",", hashes.ToArray());
                        nohash       = true;
                    }
                    break;

                    case "stagelightdatalist":
                        SA1StageLightDataList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    case "weldlist":
                        WeldList.Load(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "bmitemattrlist":
                        BlackMarketItemAttributesList.Load(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "creditstextlist":
                        CreditsTextList.Load(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "animindexlist":
                    {
                        Directory.CreateDirectory(fileOutputPath);
                        List <string> hashes = new List <string>();
                        int           i      = ByteConverter.ToInt16(datafile, address);
                        while (i != -1)
                        {
                            new NJS_MOTION(datafile, datafile.GetPointer(address + 4, imageBase), imageBase, ByteConverter.ToInt16(datafile, address + 2))
                            .Save(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim");
                            hashes.Add(i.ToString(NumberFormatInfo.InvariantInfo) + ":" + HelperFunctions.FileHash(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim"));
                            address += 8;
                            i        = ByteConverter.ToInt16(datafile, address);
                        }
                        data.MD5Hash = string.Join("|", hashes.ToArray());
                        nohash       = true;
                    }
                    break;

                    case "storysequence":
                        SA2StoryList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    default:                             // raw binary
                    {
                        byte[] bin = new byte[int.Parse(customProperties["size"], NumberStyles.HexNumber)];
                        Array.Copy(datafile, address, bin, 0, bin.Length);
                        File.WriteAllBytes(fileOutputPath, bin);
                    }
                    break;
                    }
                    if (!nohash)
                    {
                        data.MD5Hash = HelperFunctions.FileHash(fileOutputPath);
                    }
                    itemcount++;
                }
                if (inifile.MasterObjectList != null)
                {
                    foreach (KeyValuePair <string, MasterObjectListEntry> obj in masterobjlist)
                    {
                        KeyValuePair <string, int> name = new KeyValuePair <string, int>();
                        foreach (KeyValuePair <string, int> it in objnamecounts[obj.Key])
                        {
                            if (it.Value > name.Value)
                            {
                                name = it;
                            }
                        }
                        obj.Value.Name  = name.Key;
                        obj.Value.Names = objnamecounts[obj.Key].Select((it) => it.Key).ToArray();
                    }

                    string masterObjectListOutputPath = string.Concat(projectFolderName, inifile.MasterObjectList);

                    IniSerializer.Serialize(masterobjlist, masterObjectListOutputPath);
                }
                IniSerializer.Serialize(inifile, Path.Combine(projectFolderName, Path.GetFileNameWithoutExtension(datafilename) + "_data.ini"));
                timer.Stop();
                Console.WriteLine("Split " + itemcount + " items in " + timer.Elapsed.TotalSeconds + " seconds.");
                Console.WriteLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();
                return((int)ERRORVALUE.UnhandledException);
            }

            return((int)ERRORVALUE.Success);
        }
Example #11
0
 private void Awake()
 {
     gi = this;
 }
Example #12
0
 private void OnDestroy()
 {
     gi = null;
 }
Example #13
0
        public int listCount(int _list)
        {
            SoundList list = (SoundList)CRunTime.getRegisteredObject(_list);

            return(list.count);
        }
Example #14
0
        private void playNextItem()
        {
            lock (sound_lists)
            {
                if (current_list_id == -1)
                {
                    return;
                }
                if (sound_lists[current_list_id] == null)
                {
                    return;
                }
            }

            while ((current_list_item < current_list.count) &&
                   (current_list.streams[current_list_item] == null))
            {
                current_list_item++;
            }

            if (current_list_item == current_list.count)
            {
                closeCurrentList();
                if ((current_list.flags & SoundList.SOUND_LIST_NO_FREE) == 0)
                {
                    listFree(sound_lists[current_list_id]);
                }
                sound_lists[current_list_id] = null;
                current_list = null;
                playNextList();
                return;
            }

            try
            {
                int copy_index = current_list_item;
                current_list_item++;
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        lock (sound_lists)
                        {
                            // Cleanup previously played sound.

                            if (_lastSoundInstance != null)
                            {
                                _lastSoundInstance.Dispose();
                            }
                            if (_lastSound != null)
                            {
                                _lastSound.Dispose();
                            }


                            // Get the audio stream
                            _lastSound = SoundEffect.FromStream(current_list.streams[copy_index]);
                            // Update XNA on new Sound Effect
                            FrameworkDispatcher.Update();

                            // Create instance we can play concurrently
                            _lastSoundInstance = _lastSound.CreateInstance();


                            // Play the sound concurrently with max relative volume
                            _lastSoundInstance.Volume = 1;
                            _lastSoundInstance.Play();

                            Thread nextSoundThread = new Thread(new ThreadStart(
                                                                    delegate
                            {
                                // Wait for the sound to finish playing on an other thread so we won't block the UI.
                                Thread.Sleep((int)_lastSound.Duration.TotalMilliseconds + 1);


                                // Cleanup Stream
                                if (current_list != null && current_list.streams != null && current_list.streams[copy_index] != null)
                                {
                                    current_list.streams[copy_index].Close();
                                }

                                // Play Next item
                                playNextItem();
                            }));
                            nextSoundThread.Start();
                        }



                        #region Old Playback code

                        //    // re-create media element each time in order to avoid multiple subscribers to MediaEnded event
                        //    mediaElement = new MediaElement();
                        //    GamePage.get().LayoutRoot.Children.Add(mediaElement);
                        //    mediaElement.SetSource(current_list.streams[copy_index]);
                        //    mediaElement.Volume = 1.0;//todomt (double)((double)sound_level / 100.0);
                        //    mediaElement.MediaEnded += delegate
                        //    {
                        //        lock (sound_lists)
                        //        {
                        //            if (current_list != null && current_list.streams != null && current_list.streams[copy_index] != null)
                        //            {
                        //                current_list.streams[copy_index].Close();
                        //            }
                        //        }
                        //        GamePage.get().LayoutRoot.Children.Remove(mediaElement);
                        //        playNextItem();
                        //    };

                        //    mediaElement.MediaOpened += delegate
                        //    {
                        //        try
                        //        {
                        //            mediaElement.Play();
                        //        }
                        //        catch (Exception e)
                        //        {
                        //            Logger.log("Error playing sound " + e);
                        //        }
                        //    };
                        //}

                        #endregion Old Playback code
                    }
                    catch (Exception e)
                    {
                        Logger.log("Exception: " + e.ToString());
                    }
                });
            }
            catch (Exception e)
            {
                Logger.log("Exception: " + e.ToString());
                closeCurrentList();
                playNextList();
                return;
            }
        }
Example #15
0
        //public void playerUpdate(Player p, string theevent, Object eventData) {
        // //System.out.println("playerUpdate: " + event);

        // if ((theevent != END_OF_MEDIA) && (theevent != STOPPED) && (theevent != ERROR) && (theevent != CLOSED)) return;

        // if (theevent != CLOSED)
        // {
        //  new Thread()
        //  {
        //   public void run()
        //   {
        //    setPriority(Thread.MAX_PRIORITY);
        //    try
        //    {
        //     if (p.getState() == p.PREFETCHED) p.stop();
        //    }
        //    catch (Exception e) { }
        //    try { p.close(); }
        //    catch (Exception e) { }

        //    if (event == STOPPED) current_list_item--;
        //   }
        //  }.start();
        // }
        // else
        // {
        //  new Thread()
        //  {
        //   public void run()
        //   {
        //    setPriority(Thread.MAX_PRIORITY);
        //    playNextItem();
        //   }
        //  }.start();
        // }
        //}

        #endregion OldPlayerUpdate Code

        public int listCreate(int flags)
        {
            SoundList list = new SoundList(flags);

            return(CRunTime.registerObject(list));
        }
Example #16
0
        private void playNextList()
        {
            lock (sound_lists)
            {
                current_list_id = (current_list_id + 1) % MAX_LISTS;

                if (sound_lists[current_list_id] == null)
                {
                    /* nothing to play */
                    current_list_id = -1;
                }
            }
            if (current_list_id == -1)
            {
                return;
            }

            current_list_item = 0;
            current_list      = (SoundList)CRunTime.getRegisteredObject(sound_lists[current_list_id].Value);
            if ((current_list.streams == null) || (current_list.streams.Length != current_list.count))
            {
                current_list.streams = new Stream[current_list.count];
            }
            for (int i = 0; i < current_list.count; i++)
            {
                try
                {
                    if (_soundDir.Equals(""))
                    {
                        current_list.streams[i] = App.GetResourceStream(new Uri(current_list.list[i], UriKind.Relative)).Stream;
                    }
                    else
                    { // This is a downloaded
                        lock (sound_lists)
                        {
                            string soundFilename     = _soundDir + "/" + current_list.list[i];
                            string resourceSoundName = soundFilename.Replace("Userstore:///sound", "/WazeWP7;component/resources/sound");
                            if (!Syscalls.FileExists(soundFilename))
                            {
                                if (Syscalls.FileExists(resourceSoundName))
                                {
                                    Syscalls.CopyFile(resourceSoundName, soundFilename.Replace("Userstore:///", "/"));
                                }
                            }

                            if (Syscalls.FileExists(soundFilename))
                            {
                                current_list.streams[i] = Syscalls.GetFileStream(soundFilename, FileMode.Open);
                            }
                            else
                            {
                                Logger.log("Could not find sound file : " + _soundDir + "/" + current_list.list[i]);
                                UIWorker.addUIEventLog("Could not find sound file : " + _soundDir + "/" + current_list.list[i]);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.log("Error creating sound stream:" + current_list.list[i] + "excp :  " + e.ToString());
                    UIWorker.addUIEventLog("Error creating sound stream:" + current_list.list[i] + "excp :  " + e);
                }
            }

            playNextItem();
        }
    public void PlaySound(SoundList sound, bool doLoop = false)
    {
        //Debug.Log("son :" + sound);

        AudioSource emitterAvailable = null;

        foreach (AudioSource emitter in emitters)
        {
            if (!emitter.isPlaying)
            {
                emitterAvailable = emitter;
            }
        }

        if (emitterAvailable != null)
        {
            switch (sound)
            {
            case SoundList.DIALOG:
                int hasard = Random.Range(0, dialogs.Count);
                emitterAvailable.clip = dialogs[hasard];
                break;

            case SoundList.DIALOG_FURIOUS:
                int hasardFurious = Random.Range(0, dialogsFurious.Count);
                emitterAvailable.clip = dialogsFurious[hasardFurious];
                break;

            case SoundList.PLUG:
                emitterAvailable.clip = plug;
                break;

            case SoundList.SHUSH:
                emitterAvailable.clip = shush;
                break;

            case SoundList.UNPLUG:
                emitterAvailable.clip = unplug;
                break;

            case SoundList.END_CALL_BAD:
                emitterAvailable.clip = endCallBad;
                break;

            case SoundList.BROKEN_LINK:
                emitterAvailable.clip = brokenLink;
                break;

            case SoundList.HALO:
                emitterAvailable.clip = halo;
                break;

            case SoundList.VALID_CALL:
                emitterAvailable.clip = validCall;
                break;

            case SoundList.END_CALL_SUCCESS:
                emitterAvailable.clip = endCallSuccess;
                break;

            case SoundList.LINK_NODE:
                emitterAvailable.clip = linkNode;
                break;
            }

            emitterAvailable.loop = false;
            emitterAvailable.Play();
        }
        else
        {
            //Debug.Log("no emitter available");
        }
    }
Example #18
0
 private static void AwardMultiHit(SoundList sound, int points, string awardedMessage)
 {
     CoreConnector.SoundManager.PlaySound(sound);
     CoreConnector.GameManager.scoreManager.PointsCollected(points);
     CoreConnector.GameUIManager.gameMessages.DisplayInGameMessage(awardedMessage);
 }
Example #19
0
        public static int SplitFile(string datafilename, string inifilename, string projectFolderName, bool nometa = false, bool nolabel = false)
        {
#if !DEBUG
            try
#endif
            {
                byte[]  datafile;
                byte[]  datafile_temp           = File.ReadAllBytes(datafilename);
                IniData inifile                 = IniSerializer.Deserialize <IniData>(inifilename);
                string  listfile                = Path.Combine(Path.GetDirectoryName(inifilename), Path.GetFileNameWithoutExtension(datafilename) + "_labels.txt");
                Dictionary <int, string> labels = new Dictionary <int, string>();
                if (File.Exists(listfile) && !nolabel)
                {
                    labels = IniSerializer.Deserialize <Dictionary <int, string> >(listfile);
                }
                if (inifile.StartOffset != 0)
                {
                    byte[] datafile_new = new byte[inifile.StartOffset + datafile_temp.Length];
                    datafile_temp.CopyTo(datafile_new, inifile.StartOffset);
                    datafile = datafile_new;
                }
                else
                {
                    datafile = datafile_temp;
                }
                if (inifile.MD5 != null && inifile.MD5.Count > 0)
                {
                    string datahash = HelperFunctions.FileHash(datafile);
                    if (!inifile.MD5.Any(h => h.Equals(datahash, StringComparison.OrdinalIgnoreCase)))
                    {
                        Console.WriteLine("The file {0} is not valid for use with the INI {1}.", datafilename, inifilename);
                        return((int)SplitERRORVALUE.InvalidDataMapping);
                    }
                }
                ByteConverter.BigEndian      = SonicRetro.SAModel.ByteConverter.BigEndian = inifile.BigEndian;
                ByteConverter.Reverse        = SonicRetro.SAModel.ByteConverter.Reverse = inifile.Reverse;
                Environment.CurrentDirectory = Path.Combine(Environment.CurrentDirectory, Path.GetDirectoryName(datafilename));
                if (Path.GetExtension(datafilename).ToLowerInvariant() == ".prs" || (inifile.Compressed && Path.GetExtension(datafilename).ToLowerInvariant() != ".bin"))
                {
                    datafile = FraGag.Compression.Prs.Decompress(datafile);
                }
                uint imageBase = HelperFunctions.SetupEXE(ref datafile) ?? inifile.ImageBase.Value;
                if (Path.GetExtension(datafilename).Equals(".rel", StringComparison.OrdinalIgnoreCase))
                {
                    datafile = HelperFunctions.DecompressREL(datafile);
                    HelperFunctions.FixRELPointers(datafile, imageBase);
                }
                bool            SA2          = inifile.Game == Game.SA2 | inifile.Game == Game.SA2B;
                ModelFormat     modelfmt_def = 0;
                LandTableFormat landfmt_def  = 0;
                switch (inifile.Game)
                {
                case Game.SA1:
                    modelfmt_def = ModelFormat.Basic;
                    landfmt_def  = LandTableFormat.SA1;
                    break;

                case Game.SADX:
                    modelfmt_def = ModelFormat.BasicDX;
                    landfmt_def  = LandTableFormat.SADX;
                    break;

                case Game.SA2:
                    modelfmt_def = ModelFormat.Chunk;
                    landfmt_def  = LandTableFormat.SA2;
                    break;

                case Game.SA2B:
                    modelfmt_def = ModelFormat.GC;
                    landfmt_def  = LandTableFormat.SA2B;
                    break;
                }
                int itemcount = 0;
                Dictionary <string, MasterObjectListEntry>     masterobjlist = new Dictionary <string, MasterObjectListEntry>();
                Dictionary <string, Dictionary <string, int> > objnamecounts = new Dictionary <string, Dictionary <string, int> >();
                Stopwatch timer = new Stopwatch();
                timer.Start();
                foreach (KeyValuePair <string, SA_Tools.FileInfo> item in new List <KeyValuePair <string, SA_Tools.FileInfo> >(inifile.Files))
                {
                    if (string.IsNullOrEmpty(item.Key))
                    {
                        continue;
                    }
                    string                      filedesc         = item.Key;
                    SA_Tools.FileInfo           data             = item.Value;
                    Dictionary <string, string> customProperties = data.CustomProperties;
                    string                      type             = data.Type;
                    int  address = data.Address;
                    bool nohash  = false;

                    string fileOutputPath = Path.Combine(projectFolderName, data.Filename);
                    Console.WriteLine(item.Key + ": " + data.Address.ToString("X") + " → " + fileOutputPath);
                    Directory.CreateDirectory(Path.GetDirectoryName(fileOutputPath));
                    switch (type)
                    {
                    case "landtable":
                        LandTableFormat format = data.CustomProperties.ContainsKey("format") ? (LandTableFormat)Enum.Parse(typeof(LandTableFormat), data.CustomProperties["format"]) : landfmt_def;
                        new LandTable(datafile, address, imageBase, format, labels)
                        {
                            Description = item.Key
                        }.SaveToFile(fileOutputPath, landfmt_def, nometa);
                        break;

                    case "model":
                    case "basicmodel":
                    case "basicdxmodel":
                    case "chunkmodel":
                    case "gcmodel":
                    {
                        ModelFormat mdlformat;
                        switch (type)
                        {
                        case "basicmodel":
                            mdlformat = ModelFormat.Basic;
                            break;

                        case "basicdxmodel":
                            mdlformat = ModelFormat.BasicDX;
                            break;

                        case "chunkmodel":
                            mdlformat = ModelFormat.Chunk;
                            break;

                        case "gcmodel":
                            mdlformat = ModelFormat.GC;
                            break;

                        case "model":
                        default:
                            mdlformat = modelfmt_def;
                            break;
                        }
                        if (data.CustomProperties.ContainsKey("format"))
                        {
                            mdlformat = (ModelFormat)Enum.Parse(typeof(ModelFormat), data.CustomProperties["format"]);
                        }
                        NJS_OBJECT mdl     = new NJS_OBJECT(datafile, address, imageBase, mdlformat, labels, new Dictionary <int, Attach>());
                        string[]   mdlanis = new string[0];
                        if (customProperties.ContainsKey("animations"))
                        {
                            mdlanis = customProperties["animations"].Split(',');
                        }
                        string[] mdlmorphs = new string[0];
                        if (customProperties.ContainsKey("morphs"))
                        {
                            mdlmorphs = customProperties["morphs"].Split(',');
                        }
                        ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, null, item.Key, null, mdlformat, nometa);
                    }
                    break;

                    case "action":
                    {
                        ModelFormat modelfmt_act = data.CustomProperties.ContainsKey("format") ? (ModelFormat)Enum.Parse(typeof(ModelFormat), data.CustomProperties["format"]) : modelfmt_def;
                        NJS_ACTION  ani          = new NJS_ACTION(datafile, address, imageBase, modelfmt_act, labels, new Dictionary <int, Attach>());
                        if (!labels.ContainsValue(ani.Name) && !nolabel)
                        {
                            ani.Name = filedesc;
                        }
                        if (customProperties.ContainsKey("numparts"))
                        {
                            ani.Animation.ModelParts = int.Parse(customProperties["numparts"]);
                        }
                        if (ani.Animation.ModelParts == 0)
                        {
                            Console.WriteLine("Action {0} has no model data!", ani.Name);
                            continue;
                        }
                        ani.Animation.Save(fileOutputPath, nometa);
                    }
                    break;

                    case "animation":
                    case "motion":
                        int numparts = 0;
                        if (customProperties.ContainsKey("numparts"))
                        {
                            numparts = int.Parse(customProperties["numparts"], NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
                        }
                        else
                        {
                            Console.WriteLine("Number of parts not specified for {0}", filedesc);
                        }
                        if (customProperties.ContainsKey("shortrot"))
                        {
                            NJS_MOTION mot = new NJS_MOTION(datafile, address, imageBase, numparts, labels, bool.Parse(customProperties["shortrot"]));
                            if (!labels.ContainsKey(address) && !nolabel)
                            {
                                mot.Name = filedesc;
                            }
                            mot.Save(fileOutputPath, nometa);
                        }
                        else
                        {
                            NJS_MOTION mot = new NJS_MOTION(datafile, address, imageBase, numparts, labels);
                            if (!labels.ContainsKey(address) && !nolabel)
                            {
                                mot.Name = filedesc;
                            }
                            mot.Save(fileOutputPath, nometa);
                        }
                        break;

                    case "objlist":
                    {
                        ObjectListEntry[] objs = ObjectList.Load(datafile, address, imageBase, SA2);
                        if (inifile.MasterObjectList != null)
                        {
                            foreach (ObjectListEntry obj in objs)
                            {
                                if (!masterobjlist.ContainsKey(obj.CodeString))
                                {
                                    masterobjlist.Add(obj.CodeString, new MasterObjectListEntry(obj));
                                }
                                if (!objnamecounts.ContainsKey(obj.CodeString))
                                {
                                    objnamecounts.Add(obj.CodeString, new Dictionary <string, int>()
                                        {
                                            { obj.Name, 1 }
                                        });
                                }
                                else if (!objnamecounts[obj.CodeString].ContainsKey(obj.Name))
                                {
                                    objnamecounts[obj.CodeString].Add(obj.Name, 1);
                                }
                                else
                                {
                                    objnamecounts[obj.CodeString][obj.Name]++;
                                }
                            }
                        }
                        objs.Save(fileOutputPath);
                    }
                    break;

                    case "startpos":
                        if (SA2)
                        {
                            SA2StartPosList.Load(datafile, address).Save(fileOutputPath);
                        }
                        else
                        {
                            SA1StartPosList.Load(datafile, address).Save(fileOutputPath);
                        }
                        break;

                    case "texlist":
                        TextureList.Load(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "texnamearray":
                        TexnameArray texnames = new TexnameArray(datafile, address, imageBase);
                        texnames.Save(fileOutputPath);
                        break;

                    case "texlistarray":
                    {
                        int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        for (int i = 0; i < cnt; i++)
                        {
                            uint ptr = BitConverter.ToUInt32(datafile, address);
                            if (data.Filename != null && ptr != 0)
                            {
                                ptr -= imageBase;
                                TexnameArray texarr = new TexnameArray(datafile, (int)ptr, imageBase);
                                string       fn     = Path.Combine(fileOutputPath, i.ToString("D3", NumberFormatInfo.InvariantInfo) + ".txt");
                                if (data.CustomProperties.ContainsKey("filename" + i.ToString()))
                                {
                                    fn = Path.Combine(fileOutputPath, data.CustomProperties["filename" + i.ToString()] + ".txt");
                                }
                                if (!Directory.Exists(Path.GetDirectoryName(fn)))
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(fn));
                                }
                                texarr.Save(fn);
                            }
                            address += 4;
                        }
                        nohash = true;
                    }
                    break;

                    case "leveltexlist":
                        new LevelTextureList(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "triallevellist":
                        TrialLevelList.Save(TrialLevelList.Load(datafile, address, imageBase), fileOutputPath);
                        break;

                    case "bosslevellist":
                        BossLevelList.Save(BossLevelList.Load(datafile, address), fileOutputPath);
                        break;

                    case "fieldstartpos":
                        FieldStartPosList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    case "soundtestlist":
                        SoundTestList.Load(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "musiclist":
                    {
                        int muscnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        MusicList.Load(datafile, address, imageBase, muscnt).Save(fileOutputPath);
                    }
                    break;

                    case "soundlist":
                        SoundList.Load(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "stringarray":
                    {
                        int       cnt  = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        Languages lang = Languages.Japanese;
                        if (data.CustomProperties.ContainsKey("language"))
                        {
                            lang = (Languages)Enum.Parse(typeof(Languages), data.CustomProperties["language"], true);
                        }
                        StringArray.Load(datafile, address, imageBase, cnt, lang).Save(fileOutputPath);
                    }
                    break;

                    case "nextlevellist":
                        NextLevelList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    case "cutscenetext":
                    {
                        int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        new CutsceneText(datafile, address, imageBase, cnt).Save(fileOutputPath, out string[] hashes);
                        data.MD5Hash = string.Join(",", hashes);
                        nohash       = true;
                    }
                    break;

                    case "recapscreen":
                    {
                        int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        RecapScreenList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath, out string[][] hashes);
                        string[] hash2 = new string[hashes.Length];
                        for (int i = 0; i < hashes.Length; i++)
                        {
                            hash2[i] = string.Join(",", hashes[i]);
                        }
                        data.MD5Hash = string.Join(":", hash2);
                        nohash       = true;
                    }
                    break;

                    case "npctext":
                    {
                        int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        NPCTextList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath, out string[][] hashes);
                        string[] hash2 = new string[hashes.Length];
                        for (int i = 0; i < hashes.Length; i++)
                        {
                            hash2[i] = string.Join(",", hashes[i]);
                        }
                        data.MD5Hash = string.Join(":", hash2);
                        nohash       = true;
                    }
                    break;

                    case "levelclearflags":
                        LevelClearFlagList.Save(LevelClearFlagList.Load(datafile, address), fileOutputPath);
                        break;

                    case "deathzone":
                    {
                        List <DeathZoneFlags> flags = new List <DeathZoneFlags>();
                        string        path          = Path.GetDirectoryName(fileOutputPath);
                        List <string> hashes        = new List <string>();
                        int           num           = 0;
                        while (ByteConverter.ToUInt32(datafile, address + 4) != 0)
                        {
                            string file_tosave;
                            if (customProperties.ContainsKey("filename" + num.ToString()))
                            {
                                file_tosave = customProperties["filename" + num++.ToString()];
                            }
                            else
                            {
                                file_tosave = num++.ToString(NumberFormatInfo.InvariantInfo) + ".sa1mdl";
                            }
                            string file = Path.Combine(path, file_tosave);
                            flags.Add(new DeathZoneFlags(datafile, address, file_tosave));
                            ModelFormat modelfmt_death = inifile.Game == Game.SADX ? ModelFormat.BasicDX : ModelFormat.Basic;                                             // Death zones in all games except SADXPC use Basic non-DX models
                            ModelFile.CreateFile(file, new NJS_OBJECT(datafile, datafile.GetPointer(address + 4, imageBase), imageBase, modelfmt_death, new Dictionary <int, Attach>()), null, null, null, null, modelfmt_death, nometa);
                            hashes.Add(HelperFunctions.FileHash(file));
                            address += 8;
                        }
                        flags.ToArray().Save(fileOutputPath);
                        hashes.Insert(0, HelperFunctions.FileHash(fileOutputPath));
                        data.MD5Hash = string.Join(",", hashes.ToArray());
                        nohash       = true;
                    }
                    break;

                    case "skyboxscale":
                    {
                        int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        SkyboxScaleList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath);
                    }
                    break;

                    case "stageselectlist":
                    {
                        int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        StageSelectLevelList.Load(datafile, address, cnt).Save(fileOutputPath);
                    }
                    break;

                    case "levelrankscores":
                        LevelRankScoresList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    case "levelranktimes":
                        LevelRankTimesList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    case "endpos":
                        SA2EndPosList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    case "animationlist":
                    {
                        int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        SA2AnimationInfoList.Load(datafile, address, cnt).Save(fileOutputPath);
                    }
                    break;

                    case "enemyanimationlist":
                    {
                        int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        SA2EnemyAnimInfoList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath);
                    }
                    break;

                    case "sa1actionlist":
                    {
                        int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        SA1ActionInfoList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath);
                    }
                    break;

                    case "motiontable":
                    {
                        Directory.CreateDirectory(fileOutputPath);
                        List <MotionTableEntry> result = new List <MotionTableEntry>();
                        List <string>           hashes = new List <string>();
                        bool shortrot = false;
                        if (customProperties.ContainsKey("shortrot"))
                        {
                            shortrot = bool.Parse(customProperties["shortrot"]);
                        }
                        int nodeCount = int.Parse(data.CustomProperties["nodecount"], NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo);
                        int Length    = int.Parse(data.CustomProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        Dictionary <int, string> mtns = new Dictionary <int, string>();
                        for (int i = 0; i < Length; i++)
                        {
                            MotionTableEntry bmte = new MotionTableEntry();
                            int mtnaddr           = (int)(ByteConverter.ToUInt32(datafile, address) - imageBase);
                            if (!mtns.ContainsKey(mtnaddr))
                            {
                                NJS_MOTION motion = new NJS_MOTION(datafile, mtnaddr, imageBase, nodeCount, null, shortrot);
                                bmte.Motion = motion.Name;
                                mtns.Add(mtnaddr, motion.Name);
                                motion.Save(Path.Combine(fileOutputPath, $"{i}.saanim"), nometa);
                                hashes.Add($"{i}.saanim:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, $"{i}.saanim")));
                            }
                            else
                            {
                                bmte.Motion = mtns[mtnaddr];
                            }
                            bmte.LoopProperty    = ByteConverter.ToUInt16(datafile, address + 4);
                            bmte.Pose            = ByteConverter.ToUInt16(datafile, address + 6);
                            bmte.NextAnimation   = ByteConverter.ToInt32(datafile, address + 8);
                            bmte.TransitionSpeed = ByteConverter.ToUInt32(datafile, address + 0xC);
                            bmte.StartFrame      = ByteConverter.ToSingle(datafile, address + 0x10);
                            bmte.EndFrame        = ByteConverter.ToSingle(datafile, address + 0x14);
                            bmte.PlaySpeed       = ByteConverter.ToSingle(datafile, address + 0x18);
                            result.Add(bmte);
                            address += 0x1C;
                        }
                        IniSerializer.Serialize(result, Path.Combine(fileOutputPath, "info.ini"));
                        hashes.Add("info.ini:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, "info.ini")));
                        data.MD5Hash = string.Join("|", hashes.ToArray());
                        nohash       = true;
                    }
                    break;

                    case "levelpathlist":
                    {
                        List <string> hashes = new List <string>();
                        ushort        lvlnum = (ushort)ByteConverter.ToUInt32(datafile, address);
                        while (lvlnum != 0xFFFF)
                        {
                            int ptr = ByteConverter.ToInt32(datafile, address + 4);
                            if (ptr != 0)
                            {
                                ptr = (int)((uint)ptr - imageBase);
                                SA1LevelAct level  = new SA1LevelAct(lvlnum);
                                string      lvldir = Path.Combine(fileOutputPath, level.ToString());
                                PathList.Load(datafile, ptr, imageBase).Save(lvldir, out string[] lvlhashes);
                                hashes.Add(level.ToString() + ":" + string.Join(",", lvlhashes));
                            }
                            address += 8;
                            lvlnum   = (ushort)ByteConverter.ToUInt32(datafile, address);
                        }
                        data.MD5Hash = string.Join("|", hashes.ToArray());
                        nohash       = true;
                    }
                    break;

                    case "pathlist":
                    {
                        PathList.Load(datafile, address, imageBase).Save(fileOutputPath, out string[] hashes);
                        data.MD5Hash = string.Join(",", hashes.ToArray());
                        nohash       = true;
                    }
                    break;

                    case "stagelightdatalist":
                        SA1StageLightDataList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    case "weldlist":
                        WeldList.Load(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "bmitemattrlist":
                        BlackMarketItemAttributesList.Load(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "creditstextlist":
                        CreditsTextList.Load(datafile, address, imageBase).Save(fileOutputPath);
                        break;

                    case "animindexlist":
                    {
                        Directory.CreateDirectory(fileOutputPath);
                        List <string> hashes = new List <string>();
                        int           i      = ByteConverter.ToInt16(datafile, address);
                        while (i != -1)
                        {
                            new NJS_MOTION(datafile, datafile.GetPointer(address + 4, imageBase), imageBase, ByteConverter.ToInt16(datafile, address + 2))
                            .Save(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim", nometa);
                            hashes.Add(i.ToString(NumberFormatInfo.InvariantInfo) + ":" + HelperFunctions.FileHash(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim"));
                            address += 8;
                            i        = ByteConverter.ToInt16(datafile, address);
                        }
                        data.MD5Hash = string.Join("|", hashes.ToArray());
                        nohash       = true;
                    }
                    break;

                    case "storysequence":
                        SA2StoryList.Load(datafile, address).Save(fileOutputPath);
                        break;

                    case "masterstringlist":
                    {
                        int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        for (int l = 0; l < 5; l++)
                        {
                            Languages            lng = (Languages)l;
                            System.Text.Encoding enc = HelperFunctions.GetEncoding(inifile.Game, lng);
                            string ld = Path.Combine(fileOutputPath, lng.ToString());
                            Directory.CreateDirectory(ld);
                            int ptr = datafile.GetPointer(address, imageBase);
                            for (int i = 0; i < cnt; i++)
                            {
                                int ptr2 = datafile.GetPointer(ptr, imageBase);
                                if (ptr2 != 0)
                                {
                                    string fn = Path.Combine(ld, $"{i}.txt");
                                    File.WriteAllText(fn, datafile.GetCString(ptr2, enc).Replace("\n", "\r\n"));
                                    inifile.Files.Add($"{filedesc} {lng} {i}", new FileInfo()
                                        {
                                            Type = "string", Filename = fn, PointerList = new int[] { ptr }, MD5Hash = HelperFunctions.FileHash(fn), CustomProperties = new Dictionary <string, string>()
                                            {
                                                { "language", lng.ToString() }
                                            }
                                        });
                                }
                                ptr += 4;
                            }
                            address += 4;
                        }
                        inifile.Files.Remove(filedesc);
                        nohash = true;
                    }
                    break;

                    case "camera":
                        NinjaCamera cam = new NinjaCamera(datafile, address);
                        cam.Save(fileOutputPath);
                        break;

                    case "fogdatatable":
                        int fcnt = 3;
                        if (customProperties.ContainsKey("count"))
                        {
                            fcnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        }
                        FogDataTable fga = new FogDataTable(datafile, address, imageBase, fcnt);
                        fga.Save(fileOutputPath);
                        break;

                    case "palettelightlist":
                        int count = 255;
                        if (customProperties.ContainsKey("count"))
                        {
                            count = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
                        }
                        PaletteLightList pllist = new PaletteLightList(datafile, address, count);
                        pllist.Save(fileOutputPath);
                        break;

                    case "physicsdata":
                        PlayerParameter plpm = new PlayerParameter(datafile, address);
                        plpm.Save(fileOutputPath);
                        break;

                    default:                             // raw binary
                    {
                        byte[] bin = new byte[int.Parse(customProperties["size"], NumberStyles.HexNumber)];
                        Array.Copy(datafile, address, bin, 0, bin.Length);
                        File.WriteAllBytes(fileOutputPath, bin);
                    }
                    break;
                    }
                    if (!nohash)
                    {
                        data.MD5Hash = HelperFunctions.FileHash(fileOutputPath);
                    }
                    itemcount++;
                }
                if (inifile.MasterObjectList != null)
                {
                    foreach (KeyValuePair <string, MasterObjectListEntry> obj in masterobjlist)
                    {
                        KeyValuePair <string, int> name = new KeyValuePair <string, int>();
                        foreach (KeyValuePair <string, int> it in objnamecounts[obj.Key])
                        {
                            if (it.Value > name.Value)
                            {
                                name = it;
                            }
                        }
                        obj.Value.Name  = name.Key;
                        obj.Value.Names = objnamecounts[obj.Key].Select((it) => it.Key).ToArray();
                    }

                    string masterObjectListOutputPath = Path.Combine(projectFolderName, inifile.MasterObjectList);

                    IniSerializer.Serialize(masterobjlist, masterObjectListOutputPath);
                }
                IniSerializer.Serialize(inifile, Path.Combine(projectFolderName, Path.GetFileNameWithoutExtension(inifilename) + "_data.ini"));
                timer.Stop();
                Console.WriteLine("Split " + itemcount + " items in " + timer.Elapsed.TotalSeconds + " seconds.");
                Console.WriteLine();
            }
#if !DEBUG
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();
                return((int)SplitERRORVALUE.UnhandledException);
            }
#endif
            return((int)SplitERRORVALUE.Success);
        }
Example #20
0
    public void PlayShotSound(string classID, Vector3 position, float volume)
    {
        SoundList sound = (SoundList)Enum.Parse(typeof(SoundList), classID.ToLower());

        PlayOneShotEffect((int)sound, position, volume);
    }
Example #21
0
        private void playNextItem()
        {
            lock (sound_lists)
            {
                if (current_list_id == -1) return;
                if (sound_lists[current_list_id] == null) return;
            }

            while ((current_list_item < current_list.count) &&
              (current_list.streams[current_list_item] == null))
            {
                current_list_item++;
            }

            try
            {
                int copy_index = current_list_item;
                int copy_count = current_list.count;
                int copy_list_id = current_list_id;

                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        try
                        {
                            lock (sound_lists)
                            {
                                // re-create media element each time in order to avoid multiple subscribers to MediaEnded event
                                mediaElement = new MediaElement();
                                FreeMapMainScreen.get().LayoutRoot.Children.Add(mediaElement);
                                mediaElement.SetSource(current_list.streams[copy_index]);
                                mediaElement.Volume = 1.0;//todomt (double)((double)sound_level / 100.0);
                                mediaElement.MediaEnded += delegate
                                {
                                    lock (sound_lists)
                                    {
                                        if (current_list != null && current_list.streams != null && current_list.streams[copy_index] != null)
                                        {
                                            current_list.streams[copy_index].Close();
                                        }

                                        copy_index++;
                                        if (copy_index == copy_count)
                                        {
                                            closeCurrentList();
                                            FreeMapMainScreen.get().LayoutRoot.Children.Remove(mediaElement);

                                            if ((current_list.flags & SoundList.SOUND_LIST_NO_FREE) == 0)
                                            {
                                                listFree(sound_lists[copy_list_id]);
                                            }

                                            sound_lists[copy_list_id] = null;
                                            current_list = null;
                                            playNextList();

                                        }
                                        else
                                        {
                                            mediaElement.SetSource(current_list.streams[copy_index]);
                                            mediaElement.Volume = 1.0;//todomt (double)((double)sound_level / 100.0);
                                            mediaElement.Play();
                                        }
                                    }
                                };

                                try
                                {
                                    mediaElement.Play();
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Logger.log("Exception: " + e);
                        }
                    });

            }
            catch (Exception e)
            {
                Logger.log("Exception: " + e);
                closeCurrentList();
                playNextList();
                return;
            }
        }
 private Sound GetSfx(SoundList inSound)
 {
     return(_config.sfxMap.FirstOrDefault(s => s.label == inSound));
 }
Example #23
0
 /// <summary>
 /// リストのセット
 /// </summary>
 /// <param name="list"></param>
 public void SetSoundList(SoundList list)
 {
     sounds = list.Table;
 }
Example #24
0
 protected static void PlaySound(SoundList sound)
 {
     CoreConnector.SoundManager.PlaySound(sound);
 }
Example #25
0
 void Awake()
 {
     instance  = this;
     soundList = GetComponent(typeof(SoundList)) as SoundList;
 }
Example #26
0
        // This is where the magic happens. Matches SoundKitIDs to FileDataIDS and returns a formatted lua string.
        private string GetFileDataID(string ListName, List <SoundFileEntry> SoundKitData, SoundList SoundKitIds)
        {
            List <SoundFileEntry> FilteredSoundData;
            string formattedString = "";
            string soundKitErrors  = "";
            int    errorCount      = 0;
            bool   hasError        = false;

            // For each SoundKitID we are targetting for a mute.
            foreach (SoundTarget st in SoundKitIds.targets)
            {
                // Append the entry comment to the top of the current block.
                formattedString = formattedString + "   -- " + st.EntryComment + "\n";
                foreach (ulong i in st.SoundKitIDs)
                {
                    // Create a filtered list that contains the FileDataIds with the matching SoundKitID
                    FilteredSoundData = SoundKitData.FindAll(x => x.SoundKitID == i);
                    if (FilteredSoundData.Count > 0)
                    {
                        // Lua file indentation.
                        formattedString += "   ";
                        // Write each FileDataID in sequence.
                        foreach (SoundFileEntry SFE in FilteredSoundData)
                        {
                            formattedString = formattedString + SFE.FileDataID + ",";
                        }
                        // Append the SoundKitID at the end as comment.
                        formattedString = formattedString + " -- " + i + "\n";
                    }
                    else
                    {
                        hasError        = true;
                        soundKitErrors += "'" + i + "', ";
                        errorCount++;
                    }
                }
                // For sounds not part of a soundkit
                // In this case the sound ID is the FileDataID, no matching required.
                if (st.SingleSounds.Count > 0)
                {
                    foreach (int j in st.SingleSounds)
                    {
                        formattedString = formattedString + j + ",";
                    }
                    formattedString += "-- Non soundkit sounds\n";
                }
            }
            if (hasError)
            {
                soundKitErrors = parent.ReplaceLastOccurrence(soundKitErrors, ", ", ".");
                parent.AppendError("File: " + ListName + ".txt\nNo matches found for: " + soundKitErrors + "\n\n", 1);
                parent.LogMessage(" ...done with (" + errorCount + ") error(s).\n", Color.Orange, parent.Bold_Font);
            }
            else
            {
                parent.LogMessage(" ...done!\n", Color.Green, parent.Bold_Font);
            }
            return(formattedString);
        }
Example #27
0
    void OnGUI()
    {
        canRepair = EditorGUILayout.Toggle("Repair", canRepair);
        if (canRepair)
        {
            oldSoundList = EditorGUILayout.ObjectField("Chọn SoundList hỏng", oldSoundList, typeof(SoundList), false) as SoundList;
            if (GUILayout.Button("Repair..."))
            {
                var tmp = oldSoundList.list;
                SoundList      = CreateInstance <SoundList>();
                SoundList.list = new List <Sound>();
                AssetDatabase.CreateAsset(SoundList, "Assets/GameObject/SoundList.asset");
                AssetDatabase.SaveAssets();

                foreach (var item in tmp)
                {
                    Sound s = CreateInstance <Sound>();
                    s.name   = item.name;
                    s.clip   = item.clip;
                    s.volume = item.volume;
                    s.pitch  = item.pitch;
                    s.loop   = item.loop;
                    SoundList.list.Add(s);
                    AssetDatabase.AddObjectToAsset(s, SoundList);
                    AssetDatabase.SaveAssets();
                }
                canRepair = false;
            }
        }
        EditorGUILayout.Space();
        if (GUILayout.Button("Create New SoundList List"))
        {
            SoundList      = CreateInstance <SoundList>();
            SoundList.list = new List <Sound>();
            AssetDatabase.CreateAsset(SoundList, "Assets/GameObject/SoundList.asset");
            AssetDatabase.SaveAssets();
        }

        sName      = EditorGUILayout.TextField("Tên sound", sName);
        sAudioClip = EditorGUILayout.ObjectField("Chọn AudioClip", sAudioClip, typeof(AudioClip), false) as AudioClip;
        sVolume    = EditorGUILayout.Slider("Âm lượng", sVolume, 0f, 1f);
        sPitch     = EditorGUILayout.Slider("Pitch", sPitch, 0.1f, 3f);
        sLoop      = EditorGUILayout.Toggle("Tự động lặp", sLoop);

        if (GUILayout.Button("Add New Sound"))
        {
            Sound s = CreateInstance <Sound>();
            s.name   = sName;
            s.clip   = sAudioClip;
            s.volume = sVolume;
            s.pitch  = sPitch;
            s.loop   = sLoop;
            SoundList.list.Add(s);
            AssetDatabase.AddObjectToAsset(s, SoundList);
            AssetDatabase.SaveAssets();
        }

        if (GUI.changed)
        {
            EditorUtility.SetDirty(SoundList);
        }
    }
Example #28
0
        protected virtual void Update()
        {
            if (!FootstepsEnabled())
            {
                return;
            }

            //this condition helps prevent making a nuisance footstep noise when the player first
            //loads a save, or into an interior or exterior location
            if (GameManager.Instance.SaveLoadManager.LoadInProgress || GameManager.Instance.StreamingWorld.IsRepositioningPlayer)
            {
                ignoreLostGrounding = true;
                return;
            }

            DaggerfallDateTime.Seasons playerSeason = dfUnity.WorldTime.Now.SeasonValue;
            int climateIndex = GameManager.Instance.PlayerGPS.CurrentClimateIndex;

            // Get player inside flag
            // Can only do this when PlayerEnterExit is available, otherwise default to true
            bool inside     = (playerEnterExit == null) ? true : playerEnterExit.IsPlayerInside;
            bool inBuilding = (playerEnterExit == null) ? false : playerEnterExit.IsPlayerInsideBuilding;

            // Play splash footsteps whether player is walking on or swimming in exterior water
            bool onExteriorWater = IsOnExteriorWater();

            bool pnExteriorPath   = IsOnExteriorPath();
            bool onStaticGeometry = IsOnStaticGeometry();

            // Change footstep sounds between winter/summer variants, when player enters/exits an interior space, or changes between path, water, or other outdoor ground
            if (playerSeason != currentSeason || climateIndex != currentClimateIndex || isInside != inside || onExteriorWater != isInOutsideWater || pnExteriorPath != isInOutsidePath || onStaticGeometry != isOnStaticGeometry)
            {
                currentSeason       = playerSeason;
                currentClimateIndex = climateIndex;
                isInside            = inside;
                isInOutsideWater    = onExteriorWater;
                isInOutsidePath     = pnExteriorPath;
                isOnStaticGeometry  = onStaticGeometry;

                if (!isInside && !onStaticGeometry)
                {
                    if (currentSeason == DaggerfallDateTime.Seasons.Winter && !WeatherManager.IsSnowFreeClimate(currentClimateIndex))
                    {
                        currentFootstepSoundList = FootstepSoundSnow;
                    }
                    else
                    {
                        currentFootstepSoundList = FootstepSoundOutside;
                    }
                }
                else if (inBuilding)
                {
                    currentFootstepSoundList = FootstepSoundBuilding;
                }
                else // in dungeon
                {
                    currentFootstepSoundList = FootstepSoundDungeon;
                }
            }

            // walking on water tile
            if (onExteriorWater)
            {
                currentFootstepSoundList = FootstepSoundSubmerged;
            }

            // walking on path tile
            if (pnExteriorPath)
            {
                currentFootstepSoundList = FootstepSoundDungeon;
            }

            // Use water sounds if in dungeon water
            if (GameManager.Instance.PlayerEnterExit.IsPlayerInsideDungeon && playerEnterExit.blockWaterLevel != 10000)
            {
                // In water, deep depth
                if ((currentFootstepSoundList != FootstepSoundSubmerged) && playerEnterExit.IsPlayerSwimming)
                {
                    currentFootstepSoundList = FootstepSoundSubmerged;
                }
                // In water, shallow depth
                else if ((currentFootstepSoundList != FootstepSoundShallow) && !playerEnterExit.IsPlayerSwimming && (transform.position.y - 0.55f) < (playerEnterExit.blockWaterLevel * -1 * MeshReader.GlobalScale))
                {
                    currentFootstepSoundList = FootstepSoundShallow;
                }
            }

            // Not in water, reset footsteps to normal
            if ((!onExteriorWater) &&
                (currentFootstepSoundList == FootstepSoundSubmerged || currentFootstepSoundList == FootstepSoundShallow) &&
                (playerEnterExit.blockWaterLevel == 10000 || (transform.position.y - 0.95f) >= (playerEnterExit.blockWaterLevel * -1 * MeshReader.GlobalScale)))
            {
                currentFootstepSoundList = FootstepSoundDungeon;
            }

            // Check whether player is on foot and abort playing footsteps if not.
            if (IsLevitating() || !transportManager.IsOnFoot && GameManager.Instance.PlayerMotor.OnExteriorWater == PlayerMotor.OnExteriorWaterMethod.None)
            {
                distance = 0f;
                return;
            }

            // Check if player is grounded
            // Note: In classic, submerged "footstep" sound is only played when walking on the floor while in the water, but it sounds like a swimming sound
            // and when outside is played while swimming at the water's surface, so it seems better to play it all the time while submerged in water.
            if (!IsSwimming())
            {
                if (!IsGrounded())
                {
                    // Player has lost grounding
                    distance      = 0f;
                    lostGrounding = true;
                    return;
                }
                else
                {
                    // Player is grounded but we might need to reset after losing grounding
                    if (lostGrounding)
                    {
                        distance      = 0f;
                        lastPosition  = GetHorizontalPosition();
                        lostGrounding = false;

                        if (ignoreLostGrounding)
                        {
                            ignoreLostGrounding = false;
                        }
                        else if (customAudioSource && currentFootstepSoundList != null)
                        {
                            PlayFootstep(FootstepVolumeScale * DaggerfallUnity.Settings.SoundVolume);
                        }

                        return;
                    }
                }
            }

            if (IsStandingStill())
            {
                return;
            }

            // Get distance player travelled horizontally
            Vector3 position = GetHorizontalPosition();

            distance    += Vector3.Distance(position, lastPosition);
            lastPosition = position;

            // Get threshold
            float threshold = IsRunning() ? RunStepInterval : WalkStepInterval;

            // Play sound if over distance threshold
            if (distance > threshold && customAudioSource && currentFootstepSoundList != null)
            {
                float volumeScale = FootstepVolumeScale;
                if (IsMovingLessThanHalfSpeed())
                {
                    volumeScale *= 0.5f;
                }

                PlayFootstep(volumeScale * DaggerfallUnity.Settings.SoundVolume);

                distance = 0f;
            }
        }
Example #29
0
    public AudioSource PlaySound(SoundList sound, float volume = 1.0f, float timeToLoop = 0.0f)
    {
        //return null;
        AudioSource emitterAvailable = null;

        foreach (AudioSource emitter in emitters)
        {
            if (!emitter.isPlaying)
            {
                emitterAvailable = emitter;
            }
        }

        if (emitterAvailable != null)
        {
            emitterAvailable.loop   = false;
            emitterAvailable.volume = volume;
            Debug.Log(sound.ToString());
            switch (sound)
            {
            case SoundList.PAS:
                int indexWalk = Random.Range(0, listPasSounds.Count);
                emitterAvailable.clip = listPasSounds[indexWalk];
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Marche")[0];
                break;

            case SoundList.BUISSON:
                int indexBuisson = Random.Range(0, listBuissonSounds.Count);
                emitterAvailable.clip = listBuissonSounds[indexBuisson];
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Buisson")[0];
                break;

            case SoundList.LOUP_CRI:
                emitterAvailable.clip = loupCriClip;
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Cri")[0];
                break;

            case SoundList.LOUP_GROGNEMENT:
                emitterAvailable.clip = loupGrognementClip;
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Grognement")[0];
                break;

            case SoundList.CLIC:
                emitterAvailable.clip = clicClip;
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Clic")[0];
                break;

            case SoundList.DIALOGUE:
                emitterAvailable.clip = dialogueClip;
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Dialogue")[0];
                break;

            case SoundList.FEUILLAGE:
                int indexFeuillage = Random.Range(0, listFeuillageSounds.Count);
                emitterAvailable.clip = listFeuillageSounds[indexFeuillage];
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Feuillage")[0];
                break;

            case SoundList.GRAB:
                emitterAvailable.clip = grabClip;
                emitterAvailable.outputAudioMixerGroup = audioMixer.FindMatchingGroups("Ramasser")[0];
                break;
            }

            if (timeToLoop > 0.0f)
            {
                emitterAvailable.loop = true;
                LoopedSound newLoopSound = new LoopedSound
                {
                    audioSource   = emitterAvailable,
                    timeUntilStop = Utility.StartTimer(timeToLoop)
                };
                loopedSoundList.Add(newLoopSound);
            }

            emitterAvailable.Play();
            return(emitterAvailable);
        }
        else
        {
            return(null);
        }
    }
 private void SoundListEditor_Load(object sender, EventArgs e)
 {
     levelList.BeginUpdate();
     foreach (KeyValuePair <string, FileInfo> item in Program.IniData.Files)
     {
         if (item.Value.Type.Equals("soundlist", StringComparison.OrdinalIgnoreCase))
         {
             soundLists.Add(new KeyValuePair <string, SoundListEntry[]>(item.Value.Filename, SoundList.Load(item.Value.Filename)));
             levelList.Items.Add(item.Key);
         }
     }
     levelList.EndUpdate();
     levelList.SelectedIndex = 0;
     soundName.Directory     = Program.IniData.SoundFolder;
 }
Example #31
0
 public int listCreate(int flags)
 {
     SoundList list = new SoundList(flags);
     return CRunTime.registerObject(list);
 }
Example #32
0
 void OnEnable()
 {
     SoundList = AssetDatabase.LoadAssetAtPath <SoundList>("Assets/GameObject/SoundList.asset");
 }
Example #33
0
        private void playNextItem()
        {
            lock (sound_lists)
            {
                if (current_list_id == -1) return;
                if (sound_lists[current_list_id] == null) return;
            }

            while ((current_list_item < current_list.count) &&
              (current_list.streams[current_list_item] == null))
            {

                current_list_item++;
            }

            if (current_list_item == current_list.count)
            {
                closeCurrentList();
                if ((current_list.flags & SoundList.SOUND_LIST_NO_FREE) == 0)
                {
                    listFree(sound_lists[current_list_id]);
                }
                sound_lists[current_list_id] = null;
                current_list = null;
                playNextList();
                return;
            }

            try
            {
                int copy_index = current_list_item;
                current_list_item++;
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        try
                        {
                            lock (sound_lists)
                            {

                                // Cleanup previously played sound.

                                if (_lastSoundInstance != null)
                                {
                                    _lastSoundInstance.Dispose();
                                }
                                if (_lastSound != null)
                                {
                                    _lastSound.Dispose();
                                }

                                // Get the audio stream
                                _lastSound = SoundEffect.FromStream(current_list.streams[copy_index]);
                                // Update XNA on new Sound Effect
                                FrameworkDispatcher.Update();

                                // Create instance we can play concurrently
                                _lastSoundInstance = _lastSound.CreateInstance();

                                // Play the sound concurrently with max relative volume
                                _lastSoundInstance.Volume = 1;
                                _lastSoundInstance.Play();

                                Thread nextSoundThread = new Thread(new ThreadStart(
                                    delegate
                                    {

                                        // Wait for the sound to finish playing on an other thread so we won't block the UI.
                                        Thread.Sleep((int)_lastSound.Duration.TotalMilliseconds + 1);

                                        // Cleanup Stream
                                        if (current_list != null && current_list.streams != null && current_list.streams[copy_index] != null)
                                        {
                                            current_list.streams[copy_index].Close();
                                        }

                                        // Play Next item
                                        playNextItem();
                                    }));
                                nextSoundThread.Start();
                            }

                            #region Old Playback code

                            //    // re-create media element each time in order to avoid multiple subscribers to MediaEnded event
                            //    mediaElement = new MediaElement();
                            //    GamePage.get().LayoutRoot.Children.Add(mediaElement);
                            //    mediaElement.SetSource(current_list.streams[copy_index]);
                            //    mediaElement.Volume = 1.0;//todomt (double)((double)sound_level / 100.0);
                            //    mediaElement.MediaEnded += delegate
                            //    {
                            //        lock (sound_lists)
                            //        {
                            //            if (current_list != null && current_list.streams != null && current_list.streams[copy_index] != null)
                            //            {
                            //                current_list.streams[copy_index].Close();
                            //            }
                            //        }
                            //        GamePage.get().LayoutRoot.Children.Remove(mediaElement);
                            //        playNextItem();
                            //    };

                            //    mediaElement.MediaOpened += delegate
                            //    {
                            //        try
                            //        {
                            //            mediaElement.Play();
                            //        }
                            //        catch (Exception e)
                            //        {
                            //            Logger.log("Error playing sound " + e);
                            //        }
                            //    };
                            //}

                            #endregion Old Playback code

                        }
                        catch (Exception e)
                        {
                            Logger.log("Exception: " + e.ToString());
                        }

                    });

            }
            catch (Exception e)
            {
                Logger.log("Exception: " + e.ToString());
                closeCurrentList();
                playNextList();
                return;
            }
        }
Example #34
0
 public void Awake()
 {
     soundList = this;
 }
Example #35
0
        private void playNextList()
        {
            lock (sound_lists)
            {
                current_list_id = (current_list_id + 1) % MAX_LISTS;

                if (sound_lists[current_list_id] == null)
                {

                    /* nothing to play */
                    current_list_id = -1;
                }
            }
            if (current_list_id == -1) return;

            current_list_item = 0;
            current_list = (SoundList)CRunTime.getRegisteredObject(sound_lists[current_list_id].Value);
            if ((current_list.streams == null) || (current_list.streams.Length != current_list.count))
            {
                current_list.streams = new Stream[current_list.count];
            }
            for (int i = 0; i < current_list.count; i++)
            {
                try
                {
                    if (_soundDir.Equals(""))
                        current_list.streams[i] = App.GetResourceStream(new Uri(current_list.list[i], UriKind.Relative)).Stream;
                    else
                    { // This is a downloaded
                        lock (sound_lists)
                        {
                            string soundFilename = _soundDir + "/" + current_list.list[i];
                            string resourceSoundName = soundFilename.Replace("Userstore:///sound", "/WazeWP7;component/resources/sound");
                            if (!Syscalls.FileExists(soundFilename))
                            {
                                if (Syscalls.FileExists(resourceSoundName))
                                {
                                    Syscalls.CopyFile(resourceSoundName, soundFilename.Replace("Userstore:///", "/"));
                                }
                            }

                            if (Syscalls.FileExists(soundFilename))
                            {
                                current_list.streams[i] = Syscalls.GetFileStream(soundFilename, FileMode.Open);
                            }
                            else
                            {
                                Logger.log("Could not find sound file : " + _soundDir + "/" + current_list.list[i]);
                                UIWorker.addUIEventLog("Could not find sound file : " + _soundDir + "/" + current_list.list[i]);
                            }
                        }
                    }

                }
                catch (Exception e)
                {
                    Logger.log("Error creating sound stream:" + current_list.list[i] + "excp :  " + e.ToString());
                    UIWorker.addUIEventLog("Error creating sound stream:" + current_list.list[i] + "excp :  " + e);
                }
            }

            playNextItem();
        }