public Texture2D GetSteamProfileImage(CSteamID userID)
    {
        int FriendAvatar = SteamFriends.GetMediumFriendAvatar(userID);

        Texture2D m_MediumAvatar;

        if (DebugTextOn)
        {
            Debug.Log("SteamFriends.GetMediumFriendAvatar(" + userID + ") - " + FriendAvatar);
        }

        uint ImageWidth;
        uint ImageHeight;
        bool ret = SteamUtils.GetImageSize(FriendAvatar, out ImageWidth, out ImageHeight);

        if (ret && ImageWidth > 0 && ImageHeight > 0)
        {
            byte[] Image = new byte[ImageWidth * ImageHeight * 4];

            ret            = SteamUtils.GetImageRGBA(FriendAvatar, Image, (int)(ImageWidth * ImageHeight * 4));
            m_MediumAvatar = new Texture2D((int)ImageWidth, (int)ImageHeight, TextureFormat.RGBA32, false, true);
            m_MediumAvatar.LoadRawTextureData(Image);
            m_MediumAvatar.Apply();

            return(m_MediumAvatar);
        }

        //return null because Steam didn't give us an image
        return(null);
    }
예제 #2
0
        private static Texture2D GetAvatar(CSteamID steamUser)
        {
            int  avatarInt = SteamFriends.GetLargeFriendAvatar(steamUser);
            bool success   = SteamUtils.GetImageSize(avatarInt, out uint imageWidth, out uint imageHeight);

            if (success && imageWidth > 0 && imageHeight > 0)
            {
                byte[]    Image         = new byte[imageWidth * imageHeight * 4];
                Texture2D returnTexture = new Texture2D((int)imageWidth, (int)imageHeight, TextureFormat.RGBA32, false, true);
                success = SteamUtils.GetImageRGBA(avatarInt, Image, (int)(imageWidth * imageHeight * 4));

                if (success)
                {
                    returnTexture.LoadRawTextureData(Image);
                    returnTexture.Apply();
                }

                return(returnTexture);
            }
            else
            {
                Debug.LogError("Couldn't get avatar.");
                return(new Texture2D(0, 0));
            }
        }
예제 #3
0
        public void SetAchievementCorner(AchievementCorner corner)
        {
            ENotificationPosition position;

            switch (corner)
            {
            case AchievementCorner.TopLeft:
            {
                position = ENotificationPosition.k_EPositionTopLeft;
                break;
            }

            case AchievementCorner.TopRight:
            {
                position = ENotificationPosition.k_EPositionTopRight;
                break;
            }

            case AchievementCorner.BottomLeft:
            {
                position = ENotificationPosition.k_EPositionBottomLeft;
                break;
            }

            case AchievementCorner.BottomRight:
            default:
            {
                position = ENotificationPosition.k_EPositionBottomRight;
                break;
            }
            }
            SteamUtils.SetOverlayNotificationPosition(position);
        }
예제 #4
0
    public static Texture2D BuildTexture(int i_Image)
    {
        if (!SteamManager.initializedMain)
        {
            return(null);
        }

        uint imageWidth;
        uint imageHeight;
        bool ret = SteamUtils.GetImageSize(i_Image, out imageWidth, out imageHeight);

        if (ret && imageWidth > 0 && imageHeight > 0)
        {
            byte[] image = new byte[imageWidth * imageHeight * 4];

            ret = SteamUtils.GetImageRGBA(i_Image, image, (int)(imageWidth * imageHeight * 4));

            Texture2D avatar = new Texture2D((int)imageWidth, (int)imageHeight, TextureFormat.RGBA32, false, true);
            avatar.LoadRawTextureData(image); // The image is upside down! "@ares_p: in Unity all texture data starts from "bottom" (OpenGL convention)"
            avatar.Apply();

            return(avatar);
        }

        return(null);
    }
예제 #5
0
        private async Task LoadModsFromProfile()
        {
            // build a list of mods to be processed
            var modIdList = new List <string>();

            var serverMapModId = ServerProfile.GetProfileMapModId(_profile);

            if (!string.IsNullOrWhiteSpace(serverMapModId))
            {
                modIdList.Add(serverMapModId);
            }

            if (!string.IsNullOrWhiteSpace(_profile.TotalConversionModId))
            {
                modIdList.Add(_profile.TotalConversionModId);
            }

            modIdList.AddRange(ModUtils.GetModIdList(_profile.ServerModIds));
            modIdList = ModUtils.ValidateModList(modIdList);

            var response = await Task.Run(() => SteamUtils.GetSteamModDetails(modIdList));

            var workshopFiles  = WorkshopFiles;
            var modsRootFolder = Path.Combine(_profile.InstallDirectory, Config.Default.ServerModsRelativePath);
            var modDetails     = ModDetailList.GetModDetails(modIdList, modsRootFolder, workshopFiles, response);

            UpdateModDetailsList(modDetails);

            ModDetailsStatusMessage = modDetails.Count > 0 && response?.publishedfiledetails == null?_globalizer.GetResourceString("ModDetails_ModDetailFetchFailed_Label") : string.Empty;

            ModDetailsChanged = false;
        }
        public override void Init()
        {
            if (IsSignedIn)
            {
                m_GameID            = new CGameID(SteamUtils.GetAppID());
                m_UserStatsReceived = Callback <UserStatsReceived_t> .Create(OnUserStatsReceived);

                m_UserStatsStored = Callback <UserStatsStored_t> .Create(OnUserStatsStored);

                m_UserAchievementStored = Callback <UserAchievementStored_t> .Create(OnAchievementStored);

                //m_LeaderboardScoreUploaded = CallResult<LeaderboardScoreUploaded_t>.Create(OnLeaderboardScoreUploaded);


                SteamUserStats.RequestCurrentStats();

                //SteamUser.
                RaiseGameServiceEvent(new GameServiceEvent(GameServiceEventType.SignInSuccess));
                GetSmallAvatar(SteamUser.GetSteamID());
            }
            else
            {
                RaiseGameServiceEvent(new GameServiceEvent(GameServiceEventType.SingInFailed));
            }
        }
예제 #7
0
        // Remember to flip it
        public static Texture2D GetTexture(int id)
        {
            if (cache.TryGetValue(id, out Texture2D tex))
            {
                return(tex);
            }

            if (!SteamUtils.GetImageSize(id, out uint width, out uint height))
            {
                cache[id] = null;
                return(null);
            }

            uint sizeInBytes = width * height * 4;

            byte[] data = new byte[sizeInBytes];

            if (!SteamUtils.GetImageRGBA(id, data, (int)sizeInBytes))
            {
                cache[id] = null;
                return(null);
            }

            tex = new Texture2D((int)width, (int)height, TextureFormat.RGBA32, false);
            tex.LoadRawTextureData(data);
            tex.Apply();

            cache[id] = tex;

            return(tex);
        }
    /// <summary>
    /// Registers a file's info. (Must send file next with sendFileOrUpdate). This is also used when updating files.
    /// </summary>
    /// <param name="pubId">Obtained from CreateWorkshopItem</param>
    /// <param name="title">Limit the title length to 128 ASCII characters</param>
    /// <param name="description">Limit the description length to 8000 ASCII characters</param>
    /// <param name="visability">Valid visibility (ERemoteStoragePublishedFileVisibility) values include:        k_ERemoteStoragePublishedFileVisibilityPublic = 0        k_ERemoteStoragePublishedFileVisibilityFriendsOnly = 1        k_ERemoteStoragePublishedFileVisibilityPrivate = 2</param>
    /// <param name="tags">Utilizes a SteamParamStringArray_t which contains a pointer to an array of char * strings and a count of the number of strings in the array. </param>
    /// <param name="contentFolder">pszContentFolder is the absolute path to a local folder containing one or more files that represents the workshop item. For efficient upload and download, files should not be merged or compressed into single files (e.g. zip files). </param>
    /// <param name="imagePreviewFile">pszPreviewFile is the absolute path to a local preview image file for the workshop item. It must be under 1MB in size. The format should be one that both the web and the application (if necessary) can render. Suggested formats include JPG, PNG or GIF. </param>
    /// <returns></returns>
    public UGCUpdateHandle_t registerFileInfoOrUpdate(PublishedFileId_t pubId, string title, string description, ERemoteStoragePublishedFileVisibility visability, IList <string> tags, string contentFolder, string imagePreviewFile)
    {
        bool success = true;
        //2. An item update begins with a call to:
        UGCUpdateHandle_t handle;

        handle = SteamUGC.StartItemUpdate(SteamUtils.GetAppID(), pubId);

        //3. Using the UGCUpdateHandle_t that is returned from StartItemUpdate, calls can be made to update the Title, Description, Visibility, Tags, Item Content and Item Preview Image through the various SetItem methods.
        success = SteamUGC.SetItemTitle(handle, title);
        Console.Write("Title: " + success);

        success = SteamUGC.SetItemDescription(handle, description);
        Console.Write(" -- Description: " + success);

        success = SteamUGC.SetItemVisibility(handle, visability);
        Console.Write(" -- Visability: " + success);

        success = SteamUGC.SetItemTags(handle, tags);
        Console.Write(" -- Tags: " + success);

        //TODO: We need to fix these paths>>>>>>>
        success = SteamUGC.SetItemContent(handle, contentFolder);
        Console.Write(" -- Content: " + success);

        success = SteamUGC.SetItemPreview(handle, imagePreviewFile);
        Console.WriteLine(" -- Preview: " + success);

        Console.WriteLine("registerFileInfo (UGCUpdateHandle_t): " + handle);

        m_UGCUpdateHandle = handle;

        return(handle);
    }
예제 #9
0
        private Texture2D GetSteamImageAsTexture2D(int p_imageID)
        {
            Texture2D texture = null;
            uint      imageWidth;
            uint      imageHeight;

            if (SteamUtils.GetImageSize(p_imageID, out imageWidth, out imageHeight))
            {
                byte[] imageBytes = new byte[imageWidth * imageHeight * 4];
                if (SteamUtils.GetImageRGBA(p_imageID, imageBytes, imageBytes.Length))
                {
                    // vertically mirror image
                    int    byteWidth         = (int)imageWidth * 4;
                    byte[] imageBytesFlipped = new byte[imageBytes.Length];
                    for (int i = 0, j = imageBytes.Length - byteWidth; i < imageBytes.Length; i += byteWidth, j -= byteWidth)
                    {
                        for (int k = 0; k < byteWidth; k++)
                        {
                            imageBytesFlipped[i + k] = imageBytes[j + k];
                        }
                    }
                    // create Unity Texture2D
                    texture = new Texture2D((int)imageWidth, (int)imageHeight, TextureFormat.RGBA32, false, true);
                    texture.LoadRawTextureData(imageBytesFlipped);
                    texture.Apply();
                }
            }

            return(texture);
        }
예제 #10
0
 private void ProcessLobbySessionStart()
 {
     LobbyUtils.ResetLobbyData();
     Variables.LobbySession = true;
     if (Variables.OverlayWindow == null)
     {
         Variables.OverlayThread = new Thread(() => {
             Variables.OverlayApp    = new Application();
             Variables.OverlayWindow = new MainWindow();
             Task.Delay(500).ContinueWith(task => Variables.OverlayWindow.UpdateConfiguration(Variables.Config, Variables.LobbySession));
             Variables.OverlayWindow.RegisterHotKeyHooks(CopyPlayerStats, CalculateBalancedTeamsRank, CalculateBalancedTeamsTotalGames, CalculateBalancedTeamsWinRatio);
             Variables.OverlayApp.Run(Variables.OverlayWindow);
         });
         Variables.OverlayThread.SetApartmentState(ApartmentState.STA);
         Variables.OverlayThread.Start();
     }
     else
     {
         Variables.OverlayWindow.UpdateConfiguration(Variables.Config, Variables.LobbySession);
     }
     if (Variables.ReplayMode)
     {
         Task.Factory.StartNew(() => new NetHookDumpReaderJob());
     }
     else
     {
         SteamUtils.CheckNethookPaths();
         Task.Delay(5000).ContinueWith(t => SteamUtils.CheckNethookPaths()); //In case NetHook didn't start up fast enough
     }
 }
        IEnumerator _FetchAcatar(CSteamID id, RawImage ui)
        {
            var AvatarInt = SteamFriends.GetLargeFriendAvatar(id);

            while (AvatarInt == -1)
            {
                yield return(null);
            }
            if (AvatarInt > 0)
            {
                SteamUtils.GetImageSize(AvatarInt, out width, out height);

                if (width > 0 && height > 0)
                {
                    byte[] avatarStream = new byte[4 * (int)width * (int)height];
                    SteamUtils.GetImageRGBA(AvatarInt, avatarStream, 4 * (int)width * (int)height);

                    downloadedAvatar = new Texture2D((int)width, (int)height, TextureFormat.RGBA32, false);
                    downloadedAvatar.LoadRawTextureData(avatarStream);
                    downloadedAvatar.Apply();

                    ui.texture = downloadedAvatar;
                }
            }
        }
예제 #12
0
        private static Friend getFriendFromId(CSteamID id)
        {
            Friend friend = new Friend();

            friend.id = id.m_SteamID;

            string name = SteamFriends.GetPlayerNickname(id);

            friend.displayName = (name == null || name == "") ? SteamFriends.GetFriendPersonaName(id) : name;

            int  handle = SteamFriends.GetMediumFriendAvatar(id);
            uint width = 0, height = 0;

            if (handle != 0 && SteamUtils.GetImageSize(handle, out width, out height))
            {
                byte[] pixels = new byte[width * height * 4];
                if (SteamUtils.GetImageRGBA(handle, pixels, (int)(width * height * 4)))
                {
                    friend.avatar = new Texture2D(Game1.graphics.GraphicsDevice, (int)width, (int)height);
                    friend.avatar.SetData(pixels);
                }
            }

            return(friend);
        }
예제 #13
0
        /**
         * Creates a texture from a Steam image and returns the size.
         */
        public static Texture2D GetSteamImageAsTexture2D(int iImage, out Vector2 size)
        {
            Texture2D ret = null;
            uint      ImageWidth;
            uint      ImageHeight;
            bool      bIsValid = SteamUtils.GetImageSize(iImage, out ImageWidth, out ImageHeight);

            if (bIsValid)
            {
                byte[] Image = new byte[ImageWidth * ImageHeight * 4];

                bIsValid = SteamUtils.GetImageRGBA(iImage, Image, (int)(ImageWidth * ImageHeight * 4));
                if (bIsValid)
                {
                    Image = FlipVertical(Image, (int)ImageWidth, (int)ImageHeight);

                    ret = new Texture2D((int)ImageWidth, (int)ImageHeight, TextureFormat.RGBA32, false, true);
                    ret.LoadRawTextureData(Image);
                    ret.Apply();
                }
            }

            size.x = (int)ImageWidth;
            size.y = (int)ImageHeight;

            return(ret);
        }
    void OnEnable()
    {
        if (!SteamManager.Initialized)
        {
            return;
        }

        // Cache the GameID for use in the Callbacks
        m_GameID = new CGameID(SteamUtils.GetAppID());

        m_UserStatsReceived = Callback <UserStatsReceived_t> .Create(OnUserStatsReceived);

        m_UserStatsStored = Callback <UserStatsStored_t> .Create(OnUserStatsStored);

        m_UserAchievementStored = Callback <UserAchievementStored_t> .Create(OnAchievementStored);

        //添加的回调
        m_LobbyCreated = CallResult <LobbyCreated_t> .Create(OnLobbyCreated);

        m_LobbyMatchList = CallResult <LobbyMatchList_t> .Create(OnLobbyMatchedList);

        m_LobbyChatUpdate = Callback <LobbyChatUpdate_t> .Create(OnLobbyChatUpdated);

        m_LobbyEnter = CallResult <LobbyEnter_t> .Create(OnLobbyEntered);

        m_GameLobbyJoinRequested = Callback <GameLobbyJoinRequested_t> .Create(OnGameLobbyJoinRequested);

        //p2p相关回调
        m_P2PSessionRequest = Callback <P2PSessionRequest_t> .Create(OnP2PRequest);

        // These need to be reset to get the stats upon an Assembly reload in the Editor.
        m_bRequestedStats = false;
        m_bStatsValid     = false;
    }
예제 #15
0
        protected override void CheckEntitlement()
        {
            if (!Application.isEditor)
            {
                if (File.Exists("steam_appid.txt"))
                {
                    try
                    {
                        File.Delete("steam_appid.txt");
                    }
                    catch (System.Exception e) { Debug.Log(e.Message); }

                    if (File.Exists("steam_appid.txt"))
                    {
                        Debug.LogError("Found a steam_appid.txt file in the root folder.");
                        EvalEntitlement(false);
                    }
                }
            }

            if (SteamAPI.RestartAppIfNecessary(SteamUtils.GetAppID()))
            {
                EvalEntitlement(false);
            }
            else
            {
                EvalEntitlement(true);
            }
        }
예제 #16
0
        private static IEnumerable <NameValueModel> GetTradeParameters(FullTradeOffer tradeOffer)
        {
            var expirationTime = SteamUtils.ParseSteamUnixDate(tradeOffer.Offer.ExpirationTime)
                                 .ToString(CultureInfo.InvariantCulture);
            var createdTime = SteamUtils.ParseSteamUnixDate(tradeOffer.Offer.TimeCreated)
                              .ToString(CultureInfo.InvariantCulture);
            var updatedTime = SteamUtils.ParseSteamUnixDate(tradeOffer.Offer.TimeUpdated)
                              .ToString(CultureInfo.InvariantCulture);

            return(new[]
            {
                new NameValueModel("TradeOfferId", tradeOffer.Offer.TradeOfferId),
                new NameValueModel("My items count", tradeOffer.MyItems?.Count ?? 0),
                new NameValueModel("Partner items count", tradeOffer.PartnerItems?.Count ?? 0),
                new NameValueModel("TradeOfferId", tradeOffer.Offer.TradeOfferId),
                new NameValueModel(
                    "TradeOfferState",
                    tradeOffer.Offer.TradeOfferState.ToString().Replace("TradeOfferState", string.Empty)),
                new NameValueModel("Message", tradeOffer.Offer.Message),
                new NameValueModel("IsOurOffer", tradeOffer.Offer.IsOurOffer.ToString()),
                new NameValueModel("AccountIdOther", tradeOffer.Offer.AccountIdOther.ToString()),
                new NameValueModel("ExpirationTime", expirationTime),
                new NameValueModel(
                    "ConfirmationMethod",
                    tradeOffer.Offer.EConfirmationMethod.ToString().Replace(
                        "TradeOfferConfirmation",
                        string.Empty)),
                new NameValueModel("TimeCreated", createdTime),
                new NameValueModel("TimeUpdated", updatedTime),
                new NameValueModel("EscrowEndDate", tradeOffer.Offer.EscrowEndDate.ToString()),
                new NameValueModel("FromRealTimeTrade", tradeOffer.Offer.FromRealTimeTrade.ToString())
            });
        }
        private Texture2D GetSmallAvatar(CSteamID user, bool dispatchReadyEvent = true)
        {
            int       FriendAvatar = SteamFriends.GetMediumFriendAvatar(user);
            uint      ImageWidth;
            uint      ImageHeight;
            bool      success       = SteamUtils.GetImageSize(FriendAvatar, out ImageWidth, out ImageHeight);
            Texture2D returnTexture = null;

            if (success && ImageWidth > 0 && ImageHeight > 0)
            {
                byte[] Image = new byte[ImageWidth * ImageHeight * 4];
                returnTexture = new Texture2D((int)ImageWidth, (int)ImageHeight, TextureFormat.RGBA32, false, true);
                success       = SteamUtils.GetImageRGBA(FriendAvatar, Image, (int)(ImageWidth * ImageHeight * 4));
                if (success)
                {
                    returnTexture.LoadRawTextureData(Image);
                    returnTexture.Apply();
                }
                if (dispatchReadyEvent)
                {
                    RaiseGameServiceEvent(new GameServiceEvent(GameServiceEventType.AvatarTextureReady, FlipTexture(returnTexture)));
                }
            }
            else
            {
                Debug.LogError("Couldn't get avatar.");
            }

            if (returnTexture != null)
            {
                returnTexture = FlipTexture(returnTexture);
            }

            return(returnTexture);
        }
예제 #18
0
        public static void updateWorkshopItem(ModData data, string path, Action <bool> callback)
        {
            var items = initPublishedWorkshopItems();

            if (!items.ContainsKey(path))
            {
                throw new Exception("item must be published before it is updated.");
            }

            var handle = SteamUGC.StartItemUpdate(SteamUtils.GetAppID(), items[path]);

            SteamUGC.SetItemTitle(handle, data.title);
            SteamUGC.SetItemDescription(handle, data.description);
            SteamUGC.SetItemTags(handle, data.tags);
            SteamUGC.SetItemPreview(handle, data.previewImage);

            SteamUGC.SetItemContent(handle, path);
            SteamUGC.SetItemVisibility(handle, ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityPublic);
            var call = SteamUGC.SubmitItemUpdate(handle, "");

            var result = CallResult <SubmitItemUpdateResult_t> .Create();

            result.Set(call, (param, error) => {
                callback(!error && param.m_eResult == EResult.k_EResultOK);
            });
        }
예제 #19
0
    static void CreateItemTask(SteamAPICall_t handle, string title, string description, string content, string[] tags, string image, bool update = false)
    {
        while (!IsCompleted(handle))
        {
        }
        UGCUpdateHandle_t  updateHandle = UGCUpdateHandle_t.Invalid;
        CreateItemResult_t callback     = AllocCallback <CreateItemResult_t>(handle, out IntPtr pCallback, CreateItemResult_t.k_iCallback);

        if (callback.m_eResult == EResult.k_EResultOK)
        {
            PublishedFileId_t _PublishedFileID = callback.m_nPublishedFileId;
            updateHandle = SteamUGC.StartItemUpdate(SteamUtils.GetAppID(), _PublishedFileID);
            SteamUGC.SetItemTitle(updateHandle, title);
            SteamUGC.SetItemDescription(updateHandle, description);
            SteamUGC.SetItemContent(updateHandle, content);
            SteamUGC.SetItemTags(updateHandle, tags);
            SteamUGC.SetItemPreview(updateHandle, image);
            SteamUGC.SetItemVisibility(updateHandle, ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityPrivate);
            SteamAPICall_t submitHandle = SteamUGC.SubmitItemUpdate(updateHandle, "Initial commit");
            SubmitItemAsync(submitHandle, updateHandle);
        }
        else
        {
            Console.WriteLine("Couldn't create a new item ! Press any key to continue...");
        }
        ReleaseCallback(pCallback);
    }
        public Texture2D getIcon(int id)
        {
            uint num;
            uint num2;

            if (id == -1 || !SteamUtils.GetImageSize(id, ref num, ref num2))
            {
                return(null);
            }
            Texture2D texture2D = new Texture2D((int)num, (int)num2, 4, false);

            texture2D.name      = "Steam_Community_Icon_Buffer";
            texture2D.hideFlags = 61;
            byte[] array = new byte[num * num2 * 4u];
            if (SteamUtils.GetImageRGBA(id, array, array.Length))
            {
                texture2D.LoadRawTextureData(array);
                texture2D.Apply();
                Texture2D texture2D2 = new Texture2D((int)num, (int)num2, 4, false, true);
                texture2D2.name      = "Steam_Community_Icon";
                texture2D2.hideFlags = 61;
                int num3 = 0;
                while ((long)num3 < (long)((ulong)num2))
                {
                    texture2D2.SetPixels(0, num3, (int)num, 1, texture2D.GetPixels(0, (int)(num2 - 1u - (uint)num3), (int)num, 1));
                    num3++;
                }
                texture2D2.Apply();
                Object.DestroyImmediate(texture2D);
                return(texture2D2);
            }
            Object.DestroyImmediate(texture2D);
            return(null);
        }
예제 #21
0
        public void Initialize()
        {
            var gamePath = CoreContext.LaunchService.GamePath;

            if (gamePath == null)
            {
                MessageBox.Show("Soulstorm steam game not found");
                return;
            }

            if (SteamAPI.RestartAppIfNecessary(new AppId_t(9450)))
            {
                RestartAsSoulstormExe();
                return;
            }

            if (!SteamAPI.Init())
            {
                throw new Exception("Cant init SteamApi");
            }

            var appId = SteamUtils.GetAppID();

            if (appId.m_AppId != 9450)
            {
                throw new Exception("Wrong App Id!");
            }

            IsInitialized = true;
        }
예제 #22
0
    void setAvatar()
    {
        uint width     = 0;
        uint height    = 0;
        int  avatarInt = SteamFriends.GetLargeFriendAvatar(SteamUser.GetSteamID());


        if (avatarInt > 0)
        {
            SteamUtils.GetImageSize(avatarInt, out width, out height);
        }

        if (width > 0 && height > 0)
        {
            byte[] avatarStream = new byte[4 * (int)width * (int)height];
            SteamUtils.GetImageRGBA(avatarInt, avatarStream, 4 * (int)width * (int)height);

            downloadedAvatar = new Texture2D((int)width, (int)height, TextureFormat.RGBA32, false);
            downloadedAvatar.LoadRawTextureData(avatarStream);
            downloadedAvatar.Apply();

            Playerimage.texture = downloadedAvatar;
            Playerimage.rectTransform.localScale = new Vector2(1, -1);
        }
        else
        {
            Debug.Log("Get Steam AvatarINT Error");
            needReLoad = true;
        }
    }
예제 #23
0
파일: Workshop.cs 프로젝트: potsh/RimWorld
        private static void OnItemCreated(CreateItemResult_t result, bool IOFailure)
        {
            if (IOFailure || result.m_eResult != EResult.k_EResultOK)
            {
                uploadingHook = null;
                Dialog_WorkshopOperationInProgress.CloseAll();
                Log.Error("Workshop: OnItemCreated failure. Result: " + result.m_eResult.GetLabel());
                Find.WindowStack.Add(new Dialog_MessageBox("WorkshopSubmissionFailed".Translate(GenText.SplitCamelCase(result.m_eResult.GetLabel()))));
            }
            else
            {
                uploadingHook.PublishedFileId = result.m_nPublishedFileId;
                if (Prefs.LogVerbose)
                {
                    Log.Message("Workshop: Item created. PublishedFileId: " + uploadingHook.PublishedFileId);
                }
                curUpdateHandle = SteamUGC.StartItemUpdate(SteamUtils.GetAppID(), uploadingHook.PublishedFileId);
                SetWorkshopItemDataFrom(curUpdateHandle, uploadingHook, creating: true);
                curStage = WorkshopInteractStage.SubmittingItem;
                if (Prefs.LogVerbose)
                {
                    Log.Message("Workshop: Submitting item.");
                }
                SteamAPICall_t hAPICall = SteamUGC.SubmitItemUpdate(curUpdateHandle, "[Auto-generated text]: Initial upload.");
                submitResult = CallResult <SubmitItemUpdateResult_t> .Create(OnItemSubmitted);

                submitResult.Set(hAPICall);
                createResult = null;
            }
        }
예제 #24
0
    public unsafe bool ApplyWorkshopData(WorkshopItemData data)
    {
        UGCUpdateHandle_t handle = SteamUGC.StartItemUpdate(SteamUtils.GetAppID(), _id);

        if (handle.m_UGCUpdateHandle == 0)
        {
            return(false);
        }
        this.data = data;
        if (data.name != null)
        {
            SteamUGC.SetItemTitle(handle, data.name);
            SteamUGC.SetItemVisibility(handle, (ERemoteStoragePublishedFileVisibility)data.visibility);
        }
        if (data.description != null)
        {
            SteamUGC.SetItemDescription(handle, data.description);
        }
        List <string> tags = data.tags;

        if (tags != null && tags.Count != 0)
        {
            SteamUGC.SetItemTags(handle, data.tags);
        }
        SteamUGC.SetItemPreview(handle, data.previewPath);
        SteamUGC.SetItemContent(handle, data.contentFolder);
        _currentUpdateHandle = handle;
        Steam.StartUpload(this);
        return(true);
    }
예제 #25
0
        private async Task LoadModsFromServerFolder()
        {
            // build a list of mods to be processed
            var modIdList = new List <string>();

            var modDirectory = new DirectoryInfo(Path.Combine(_profile.InstallDirectory, Config.Default.ServerModsRelativePath));

            foreach (var file in modDirectory.GetFiles("*.mod"))
            {
                var modId = Path.GetFileNameWithoutExtension(file.Name);
                if (ModUtils.IsOfficialMod(modId))
                {
                    continue;
                }

                modIdList.Add(modId);
            }
            modIdList = ModUtils.ValidateModList(modIdList);

            var response = await Task.Run(() => SteamUtils.GetSteamModDetails(modIdList));

            var workshopFiles  = WorkshopFiles;
            var modsRootFolder = Path.Combine(_profile.InstallDirectory, Config.Default.ServerModsRelativePath);
            var modDetails     = ModDetailList.GetModDetails(modIdList, modsRootFolder, workshopFiles, response);

            UpdateModDetailsList(modDetails);

            ModDetailsStatusMessage = modDetails.Count > 0 && response?.publishedfiledetails == null?_globalizer.GetResourceString("ModDetails_ModDetailFetchFailed_Label") : string.Empty;

            ModDetailsChanged = true;
        }
예제 #26
0
    private Texture2D GetSteamAvatar()
    {
        int  FriendAvatar = SteamFriends.GetMediumFriendAvatar(id);
        uint ImageWidth;
        uint ImageHeight;
        bool success = SteamUtils.GetImageSize(FriendAvatar, out ImageWidth, out ImageHeight);

        if (success && ImageWidth > 0 && ImageHeight > 0)
        {
            byte[]    Image         = new byte[ImageWidth * ImageHeight * 4];
            Texture2D returnTexture = new Texture2D((int)ImageWidth, (int)ImageHeight, TextureFormat.RGBA32, false, true);
            success = SteamUtils.GetImageRGBA(FriendAvatar, Image, (int)(ImageWidth * ImageHeight * 4));
            if (success)
            {
                returnTexture.LoadRawTextureData(Image);
                returnTexture.Apply();
            }
            return(returnTexture);
        }
        else
        {
            Debug.LogError("[Leaderboard] Couldn't get a steam avatar.");
            return(new Texture2D(0, 0));
        }
    }
예제 #27
0
        private async Task <User> FetchUserInfoAsync(string userId)
        {
            var url     = SteamUtils.GetUserInfoUrl(_secrets.Value.SteamApiKey, userId);
            var jsonObj = await _remoteApiService.GetJsonObjectAsync(url, SteamUtils.ApiName);

            var token = jsonObj["response"]["players"].First;
            var user  = token.ToObject <User>();

            if (user.CommunityVisibilityState == 3)
            {
                try
                {
                    user.Friends = await FetchFriendsAsync(userId);
                }
                catch (ApiUnavailableException)
                {
                    var key = SiteUtils.CacheKeys.UserInfo;

                    _cache.Remove(key);

                    throw;
                }
            }

            user.LatestUpdate = DateTime.Now;

            return(user);
        }
예제 #28
0
        IEnumerator WaitForSteamworksInitialization()
        {
            float time = Time.realtimeSinceStartup;

            while (!SteamManager.Initialized)
            {
                time += Time.deltaTime;
                if (time > 10f)
                {
                    Debug.LogError("Steamworks initialization timed out!"); // This might happen if the user doesn't have Steam installed.
                    EvalEntitlement(false);
                    break;
                }
                yield return(null);
            }

            _gameID = new CGameID(SteamUtils.GetAppID());

            // Setup callbacks for server communication events.
            _userStatsReceivedCallback = Callback <UserStatsReceived_t> .Create(OnUserStatsReceived);

            _achievementStoredCallback = Callback <UserAchievementStored_t> .Create(OnAchievementStored);

            base.Initialize();  // Finish initializing only after Steamworks is ready.
        }
예제 #29
0
    void OnEnable()
    {
        if (!SteamManager.Initialized)
        {
            return;
        }

        // Cache the GameID for use in the Callbacks
        m_GameID = new CGameID(SteamUtils.GetAppID());

        //游戏会话开始后,从Steam后端获取用户的数据:SteamUserStats()->RequestCurrentStats()
        //得到回调:UserStatsReceived_t
        m_UserStatsReceived = Callback <UserStatsReceived_t> .Create(OnUserStatsReceived);

        //上传数据后:SteamUserStats()->StoreStats()
        //得到回调:UserStatsStored_t
        m_UserStatsStored = Callback <UserStatsStored_t> .Create(OnUserStatsStored);

        //解锁了一项或多项成就时,针对各项解锁的成就调用 SteamUserStats->SetAchievement();
        //回调UserAchievementStored_t
        m_UserAchievementStored = Callback <UserAchievementStored_t> .Create(OnAchievementStored);

        // m_LeaderboardFindResult = CallResult<LeaderboardFindResult_t>.Create(OnLeaderboardFindResult);
        // m_LeaderboardScoreUploaded = CallResult<LeaderboardScoreUploaded_t>.Create(OnLeaerboardScoreUploaded);
        //m_LeaderboardScoresDownloaded = CallResult<LeaderboardScoresDownloaded_t>.Create(OnLeaderboardScoresDownloaded);
        // These need to be reset to get the stats upon an Assembly reload in the Editor.
        m_bRequestedStats = false;
        m_bStatsValid     = false;
        // SteamAPICall_t handle = SteamUserStats.FindOrCreateLeaderboard("PlayerValue", ELeaderboardSortMethod.k_ELeaderboardSortMethodDescending, ELeaderboardDisplayType.k_ELeaderboardDisplayTypeNumeric);
        // m_LeaderboardFindResult.Set(handle);
    }
예제 #30
0
        /// <summary>
        /// Inserts a new ban into the database.
        /// </summary>
        /// <param name="auth">The auth ID of the player.</param>
        /// <param name="ip">The IP address of the player.</param>
        /// <param name="name">The escaped name of the player.</param>
        /// <param name="startTime">The Unix timestamp of the time the ban was initiated.</param>
        /// <param name="duration">The duration of the ban in seconds.</param>
        /// <param name="reason">The escaped reason for the ban.</param>
        /// <param name="adminAuth">The auth ID of the admin invoking the ban.</param>
        /// <param name="adminIp">The IP address of the admin invoking the ban.</param>
        private void InsertBan(string auth, string ip, string name, long startTime, uint duration, string reason, string adminAuth, string adminIp)
        {
            var prefix = this.databasePrefix.AsString;
            var type   = string.IsNullOrEmpty(auth) ? 1 : 0;
            var data   = new Dictionary <string, object>
            {
                { "auth", auth },
                { "ip", ip },
                { "name", name },
                { "startTime", startTime },
                { "duration", duration },
                { "reason", reason },
                { "adminAuth", adminAuth },
                { "adminIp", adminIp },
            };
            var ends = startTime + duration;

            this.database.TFastQuery($"INSERT INTO {prefix}_bans (type, authid, ip, name, created, ends, length, reason, aid, adminIp, sid, country) VALUES ({type}, '{auth}', '{ip}', '{name}', {startTime}, {ends}, {duration}, '{reason}', IFNULL((SELECT aid FROM {prefix}_admins WHERE authid = '{adminAuth}' OR authid REGEXP '^STEAM_[0-9]:{adminAuth.Substring(8)}$'), '0'), '{adminIp}', {this.serverId.AsInt}, ' ')", data).QueryCompleted += this.OnInsertBanQueryCompleted;

            if (ends > GetTime())
            {
                SteamUtils.NormalizeSteamId(auth, out var playerId);
                this.cache.SetPlayerStatus(playerId, true);
            }
        }