Inheritance: MonoBehaviour
		public void SetUp()
		{
			GameInfo gameInfo = new GameInfo();
			gameInfo.Mock();
			this.Manager = new ScreensManager(gameInfo);

			this.Screen1 = new Mock<Screen>("Screen1", ScreenType.Fullscreen);
			this.Screen1.Setup(s => s.OnInit());
			this.Screen1.Setup(s => s.OnDeinit());

			this.Screen2 = new Mock<Screen>("Screen2", ScreenType.Popup);
			this.Screen2.Setup(s => s.OnInit());
			this.Screen2.Setup(s => s.OnDeinit());

			this.Screen3 = new Mock<Screen>("Screen3", ScreenType.Normal);
			this.Screen3.Setup(s => s.OnInit());
			this.Screen3.Setup(s => s.OnDeinit());

			this.Screen4 = new Mock<Screen>("Screen4", ScreenType.Normal);
			this.Screen4.Setup(s => s.OnInit());
			this.Screen4.Setup(s => s.OnDeinit());

			this.Manager.Add(this.Screen1.Object);
			this.Manager.Add(this.Screen2.Object);
			this.Manager.Add(this.Screen3.Object);
			this.Manager.Add(this.Screen4.Object);

			this.ScreensList = new IScreen[]
			{
				this.Screen1.Object,
				this.Screen2.Object,
				this.Screen3.Object,
				this.Screen4.Object
			};
		}
Beispiel #2
0
        public World(GameInfo game, int size)
        {
            Game       = game;
            Size       = size;
            Cells      = TerrainGenerator.generateCells(this);
            BaseCell   = Cells.Where(c => c.Type == CellType.Start).First();
            ActiveCell = BaseCell;
            FogOfWar   = new FogOfWar(this);

            var brush = Marooned.Instance.GetService<ContentCache>().Load<TiledBrush>("brush/base");
            brush.Stamp(BaseCell, (Vector2.One * Cell.CELL_SIZE - brush.Bounds) / 2);
            // TEMP: Debug
            new UnitKekeke(BaseCell[10, 10]);
            new UnitKekeke(BaseCell[23, 52]);
            new UnitKekeke(BaseCell[5, 49]);
            new UnitKekeke(BaseCell[40, 52]);
            new UnitKekeke(BaseCell[36, 15]);
            //for (int i = 0; i < game.ArtifactsTotal; ++i)
            //    new ItemArtifact(BaseCell[21, 20 + i]);
            // Setup any entities created/etc....
            foreach (var c in Cells) c.Update(new TimeSpan(0));
            foreach (var u in BaseCell.Entities.Where(e => e is UnitCrew)
                                               .Select(e => (UnitCrew)e))
                u.IFF = IFFPlayer;
        }
    public void AddStatusEffect(GameInfo.StatusEffect effectName, int duration, int magnitude, int addMagnitude, int removeMagnitude)
    {
        bool hasDuplicate = false;
        GameObject duplicate = null;
        StatusEffect duplicateEffect = null;

        for (int i = 0; i < statusEffectList.Count; i++) {
            if (statusEffectList[i].GetComponent<StatusEffect>().GetEffectName() == effectName) {
                hasDuplicate = true;
                duplicate = statusEffectList[i];
                duplicateEffect = duplicate.GetComponent<StatusEffect>();
                break;
            }
        }
        if (hasDuplicate && duplicateEffect.maxStacks > 0 && (duplicateEffect.GetNumberOfStacks() < duplicateEffect.GetMaxStacks())) {
            duplicateEffect.AddStack(duration, magnitude);
        }

        else {
            GameObject newEffect = (GameObject)Instantiate(gameInfo.statusEffectList[(int)effectName], transform.position, Quaternion.identity);
            newEffect.GetComponent<StatusEffect>().Initialize(duration, magnitude, addMagnitude, removeMagnitude);
            newEffect.transform.parent = transform;
            statusEffectList.Add(newEffect);
            newEffect.GetComponent<StatusEffect>().AddStatusEffect();
        }
    }
Beispiel #4
0
 public static void AddBuilding(GameObject go, GameInfo.BuildingsTypes type)
 {
     if(type == GameInfo.BuildingsTypes.BunkRoom)
         bunkRooms.Add(go);
     if(type == GameInfo.BuildingsTypes.GreasySpoon)
         greasySpoons.Add(go);
 }
Beispiel #5
0
        // ランダムに移動
        void idle(GameInfo gameInfo)
        {
            if (gameInfo.GameTime.TotalGameTime.TotalMilliseconds - preActionTime > 200)
            {
                Random rnd = new Random((PlayerIndex - PlayerIndex.One)*100 + Environment.TickCount);
                int act = rnd.Next(100);
                act /= 25;
                switch (act)
                {
                    case 0:
                        nowDirection=Direction.UP;
                        break;
                    case 1:
                        nowDirection=Direction.RIGHT;
                        break;
                    case 2:
                        nowDirection=Direction.LEFT;
                        break;
                    case 3:
                        nowDirection=Direction.DOWN;
                        break;
                }
                preActionTime = gameInfo.GameTime.TotalGameTime.TotalMilliseconds;
            }

            Move(nowDirection);
            return;
        }
        public IGameState[] PerformLogic(GameTime gameTime, GameInfo gameInfo)
        {
            var currentPlayer = gameInfo.CurrentPlayer;

            bool reversing = currentPlayer.CurrentNode == currentPlayer.NextNode;
            var currentLocation = currentPlayer.ActualLocation;
            var targetLocation =
                reversing
                    ? currentPlayer.NextNode.GetTravelPosition(gameInfo.CurrentPlayerIndex, gameInfo.TotalPlayers)
                    : currentPlayer.NextNode.Center;

            float newRotation;
            Vector2 normalisedVector;

            // If we've reached our destination
            if (TravelTo(currentLocation, targetLocation, currentPlayer.Rotation, reversing, out normalisedVector, out newRotation)) {
                // We have now reached the 'next' node, and thus it is our current node.
                currentPlayer.CurrentNode = currentPlayer.NextNode;

                return (!reversing && currentPlayer.RollAmount == 0) ? new IGameState[] { this } : null;
            }

            currentPlayer.ActualLocation += normalisedVector * MoveSpeed;
            currentPlayer.Rotation = newRotation;

            return new IGameState[] { this };
        }
    public int CalculateModifiedEffect(GameObject character, int initial, GameInfo.Stat stat, float modifierAmount)
    {
        float modifier = modifierAmount;
        CharacterInfo characterInfo = character.GetComponent<CharacterInfo>();
        switch (stat) {
            case GameInfo.Stat.Strength:
                modifier *= characterInfo.GetStrength();
                break;
            case GameInfo.Stat.Agility:
                modifier *= characterInfo.GetAgility();
                break;
            case GameInfo.Stat.Intelligence:
                modifier *= characterInfo.GetIntelligence();
                break;
            case GameInfo.Stat.Wisdom:
                modifier *= characterInfo.GetWisdom();
                break;
            case GameInfo.Stat.Defense:
                modifier *= characterInfo.GetDefense();
                break;
            default:
                break;
        }

        return (int)(initial + modifier);
    }
Beispiel #8
0
    void Start()
    {
        try
        {
            gameInfo = GameObject.Find("GameInfo").GetComponent<GameInfo>();
        }
        catch (Exception e)
        {

        }
        if (gameInfo == null)
        {
            GameObject gameInfoObj = new GameObject("GameInfo");
            UnityEngine.Object.DontDestroyOnLoad(gameInfoObj);

            gameInfoObj.AddComponent<GameInfo>();
            gameInfo = gameInfoObj.GetComponent<GameInfo>();
        }

        mapName = gameInfo.mapName;

        sr = gameObject.GetComponent<SpriteRenderer>();
        sr.sprite = Resources.Load<Sprite>("Sprites/Loading/loading_" + mapName + "_01");

        beep1 = Resources.Load<AudioClip>("Sounds/Loading/loading_beep_01");
        beep2 = Resources.Load<AudioClip>("Sounds/Loading/loading_beep_02");
        beep3 = Resources.Load<AudioClip>("Sounds/Loading/loading_beep_03");
        beep4 = Resources.Load<AudioClip>("Sounds/Loading/loading_beep_04");

        frameCountSinceLvlLoad = 0;
        SoundManager.instance.PlaySingle(beep1, false, 1f, 128, false);
    }
Beispiel #9
0
        public override IGameState[] PerformLogic(GameTime gameTime, GameInfo gameInfo)
        {
            var currentPlayer = gameInfo.CurrentPlayer;

            currentPlayer.CareerType = CareerType.CollegeCareer;

            // Test if they're already taken the exam before
            if (currentPlayer.PassedExam) {
                return null;
            }

            var waitState = StateFactory.GetState(GameStates.GameStates.Wait);

            if (currentPlayer.CurrentlyTakingExam) {
                return TestPassedExamLogic(gameInfo, waitState);
            }

            if (currentPlayer.CareerType != CareerType.CollegeCareer) {
                return CreateAlert(gameInfo, waitState, "You can only take an exam if you took college path", icon: "Images/AlertIcons/Fail");
            }

            // Strip their roll amount;
            currentPlayer.RollAmount = 0;

            // Set their taking exam boolean to be true
            currentPlayer.CurrentlyTakingExam = true;

            return TakeExamLogic(gameInfo);
        }
Beispiel #10
0
    public void ProducePart( GameInfo gameInfo, GameObject myGO, int amount = 1 )
    {
        int myGOTeam = myGO.GetComponent<Generic_Team>().TeamNum;

        if (isServer)
        {
            List<GameObject> parts = new List<GameObject>();
            for ( int i = 0; i < amount; i++ )
            {
                parts.Add(MakePart( new Vector2( i, 0 ), Vector2.zero, 0.0f, myGOTeam ));
            }

            List<GameObject> myGO_parts;
            myGO_parts = myGO.GetComponent<Unit_PartPlacement>().parts;
            myGO_parts.Clear();
            int gOID = myGO.GetInstanceID();
            //u16 playerID = blob.getPlayer().getNetworkID();
            for (int i = 0; i < parts.Count; i++)
            {
                GameObject gO = parts[i];
                myGO_parts.Add( gO );
                gO.GetComponent<Part_Info>().OwnerID = gOID;
                //b.set_u16( "playerID", playerID );
                gO.GetComponent<Part_Info>().ShipID = -1; // don't push on ship
            }
        }
    }
Beispiel #11
0
	void Awake ()
	{
		_gi = GetComponent<GameInfo> ();
		switch (_gi.Level) {
		case GameInfo.Difficulty.easy:
			_modifier = 0.85f;
			break;
		case GameInfo.Difficulty.normal:
			_modifier = 1.0f;
			break;
		case GameInfo.Difficulty.hard:
			_modifier = 1.15f;
			break;
		}
		_player = Instantiate (player, Vector3.zero, Quaternion.identity) as GameObject;
		_missileLaunchers = new GameObject[4];
		_spawnIndex = 0;

		if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer) {
			helpUI.GetComponent<Text> ().enabled = false;
			restartUI.GetComponent<Text> ().text = "Tap to restart";
		} else {
			helpLeftUI.GetComponent<Text> ().enabled = false;
			helpRightUI.GetComponent<Text> ().enabled = false;
		}
		score = GetComponent<Score> ();
	}
	public static void SetNextId( GameInfo gameInfo, Ship ship )
	{
		//islands.id = this.get_u32("islands id")+1;
		//this.set_u32("islands id", islands.id);
		ship.id = gameInfo.ShipsID+1;
		gameInfo.ShipsID = ship.id;
	}
Beispiel #13
0
 void Start()
 {
     m_Count = 0;
     board = GameObject.Find ("Board").GetComponent<Board> ();
     player = GameObject.Find ("PlayerInput").GetComponent<PlayerInput>();
     gameInfo = GameObject.Find ("GameInfo").GetComponent<GameInfo>();
 }
Beispiel #14
0
        /// <summary>
        /// これがAIの動作の処理です。
        /// gameInfoを用いて1フレームに与える指示を出してください。
        /// HumanControllerも全く同じ仕組です
        /// </summary>
        /// <param name="gameInfo"></param>
        /// <param name="input"></param>
        public override void Update(GameInfo gameInfo, Input input)
        {
            //最初に必ずbaseのUpdateを呼び出してください
            base.Update(gameInfo, input);

            //攻撃する。
            Attack();
            //移動する(同じフレームでAttackが呼ばれているときはAttackが無条件で優先されます)
            //複数回呼んだ場合最後のMoveが使われます。
            Move(Direction.UP);

            //gameInfoから自分のPlayerInfoを取得
            PlayerInfo myInfo;
            foreach (PlayerInfo info in gameInfo.PlayerInfos)
            {
                if (info.Index == PlayerIndex)
                {
                    myInfo = info;
                }
            }


            //おまけ:PlayerIndexをintにしたい!(キャラごとにユニークな値が取れるので乱数のシードなどに使えます)
            int index = PlayerIndex - PlayerIndex.One;
        }
Beispiel #15
0
    public void ChangeTo(GameInfo.States state)
    {
        uSC.uMC.Reset();

        if(state == GameInfo.States.Idle)
            uSC.currentState = uSC.idle;
    }
Beispiel #16
0
 public void TestCreation()
 {
     GameInfo info = new GameInfo("GameInfoTest.xml");
     Assert.AreEqual("cool game", info.Title);
     Assert.AreEqual("../pony", info.Path);
     Assert.AreEqual("a very cool game", info.Description);
     Assert.AreEqual("images/dinosaur.png", info.ImagePath);
 }
        public IGameState[] PerformLogic(GameTime gameTime, GameInfo gameInfo)
        {
            var availablePaths = gameInfo.CurrentPlayer.CurrentNode.LinksTo;
            var waitState = StateFactory.GetState(GameStates.Wait);

            ChoosePathHelper.TravelToNodes(availablePaths, gameInfo, (node, location) => PathChosen(node, gameInfo, waitState));
            return new[] { waitState };
        }
 public void Update(GameInfo gameInfo)
 {
     foreach (StockDrawer stackDrawer in stockDrawers)
     {
         stackDrawer.Update();
     }
     timer.Update(gameInfo);
 }
Beispiel #19
0
        private IGameState[] CreateAlert(GameInfo gameInfo, IGameState waitState, String message, IGameState[] addStates = null, String icon = null)
        {
            var alert = new Alert(gameInfo.Manager, message, icon: icon);
            gameInfo.Manager.Add(alert);
            alert.Closing += (sender, args) => gameInfo.Fsm.Remove(waitState);

            return addStates ?? new[] { waitState };
        }
 private IGameState[] CreateSuccessWindow(GameInfo gameInfo)
 {
     var waitState = StateFactory.GetState(GameStates.GameStates.Wait);
     var alert = new Alert(gameInfo.Manager, SuccessText, "You now have a new " + Transportable.Name, icon: Transportable.Icon);
     alert.Closed += (sender, args) => WindowClosed(gameInfo, waitState);
     gameInfo.Manager.Add(alert);
     return new[] { waitState };
 }
Beispiel #21
0
        protected override IGameState[] HandleAssetResponse(GameInfo gameInfo, AssetResponse assetResponse)
        {
            if (assetResponse == AssetResponse.HasNoPartner) {
                return CreateNoPartnerWindow(gameInfo);
            }

            return base.HandleAssetResponse(gameInfo, assetResponse);
        }
Beispiel #22
0
 protected override IGameState[] HandleAssetResponse(GameInfo gameInfo, AssetResponse assetResponse)
 {
     if (assetResponse == AssetResponse.HasPartnerAlready) {
         return CreateAlreadyMarriedWindow(gameInfo);
     }
     gameInfo.Content.Load<SoundEffect>("Sounds/wedding").Play();
     return base.HandleAssetResponse(gameInfo, assetResponse);
 }
Beispiel #23
0
        public IGameState[] PerformLogic(GameTime gameTime, GameInfo gameInfo)
        {
            var availablePaths = gameInfo.WorldNodes;
            var waitState = StateFactory.GetState(GameStates.GameStates.Wait);

            ChoosePathHelper.TravelToNodes(availablePaths, gameInfo, (node, location) => PathChosen(node, gameInfo, waitState), false);
            return new[] { waitState };
        }
 private IGameState[] CreateCarFullWindow(GameInfo gameInfo)
 {
     var waitState = StateFactory.GetState(GameStates.GameStates.Wait);
     var alert = new Alert(gameInfo.Manager, String.Format("Your car is too full for another {0}", Transportable.Name), "Car Full!", icon: "Images/AlertIcons/Fail");
     alert.Closed += (sender, args) => WindowClosed(gameInfo, waitState);
     gameInfo.Manager.Add(alert);
     return new[] { waitState };
 }
Beispiel #25
0
 private IGameState[] CreateNoPartnerWindow(GameInfo gameInfo)
 {
     var waitState = StateFactory.GetState(GameStates.GameStates.Wait);
     var alert = new Alert(gameInfo.Manager, "You can not have children\nYou must have a partner", "No partner", icon: "Images/AlertIcons/NoPartner");
     alert.Closed += (sender, args) => WindowClosed(gameInfo, waitState);
     gameInfo.Manager.Add(alert);
     return new[] { waitState };
 }
 public void UpdateGameInfo(GameInfo game)
 {
     foreach (var provider in _providers)
     {
         if (provider.UpdateMode == GameInfoProviderUpdateMode.GameSelected)
             provider.UpdateGameInfo(game);
     }
 }
Beispiel #27
0
 public static List<GameObject> GetBuildings(GameInfo.BuildingsTypes type)
 {
     if(type == GameInfo.BuildingsTypes.BunkRoom)
         return bunkRooms;
     if(type == GameInfo.BuildingsTypes.GreasySpoon)
         return greasySpoons;
     return null;
 }
Beispiel #28
0
 // Use this for initialization
 void Awake()
 {
     forNext = GameObject.Find ("ForNextScene").GetComponent<For_next> ();
     forNext.SetFlag(PhotonNetwork.player.ID,0);
     gameInfo = GameObject.Find ("GameMaster").GetComponent<GameInfo> ();
     ghostList = GameObject.Find ("GhostList");
     myEnd = true;
 }
 private void PathChosen(Node selectedNode, GameInfo gameInfo, IGameState waitState)
 {
     gameInfo.ClearTargets();
     gameInfo.PanCameraToObject(gameInfo.CurrentPlayer);
     var currentPlayer = gameInfo.CurrentPlayer;
     currentPlayer.NextNode = selectedNode;
     gameInfo.Fsm.Remove(waitState);
 }
Beispiel #30
0
 public IGameState[] PerformLogic(GameTime gameTime, GameInfo gameInfo)
 {
     _opacity += Constants.Graphical.FadeValue;
     foreach (var worldObject in _worldObjects) {
         worldObject.Opacity = _opacity;
     }
     return _opacity <= 1f ? new IGameState[] { this } : null;
 }
 public void StartGame()
 {
     GameInfo.SetStartingGameInfo();
     Distribute();
     Net.GetConnectionByClientId(RoomInfo.Players[StartingPlayer].Id)?.SendObject("YourTurnCall", new YourTurnCall());
 }
 public void StartPlayerDogHandling()
 {
     GameInfo.ResetOtherPlayersCall();
     SendMessageToRoom("PlayerWinningCallInfo", new PlayerWinningCallInfo(GetPlayerById(GameInfo.GetCallingPlayerId()), GameInfo.GetWinningCall(), GameInfo.Dog));
     GameInfo.DropDog();
 }
Beispiel #33
0
        public bool LoadRom(string path, CoreComm nextComm, bool forceAccurateCore = false,
                            int recursiveCount = 0) // forceAccurateCore is currently just for Quicknes vs Neshawk but could be used for other situations
        {
            if (recursiveCount > 1)                 // hack to stop recursive calls from endlessly rerunning if we can't load it
            {
                DoLoadErrorCallback("Failed multiple attempts to load ROM.", "");
                return(false);
            }

            bool cancel = false;

            if (path == null)
            {
                return(false);
            }

            using (var file = new HawkFile())
            {
                // only try mounting a file if a filename was given
                if (!string.IsNullOrEmpty(path))
                {
                    // lets not use this unless we need to
                    // file.NonArchiveExtensions = romExtensions;
                    file.Open(path);

                    // if the provided file doesnt even exist, give up!
                    if (!file.Exists)
                    {
                        return(false);
                    }
                }

                CanonicalFullPath = file.CanonicalFullPath;

                IEmulator nextEmulator = null;
                RomGame   rom          = null;
                GameInfo  game         = null;

                try
                {
                    string ext = null;

                    if (AsLibretro)
                    {
                        string codePathPart = Path.GetFileNameWithoutExtension(nextComm.LaunchLibretroCore);

                        var retro = new LibretroCore(nextComm, nextComm.LaunchLibretroCore);
                        nextEmulator = retro;

                        // kind of dirty.. we need to stash this, and then we can unstash it in a moment, in case the core doesnt fail
                        var oldGame = Global.Game;

                        if (retro.Description.SupportsNoGame && string.IsNullOrEmpty(path))
                        {
                            // must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core)
                            // game name == name of core
                            var gameName = codePathPart;
                            Global.Game = game = new GameInfo {
                                Name = gameName, System = "Libretro"
                            };

                            // if we are allowed to run NoGame and we dont have a game, boot up the core that way
                            bool ret = retro.LoadNoGame();

                            Global.Game = oldGame;

                            if (!ret)
                            {
                                DoLoadErrorCallback("LibretroNoGame failed to load. This is weird", "Libretro");
                                retro.Dispose();
                                return(false);
                            }
                        }
                        else
                        {
                            bool ret;

                            // must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core)
                            // game name == name of core + extensionless_game_filename
                            var gameName = Path.Combine(codePathPart, Path.GetFileNameWithoutExtension(file.Name));
                            Global.Game = game = new GameInfo {
                                Name = gameName, System = "Libretro"
                            };

                            // if the core requires an archive file, then try passing the filename of the archive
                            // (but do we ever need to actually load the contents of the archive file into ram?)
                            if (retro.Description.NeedsArchives)
                            {
                                if (file.IsArchiveMember)
                                {
                                    throw new InvalidOperationException("Should not have bound file member for libretro block_extract core");
                                }

                                ret = retro.LoadPath(file.FullPathWithoutMember);
                            }
                            else
                            {
                                // otherwise load the data or pass the filename, as requested. but..
                                if (retro.Description.NeedsRomAsPath && file.IsArchiveMember)
                                {
                                    throw new InvalidOperationException("Cannot pass archive member to libretro needs_fullpath core");
                                }

                                if (retro.Description.NeedsRomAsPath)
                                {
                                    ret = retro.LoadPath(file.FullPathWithoutMember);
                                }
                                else
                                {
                                    ret = HandleArchiveBinding(file);
                                    if (ret)
                                    {
                                        ret = retro.LoadData(file.ReadAllBytes(), file.Name);
                                    }
                                }
                            }

                            Global.Game = oldGame;

                            if (!ret)
                            {
                                DoLoadErrorCallback("Libretro failed to load the given file. This is probably due to a core/content mismatch. Moreover, the process is now likely to be hosed. We suggest you restart the program.", "Libretro");
                                retro.Dispose();
                                return(false);
                            }
                        }
                    }
                    else
                    {
                        // if not libretro:
                        // do extension checknig
                        ext = file.Extension.ToLowerInvariant();

                        // do the archive binding we had to skip
                        if (!HandleArchiveBinding(file))
                        {
                            return(false);
                        }
                    }

                    if (string.IsNullOrEmpty(ext))
                    {
                    }
                    else if (ext == ".m3u")
                    {
                        // HACK ZONE - currently only psx supports m3u
                        M3U_File m3u;
                        using (var sr = new StreamReader(path))
                        {
                            m3u = M3U_File.Read(sr);
                        }

                        if (m3u.Entries.Count == 0)
                        {
                            throw new InvalidOperationException("Can't load an empty M3U");
                        }

                        // load discs for all the m3u
                        m3u.Rebase(Path.GetDirectoryName(path));
                        List <Disc>   discs     = new List <Disc>();
                        List <string> discNames = new List <string>();
                        StringWriter  sw        = new StringWriter();
                        foreach (var e in m3u.Entries)
                        {
                            Disc   disc     = null;
                            string discPath = e.Path;

                            //--- load the disc in a context which will let us abort if it's going to take too long
                            var discMountJob = new DiscMountJob {
                                IN_FromPath = discPath, IN_SlowLoadAbortThreshold = 8
                            };
                            discMountJob.Run();
                            disc = discMountJob.OUT_Disc;

                            if (discMountJob.OUT_SlowLoadAborted)
                            {
                                DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "", LoadErrorType.DiscError);
                                return(false);
                            }

                            if (discMountJob.OUT_ErrorLevel)
                            {
                                throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
                            }

                            if (disc == null)
                            {
                                throw new InvalidOperationException("Can't load one of the files specified in the M3U");
                            }

                            var discName = Path.GetFileNameWithoutExtension(discPath);
                            discNames.Add(discName);
                            discs.Add(disc);

                            var discType = new DiscIdentifier(disc).DetectDiscType();
                            sw.WriteLine("{0}", Path.GetFileName(discPath));
                            if (discType == DiscType.SonyPSX)
                            {
                                string discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
                                game = Database.CheckDatabase(discHash);
                                if (game == null || game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
                                {
                                    sw.WriteLine("Disc could not be identified as known-good. Look for a better rip.");
                                }
                                else
                                {
                                    sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash);
                                    sw.WriteLine("Nonetheless it could be an unrecognized romhack or patched version.");
                                    sw.WriteLine("According to redump.org, the ideal hash for entire disc is: CRC32:{0:X8}", game.GetStringValue("dh"));
                                    sw.WriteLine("The file you loaded hasn't been hashed entirely (it would take too long)");
                                    sw.WriteLine("Compare it with the full hash calculated by the PSX menu's Hash Discs tool");
                                }
                            }
                            else
                            {
                                sw.WriteLine("Not a PSX disc");
                            }

                            sw.WriteLine("-------------------------");
                        }

                        nextEmulator = new Octoshock(nextComm, discs, discNames, null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                        nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
                        game = new GameInfo
                        {
                            Name   = Path.GetFileNameWithoutExtension(file.Name),
                            System = "PSX"
                        };
                    }
                    else if (ext == ".iso" || ext == ".cue" || ext == ".ccd")
                    {
                        if (file.IsArchive)
                        {
                            throw new InvalidOperationException("Can't load CD files from archives!");
                        }

                        string discHash = null;

                        //--- load the disc in a context which will let us abort if it's going to take too long
                        var discMountJob = new DiscMountJob {
                            IN_FromPath = path, IN_SlowLoadAbortThreshold = 8
                        };
                        discMountJob.Run();

                        if (discMountJob.OUT_SlowLoadAborted)
                        {
                            DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "", LoadErrorType.DiscError);
                            return(false);
                        }

                        if (discMountJob.OUT_ErrorLevel)
                        {
                            throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
                        }

                        var disc = discMountJob.OUT_Disc;

                        // -----------
                        // TODO - use more sophisticated IDer
                        var discType = new DiscIdentifier(disc).DetectDiscType();
                        if (discType == DiscType.SonyPSX)
                        {
                            discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
                        }
                        else
                        {
                            discHash = new DiscHasher(disc).OldHash();
                        }

                        game = Database.CheckDatabase(discHash);
                        if (game == null)
                        {
                            // try to use our wizard methods
                            game = new GameInfo {
                                Name = Path.GetFileNameWithoutExtension(file.Name), Hash = discHash
                            };

                            switch (new DiscIdentifier(disc).DetectDiscType())
                            {
                            case DiscType.SegaSaturn:
                                game.System = "SAT";
                                break;

                            case DiscType.SonyPSP:
                                game.System = "PSP";
                                break;

                            default:
                            case DiscType.SonyPSX:
                                game.System = "PSX";
                                break;

                            case DiscType.MegaCD:
                                game.System = "GEN";
                                break;

                            case DiscType.AudioDisc:
                            case DiscType.TurboCD:
                            case DiscType.UnknownCDFS:
                            case DiscType.UnknownFormat:
                                game.System = "PCECD";
                                break;
                            }
                        }

                        switch (game.System)
                        {
                        case "GEN":
                            if (Environment.Is64BitProcess)
                            {
                                var genesis = new GPGX64.GPGX(nextComm, null, disc, GetCoreSettings <GPGX64.GPGX>(), GetCoreSyncSettings <GPGX64.GPGX>());
                                nextEmulator = genesis;
                            }
                            else
                            {
                                var genesis = new GPGX(nextComm, null, disc, GetCoreSettings <GPGX>(), GetCoreSyncSettings <GPGX>());
                                nextEmulator = genesis;
                            }

                            break;

                        case "SAT":
                            nextEmulator = new Yabause(nextComm, disc, GetCoreSyncSettings <Yabause>());
                            break;

                        case "PSP":
                            nextEmulator = new PSP(nextComm, file.Name);
                            break;

                        case "PSX":
                            nextEmulator = new Octoshock(nextComm, new List <Disc>(new[] { disc }), new List <string>(new[] { Path.GetFileNameWithoutExtension(path) }), null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                            if (game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
                            {
                                nextEmulator.CoreComm.RomStatusDetails = "Disc could not be identified as known-good. Look for a better rip.";
                            }
                            else
                            {
                                StringWriter sw = new StringWriter();
                                sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash);
                                sw.WriteLine("Nonetheless it could be an unrecognized romhack or patched version.");
                                sw.WriteLine("According to redump.org, the ideal hash for entire disc is: CRC32:{0:X8}", game.GetStringValue("dh"));
                                sw.WriteLine("The file you loaded hasn't been hashed entirely (it would take too long)");
                                sw.WriteLine("Compare it with the full hash calculated by the PSX menu's Hash Discs tool");
                                nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
                            }

                            break;

                        case "PCE":
                        case "PCECD":
                            nextEmulator = new PCEngine(nextComm, game, disc, GetCoreSettings <PCEngine>(), GetCoreSyncSettings <PCEngine>());
                            break;
                        }
                    }
                    else if (file.Extension.ToLowerInvariant() == ".xml")
                    {
                        try
                        {
                            var xmlGame = XmlGame.Create(file);                             // if load fails, are we supposed to retry as a bsnes XML????????
                            game = xmlGame.GI;

                            switch (game.System)
                            {
                            case "GB":
                            case "DGB":
                                // adelikat: remove need for tags to be hardcoded to left and right, we should clean this up, also maybe the DGB core should just take the xml file and handle it itself
                                var leftBytes  = xmlGame.Assets.First().Value;
                                var rightBytes = xmlGame.Assets.Skip(1).First().Value;

                                var left  = Database.GetGameInfo(leftBytes, "left.gb");
                                var right = Database.GetGameInfo(rightBytes, "right.gb");
                                nextEmulator = new GambatteLink(
                                    nextComm,
                                    left,
                                    leftBytes,
                                    right,
                                    rightBytes,
                                    GetCoreSettings <GambatteLink>(),
                                    GetCoreSyncSettings <GambatteLink>(),
                                    Deterministic);

                                // other stuff todo
                                break;

                            case "AppleII":
                                var assets = xmlGame.Assets.Select(a => Database.GetGameInfo(a.Value, a.Key));
                                var roms   = xmlGame.Assets.Select(a => a.Value);
                                nextEmulator = new AppleII(
                                    nextComm,
                                    assets,
                                    roms,
                                    (AppleII.Settings)GetCoreSettings <AppleII>());
                                break;

                            case "C64":
                                nextEmulator = new C64(
                                    nextComm,
                                    xmlGame.Assets.Select(a => a.Value),
                                    (C64.C64Settings)GetCoreSettings <C64>(),
                                    (C64.C64SyncSettings)GetCoreSyncSettings <C64>());
                                break;

                            case "PSX":
                                var entries   = xmlGame.AssetFullPaths;
                                var discs     = new List <Disc>();
                                var discNames = new List <string>();
                                var sw        = new StringWriter();
                                foreach (var e in entries)
                                {
                                    Disc   disc     = null;
                                    string discPath = e;

                                    //--- load the disc in a context which will let us abort if it's going to take too long
                                    var discMountJob = new DiscMountJob {
                                        IN_FromPath = discPath, IN_SlowLoadAbortThreshold = 8
                                    };
                                    discMountJob.Run();
                                    disc = discMountJob.OUT_Disc;

                                    if (discMountJob.OUT_SlowLoadAborted)
                                    {
                                        DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "PSX", LoadErrorType.DiscError);
                                        return(false);
                                    }

                                    if (discMountJob.OUT_ErrorLevel)
                                    {
                                        throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
                                    }

                                    if (disc == null)
                                    {
                                        throw new InvalidOperationException("Can't load one of the files specified in the M3U");
                                    }

                                    var discName = Path.GetFileNameWithoutExtension(discPath);
                                    discNames.Add(discName);
                                    discs.Add(disc);

                                    var discType = new DiscIdentifier(disc).DetectDiscType();
                                    sw.WriteLine("{0}", Path.GetFileName(discPath));
                                    if (discType == DiscType.SonyPSX)
                                    {
                                        string discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
                                        game = Database.CheckDatabase(discHash);
                                        if (game == null || game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
                                        {
                                            sw.WriteLine("Disc could not be identified as known-good. Look for a better rip.");
                                        }
                                        else
                                        {
                                            sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash);
                                            sw.WriteLine("Nonetheless it could be an unrecognized romhack or patched version.");
                                            sw.WriteLine("According to redump.org, the ideal hash for entire disc is: CRC32:{0:X8}", game.GetStringValue("dh"));
                                            sw.WriteLine("The file you loaded hasn't been hashed entirely (it would take too long)");
                                            sw.WriteLine("Compare it with the full hash calculated by the PSX menu's Hash Discs tool");
                                        }
                                    }
                                    else
                                    {
                                        sw.WriteLine("Not a PSX disc");
                                    }

                                    sw.WriteLine("-------------------------");
                                }

                                // todo: copy pasta from PSX .cue section
                                nextEmulator = new Octoshock(nextComm, discs, discNames, null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                                nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
                                game = new GameInfo
                                {
                                    Name   = Path.GetFileNameWithoutExtension(file.Name),
                                    System = "PSX"
                                };
                                break;

                            default:
                                return(false);
                            }
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                // need to get rid of this hack at some point
                                rom = new RomGame(file);
                                ((CoreFileProvider)nextComm.CoreFileProvider).SubfileDirectory = Path.GetDirectoryName(path.Replace("|", ""));                                 // Dirty hack to get around archive filenames (since we are just getting the directory path, it is safe to mangle the filename
                                byte[] romData = null;
                                byte[] xmlData = rom.FileData;

                                game        = rom.GameInfo;
                                game.System = "SNES";

                                var snes = new LibsnesCore(game, romData, Deterministic, xmlData, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                nextEmulator = snes;
                            }
                            catch
                            {
                                DoLoadErrorCallback(ex.ToString(), "DGB", LoadErrorType.XML);
                                return(false);
                            }
                        }
                    }
                    else if (file.Extension.ToLowerInvariant() == ".psf" || file.Extension.ToLowerInvariant() == ".minipsf")
                    {
                        Func <Stream, int, byte[]> cbDeflater = (Stream instream, int size) =>
                        {
                            var          inflater = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater(false);
                            var          iis      = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(instream, inflater);
                            MemoryStream ret      = new MemoryStream();
                            iis.CopyTo(ret);
                            return(ret.ToArray());
                        };
                        PSF psf = new PSF();
                        psf.Load(path, cbDeflater);
                        nextEmulator = new Octoshock(nextComm, psf, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                        nextEmulator.CoreComm.RomStatusDetails = "It's a PSF, what do you want. Oh, tags maybe?";

                        // total garbage, this
                        rom  = new RomGame(file);
                        game = rom.GameInfo;
                    }
                    else if (ext != null)                     // most extensions
                    {
                        rom = new RomGame(file);

                        // hacky for now
                        if (file.Extension.ToLowerInvariant() == ".exe")
                        {
                            rom.GameInfo.System = "PSX";
                        }
                        else if (file.Extension.ToLowerInvariant() == ".nsf")
                        {
                            rom.GameInfo.System = "NES";
                        }

                        if (string.IsNullOrEmpty(rom.GameInfo.System))
                        {
                            // Has the user picked a preference for this extension?
                            if (PreferredPlatformIsDefined(rom.Extension.ToLowerInvariant()))
                            {
                                rom.GameInfo.System = Global.Config.PreferredPlatformsForExtensions[rom.Extension.ToLowerInvariant()];
                            }
                            else if (ChoosePlatform != null)
                            {
                                var result = ChoosePlatform(rom);
                                if (!string.IsNullOrEmpty(result))
                                {
                                    rom.GameInfo.System = result;
                                }
                                else
                                {
                                    cancel = true;
                                }
                            }
                        }

                        game = rom.GameInfo;

                        var isXml = false;

                        // other xml has already been handled
                        if (file.Extension.ToLowerInvariant() == ".xml")
                        {
                            game.System = "SNES";
                            isXml       = true;
                        }

                        CoreInventory.Core core = null;

                        switch (game.System)
                        {
                        default:
                            core = CoreInventory.Instance[game.System];
                            break;

                        case null:
                            // The user picked nothing in the Core picker
                            break;

                        case "83P":
                            var ti83Bios     = ((CoreFileProvider)nextComm.CoreFileProvider).GetFirmware("TI83", "Rom", true);
                            var ti83BiosPath = ((CoreFileProvider)nextComm.CoreFileProvider).GetFirmwarePath("TI83", "Rom", true);
                            using (var ti83AsHawkFile = new HawkFile())
                            {
                                ti83AsHawkFile.Open(ti83BiosPath);
                                var ti83BiosAsRom = new RomGame(ti83AsHawkFile);
                                var ti83          = new TI83(nextComm, ti83BiosAsRom.GameInfo, ti83Bios, GetCoreSettings <TI83>());
                                ti83.LinkPort.SendFileToCalc(File.OpenRead(path), false);
                                nextEmulator = ti83;
                            }

                            break;

                        case "SNES":
                            if (Global.Config.SNES_InSnes9x && VersionInfo.DeveloperBuild)
                            {
                                core = CoreInventory.Instance["SNES", "Snes9x"];
                            }
                            else
                            {
                                // need to get rid of this hack at some point
                                ((CoreFileProvider)nextComm.CoreFileProvider).SubfileDirectory = Path.GetDirectoryName(path.Replace("|", ""));                                         // Dirty hack to get around archive filenames (since we are just getting the directory path, it is safe to mangle the filename
                                var romData = isXml ? null : rom.FileData;
                                var xmlData = isXml ? rom.FileData : null;
                                var snes    = new LibsnesCore(game, romData, Deterministic, xmlData, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                nextEmulator = snes;
                            }

                            break;

                        case "NES":
                        {
                            // apply main spur-of-the-moment switcheroo as lowest priority
                            string preference = "neshawk";
                            if (Global.Config.NES_InQuickNES)
                            {
                                preference = "quicknes";
                            }

                            // if user has saw fit to override in gamedb, apply that
                            if (Global.Config.CoreForcingViaGameDB && !string.IsNullOrEmpty(game.ForcedCore))
                            {
                                preference = game.ForcedCore;
                            }

                            // but only neshawk is accurate
                            if (forceAccurateCore)
                            {
                                preference = "neshawk";
                            }

                            if (preference == "neshawk")
                            {
                                core = CoreInventory.Instance["NES", "NesHawk"];
                            }
                            else
                            {
                                core = CoreInventory.Instance["NES", "QuickNes"];
                            }
                        }

                        break;

                        case "GB":
                        case "GBC":
                            if (!Global.Config.GB_AsSGB)
                            {
                                core = CoreInventory.Instance["GB", "Gambatte"];
                            }
                            else
                            {
                                try
                                {
                                    game.System = "SNES";
                                    game.AddOption("SGB");
                                    var snes = new LibsnesCore(game, rom.FileData, Deterministic, null, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                    nextEmulator = snes;
                                }
                                catch
                                {
                                    // failed to load SGB bios or game does not support SGB mode.
                                    // To avoid catch-22, disable SGB mode
                                    Global.Config.GB_AsSGB = false;
                                    throw;
                                }
                            }

                            break;

                        case "A78":
                            var gamedbpath = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "EMU7800.csv");
                            nextEmulator = new Atari7800(nextComm, game, rom.RomData, gamedbpath);
                            break;

                        case "C64":
                            var c64 = new C64(nextComm, Enumerable.Repeat(rom.RomData, 1), GetCoreSettings <C64>(), GetCoreSyncSettings <C64>());
                            nextEmulator = c64;
                            break;

                        case "GBA":
                            // core = CoreInventory.Instance["GBA", "Meteor"];
                            if (Global.Config.GBA_UsemGBA)
                            {
                                core = CoreInventory.Instance["GBA", "mGBA"];
                            }
                            else
                            {
                                core = CoreInventory.Instance["GBA", "VBA-Next"];
                            }

                            break;

                        case "PSX":
                            nextEmulator = new Octoshock(nextComm, null, null, rom.FileData, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                            nextEmulator.CoreComm.RomStatusDetails = "PSX etc.";
                            break;

                        case "GEN":
                            // discard "Genplus-gx64", auto-added due to implementing IEmulator // HUH?
                            // core = CoreInventory.Instance["GEN", "Genplus-gx"];
                            if (Environment.Is64BitProcess)
                            {
                                core = CoreInventory.Instance["GEN", "Genplus-gx64"];
                            }
                            else
                            {
                                core = CoreInventory.Instance["GEN", "Genplus-gx"];
                            }

                            break;
                        }

                        if (core != null)
                        {
                            // use coreinventory
                            nextEmulator = core.Create(nextComm, game, rom.RomData, rom.FileData, Deterministic, GetCoreSettings(core.Type), GetCoreSyncSettings(core.Type));
                        }
                    }

                    if (nextEmulator == null)
                    {
                        if (!cancel)
                        {
                            DoLoadErrorCallback("No core could load the rom.", null);
                        }

                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    string system = null;
                    if (game != null)
                    {
                        system = game.System;
                    }

                    // all of the specific exceptions we're trying to catch here aren't expected to have inner exceptions,
                    // so drill down in case we got a TargetInvocationException or something like that
                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                    }

                    // Specific hack here, as we get more cores of the same system, this isn't scalable
                    if (ex is UnsupportedGameException)
                    {
                        if (system == "NES")
                        {
                            DoMessageCallback("Unable to use quicknes, using NESHawk instead");
                        }

                        return(LoadRom(path, nextComm, true, recursiveCount + 1));
                    }
                    else if (ex is MissingFirmwareException)
                    {
                        DoLoadErrorCallback(ex.Message, system, path, Deterministic, LoadErrorType.MissingFirmware);
                    }
                    else if (ex is CGBNotSupportedException)
                    {
                        // Note: GB as SGB was set to false by this point, otherwise we would want to do it here
                        DoMessageCallback("Failed to load a GB rom in SGB mode.  Disabling SGB Mode.");
                        return(LoadRom(path, nextComm, false, recursiveCount + 1));
                    }
                    else
                    {
                        DoLoadErrorCallback("A core accepted the rom, but threw an exception while loading it:\n\n" + ex, system);
                    }

                    return(false);
                }

                Rom            = rom;
                LoadedEmulator = nextEmulator;
                Game           = game;
                return(true);
            }
        }
Beispiel #34
0
        public void RefreshBoardStateSuccess()
        {
            var assignedPlayerId = Guid.NewGuid().ToString();

            var playerPos1 = new PlayerPositionDTO
            {
                PlayerId = assignedPlayerId,
                X        = 10,
                Y        = 10
            };

            var playerPos2 = new PlayerPositionDTO
            {
                PlayerId = Guid.NewGuid().ToString(),
                X        = 20,
                Y        = 20
            };

            var playerPositions = new List <PlayerPositionDTO>
            {
                playerPos1, playerPos2
            };

            var msg2 = new Message <RefreshStateResponsePayload>
            {
                Type        = Common.Consts.RefreshStateResponse,
                SenderId    = Common.Consts.GameMasterId,
                RecipientId = assignedPlayerId,
                Payload     = new RefreshStateResponsePayload
                {
                    CurrentPositionDistanceToClosestPiece = 10,
                    Team1Score      = 5,
                    Team2Score      = 6,
                    Timestamp       = 123,
                    PlayerPositions = playerPositions
                }
            };

            _messageProvider.Setup(x => x.Receive <ActionValidPayload>()).Returns(new Message <ActionValidPayload>());
            _messageProvider.Setup(x => x.Receive <RefreshStateResponsePayload>()).Returns(msg2);


            var game = new GameInfo()
            {
                BoardSize = new BoardSize
                {
                    GoalArea = 20,
                    TaskArea = 20,
                    X        = 20
                }
            };

            _playerState.Game  = game;
            _playerState.Board = new Board(game.BoardSize);
            _playerState.Id    = assignedPlayerId;

            var actionExecutor = new ActionExecutor(_messageProvider.Object, _playerState);

            var result = actionExecutor.RefreshBoardState();

            Assert.That(result, Is.True);
            (int foundX, int foundY) = _playerState.Board.FindPlayerPosition(assignedPlayerId);
            Assert.That(foundX, Is.Not.Negative);
            Assert.That(foundY, Is.Not.Negative);
            Assert.That(_playerState.Board.At(foundX, foundY).DistanceToClosestPiece, Is.EqualTo(msg2.Payload.CurrentPositionDistanceToClosestPiece));
            Assert.That(_playerState.X, Is.EqualTo(playerPos1.X));
            Assert.That(_playerState.Y, Is.EqualTo(playerPos1.Y));

            foreach (var p in playerPositions)
            {
                Assert.That(_playerState.Board.At(p.X, p.Y).PlayerId, Is.EqualTo(p.PlayerId));
                Assert.That(_playerState.Board.At(p.X, p.Y).Timestamp, Is.EqualTo(msg2.Payload.Timestamp));
            }
        }
Beispiel #35
0
        public SMS(CoreComm comm, GameInfo game, byte[] rom, object settings, object syncSettings)
        {
            ServiceProvider = new BasicServiceProvider(this);
            Settings        = (SMSSettings)settings ?? new SMSSettings();
            SyncSettings    = (SMSSyncSettings)syncSettings ?? new SMSSyncSettings();
            CoreComm        = comm;
            MemoryCallbacks = new MemoryCallbackSystem(new[] { "System Bus" });

            IsGameGear = game.System == "GG";
            IsSG1000   = game.System == "SG";
            RomData    = rom;

            if (RomData.Length % BankSize != 0)
            {
                Array.Resize(ref RomData, ((RomData.Length / BankSize) + 1) * BankSize);
            }

            RomBanks = (byte)(RomData.Length / BankSize);

            Region = DetermineDisplayType(SyncSettings.DisplayType, game.Region);
            if (game["PAL"] && Region != DisplayType.PAL)
            {
                Region = DisplayType.PAL;
                CoreComm.Notify("Display was forced to PAL mode for game compatibility.");
            }

            if (IsGameGear)
            {
                Region = DisplayType.NTSC;                 // all game gears run at 60hz/NTSC mode
            }

            RegionStr = SyncSettings.ConsoleRegion;
            if (RegionStr == "Auto")
            {
                RegionStr = DetermineRegion(game.Region);
            }

            if (game["Japan"] && RegionStr != "Japan")
            {
                RegionStr = "Japan";
                CoreComm.Notify("Region was forced to Japan for game compatibility.");
            }

            if ((game.NotInDatabase || game["FM"]) && SyncSettings.EnableFM && !IsGameGear)
            {
                HasYM2413 = true;
            }

            Cpu = new Z80A()
            {
                ReadHardware    = ReadPort,
                WriteHardware   = WritePort,
                FetchMemory     = ReadMemory,
                ReadMemory      = ReadMemory,
                WriteMemory     = WriteMemory,
                MemoryCallbacks = MemoryCallbacks
            };

            Vdp = new VDP(this, Cpu, IsGameGear ? VdpMode.GameGear : VdpMode.SMS, Region);
            (ServiceProvider as BasicServiceProvider).Register <IVideoProvider>(Vdp);
            PSG        = new SN76489();
            YM2413     = new YM2413();
            SoundMixer = new SoundMixer(YM2413, PSG);
            if (HasYM2413 && game["WhenFMDisablePSG"])
            {
                SoundMixer.DisableSource(PSG);
            }

            ActiveSoundProvider = HasYM2413 ? (IAsyncSoundProvider)SoundMixer : PSG;
            _fakeSyncSound      = new FakeSyncSound(ActiveSoundProvider, 735);
            (ServiceProvider as BasicServiceProvider).Register <ISoundProvider>(_fakeSyncSound);

            SystemRam = new byte[0x2000];

            if (game["CMMapper"])
            {
                InitCodeMastersMapper();
            }
            else if (game["CMMapperWithRam"])
            {
                InitCodeMastersMapperRam();
            }
            else if (game["ExtRam"])
            {
                InitExt2kMapper(int.Parse(game.OptionValue("ExtRam")));
            }
            else if (game["KoreaMapper"])
            {
                InitKoreaMapper();
            }
            else if (game["MSXMapper"])
            {
                InitMSXMapper();
            }
            else if (game["NemesisMapper"])
            {
                InitNemesisMapper();
            }
            else if (game["TerebiOekaki"])
            {
                InitTerebiOekaki();
            }
            else if (game["EEPROM"])
            {
                InitEEPROMMapper();
            }
            else
            {
                InitSegaMapper();
            }

            if (Settings.ForceStereoSeparation && !IsGameGear)
            {
                if (game["StereoByte"])
                {
                    ForceStereoByte = byte.Parse(game.OptionValue("StereoByte"));
                }

                PSG.StereoPanning = ForceStereoByte;
            }

            if (SyncSettings.AllowOverlock && game["OverclockSafe"])
            {
                Vdp.IPeriod = 512;
            }

            if (Settings.SpriteLimit)
            {
                Vdp.SpriteLimit = true;
            }

            if (game["3D"])
            {
                IsGame3D = true;
            }

            if (game["BIOS"])
            {
                Port3E = 0xF7;                 // Disable cartridge, enable BIOS rom
                InitBiosMapper();
            }
            else if (game.System == "SMS")
            {
                BiosRom = comm.CoreFileProvider.GetFirmware("SMS", RegionStr, false);

                if (BiosRom == null)
                {
                    throw new MissingFirmwareException("No BIOS found");
                }
                else if (!game["RequireBios"] && !SyncSettings.UseBIOS)
                {
                    // we are skipping the BIOS
                    // but only if it won't break the game
                }
                else
                {
                    Port3E = 0xF7;
                }
            }

            if (game["SRAM"])
            {
                SaveRAM = new byte[int.Parse(game.OptionValue("SRAM"))];
                Console.WriteLine(SaveRAM.Length);
            }
            else if (game.NotInDatabase)
            {
                SaveRAM = new byte[0x8000];
            }

            SetupMemoryDomains();

            //this manages the linkage between the cpu and mapper callbacks so it needs running before bootup is complete
            ((ICodeDataLogger)this).SetCDL(null);

            InputCallbacks = new InputCallbackSystem();

            Tracer = new TraceBuffer {
                Header = Cpu.TraceHeader
            };

            var serviceProvider = ServiceProvider as BasicServiceProvider;

            serviceProvider.Register <ITraceable>(Tracer);
            serviceProvider.Register <IDisassemblable>(Cpu);
            Vdp.ProcessOverscan();

            Cpu.ReadMemory  = ReadMemory;
            Cpu.WriteMemory = WriteMemory;
        }
Beispiel #36
0
        public static void RegisterDependencies()
        {
#if UNITY_ANDROID
            // Setup the resolver using reflection as the module may not be
            // available at compile time.
            Type playServicesSupport = Google.VersionHandler.FindClass(
                "Google.JarResolver", "Google.JarResolver.PlayServicesSupport");
            if (playServicesSupport == null)
            {
                return;
            }
            svcSupport = svcSupport ?? Google.VersionHandler.InvokeStaticMethod(
                playServicesSupport, "CreateInstance",
                new object[] {
                "GooglePlayGames",
                EditorPrefs.GetString("AndroidSdkRoot"),
                "ProjectSettings"
            });

            Google.VersionHandler.InvokeInstanceMethod(
                svcSupport, "DependOn",
                new object[] { "com.google.android.gms", "play-services-games",
                               PluginVersion.PlayServicesVersionConstraint },
                namedArgs: new Dictionary <string, object>()
            {
                { "packageIds", new string[] { "extra-google-m2repository" } }
            });

            Google.VersionHandler.InvokeInstanceMethod(
                svcSupport, "DependOn",
                new object[] { "com.google.android.gms", "play-services-nearby",
                               PluginVersion.PlayServicesVersionConstraint },
                namedArgs: new Dictionary <string, object>()
            {
                { "packageIds", new string[] { "extra-google-m2repository" } }
            });

            // Auth is needed for getting the token and email.
            Google.VersionHandler.InvokeInstanceMethod(
                svcSupport, "DependOn",
                new object[] { "com.google.android.gms", "play-services-auth",
                               PluginVersion.PlayServicesVersionConstraint },
                namedArgs: new Dictionary <string, object>()
            {
                { "packageIds", new string[] { "extra-google-m2repository" } }
            });

            // if google+ is needed, add it
            if (GameInfo.RequireGooglePlus())
            {
                Google.VersionHandler.InvokeInstanceMethod(
                    svcSupport, "DependOn",
                    new object[] { "com.google.android.gms", "play-services-plus",
                                   PluginVersion.PlayServicesVersionConstraint },
                    namedArgs: new Dictionary <string, object>()
                {
                    { "packageIds", new string[] { "extra-google-m2repository" } }
                });
            }

            Google.VersionHandler.InvokeInstanceMethod(
                svcSupport, "DependOn",
                new object[] { "com.android.support", "support-v4", "23.1+" },
                namedArgs: new Dictionary <string, object>()
            {
                { "packageIds", new string[] { "extra-android-m2repository" } }
            });
#elif UNITY_IOS && !NO_GPGS
            Type iosResolver = Google.VersionHandler.FindClass(
                "Google.IOSResolver", "Google.IOSResolver");
            if (iosResolver == null)
            {
                return;
            }
            Google.VersionHandler.InvokeStaticMethod(
                iosResolver, "AddPod",
                new object[] { "GooglePlayGames" },
                namedArgs: new Dictionary <string, object>()
            {
                { "version", "5.0+" },
                { "bitcodeEnabled", false },
            });
#endif  // UNITY_IOS
        }
Beispiel #37
0
 public XmlGame()
 {
     Assets         = new List <KeyValuePair <string, byte[]> >();
     AssetFullPaths = new List <string>();
     GI             = new GameInfo();
 }
Beispiel #38
0
        private string[] GetStringList(string type)
        {
            switch (SAV.Version)
            {
            case GameVersion.X:
            case GameVersion.Y:
                gamePrefix = "xy";
                break;

            case GameVersion.OR:
            case GameVersion.AS:
                gamePrefix = "oras";
                break;

            case GameVersion.SN:
            case GameVersion.MN:
                gamePrefix = "sm";
                break;

            case GameVersion.US:
            case GameVersion.UM:
                gamePrefix = "usum";
                break;

            case GameVersion.DP:
                gamePrefix = "dp";
                break;

            case GameVersion.Pt:
                gamePrefix = "pt";
                break;

            case GameVersion.HGSS:
                gamePrefix = "hgss";
                break;

            case GameVersion.BW:
                gamePrefix = "bw";
                break;

            case GameVersion.B2W2:
                gamePrefix = "b2w2";
                break;

            case GameVersion.R:
            case GameVersion.S:
            case GameVersion.RS:
                gamePrefix = "rs";
                break;

            case GameVersion.E:
                gamePrefix = "e";
                break;

            case GameVersion.FR:
            case GameVersion.LG:
            case GameVersion.FRLG:
                gamePrefix = "frlg";
                break;

            case GameVersion.C:
                gamePrefix = "c";
                break;

            default:
                return(null);
            }
            return(GameInfo.GetStrings(gamePrefix, GameInfo.CurrentLanguage, type));
        }
Beispiel #39
0
        public GPGX(CoreComm comm, GameInfo game, byte[] rom, IEnumerable <Disc> cds, object settings, object syncSettings)
        {
            ServiceProvider = new BasicServiceProvider(this);
            // this can influence some things internally (autodetect romtype, etc)
            string romextension = "GEN";

            // three or six button?
            // http://www.sega-16.com/forum/showthread.php?4398-Forgotten-Worlds-giving-you-GAME-OVER-immediately-Fix-inside&highlight=forgotten%20worlds

            //hack, don't use
            if (rom != null && rom.Length > 32 * 1024 * 1024)
            {
                throw new InvalidOperationException("ROM too big!  Did you try to load a CD as a ROM?");
            }

            _elf = new WaterboxHost(new WaterboxOptions
            {
                Path                       = comm.CoreFileProvider.DllPath(),
                Filename                   = "gpgx.wbx",
                SbrkHeapSizeKB             = 512,
                SealedHeapSizeKB           = 36 * 1024,
                InvisibleHeapSizeKB        = 4 * 1024,
                PlainHeapSizeKB            = 64 + 1024,
                MmapHeapSizeKB             = 1 * 1024,
                SkipCoreConsistencyCheck   = comm.CorePreferences.HasFlag(CoreComm.CorePreferencesFlags.WaterboxCoreConsistencyCheck),
                SkipMemoryConsistencyCheck = comm.CorePreferences.HasFlag(CoreComm.CorePreferencesFlags.WaterboxMemoryConsistencyCheck),
            });

            using (_elf.EnterExit())
            {
                Core          = BizInvoker.GetInvoker <LibGPGX>(_elf, _elf, CallingConventionAdapters.Waterbox);
                _syncSettings = (GPGXSyncSettings)syncSettings ?? new GPGXSyncSettings();
                _settings     = (GPGXSettings)settings ?? new GPGXSettings();

                CoreComm = comm;

                LoadCallback = new LibGPGX.load_archive_cb(load_archive);

                _romfile = rom;

                if (cds != null)
                {
                    _cds               = cds.ToArray();
                    _cdReaders         = cds.Select(c => new DiscSectorReader(c)).ToArray();
                    cd_callback_handle = new LibGPGX.cd_read_cb(CDRead);
                    Core.gpgx_set_cdd_callback(cd_callback_handle);
                    DriveLightEnabled = true;
                }

                LibGPGX.INPUT_SYSTEM system_a = LibGPGX.INPUT_SYSTEM.SYSTEM_NONE;
                LibGPGX.INPUT_SYSTEM system_b = LibGPGX.INPUT_SYSTEM.SYSTEM_NONE;

                switch (_syncSettings.ControlType)
                {
                case ControlType.None:
                default:
                    break;

                case ControlType.Activator:
                    system_a = LibGPGX.INPUT_SYSTEM.SYSTEM_ACTIVATOR;
                    system_b = LibGPGX.INPUT_SYSTEM.SYSTEM_ACTIVATOR;
                    break;

                case ControlType.Normal:
                    system_a = LibGPGX.INPUT_SYSTEM.SYSTEM_MD_GAMEPAD;
                    system_b = LibGPGX.INPUT_SYSTEM.SYSTEM_MD_GAMEPAD;
                    break;

                case ControlType.OnePlayer:
                    system_a = LibGPGX.INPUT_SYSTEM.SYSTEM_MD_GAMEPAD;
                    break;

                case ControlType.Xea1p:
                    system_a = LibGPGX.INPUT_SYSTEM.SYSTEM_XE_A1P;
                    break;

                case ControlType.Teamplayer:
                    system_a = LibGPGX.INPUT_SYSTEM.SYSTEM_TEAMPLAYER;
                    system_b = LibGPGX.INPUT_SYSTEM.SYSTEM_TEAMPLAYER;
                    break;

                case ControlType.Wayplay:
                    system_a = LibGPGX.INPUT_SYSTEM.SYSTEM_WAYPLAY;
                    system_b = LibGPGX.INPUT_SYSTEM.SYSTEM_WAYPLAY;
                    break;

                case ControlType.Mouse:
                    system_a = LibGPGX.INPUT_SYSTEM.SYSTEM_MD_GAMEPAD;
                    // seems like mouse in port 1 would be supported, but not both at the same time
                    system_b = LibGPGX.INPUT_SYSTEM.SYSTEM_MOUSE;
                    break;
                }

                var initResult = Core.gpgx_init(
                    romextension,
                    LoadCallback, _syncSettings.UseSixButton, system_a, system_b, _syncSettings.Region, game["sram"],
                    _syncSettings.GetNativeSettings());

                if (!initResult)
                {
                    throw new Exception($"{nameof(Core.gpgx_init)}() failed");
                }

                {
                    int fpsnum = 60;
                    int fpsden = 1;
                    Core.gpgx_get_fps(ref fpsnum, ref fpsden);
                    VsyncNumerator   = fpsnum;
                    VsyncDenominator = fpsden;
                    Region           = VsyncNumerator / VsyncDenominator > 55 ? DisplayType.NTSC : DisplayType.PAL;
                }

                // when we call Seal, ANY pointer passed from managed code must be 0.
                // this is so the initial state is clean
                // the only two pointers set so far are LoadCallback, which the core zeroed itself,
                // and CdCallback
                Core.gpgx_set_cdd_callback(null);
                _elf.Seal();
                Core.gpgx_set_cdd_callback(cd_callback_handle);

                SetControllerDefinition();

                // pull the default video size from the core
                UpdateVideo();

                SetMemoryDomains();

                _inputCallback = new LibGPGX.input_cb(input_callback);
                Core.gpgx_set_input_callback(_inputCallback);

                // process the non-init settings now
                PutSettings(_settings);

                //TODO - this hits performance, we need to make it controllable
                CDCallback = new LibGPGX.CDCallback(CDCallbackProc);

                InitMemCallbacks();
                KillMemCallbacks();

                _tracer = new GPGXTraceBuffer(this, _memoryDomains, this);
                (ServiceProvider as BasicServiceProvider).Register <ITraceable>(_tracer);
            }

            _romfile = null;
        }
Beispiel #40
0
 public GPGX(CoreComm comm, GameInfo game, byte[] file, object settings, object syncSettings)
     : this(comm, game, file, null, settings, syncSettings)
 {
 }
Beispiel #41
0
        /// <inheritdoc />
        public override AutoCatResult CategorizeGame(GameInfo game, Filter filter)
        {
            if (games == null)
            {
                Logger.Error(GlobalStrings.Log_AutoCat_GamelistNull);
                throw new ApplicationException(GlobalStrings.AutoCatGenre_Exception_NoGameList);
            }

            if (game == null)
            {
                Logger.Error(GlobalStrings.Log_AutoCat_GameNull);
                return(AutoCatResult.Failure);
            }

            if (!game.IncludeGame(filter))
            {
                return(AutoCatResult.Filtered);
            }

            if (!Database.Contains(game.Id, out DatabaseEntry entry) || entry.LastStoreScrape == 0)
            {
                return(AutoCatResult.NotInDatabase);
            }

            if (RemoveAllCategories)
            {
                game.ClearCategories();
            }
            else if (RemoveCategories != null)
            {
                List <Category> removed = new List <Category>();

                foreach (string category in RemoveCategories)
                {
                    Category c = gamelist.GetCategory(category);
                    if (!game.ContainsCategory(c))
                    {
                        continue;
                    }

                    game.RemoveCategory(c);
                    removed.Add(c);
                }

                foreach (Category c in removed)
                {
                    if (c.Count == 0)
                    {
                        gamelist.RemoveCategory(c);
                    }
                }
            }

            if (AddCategories == null)
            {
                return(AutoCatResult.Success);
            }

            foreach (string category in AddCategories)
            // add Category, or create it if it doesn't exist
            {
                game.AddCategory(gamelist.GetCategory(GetCategoryName(category)));
            }

            return(AutoCatResult.Success);
        }
Beispiel #42
0
        public Lynx(byte[] file, GameInfo game, CoreComm comm)
        {
            ServiceProvider = new BasicServiceProvider(this);
            CoreComm        = comm;

            byte[] bios = CoreComm.CoreFileProvider.GetFirmware("Lynx", "Boot", true, "Boot rom is required");
            if (bios.Length != 512)
            {
                throw new MissingFirmwareException("Lynx Bootrom must be 512 bytes!");
            }

            int pagesize0 = 0;
            int pagesize1 = 0;

            byte[] realfile = null;

            {
                using var ms = new MemoryStream(file, false);
                using var br = new BinaryReader(ms);
                string header = Encoding.ASCII.GetString(br.ReadBytes(4));
                int    p0     = br.ReadUInt16();
                int    p1     = br.ReadUInt16();
                int    ver    = br.ReadUInt16();
                string cname  = Encoding.ASCII.GetString(br.ReadBytes(32)).Trim();
                string mname  = Encoding.ASCII.GetString(br.ReadBytes(16)).Trim();
                int    rot    = br.ReadByte();

                ms.Position = 6;
                string bs93 = Encoding.ASCII.GetString(br.ReadBytes(6));
                if (bs93 == "BS93")
                {
                    throw new InvalidOperationException("Unsupported BS93 Lynx ram image");
                }

                if (header == "LYNX" && (ver & 255) == 1)
                {
                    Console.WriteLine("Processing Handy-Lynx header");
                    pagesize0 = p0;
                    pagesize1 = p1;
                    Console.WriteLine("TODO: Rotate {0}", rot);
                    Console.WriteLine("Cart: {0} Manufacturer: {1}", cname, mname);
                    realfile = new byte[file.Length - 64];
                    Buffer.BlockCopy(file, 64, realfile, 0, realfile.Length);
                    Console.WriteLine("Header Listed banking: {0} {1}", p0, p1);
                }
                else
                {
                    Console.WriteLine("No Handy-Lynx header found!  Assuming raw rom image.");
                    realfile = file;
                }
            }

            if (game.OptionPresent("pagesize0"))
            {
                pagesize0 = int.Parse(game.OptionValue("pagesize0"));
                pagesize1 = int.Parse(game.OptionValue("pagesize1"));
                Console.WriteLine("Loading banking options {0} {1} from gamedb", pagesize0, pagesize1);
            }

            if (pagesize0 == 0 && pagesize1 == 0)
            {
                switch (realfile.Length)
                {
                case 0x10000: pagesize0 = 0x100; break;

                case 0x20000: pagesize0 = 0x200; break;                         //

                case 0x40000: pagesize0 = 0x400; break;                         // all known good dumps fall in one of these three categories

                case 0x80000: pagesize0 = 0x800; break;                         //

                case 0x30000: pagesize0 = 0x200; pagesize1 = 0x100; break;

                case 0x50000: pagesize0 = 0x400; pagesize1 = 0x100; break;

                case 0x60000: pagesize0 = 0x400; pagesize1 = 0x200; break;

                case 0x90000: pagesize0 = 0x800; pagesize1 = 0x100; break;

                case 0xa0000: pagesize0 = 0x800; pagesize1 = 0x200; break;

                case 0xc0000: pagesize0 = 0x800; pagesize1 = 0x400; break;

                case 0x100000: pagesize0 = 0x800; pagesize1 = 0x800; break;
                }
                Console.WriteLine("Auto-guessed banking options {0} {1}", pagesize0, pagesize1);
            }

            Core = LibLynx.Create(realfile, realfile.Length, bios, bios.Length, pagesize0, pagesize1, false);
            try
            {
                _saveBuff  = new byte[LibLynx.BinStateSize(Core)];
                _saveBuff2 = new byte[_saveBuff.Length + 13];

                int rot = game.OptionPresent("rotate") ? int.Parse(game.OptionValue("rotate")) : 0;
                LibLynx.SetRotation(Core, rot);
                if ((rot & 1) != 0)
                {
                    BufferWidth  = Height;
                    BufferHeight = Width;
                }
                else
                {
                    BufferWidth  = Width;
                    BufferHeight = Height;
                }
                SetupMemoryDomains();
            }
            catch
            {
                Dispose();
                throw;
            }
        }
Beispiel #43
0
        public Gameboy(CoreComm comm, GameInfo game, byte[] file, object Settings, object SyncSettings, bool deterministic)
        {
            var ser = new BasicServiceProvider(this);

            ser.Register <IDisassemblable>(new GBDisassembler());
            ServiceProvider = ser;
            Tracer          = new TraceBuffer
            {
                Header = "Z80: PC, opcode, registers(SP, A, B, C, D, E, F, H, L, LY, CY)"
            };
            ser.Register <ITraceable>(Tracer);
            InitMemoryCallbacks();
            CoreComm = comm;

            comm.VsyncNum            = 262144;
            comm.VsyncDen            = 4389;
            comm.RomStatusAnnotation = null;
            comm.RomStatusDetails    = null;
            comm.NominalWidth        = 160;
            comm.NominalHeight       = 144;

            ThrowExceptionForBadRom(file);
            BoardName = MapperName(file);

            DeterministicEmulation = deterministic;

            GambatteState = LibGambatte.gambatte_create();

            if (GambatteState == IntPtr.Zero)
            {
                throw new InvalidOperationException("gambatte_create() returned null???");
            }

            try
            {
                this._syncSettings = (GambatteSyncSettings)SyncSettings ?? new GambatteSyncSettings();
                // copy over non-loadflag syncsettings now; they won't take effect if changed later
                zerotime      = (uint)this._syncSettings.RTCInitialTime;
                real_rtc_time = DeterministicEmulation ? false : this._syncSettings.RealTimeRTC;

                LibGambatte.LoadFlags flags = 0;

                if (this._syncSettings.ForceDMG)
                {
                    flags |= LibGambatte.LoadFlags.FORCE_DMG;
                }
                if (this._syncSettings.GBACGB)
                {
                    flags |= LibGambatte.LoadFlags.GBA_CGB;
                }
                if (this._syncSettings.MulticartCompat)
                {
                    flags |= LibGambatte.LoadFlags.MULTICART_COMPAT;
                }

                if (LibGambatte.gambatte_load(GambatteState, file, (uint)file.Length, GetCurrentTime(), flags) != 0)
                {
                    throw new InvalidOperationException("gambatte_load() returned non-zero (is this not a gb or gbc rom?)");
                }

                // set real default colors (before anyone mucks with them at all)
                PutSettings((GambatteSettings)Settings ?? new GambatteSettings());

                InitSound();

                Frame      = 0;
                LagCount   = 0;
                IsLagFrame = false;

                InputCallback = new LibGambatte.InputGetter(ControllerCallback);

                LibGambatte.gambatte_setinputgetter(GambatteState, InputCallback);

                InitMemoryDomains();

                CoreComm.RomStatusDetails = string.Format("{0}\r\nSHA1:{1}\r\nMD5:{2}\r\n",
                                                          game.Name,
                                                          file.HashSHA1(),
                                                          file.HashMD5());

                {
                    byte[] buff = new byte[32];
                    LibGambatte.gambatte_romtitle(GambatteState, buff);
                    string romname = System.Text.Encoding.ASCII.GetString(buff);
                    Console.WriteLine("Core reported rom name: {0}", romname);
                }

                TimeCallback = new LibGambatte.RTCCallback(GetCurrentTime);
                LibGambatte.gambatte_setrtccallback(GambatteState, TimeCallback);

                CDCallback = new LibGambatte.CDCallback(CDCallbackProc);

                NewSaveCoreSetBuff();
            }
            catch
            {
                Dispose();
                throw;
            }
        }
Beispiel #44
0
        private static void ClientOnDataReceived(object sender, Message message)
        {
            try
            {
                var messages = message.MessageString.Split('\u0013');
                foreach (var msg in messages)
                {
                    if (msg == "ping" || string.IsNullOrWhiteSpace(msg))
                    {
                        return; //ignore
                    }

                    string t;
                    try
                    {
                        dynamic m = JsonConvert.DeserializeObject(msg);
                        t = m.JType?.ToString();
                    }
                    catch (Exception)
                    {
                        //Bot.SendTextMessage(Settings.MainChatId, e.Message);
                        continue;
                    }

                    if (t == null)
                    {
                        continue;
                    }

                    Console.WriteLine(t);
                    Werewolf game;

                    switch (t)
                    {
                    case "PlayerJoinInfo":
                        var pji = JsonConvert.DeserializeObject <PlayerJoinInfo>(msg);
                        game = Games.FirstOrDefault(x => x.ChatId == pji.GroupId);
                        game?.AddPlayer(pji.User);
                        break;

                    case "GameStartInfo":
                        var gsi = JsonConvert.DeserializeObject <GameStartInfo>(msg);
                        //double check we don't already have a game...
                        game = Games.FirstOrDefault(x => x.ChatId == gsi.Chat.Id);
                        if (game != null)
                        {
                            game.AddPlayer(gsi.User);
                        }
                        else
                        {
                            game = new Werewolf(gsi.Chat.Id, gsi.User, gsi.Chat.Title, gsi.Chaos);
                            Games.Add(game);
                            GamesStarted++;
                        }

                        break;

                    case "ForceStartInfo":
                        var fsi = JsonConvert.DeserializeObject <ForceStartInfo>(msg);
                        game = Games.FirstOrDefault(x => x.ChatId == fsi.GroupId);
                        game?.ForceStart();
                        break;

                    case "CallbackInfo":
                        var ci = JsonConvert.DeserializeObject <CallbackInfo>(msg);
                        game =
                            Games.FirstOrDefault(
                                x => x.Players?.Any(p =>
                                                    p != null && !p.IsDead && p.TeleUser.Id == ci.Query.From.Id) ?? false);
                        game?.HandleReply(ci.Query);
                        break;

                    case "PlayerListRequestInfo":
                        var plri = JsonConvert.DeserializeObject <PlayerListRequestInfo>(msg);
                        game = Games.FirstOrDefault(x => x.ChatId == plri.GroupId);
                        game?.OutputPlayers();
                        break;

                    case "PlayerFleeInfo":
                        var pfi = JsonConvert.DeserializeObject <PlayerFleeInfo>(msg);
                        game = Games.FirstOrDefault(x => x.ChatId == pfi.GroupId);
                        game?.RemovePlayer(pfi.User);
                        break;

                    case "LoadLangInfo":
                        var lli = JsonConvert.DeserializeObject <LoadLangInfo>(msg);
                        game = Games.FirstOrDefault(x => x.ChatId == lli.GroupId);
                        game?.LoadLanguage(lli.FileName);
                        break;

                    case "PlayerSmiteInfo":
                        var psi = JsonConvert.DeserializeObject <PlayerSmiteInfo>(msg);
                        game = Games.FirstOrDefault(x => x.ChatId == psi.GroupId);
                        game?.FleePlayer(psi.UserId);
                        break;

                    case "UpdateNodeInfo":
                        var uni = JsonConvert.DeserializeObject <UpdateNodeInfo>(msg);
                        IsShuttingDown = true;
                        if (uni.Kill)
                        {
                            //force kill
                            Environment.Exit(1);
                        }

                        break;

                    case "SkipVoteInfo":
                        var svi = JsonConvert.DeserializeObject <SkipVoteInfo>(msg);
                        game = Games.FirstOrDefault(x => x.ChatId == svi.GroupId);
                        game?.SkipVote();
                        break;

                    case "GameKillInfo":
                        var gki = JsonConvert.DeserializeObject <GameKillInfo>(msg);
                        game = Games.FirstOrDefault(x => x.ChatId == gki.GroupId);
                        game?.Kill();
                        break;

                    case "GetGameInfo":
                        var ggi = JsonConvert.DeserializeObject <GetGameInfo>(msg);
                        var g   = Games.FirstOrDefault(x => x.ChatId == ggi.GroupId);
                        if (g == null)
                        {
                            message.Reply("null");
                        }

                        //build our response
                        var gi = new GameInfo
                        {
                            Language  = g.Language,
                            ChatGroup = g.ChatGroup,
                            GroupId   = g.ChatId,
                            NodeId    = ClientId,
                            Guid      = g.Guid,
                            Cycle     = g.Time,
                            State     = g.IsRunning ? GameState.Running :
                                        g.IsJoining ? GameState.Joining : GameState.Dead,
                            Users = new HashSet <int>(
                                g.Players?.Where(x => !x.IsDead)?.Select(x => x.TeleUser.Id) ?? new[] { 0 }),
                            Players = g.Players?.Select(x => new
                            {
                                Bitten = x.Bitten ? "Yes" : "No",
                                x.Bullet,
                                Choice          = g.Players.FirstOrDefault(p => p.Id == x.Choice)?.Name,
                                CurrentQuestion = x.CurrentQuestion?.QType.ToString(),
                                x.DonationLevel,
                                IsDead = x.IsDead ? "Yes" : "No",
                                x.Name,
                                LoverId    = g.Players.FirstOrDefault(p => p.Id == x.LoverId)?.Name,
                                PlayerRole = x.PlayerRole.ToString(),
                                Team       = x.Team.ToString(),
                                x.Votes,
                                x.Id
                            })
                        };
                        message.Reply(JsonConvert.SerializeObject(gi));
                        break;

                    case "ExtendTimeInfo":
                        var eti = JsonConvert.DeserializeObject <ExtendTimeInfo>(msg);
                        game = Games.FirstOrDefault(x => x.ChatId == eti.GroupId);
                        game?.ExtendTime(eti.User, eti.Admin, eti.Seconds);
                        break;

                    case "JoinButtonRequestInfo":
                        var jbri = JsonConvert.DeserializeObject <PlayerListRequestInfo>(msg);
                        game = Games.FirstOrDefault(x => x.ChatId == jbri.GroupId);
                        game?.ShowJoinButton();
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine(jbri.GroupId);
                        Console.ForegroundColor = ConsoleColor.Gray;
                        break;

                    default:
                        Console.WriteLine(msg);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + "\n" + message.MessageString);
                try
                {
                    Directory.CreateDirectory(Path.Combine(RootDirectory, "ReceiveErrors"));
                    using (var sw = new StreamWriter(Path.Combine(RootDirectory, "ReceiveErrors", "error.log"), true))
                    {
                        sw.WriteLine(e.Message + Environment.NewLine + message.MessageString + Environment.NewLine +
                                     e.StackTrace);
                    }
                }
                catch
                {
                    // ignored
                }
            }
        }
Beispiel #45
0
 public HyperNyma(GameInfo game, byte[] rom, CoreComm comm, string extension,
                  NymaSettings settings, NymaSyncSettings syncSettings, bool deterministic)
     : base(comm, "PCE", "PC Engine Controller", settings, syncSettings)
 {
     _hyperNyma = DoInit <LibHyperNyma>(game, rom, null, "hyper.wbx", extension, deterministic);
 }
        public override GameMetadata GetMetadata(Game game)
        {
            var gameInfo = new GameInfo()
            {
                Links = new List <Link>()
            };
            var metadata = new GameMetadata()
            {
                GameInfo = gameInfo
            };

            using (var client = new WebStoreClient())
            {
                var catalogs = client.QuerySearch(game.Name).GetAwaiter().GetResult();
                if (catalogs.HasItems())
                {
                    var product = client.GetProductInfo(catalogs[0].productSlug).GetAwaiter().GetResult();
                    if (product.pages.HasItems())
                    {
                        var page = product.pages[0];
                        gameInfo.Description = page.data.about.description;
                        gameInfo.Developers  = new List <string>()
                        {
                            page.data.about.developerAttribution
                        };
                        metadata.BackgroundImage = new MetadataFile(page.data.hero.backgroundImageUrl);
                        gameInfo.Links.Add(new Link(
                                               library.PlayniteApi.Resources.GetString("LOCCommonLinksStorePage"),
                                               "https://www.epicgames.com/store/en-US/product/" + catalogs[0].productSlug));

                        if (page.data.socialLinks.HasItems())
                        {
                            var links = page.data.socialLinks.
                                        Where(a => a.Key.StartsWith("link") && !a.Value.IsNullOrEmpty()).
                                        Select(a => new Link(a.Key.Replace("link", ""), a.Value)).ToList();
                            if (links.HasItems())
                            {
                                gameInfo.Links.AddRange(links);
                            }
                        }

                        if (!gameInfo.Description.IsNullOrEmpty())
                        {
                            gameInfo.Description = gameInfo.Description.Replace("\n", "\n<br>");
                        }
                    }
                }
            }

            gameInfo.Links.Add(new Link("PCGamingWiki", @"http://pcgamingwiki.com/w/index.php?search=" + game.Name));

            // There's not icon available on Epic servers so we will load one from EXE
            if (game.IsInstalled && string.IsNullOrEmpty(game.Icon))
            {
                var manifest = EpicLauncher.GetInstalledManifests().FirstOrDefault(a => a.AppName == game.GameId);
                if (manifest != null)
                {
                    var exePath = Path.Combine(manifest.InstallLocation, manifest.LaunchExecutable);
                    if (File.Exists(exePath))
                    {
                        using (var ms = new MemoryStream())
                        {
                            if (IconExtractor.ExtractMainIconFromFile(exePath, ms))
                            {
                                var iconName = Guid.NewGuid() + ".ico";
                                metadata.Icon = new MetadataFile(iconName, ms.ToArray());
                            }
                        }
                    }
                }
            }

            return(metadata);
        }
Beispiel #47
0
        public MGBAHawk(byte[] file, CoreComm comm, SyncSettings syncSettings, Settings settings, bool deterministic, GameInfo game)
        {
            _syncSettings          = syncSettings ?? new SyncSettings();
            _settings              = settings ?? new Settings();
            DeterministicEmulation = deterministic;

            byte[] bios = comm.CoreFileProvider.GetFirmware("GBA", "Bios", false);
            DeterministicEmulation &= bios != null;

            if (DeterministicEmulation != deterministic)
            {
                throw new MissingFirmwareException("A BIOS is required for deterministic recordings!");
            }

            if (!DeterministicEmulation && bios != null && !_syncSettings.RTCUseRealTime && !_syncSettings.SkipBios)
            {
                // in these situations, this core is deterministic even though it wasn't asked to be
                DeterministicEmulation = true;
            }

            if (bios != null && bios.Length != 16384)
            {
                throw new InvalidOperationException("BIOS must be exactly 16384 bytes!");
            }

            var skipBios = !DeterministicEmulation && _syncSettings.SkipBios;

            Core = LibmGBA.BizCreate(bios, file, file.Length, GetOverrideInfo(game), skipBios);
            if (Core == IntPtr.Zero)
            {
                throw new InvalidOperationException($"{nameof(LibmGBA.BizCreate)}() returned NULL!  Bad BIOS? and/or ROM?");
            }

            try
            {
                CreateMemoryDomains(file.Length);
                var ser = new BasicServiceProvider(this);
                ser.Register <IDisassemblable>(new ArmV4Disassembler());
                ser.Register <IMemoryDomains>(_memoryDomains);

                ServiceProvider = ser;
                PutSettings(_settings);

                Tracer = new TraceBuffer
                {
                    Header = "ARM7: PC, machine code, mnemonic, operands, registers"
                };
                _tracecb = msg => Tracer.Put(_traceInfo(msg));
                ser.Register(Tracer);
                MemoryCallbacks = new MGBAMemoryCallbackSystem(this);
            }
            catch
            {
                LibmGBA.BizDestroy(Core);
                throw;
            }

            InputCallbacks = new MemoryBasedInputCallbackSystem(this, "System Bus", new[] { 0x4000130u });
        }
Beispiel #48
0
        private static void KeepAlive()
        {
            var ver = Version.FileVersion;

            Connect();
            while (Running)
            {
                if ((DateTime.Now - StartupTime).Hours > 10)
                {
                    IsShuttingDown = true;
                }

                var infoGathered = false;

                if (Games == null || IsShuttingDown && Games.Count == 0)
                {
                    Thread.Sleep(5000);
                    //Running = false;
                    Environment.Exit(0);
                    return;
                }

                //monitor the tcp connection to keep it open
                try
                {
                    if (Games == null)
                    {
                        //uhhhhhhhhh  ok.....
                        continue;
                    }

                    var games = Games.ToList();

                    var info = new NodeInfo
                    {
                        Games                 = new HashSet <GameInfo>(),
                        ClientId              = ClientId,
                        CurrentGames          = games.Count,
                        CurrentPlayers        = games.Sum(x => x?.Players?.Count ?? 0),
                        DuplicateGamesRemoved = DupGamesKilled,
                        ThreadCount           = 0, //Process.GetCurrentProcess().Threads.Count,
                        //TotalGames = GamesStarted,
                        //TotalPlayers = games.Sum(x => x.Players?.Count ?? 0) + TotalPlayers,
                        Uptime       = DateTime.Now - StartupTime,
                        Version      = ver,
                        ShuttingDown = IsShuttingDown,
                        MessagesSent = MessagesSent
                    };

                    foreach (var g in games)
                    {
                        if (g?.Players == null)
                        {
                            try
                            {
                                Games.Remove(g);
                            }
                            catch
                            {
                                // ignored, it was already removed
                            }

                            continue;
                        }

                        var gi = new GameInfo
                        {
                            Language  = g.Language,
                            ChatGroup = g.ChatGroup,
                            GroupId   = g.ChatId,
                            NodeId    = ClientId,
                            Guid      = g.Guid,
                            State     = g.IsRunning ? GameState.Running : g.IsJoining ? GameState.Joining : GameState.Dead,
                            Users     = g.Players != null
                                ? new HashSet <int>(g.Players.Where(x => !x.IsDead).Select(x => x.TeleUser.Id))
                                : new HashSet <int>(),
                            PlayerCount = g.Players?.Count ?? 0
                                          //Players = new HashSet<IPlayer>(g.Players)
                        };
                        info.Games.Add(gi);
                    }

                    var json = JsonConvert.SerializeObject(info);
                    infoGathered = true;
                    Client.WriteLine(json);
                }
                catch (Exception e)
                {
                    while (e.InnerException != null)
                    {
                        e = e.InnerException;
                    }

                    Console.WriteLine($"Error in KeepAlive: {e.Message}\n{e.StackTrace}\n");
                    if (infoGathered) //only disconnect if tcp error
                    {
                        if (Client != null)
                        {
                            try
                            {
                                Client.DataReceived          -= ClientOnDataReceived;
                                Client.DelimiterDataReceived -= ClientOnDelimiterDataReceived;
                                Client.Disconnect();
                            }
                            catch
                            {
                                // ignored
                            }
                        }

                        Connect();
                    }
                }

                Thread.Sleep(500);
            }
        }
Beispiel #49
0
        private void Init(GameInfo game, byte[] rom)
        {
            Cpu  = new HuC6280(MemoryCallbacks);
            VCE  = new VCE();
            VDC1 = new VDC(this, Cpu, VCE);
            PSG  = new HuC6280PSG(735);
            SCSI = new ScsiCDBus(this, disc);

            Cpu.Logger = s => Tracer.Put(s);

            if (TurboGrafx)
            {
                Ram = new byte[0x2000];
                Cpu.ReadMemory21  = ReadMemory;
                Cpu.WriteMemory21 = WriteMemory;
                Cpu.WriteVDC      = VDC1.WriteVDC;
                _soundProvider    = PSG;
                CDAudio           = new CDAudio(null, 0);
            }

            else if (SuperGrafx)
            {
                VDC2              = new VDC(this, Cpu, VCE);
                VPC               = new VPC(this, VDC1, VDC2, VCE, Cpu);
                Ram               = new byte[0x8000];
                Cpu.ReadMemory21  = ReadMemorySGX;
                Cpu.WriteMemory21 = WriteMemorySGX;
                Cpu.WriteVDC      = VDC1.WriteVDC;
                _soundProvider    = PSG;
                CDAudio           = new CDAudio(null, 0);
            }

            else if (TurboCD)
            {
                Ram               = new byte[0x2000];
                CDRam             = new byte[0x10000];
                ADPCM             = new ADPCM(this, SCSI);
                Cpu.ReadMemory21  = ReadMemoryCD;
                Cpu.WriteMemory21 = WriteMemoryCD;
                Cpu.WriteVDC      = VDC1.WriteVDC;
                CDAudio           = new CDAudio(disc);
                SetCDAudioCallback();
                PSG.MaxVolume   = short.MaxValue * 3 / 4;
                SoundMixer      = new SoundMixer(735, PSG, CDAudio, ADPCM);
                _soundProvider  = SoundMixer;
                Cpu.ThinkAction = cycles => { SCSI.Think(); ADPCM.Think(cycles); };
            }

            if (rom.Length == 0x60000)
            {
                // 384k roms require special loading code. Why ;_;
                // In memory, 384k roms look like [1st 256k][Then full 384k]
                RomData = new byte[0xA0000];
                var origRom = rom;
                for (int i = 0; i < 0x40000; i++)
                {
                    RomData[i] = origRom[i];
                }
                for (int i = 0; i < 0x60000; i++)
                {
                    RomData[i + 0x40000] = origRom[i];
                }
                RomLength = RomData.Length;
            }
            else if (rom.Length > 1024 * 1024)
            {
                // If the rom is bigger than 1 megabyte, switch to Street Fighter 2 mapper
                Cpu.ReadMemory21  = ReadMemorySF2;
                Cpu.WriteMemory21 = WriteMemorySF2;
                RomData           = rom;
                RomLength         = RomData.Length;

                // user request: current value of the SF2MapperLatch on the tracelogger
                Cpu.Logger = s => Tracer.Put(new TraceInfo
                {
                    Disassembly  = $"{SF2MapperLatch:X1}:{s}",
                    RegisterInfo = ""
                });
            }
            else
            {
                // normal rom.
                RomData   = rom;
                RomLength = RomData.Length;
            }

            if (game["BRAM"] || Type == NecSystemType.TurboCD)
            {
                BramEnabled = true;
                BRAM        = new byte[2048];

                // pre-format BRAM. damn are we helpful.
                BRAM[0] = 0x48; BRAM[1] = 0x55; BRAM[2] = 0x42; BRAM[3] = 0x4D;
                BRAM[4] = 0x00; BRAM[5] = 0x88; BRAM[6] = 0x10; BRAM[7] = 0x80;
            }

            if (game["SuperSysCard"])
            {
                SuperRam = new byte[0x30000];
            }

            if (game["ArcadeCard"])
            {
                ArcadeRam            = new byte[0x200000];
                ArcadeCard           = true;
                ArcadeCardRewindHack = Settings.ArcadeCardRewindHack;
                for (int i = 0; i < 4; i++)
                {
                    ArcadePage[i] = new ArcadeCardPage();
                }
            }

            if (game["PopulousSRAM"])
            {
                PopulousRAM       = new byte[0x8000];
                Cpu.ReadMemory21  = ReadMemoryPopulous;
                Cpu.WriteMemory21 = WriteMemoryPopulous;
            }

            // the gamedb can force sprite limit on, ignoring settings
            if (game["ForceSpriteLimit"] || game.NotInDatabase)
            {
                ForceSpriteLimit = true;
            }

            if (game["CdVol"])
            {
                CDAudio.MaxVolume = int.Parse(game.OptionValue("CdVol"));
            }

            if (game["PsgVol"])
            {
                PSG.MaxVolume = int.Parse(game.OptionValue("PsgVol"));
            }

            if (game["AdpcmVol"])
            {
                ADPCM.MaxVolume = int.Parse(game.OptionValue("AdpcmVol"));
            }

            // the gamedb can also force equalizevolumes on
            if (TurboCD && (Settings.EqualizeVolume || game["EqualizeVolumes"] || game.NotInDatabase))
            {
                SoundMixer.EqualizeVolumes();
            }

            // Ok, yes, HBlankPeriod's only purpose is game-specific hax.
            // 1) At least they're not coded directly into the emulator, but instead data-driven.
            // 2) The games which have custom HBlankPeriods work without it, the override only
            //    serves to clean up minor gfx anomalies.
            // 3) There's no point in haxing the timing with incorrect values in an attempt to avoid this.
            //    The proper fix is cycle-accurate/bus-accurate timing. That isn't coming to the C#
            //    version of this core. Let's just acknolwedge that the timing is imperfect and fix
            //    it in the least intrusive and most honest way we can.
            if (game["HBlankPeriod"])
            {
                VDC1.HBlankCycles = game.GetIntValue("HBlankPeriod");
            }

            // This is also a hack. Proper multi-res/TV emulation will be a native-code core feature.
            if (game["MultiResHack"])
            {
                VDC1.MultiResHack = game.GetIntValue("MultiResHack");
            }

            Cpu.ResetPC();

            Tracer = new TraceBuffer {
                Header = Cpu.TraceHeader
            };
            var ser = new BasicServiceProvider(this);

            ServiceProvider = ser;
            ser.Register <ITraceable>(Tracer);
            ser.Register <IDisassemblable>(Cpu);
            ser.Register <IVideoProvider>((IVideoProvider)VPC ?? VDC1);
            ser.Register <ISoundProvider>(_soundProvider);
            ser.Register <IStatable>(new StateSerializer(SyncState));
            SetupMemoryDomains();
        }
Beispiel #50
0
        public override GameMetadata GetMetadata(Game game)
        {
            var gameInfo = new GameInfo();
            var metadata = new GameMetadata()
            {
                GameInfo = gameInfo,
            };

            using (var client = new WebStoreClient())
            {
                var catalogs = client.QuerySearch(game.Name).GetAwaiter().GetResult();
                if (catalogs.HasItems())
                {
                    var product = client.GetProductInfo(catalogs[0].productSlug).GetAwaiter().GetResult();
                    if (product.pages.HasItems())
                    {
                        var page = product.pages[0];
                        gameInfo.Description = page.data.about.description;
                        gameInfo.Developers  = new List <string>()
                        {
                            page.data.about.developerAttribution
                        };
                        metadata.BackgroundImage = new MetadataFile(page.data.hero.backgroundImageUrl);

                        if (page.data.socialLinks.HasItems())
                        {
                            gameInfo.Links = page.data.socialLinks.
                                             Where(a => a.Key.StartsWith("link")).
                                             Select(a => new Link(a.Key.Replace("link", ""), a.Value)).ToList();
                        }

                        if (!gameInfo.Description.IsNullOrEmpty())
                        {
                            gameInfo.Description = gameInfo.Description.Replace("\n", "\n<br>");
                        }
                    }
                }
            }

            // There's not icon available on Epic servers so we will load one from EXE
            if (game.IsInstalled && string.IsNullOrEmpty(game.Icon))
            {
                var playAction = api.ExpandGameVariables(game, game.PlayAction);
                var executable = string.Empty;
                if (File.Exists(playAction.Path))
                {
                    executable = playAction.Path;
                }
                else if (!string.IsNullOrEmpty(playAction.WorkingDir))
                {
                    executable = Path.Combine(playAction.WorkingDir, playAction.Path);
                }

                var exeIcon = IconExtension.ExtractIconFromExe(executable, true);
                if (exeIcon != null)
                {
                    var iconName = Guid.NewGuid() + ".png";
                    metadata.Icon = new MetadataFile(iconName, exeIcon.ToByteArray(System.Drawing.Imaging.ImageFormat.Png));
                }
            }

            return(metadata);
        }
Beispiel #51
0
        public Dictionary <string, GameInfo> GetInstalledGames(bool useDataCache = false)
        {
            var contentPath = Path.Combine(Origin.DataPath, "LocalContent");
            var games       = new Dictionary <string, GameInfo>();

            if (Directory.Exists(contentPath))
            {
                var packages = Directory.GetFiles(contentPath, "*.mfst", SearchOption.AllDirectories);
                foreach (var package in packages)
                {
                    try
                    {
                        var gameId = Path.GetFileNameWithoutExtension(package);
                        if (!gameId.StartsWith("Origin"))
                        {
                            // Get game id by fixing file via adding : before integer part of the name
                            // for example OFB-EAST52017 converts to OFB-EAST:52017
                            var match = Regex.Match(gameId, @"^(.*?)(\d+)$");
                            if (!match.Success)
                            {
                                logger.Warn("Failed to get game id from file " + package);
                                continue;
                            }

                            gameId = match.Groups[1].Value + ":" + match.Groups[2].Value;
                        }

                        var newGame = new GameInfo()
                        {
                            Source      = "Origin",
                            GameId      = gameId,
                            IsInstalled = true
                        };

                        GameLocalDataResponse localData = null;

                        try
                        {
                            localData = GetLocalManifest(gameId, useDataCache);
                        }
                        catch (Exception e) when(!Environment.IsDebugBuild)
                        {
                            logger.Error(e, $"Failed to get Origin manifest for a {gameId}, {package}");
                            continue;
                        }

                        if (localData == null)
                        {
                            continue;
                        }

                        if (localData.offerType != "Base Game" && localData.offerType != "DEMO")
                        {
                            continue;
                        }

                        newGame.Name = StringExtensions.NormalizeGameName(localData.localizableAttributes.displayName);
                        var platform = localData.publishing.softwareList.software.FirstOrDefault(a => a.softwarePlatform == "PCWIN");

                        if (platform == null)
                        {
                            logger.Warn(gameId + " game doesn't have windows platform, skipping install import.");
                            continue;
                        }

                        var installPath = GetPathFromPlatformPath(platform.fulfillmentAttributes.installCheckOverride);
                        if (installPath == null ||
                            installPath.CompletePath.IsNullOrEmpty() ||
                            !File.Exists(installPath.CompletePath))
                        {
                            continue;
                        }

                        newGame.PlayAction = GetGamePlayTask(localData);
                        if (newGame.PlayAction?.Type == GameActionType.File)
                        {
                            newGame.InstallDirectory      = newGame.PlayAction.WorkingDir;
                            newGame.PlayAction.WorkingDir = newGame.PlayAction.WorkingDir.Replace(newGame.InstallDirectory, ExpandableVariables.InstallationDirectory);
                            newGame.PlayAction.Path       = newGame.PlayAction.Path.Replace(newGame.InstallDirectory, "").Trim(new char[] { '\\', '/' });
                        }
                        else
                        {
                            newGame.InstallDirectory = Path.GetDirectoryName(installPath.CompletePath);
                        }

                        // For games like Sims 4
                        if (newGame.PlayAction?.Path.EndsWith("exe", StringComparison.OrdinalIgnoreCase) == false)
                        {
                            var task = GetGamePlayTask(newGame.InstallDirectory);
                            newGame.InstallDirectory      = task.WorkingDir;
                            newGame.PlayAction.WorkingDir = task.WorkingDir.Replace(newGame.InstallDirectory, ExpandableVariables.InstallationDirectory);
                            newGame.PlayAction.Path       = task.Path.Replace(newGame.InstallDirectory, "").Trim(new char[] { '\\', '/' });
                        }

                        // If game uses EasyAntiCheat then use executable referenced by it
                        if (Origin.GetGameUsesEasyAntiCheat(newGame.InstallDirectory))
                        {
                            var eac = EasyAntiCheat.GetLauncherSettings(newGame.InstallDirectory);
                            if (newGame.PlayAction == null)
                            {
                                newGame.PlayAction = new GameAction
                                {
                                    Type = GameActionType.File,
                                    IsHandledByPlugin = true
                                };
                            }

                            newGame.PlayAction.Path = eac.Executable;
                            if (!string.IsNullOrEmpty(eac.Parameters) && eac.UseCmdlineParameters == "1")
                            {
                                newGame.PlayAction.Arguments = eac.Parameters;
                            }

                            if (!string.IsNullOrEmpty(eac.WorkingDirectory))
                            {
                                newGame.PlayAction.WorkingDir = Path.Combine(ExpandableVariables.InstallationDirectory, eac.WorkingDirectory);
                            }
                            else
                            {
                                newGame.PlayAction.WorkingDir = ExpandableVariables.InstallationDirectory;
                            }
                        }

                        games.Add(newGame.GameId, newGame);
                    }
                    catch (Exception e) when(!Environment.IsDebugBuild)
                    {
                        logger.Error(e, $"Failed to import installed Origin game {package}.");
                    }
                }
            }

            return(games);
        }
Beispiel #52
0
 private void newGame()
 {
     Game = new GameInfo();
     clearAllCells();
     generateGamefieldMatrix();
 }
Beispiel #53
0
        public SteamGameMetadata GetGameMetadata(
            uint appId,
            BackgroundSource backgroundSource,
            bool downloadVerticalCovers)
        {
            var downloadedMetadata = DownloadGameMetadata(appId, backgroundSource, downloadVerticalCovers);
            var gameInfo           = new GameInfo
            {
                Name  = downloadedMetadata.ProductDetails?["common"]["name"]?.Value ?? downloadedMetadata.StoreDetails?.name,
                Links = new List <Link>()
                {
                    new Link(ResourceProvider.GetString("LOCSteamLinksCommunityHub"), $"https://steamcommunity.com/app/{appId}"),
                    new Link(ResourceProvider.GetString("LOCSteamLinksDiscussions"), $"https://steamcommunity.com/app/{appId}/discussions/"),
                    new Link(ResourceProvider.GetString("LOCCommonLinksNews"), $"https://store.steampowered.com/news/?appids={appId}"),
                    new Link(ResourceProvider.GetString("LOCCommonLinksStorePage"), $"https://store.steampowered.com/app/{appId}"),
                    new Link("PCGamingWiki", $"https://pcgamingwiki.com/api/appid.php?appid={appId}")
                }
            };

            downloadedMetadata.GameInfo = gameInfo;

            var metadata = new GameMetadata()
            {
                GameInfo        = gameInfo,
                Icon            = downloadedMetadata.Icon,
                CoverImage      = downloadedMetadata.CoverImage,
                BackgroundImage = downloadedMetadata.BackgroundImage
            };

            if (downloadedMetadata.StoreDetails?.categories?.FirstOrDefault(a => a.id == 22) != null)
            {
                gameInfo.Links.Add(new Link(ResourceProvider.GetString("LOCCommonLinksAchievements"), GetAchievementsUrl(appId)));
            }

            if (downloadedMetadata.StoreDetails?.categories?.FirstOrDefault(a => a.id == 30) != null)
            {
                gameInfo.Links.Add(new Link(ResourceProvider.GetString("LOCSteamLinksWorkshop"), GetWorkshopUrl(appId)));
            }

            if (downloadedMetadata.StoreDetails != null)
            {
                gameInfo.Description = ParseDescription(downloadedMetadata.StoreDetails.detailed_description);
                var cultInfo = new CultureInfo("en-US", false).TextInfo;
                gameInfo.ReleaseDate = downloadedMetadata.StoreDetails.release_date.date;
                gameInfo.CriticScore = downloadedMetadata.StoreDetails.metacritic?.score;
                if (downloadedMetadata.UserReviewDetails?.total_reviews > 0)
                {
                    gameInfo.CommunityScore = CalculateUserScore(downloadedMetadata.UserReviewDetails);
                }

                if (downloadedMetadata.StoreDetails.publishers.HasNonEmptyItems())
                {
                    gameInfo.Publishers = new List <string>(downloadedMetadata.StoreDetails.publishers);
                }

                if (downloadedMetadata.StoreDetails.developers.HasNonEmptyItems())
                {
                    gameInfo.Developers = new List <string>(downloadedMetadata.StoreDetails.developers);
                }

                if (downloadedMetadata.StoreDetails.categories.HasItems())
                {
                    gameInfo.Features = new List <string>();
                    foreach (var category in downloadedMetadata.StoreDetails.categories)
                    {
                        // Ignore VR category, will be set from appinfo
                        if (category.id == 31)
                        {
                            continue;
                        }

                        if (category.description == "Steam Cloud")
                        {
                            category.description = "Cloud Saves";
                        }

                        gameInfo.Features.Add(cultInfo.ToTitleCase(category.description.Replace("steam", "", StringComparison.OrdinalIgnoreCase).Trim()));
                    }
                }

                if (downloadedMetadata.StoreDetails.genres.HasItems())
                {
                    gameInfo.Genres = new List <string>(downloadedMetadata.StoreDetails.genres.Select(a => a.description));
                }
            }

            if (downloadedMetadata.ProductDetails != null)
            {
                var tasks      = new List <GameAction>();
                var launchList = downloadedMetadata.ProductDetails["config"]["launch"].Children;
                foreach (var task in launchList.Skip(1))
                {
                    var properties = task["config"];
                    if (properties.Name != null)
                    {
                        if (properties["oslist"].Name != null)
                        {
                            if (properties["oslist"].Value != "windows")
                            {
                                continue;
                            }
                        }
                    }

                    // Ignore action without name  - shoudn't be visible to end user
                    if (task["description"].Name != null)
                    {
                        var newTask = new GameAction()
                        {
                            Name              = task["description"].Value,
                            Arguments         = task["arguments"].Value ?? string.Empty,
                            Path              = task["executable"].Value,
                            IsHandledByPlugin = false,
                            WorkingDir        = ExpandableVariables.InstallationDirectory
                        };

                        tasks.Add(newTask);
                    }
                }

                var manual = downloadedMetadata.ProductDetails["extended"]["gamemanualurl"];
                if (manual.Name != null)
                {
                    tasks.Add((new GameAction()
                    {
                        Name = "Manual",
                        Type = GameActionType.URL,
                        Path = manual.Value,
                        IsHandledByPlugin = false
                    }));
                }

                gameInfo.OtherActions = tasks;

                // VR features
                var vrSupport = false;
                foreach (var vrArea in downloadedMetadata.ProductDetails["common"]["playareavr"].Children)
                {
                    if (vrArea.Name == "seated" && vrArea.Value == "1")
                    {
                        gameInfo.Features.Add("VR Seated");
                        vrSupport = true;
                    }
                    else if (vrArea.Name == "standing" && vrArea.Value == "1")
                    {
                        gameInfo.Features.Add("VR Standing");
                        vrSupport = true;
                    }
                    if (vrArea.Name.Contains("roomscale"))
                    {
                        gameInfo.Features.AddMissing("VR Room-Scale");
                        vrSupport = true;
                    }
                }

                foreach (var vrArea in downloadedMetadata.ProductDetails["common"]["controllervr"].Children)
                {
                    if (vrArea.Name == "kbm" && vrArea.Value == "1")
                    {
                        gameInfo.Features.Add("VR Keyboard / Mouse");
                        vrSupport = true;
                    }
                    else if (vrArea.Name == "xinput" && vrArea.Value == "1")
                    {
                        gameInfo.Features.Add("VR Gamepad");
                        vrSupport = true;
                    }
                    if ((vrArea.Name == "oculus" && vrArea.Value == "1") ||
                        (vrArea.Name == "steamvr" && vrArea.Value == "1"))
                    {
                        gameInfo.Features.Add("VR Motion Controllers");
                        vrSupport = true;
                    }
                }

                if (vrSupport)
                {
                    gameInfo.Features.Add("VR");
                }
            }

            return(downloadedMetadata);
        }
        public override GameMetadata GetMetadata(Game game)
        {
            var storeMetadata = DownloadGameMetadata(game.GameId);
            var gameInfo      = new GameInfo
            {
                Name        = StringExtensions.NormalizeGameName(storeMetadata.StoreDetails.i18n.displayName),
                Description = storeMetadata.StoreDetails.i18n.longDescription,
                ReleaseDate = storeMetadata.StoreDetails.platforms.First(a => a.platform == "PCWIN").releaseDate,
                Links       = new List <Link>()
                {
                    new Link("Store Page", @"https://www.origin.com/store" + storeMetadata.StoreDetails.offerPath),
                    new Link("PCGamingWiki", @"http://pcgamingwiki.com/w/index.php?search=" + game.Name)
                }
            };

            if (!storeMetadata.StoreDetails.publisherFacetKey.IsNullOrEmpty())
            {
                gameInfo.Publishers = new List <string>()
                {
                    storeMetadata.StoreDetails.publisherFacetKey
                };
            }

            if (!storeMetadata.StoreDetails.developerFacetKey.IsNullOrEmpty())
            {
                gameInfo.Developers = new List <string>()
                {
                    storeMetadata.StoreDetails.developerFacetKey
                };
            }

            if (!storeMetadata.StoreDetails.genreFacetKey.IsNullOrEmpty())
            {
                gameInfo.Genres = new List <string>(storeMetadata.StoreDetails.genreFacetKey?.Split(','));
            }

            var metadata = new GameMetadata()
            {
                GameInfo        = gameInfo,
                Icon            = storeMetadata.Icon,
                CoverImage      = storeMetadata.CoverImage,
                BackgroundImage = storeMetadata.BackgroundImage
            };

            if (!string.IsNullOrEmpty(storeMetadata.StoreDetails.i18n.gameForumURL))
            {
                gameInfo.Links.Add(new Link("Forum", storeMetadata.StoreDetails.i18n.gameForumURL));
            }

            if (!string.IsNullOrEmpty(storeMetadata.StoreDetails.i18n.gameManualURL))
            {
                game.OtherActions = new ObservableCollection <GameAction>()
                {
                    new GameAction()
                    {
                        IsHandledByPlugin = false,
                        Type = GameActionType.URL,
                        Path = storeMetadata.StoreDetails.i18n.gameManualURL,
                        Name = "Manual"
                    }
                };
            }

            // There's not icon available on Origin servers so we will load one from EXE
            if (game.IsInstalled && string.IsNullOrEmpty(game.Icon))
            {
                var playAction = api.ExpandGameVariables(game, game.PlayAction);
                var executable = string.Empty;
                if (File.Exists(playAction.Path))
                {
                    executable = playAction.Path;
                }
                else if (!string.IsNullOrEmpty(playAction.WorkingDir))
                {
                    executable = Path.Combine(playAction.WorkingDir, playAction.Path);
                }

                if (string.IsNullOrEmpty(executable))
                {
                    return(storeMetadata);
                }

                var exeIcon = IconExtension.ExtractIconFromExe(executable, true);
                if (exeIcon != null)
                {
                    var iconName = Guid.NewGuid() + ".png";
                    metadata.Icon = new MetadataFile(iconName, exeIcon.ToByteArray(System.Drawing.Imaging.ImageFormat.Png));
                }
            }

            return(metadata);
        }
Beispiel #55
0
        private static LibmGBA.OverrideInfo GetOverrideInfo(GameInfo game)
        {
            if (!game.OptionPresent("mgbaNeedsOverrides"))
            {
                // the gba game db predates the mgba core in bizhawk, but was never used by the mgba core,
                // which had its own handling for overrides
                // to avoid possible regressions, we don't want to be overriding things that we already
                // know work in mgba, so unless this parameter is set, we do nothing
                return(null);
            }

            var ret = new LibmGBA.OverrideInfo();

            if (game.OptionPresent("flashSize"))
            {
                switch (game.GetIntValue("flashSize"))
                {
                case 65536:
                    ret.Savetype = LibmGBA.SaveType.Flash512;
                    break;

                case 131072:
                    ret.Savetype = LibmGBA.SaveType.Flash1m;
                    break;

                default:
                    throw new InvalidOperationException("Unknown flashSize");
                }
            }
            else if (game.OptionPresent("saveType"))
            {
                switch (game.GetIntValue("saveType"))
                {
                // 3 specifies either flash 512 or 1024, but in vba-over.ini, the latter will have a flashSize as well
                case 3:
                    ret.Savetype = LibmGBA.SaveType.Flash512;
                    break;

                case 4:
                    ret.Savetype = LibmGBA.SaveType.Eeprom;
                    break;

                default:
                    throw new InvalidOperationException("Unknown saveType");
                }
            }

            if (game.GetInt("rtcEnabled", 0) == 1)
            {
                ret.Hardware |= LibmGBA.Hardware.Rtc;
            }

            if (game.GetInt("mirroringEnabled", 0) == 1)
            {
                throw new InvalidOperationException("Don't know what to do with mirroringEnabled!");
            }

            if (game.OptionPresent("idleLoop"))
            {
                ret.IdleLoop = (uint)game.GetHexValue("idleLoop");
            }

            return(ret);
        }
Beispiel #56
0
        public Genesis(CoreComm comm, GameInfo game, byte[] rom)
        {
            CoreComm = comm;
            MainCPU  = new MC68000();
            SoundCPU = new Z80A();
            YM2612   = new YM2612()
            {
                MaxVolume = 23405
            };
            PSG = new SN76489()
            {
                MaxVolume = 4681
            };
            VDP = new GenVDP();
            VDP.DmaReadFrom68000 = ReadWord;
            SoundMixer           = new SoundMixer(YM2612, PSG);

            MainCPU.ReadByte    = ReadByte;
            MainCPU.ReadWord    = ReadWord;
            MainCPU.ReadLong    = ReadLong;
            MainCPU.WriteByte   = WriteByte;
            MainCPU.WriteWord   = WriteWord;
            MainCPU.WriteLong   = WriteLong;
            MainCPU.IrqCallback = InterruptCallback;

            // ---------------------- musashi -----------------------
#if MUSASHI
            _vdp    = vdpcallback;
            read8   = Read8;
            read16  = Read16;
            read32  = Read32;
            write8  = Write8;
            write16 = Write16;
            write32 = Write32;

            Musashi.RegisterVdpCallback(Marshal.GetFunctionPointerForDelegate(_vdp));
            Musashi.RegisterRead8(Marshal.GetFunctionPointerForDelegate(read8));
            Musashi.RegisterRead16(Marshal.GetFunctionPointerForDelegate(read16));
            Musashi.RegisterRead32(Marshal.GetFunctionPointerForDelegate(read32));
            Musashi.RegisterWrite8(Marshal.GetFunctionPointerForDelegate(write8));
            Musashi.RegisterWrite16(Marshal.GetFunctionPointerForDelegate(write16));
            Musashi.RegisterWrite32(Marshal.GetFunctionPointerForDelegate(write32));
#endif
            // ---------------------- musashi -----------------------

            SoundCPU.ReadMemory    = ReadMemoryZ80;
            SoundCPU.WriteMemory   = WriteMemoryZ80;
            SoundCPU.WriteHardware = (a, v) => { Console.WriteLine("Z80: Attempt I/O Write {0:X2}:{1:X2}", a, v); };
            SoundCPU.ReadHardware  = x => 0xFF;
            SoundCPU.IRQCallback   = () => SoundCPU.Interrupt = false;
            Z80Reset = true;
            RomData  = new byte[0x400000];
            for (int i = 0; i < rom.Length; i++)
            {
                RomData[i] = rom[i];
            }

            SetupMemoryDomains();
#if MUSASHI
            Musashi.Init();
            Musashi.Reset();
            VDP.GetPC = () => Musashi.PC;
#else
            MainCPU.Reset();
            VDP.GetPC = () => MainCPU.PC;
#endif
            InitializeCartHardware(game);
        }
Beispiel #57
0
 protected abstract double GetPlayerWinProbability(GameInfo gameInfo, double playerRating, double opponentRating);
 private void OnJoinButtonPressed(GameInfo _game)
 {
     FirebaseRealtimeDatabase.m_Instance.JoinGame(_game);
 }
Beispiel #59
0
 protected ScriptParser(GameInfo info)
 {
     Game = info;
 }
Beispiel #60
0
 void InitializeCartHardware(GameInfo game)
 {
     LogCartInfo();
     InitializeEeprom(game);
     InitializeSaveRam(game);
 }