diff options
| author | Matthew Collins <[email protected]> | 2019-03-16 10:57:21 +0000 |
|---|---|---|
| committer | Matthew Collins <[email protected]> | 2019-03-16 10:57:21 +0000 |
| commit | 6bcb5567baa03e8e4b00569a3d3634f887482798 (patch) | |
| tree | 9dc47830f5b0bdf6f0c92861086b8ec81703c8a5 | |
| parent | Add basic leaderboard handling (Work on #4) (diff) | |
| download | steamworks-rs-6bcb5567baa03e8e4b00569a3d3634f887482798.tar.xz steamworks-rs-6bcb5567baa03e8e4b00569a3d3634f887482798.zip | |
Generate the bindings from the provided json file instead of bindgen (Fixes #3)
Allow us to remove the hack for accessing packed structs
| -rw-r--r-- | Cargo.toml | 12 | ||||
| -rw-r--r-- | src/app.rs | 10 | ||||
| -rw-r--r-- | src/callback.rs | 8 | ||||
| -rw-r--r-- | src/error.rs | 218 | ||||
| -rw-r--r-- | src/friends.rs | 50 | ||||
| -rw-r--r-- | src/lib.rs | 2 | ||||
| -rw-r--r-- | src/matchmaking.rs | 36 | ||||
| -rw-r--r-- | src/networking.rs | 22 | ||||
| -rw-r--r-- | src/server.rs | 27 | ||||
| -rw-r--r-- | src/user.rs | 56 | ||||
| -rw-r--r-- | src/user_stats.rs | 56 | ||||
| -rw-r--r-- | src/utils.rs | 10 | ||||
| -rw-r--r-- | steamworks-sys/Cargo.toml | 12 | ||||
| -rwxr-xr-x | steamworks-sys/build.rs | 291 | ||||
| -rw-r--r-- | steamworks-sys/src/lib.rs | 128 |
15 files changed, 457 insertions, 481 deletions
@@ -9,6 +9,9 @@ documentation = "https://docs.rs/steamworks" keywords = ["steam", "gamedev"] categories = ["games"] +[package.metadata.docs.rs] +features = [ "docs-only" ] + [features] default = [] # Skip looking for the steamworks sdk for docs builds @@ -21,9 +24,6 @@ members = [ [dependencies] steamworks-sys = {path = "./steamworks-sys", version = "0.3.0"} -failure = "0.1.1" -bitflags = "1.0.1" -libc = "0.2.36" - -[package.metadata.docs.rs] -features = [ "docs-only" ]
\ No newline at end of file +failure = "0.1.5" +bitflags = "1.0.4" +libc = "0.2.50" @@ -18,7 +18,7 @@ impl <Manager> Apps<Manager> { /// This does not mean the user owns the game. pub fn is_app_installed(&self, app_id: AppId) -> bool { unsafe { - sys::SteamAPI_ISteamApps_BIsAppInstalled(self.apps, app_id.0) != 0 + sys::SteamAPI_ISteamApps_BIsAppInstalled(self.apps, sys::AppId_t(app_id.0)) != 0 } } @@ -26,7 +26,7 @@ impl <Manager> Apps<Manager> { /// installed. pub fn is_dlc_installed(&self, app_id: AppId) -> bool { unsafe { - sys::SteamAPI_ISteamApps_BIsDlcInstalled(self.apps, app_id.0) != 0 + sys::SteamAPI_ISteamApps_BIsDlcInstalled(self.apps, sys::AppId_t(app_id.0)) != 0 } } @@ -37,7 +37,7 @@ impl <Manager> Apps<Manager> { /// yours (e.g. demo). pub fn is_subscribed_app(&self, app_id: AppId) -> bool { unsafe { - sys::SteamAPI_ISteamApps_BIsSubscribedApp(self.apps, app_id.0) != 0 + sys::SteamAPI_ISteamApps_BIsSubscribedApp(self.apps, sys::AppId_t(app_id.0)) != 0 } } @@ -92,7 +92,7 @@ impl <Manager> Apps<Manager> { pub fn app_install_dir(&self, app_id: AppId) -> String { unsafe { let buffer = vec![0; 2048]; - sys::SteamAPI_ISteamApps_GetAppInstallDir(self.apps, app_id.0, buffer.as_ptr(), buffer.len() as u32); + sys::SteamAPI_ISteamApps_GetAppInstallDir(self.apps, sys::AppId_t(app_id.0), buffer.as_ptr(), buffer.len() as u32); let path = CStr::from_ptr(buffer.as_ptr()); path.to_string_lossy().into_owned() } @@ -103,7 +103,7 @@ impl <Manager> Apps<Manager> { /// Differs from the current user if the app is borrowed. pub fn app_owner(&self) -> SteamId { unsafe { - SteamId(sys::SteamAPI_ISteamApps_GetAppOwner(self.apps)) + SteamId(sys::SteamAPI_ISteamApps_GetAppOwner(self.apps).0) } } diff --git a/src/callback.rs b/src/callback.rs index d8e186d..aec4b73 100644 --- a/src/callback.rs +++ b/src/callback.rs @@ -64,7 +64,7 @@ pub(crate) unsafe fn register_callback<C, F, Manager>(inner: &Arc<Inner<Manager> func(param); } - unsafe extern "C" fn run_extra<C, F>(cb: *mut c_void, userdata: *mut c_void, param: *mut c_void, _: u8, _: sys::SteamAPICall) + unsafe extern "C" fn run_extra<C, F>(cb: *mut c_void, userdata: *mut c_void, param: *mut c_void, _: u8, _: sys::SteamAPICall_t) where C: Callback, F: FnMut(C) + Send + 'static { @@ -103,12 +103,12 @@ pub(crate) unsafe fn register_callback<C, F, Manager>(inner: &Arc<Inner<Manager> } } -pub(crate) unsafe fn register_call_result<C, F, Manager>(inner: &Arc<Inner<Manager>>, api_call: sys::SteamAPICall, callback_id: i32, f: F) +pub(crate) unsafe fn register_call_result<C, F, Manager>(inner: &Arc<Inner<Manager>>, api_call: sys::SteamAPICall_t, callback_id: i32, f: F) where F: for <'a> FnMut(&'a C, bool) + 'static + Send { struct CallData<F, Manager> { func: F, - api_call: sys::SteamAPICall, + api_call: sys::SteamAPICall_t, inner: Weak<Inner<Manager>>, } @@ -135,7 +135,7 @@ pub(crate) unsafe fn register_call_result<C, F, Manager>(inner: &Arc<Inner<Manag sys::delete_rust_callback(cb); } - unsafe extern "C" fn run_extra<C, F, Manager>(cb: *mut c_void, userdata: *mut c_void, param: *mut c_void, io_error: u8, api_call: sys::SteamAPICall) + unsafe extern "C" fn run_extra<C, F, Manager>(cb: *mut c_void, userdata: *mut c_void, param: *mut c_void, io_error: u8, api_call: sys::SteamAPICall_t) where F: for<'a> FnMut(&'a C, bool) + Send + 'static { let data: &mut CallData<F, Manager> = &mut *(userdata as *mut CallData<F, Manager>); diff --git a/src/error.rs b/src/error.rs index 6f3b0a9..dd5e57f 100644 --- a/src/error.rs +++ b/src/error.rs @@ -382,115 +382,115 @@ pub enum SteamError { impl From<sys::EResult> for SteamError { fn from(r: sys::EResult) -> Self { match r { - sys::EResult_k_EResultOK => panic!("EResult_k_EResultOK isn't an error"), - sys::EResult_k_EResultFail => SteamError::Generic, - sys::EResult_k_EResultNoConnection => SteamError::NoConnection, - sys::EResult_k_EResultInvalidPassword => SteamError::InvalidPassword, - sys::EResult_k_EResultLoggedInElsewhere => SteamError::LoggedInElsewhere, - sys::EResult_k_EResultInvalidProtocolVer => SteamError::InvalidProtocolVersion, - sys::EResult_k_EResultInvalidParam => SteamError::InvalidParameter, - sys::EResult_k_EResultFileNotFound => SteamError::FileNotFound, - sys::EResult_k_EResultBusy => SteamError::Busy, - sys::EResult_k_EResultInvalidState => SteamError::InvalidState, - sys::EResult_k_EResultInvalidName => SteamError::InvalidName, - sys::EResult_k_EResultInvalidEmail => SteamError::InvalidEmail, - sys::EResult_k_EResultDuplicateName => SteamError::DuplicateName, - sys::EResult_k_EResultAccessDenied => SteamError::AccessDenied, - sys::EResult_k_EResultTimeout => SteamError::Timeout, - sys::EResult_k_EResultBanned => SteamError::Banned, - sys::EResult_k_EResultAccountNotFound => SteamError::AccountNotFound, - sys::EResult_k_EResultInvalidSteamID => SteamError::InvalidSteamID, - sys::EResult_k_EResultServiceUnavailable => SteamError::ServiceUnavailable, - sys::EResult_k_EResultNotLoggedOn => SteamError::NotLoggedOn, - sys::EResult_k_EResultPending => SteamError::Pending, - sys::EResult_k_EResultEncryptionFailure => SteamError::EncryptionFailure, - sys::EResult_k_EResultInsufficientPrivilege => SteamError::InsufficientPrivilege, - sys::EResult_k_EResultLimitExceeded => SteamError::LimitExceeded, - sys::EResult_k_EResultRevoked => SteamError::Revoked, - sys::EResult_k_EResultExpired => SteamError::Expired, - sys::EResult_k_EResultAlreadyRedeemed => SteamError::AlreadyRedeemed, - sys::EResult_k_EResultDuplicateRequest => SteamError::DuplicateRequest, - sys::EResult_k_EResultAlreadyOwned => SteamError::AlreadyOwned, - sys::EResult_k_EResultIPNotFound => SteamError::IPNotFound, - sys::EResult_k_EResultPersistFailed => SteamError::PersistFailed, - sys::EResult_k_EResultLockingFailed => SteamError::LockingFailed, - sys::EResult_k_EResultLogonSessionReplaced => SteamError::LogonSessionReplaced, - sys::EResult_k_EResultConnectFailed => SteamError::ConnectFailed, - sys::EResult_k_EResultHandshakeFailed => SteamError::HandshakeFailed, - sys::EResult_k_EResultIOFailure => SteamError::IOFailure, - sys::EResult_k_EResultRemoteDisconnect => SteamError::RemoteDisconnect, - sys::EResult_k_EResultShoppingCartNotFound => SteamError::ShoppingCartNotFound, - sys::EResult_k_EResultBlocked => SteamError::Blocked, - sys::EResult_k_EResultIgnored => SteamError::Ignored, - sys::EResult_k_EResultNoMatch => SteamError::NoMatch, - sys::EResult_k_EResultAccountDisabled => SteamError::AccountDisabled, - sys::EResult_k_EResultServiceReadOnly => SteamError::ServiceReadOnly, - sys::EResult_k_EResultAccountNotFeatured => SteamError::AccountNotFeatured, - sys::EResult_k_EResultAdministratorOK => SteamError::AdministratorOK, - sys::EResult_k_EResultContentVersion => SteamError::ContentVersion, - sys::EResult_k_EResultTryAnotherCM => SteamError::TryAnotherCM, - sys::EResult_k_EResultPasswordRequiredToKickSession => SteamError::PasswordRequiredToKickSession, - sys::EResult_k_EResultAlreadyLoggedInElsewhere => SteamError::AlreadyLoggedInElsewhere, - sys::EResult_k_EResultSuspended => SteamError::Suspended, - sys::EResult_k_EResultCancelled => SteamError::Cancelled, - sys::EResult_k_EResultDataCorruption => SteamError::DataCorruption, - sys::EResult_k_EResultDiskFull => SteamError::DiskFull, - sys::EResult_k_EResultRemoteCallFailed => SteamError::RemoteCallFailed, - sys::EResult_k_EResultPasswordUnset => SteamError::PasswordUnset, - sys::EResult_k_EResultExternalAccountUnlinked => SteamError::ExternalAccountUnlinked, - sys::EResult_k_EResultPSNTicketInvalid => SteamError::PSNTicketInvalid, - sys::EResult_k_EResultExternalAccountAlreadyLinked => SteamError::ExternalAccountAlreadyLinked, - sys::EResult_k_EResultRemoteFileConflict => SteamError::RemoteFileConflict, - sys::EResult_k_EResultIllegalPassword => SteamError::IllegalPassword, - sys::EResult_k_EResultSameAsPreviousValue => SteamError::SameAsPreviousValue, - sys::EResult_k_EResultAccountLogonDenied => SteamError::AccountLogonDenied, - sys::EResult_k_EResultCannotUseOldPassword => SteamError::CannotUseOldPassword, - sys::EResult_k_EResultInvalidLoginAuthCode => SteamError::InvalidLoginAuthCode, - sys::EResult_k_EResultAccountLogonDeniedNoMail => SteamError::AccountLogonDeniedNoMail, - sys::EResult_k_EResultHardwareNotCapableOfIPT => SteamError::HardwareNotCapableOfIPT, - sys::EResult_k_EResultIPTInitError => SteamError::IPTInitError, - sys::EResult_k_EResultParentalControlRestricted => SteamError::ParentalControlRestricted, - sys::EResult_k_EResultFacebookQueryError => SteamError::FacebookQueryError, - sys::EResult_k_EResultExpiredLoginAuthCode => SteamError::ExpiredLoginAuthCode, - sys::EResult_k_EResultIPLoginRestrictionFailed => SteamError::IPLoginRestrictionFailed, - sys::EResult_k_EResultAccountLockedDown => SteamError::AccountLockedDown, - sys::EResult_k_EResultAccountLogonDeniedVerifiedEmailRequired => SteamError::AccountLogonDeniedVerifiedEmailRequired, - sys::EResult_k_EResultNoMatchingURL => SteamError::NoMatchingURL, - sys::EResult_k_EResultBadResponse => SteamError::BadResponse, - sys::EResult_k_EResultRequirePasswordReEntry => SteamError::RequirePasswordReEntry, - sys::EResult_k_EResultValueOutOfRange => SteamError::ValueOutOfRange, - sys::EResult_k_EResultUnexpectedError => SteamError::UnexpectedError, - sys::EResult_k_EResultDisabled => SteamError::Disabled, - sys::EResult_k_EResultInvalidCEGSubmission => SteamError::InvalidCEGSubmission, - sys::EResult_k_EResultRestrictedDevice => SteamError::RestrictedDevice, - sys::EResult_k_EResultRegionLocked => SteamError::RegionLocked, - sys::EResult_k_EResultRateLimitExceeded => SteamError::RateLimitExceeded, - sys::EResult_k_EResultAccountLoginDeniedNeedTwoFactor => SteamError::AccountLoginDeniedNeedTwoFactor, - sys::EResult_k_EResultItemDeleted => SteamError::ItemDeleted, - sys::EResult_k_EResultAccountLoginDeniedThrottle => SteamError::AccountLoginDeniedThrottle, - sys::EResult_k_EResultTwoFactorCodeMismatch => SteamError::TwoFactorCodeMismatch, - sys::EResult_k_EResultTwoFactorActivationCodeMismatch => SteamError::TwoFactorActivationCodeMismatch, - sys::EResult_k_EResultAccountAssociatedToMultiplePartners => SteamError::AccountAssociatedToMultiplePartners, - sys::EResult_k_EResultNotModified => SteamError::NotModified, - sys::EResult_k_EResultNoMobileDevice => SteamError::NoMobileDevice, - sys::EResult_k_EResultTimeNotSynced => SteamError::TimeNotSynced, - sys::EResult_k_EResultSmsCodeFailed => SteamError::SmsCodeFailed, - sys::EResult_k_EResultAccountLimitExceeded => SteamError::AccountLimitExceeded, - sys::EResult_k_EResultAccountActivityLimitExceeded => SteamError::AccountActivityLimitExceeded, - sys::EResult_k_EResultPhoneActivityLimitExceeded => SteamError::PhoneActivityLimitExceeded, - sys::EResult_k_EResultRefundToWallet => SteamError::RefundToWallet, - sys::EResult_k_EResultEmailSendFailure => SteamError::EmailSendFailure, - sys::EResult_k_EResultNotSettled => SteamError::NotSettled, - sys::EResult_k_EResultNeedCaptcha => SteamError::NeedCaptcha, - sys::EResult_k_EResultGSLTDenied => SteamError::GSLTDenied, - sys::EResult_k_EResultGSOwnerDenied => SteamError::GSOwnerDenied, - sys::EResult_k_EResultInvalidItemType => SteamError::InvalidItemType, - sys::EResult_k_EResultIPBanned => SteamError::IPBanned, - sys::EResult_k_EResultGSLTExpired => SteamError::GSLTExpired, - sys::EResult_k_EResultInsufficientFunds => SteamError::InsufficientFunds, - sys::EResult_k_EResultTooManyPending => SteamError::TooManyPending, - sys::EResult_k_EResultNoSiteLicensesFound => SteamError::NoSiteLicensesFound, - sys::EResult_k_EResultWGNetworkSendExceeded => SteamError::WGNetworkSendExceeded, + sys::EResult::EResultOK => panic!("EResult::EResultOK isn't an error"), + sys::EResult::EResultFail => SteamError::Generic, + sys::EResult::EResultNoConnection => SteamError::NoConnection, + sys::EResult::EResultInvalidPassword => SteamError::InvalidPassword, + sys::EResult::EResultLoggedInElsewhere => SteamError::LoggedInElsewhere, + sys::EResult::EResultInvalidProtocolVer => SteamError::InvalidProtocolVersion, + sys::EResult::EResultInvalidParam => SteamError::InvalidParameter, + sys::EResult::EResultFileNotFound => SteamError::FileNotFound, + sys::EResult::EResultBusy => SteamError::Busy, + sys::EResult::EResultInvalidState => SteamError::InvalidState, + sys::EResult::EResultInvalidName => SteamError::InvalidName, + sys::EResult::EResultInvalidEmail => SteamError::InvalidEmail, + sys::EResult::EResultDuplicateName => SteamError::DuplicateName, + sys::EResult::EResultAccessDenied => SteamError::AccessDenied, + sys::EResult::EResultTimeout => SteamError::Timeout, + sys::EResult::EResultBanned => SteamError::Banned, + sys::EResult::EResultAccountNotFound => SteamError::AccountNotFound, + sys::EResult::EResultInvalidSteamID => SteamError::InvalidSteamID, + sys::EResult::EResultServiceUnavailable => SteamError::ServiceUnavailable, + sys::EResult::EResultNotLoggedOn => SteamError::NotLoggedOn, + sys::EResult::EResultPending => SteamError::Pending, + sys::EResult::EResultEncryptionFailure => SteamError::EncryptionFailure, + sys::EResult::EResultInsufficientPrivilege => SteamError::InsufficientPrivilege, + sys::EResult::EResultLimitExceeded => SteamError::LimitExceeded, + sys::EResult::EResultRevoked => SteamError::Revoked, + sys::EResult::EResultExpired => SteamError::Expired, + sys::EResult::EResultAlreadyRedeemed => SteamError::AlreadyRedeemed, + sys::EResult::EResultDuplicateRequest => SteamError::DuplicateRequest, + sys::EResult::EResultAlreadyOwned => SteamError::AlreadyOwned, + sys::EResult::EResultIPNotFound => SteamError::IPNotFound, + sys::EResult::EResultPersistFailed => SteamError::PersistFailed, + sys::EResult::EResultLockingFailed => SteamError::LockingFailed, + sys::EResult::EResultLogonSessionReplaced => SteamError::LogonSessionReplaced, + sys::EResult::EResultConnectFailed => SteamError::ConnectFailed, + sys::EResult::EResultHandshakeFailed => SteamError::HandshakeFailed, + sys::EResult::EResultIOFailure => SteamError::IOFailure, + sys::EResult::EResultRemoteDisconnect => SteamError::RemoteDisconnect, + sys::EResult::EResultShoppingCartNotFound => SteamError::ShoppingCartNotFound, + sys::EResult::EResultBlocked => SteamError::Blocked, + sys::EResult::EResultIgnored => SteamError::Ignored, + sys::EResult::EResultNoMatch => SteamError::NoMatch, + sys::EResult::EResultAccountDisabled => SteamError::AccountDisabled, + sys::EResult::EResultServiceReadOnly => SteamError::ServiceReadOnly, + sys::EResult::EResultAccountNotFeatured => SteamError::AccountNotFeatured, + sys::EResult::EResultAdministratorOK => SteamError::AdministratorOK, + sys::EResult::EResultContentVersion => SteamError::ContentVersion, + sys::EResult::EResultTryAnotherCM => SteamError::TryAnotherCM, + sys::EResult::EResultPasswordRequiredToKickSession => SteamError::PasswordRequiredToKickSession, + sys::EResult::EResultAlreadyLoggedInElsewhere => SteamError::AlreadyLoggedInElsewhere, + sys::EResult::EResultSuspended => SteamError::Suspended, + sys::EResult::EResultCancelled => SteamError::Cancelled, + sys::EResult::EResultDataCorruption => SteamError::DataCorruption, + sys::EResult::EResultDiskFull => SteamError::DiskFull, + sys::EResult::EResultRemoteCallFailed => SteamError::RemoteCallFailed, + sys::EResult::EResultPasswordUnset => SteamError::PasswordUnset, + sys::EResult::EResultExternalAccountUnlinked => SteamError::ExternalAccountUnlinked, + sys::EResult::EResultPSNTicketInvalid => SteamError::PSNTicketInvalid, + sys::EResult::EResultExternalAccountAlreadyLinked => SteamError::ExternalAccountAlreadyLinked, + sys::EResult::EResultRemoteFileConflict => SteamError::RemoteFileConflict, + sys::EResult::EResultIllegalPassword => SteamError::IllegalPassword, + sys::EResult::EResultSameAsPreviousValue => SteamError::SameAsPreviousValue, + sys::EResult::EResultAccountLogonDenied => SteamError::AccountLogonDenied, + sys::EResult::EResultCannotUseOldPassword => SteamError::CannotUseOldPassword, + sys::EResult::EResultInvalidLoginAuthCode => SteamError::InvalidLoginAuthCode, + sys::EResult::EResultAccountLogonDeniedNoMail => SteamError::AccountLogonDeniedNoMail, + sys::EResult::EResultHardwareNotCapableOfIPT => SteamError::HardwareNotCapableOfIPT, + sys::EResult::EResultIPTInitError => SteamError::IPTInitError, + sys::EResult::EResultParentalControlRestricted => SteamError::ParentalControlRestricted, + sys::EResult::EResultFacebookQueryError => SteamError::FacebookQueryError, + sys::EResult::EResultExpiredLoginAuthCode => SteamError::ExpiredLoginAuthCode, + sys::EResult::EResultIPLoginRestrictionFailed => SteamError::IPLoginRestrictionFailed, + sys::EResult::EResultAccountLockedDown => SteamError::AccountLockedDown, + sys::EResult::EResultAccountLogonDeniedVerifiedEmailRequired => SteamError::AccountLogonDeniedVerifiedEmailRequired, + sys::EResult::EResultNoMatchingURL => SteamError::NoMatchingURL, + sys::EResult::EResultBadResponse => SteamError::BadResponse, + sys::EResult::EResultRequirePasswordReEntry => SteamError::RequirePasswordReEntry, + sys::EResult::EResultValueOutOfRange => SteamError::ValueOutOfRange, + sys::EResult::EResultUnexpectedError => SteamError::UnexpectedError, + sys::EResult::EResultDisabled => SteamError::Disabled, + sys::EResult::EResultInvalidCEGSubmission => SteamError::InvalidCEGSubmission, + sys::EResult::EResultRestrictedDevice => SteamError::RestrictedDevice, + sys::EResult::EResultRegionLocked => SteamError::RegionLocked, + sys::EResult::EResultRateLimitExceeded => SteamError::RateLimitExceeded, + sys::EResult::EResultAccountLoginDeniedNeedTwoFactor => SteamError::AccountLoginDeniedNeedTwoFactor, + sys::EResult::EResultItemDeleted => SteamError::ItemDeleted, + sys::EResult::EResultAccountLoginDeniedThrottle => SteamError::AccountLoginDeniedThrottle, + sys::EResult::EResultTwoFactorCodeMismatch => SteamError::TwoFactorCodeMismatch, + sys::EResult::EResultTwoFactorActivationCodeMismatch => SteamError::TwoFactorActivationCodeMismatch, + sys::EResult::EResultAccountAssociatedToMultiplePartners => SteamError::AccountAssociatedToMultiplePartners, + sys::EResult::EResultNotModified => SteamError::NotModified, + sys::EResult::EResultNoMobileDevice => SteamError::NoMobileDevice, + sys::EResult::EResultTimeNotSynced => SteamError::TimeNotSynced, + sys::EResult::EResultSmsCodeFailed => SteamError::SmsCodeFailed, + sys::EResult::EResultAccountLimitExceeded => SteamError::AccountLimitExceeded, + sys::EResult::EResultAccountActivityLimitExceeded => SteamError::AccountActivityLimitExceeded, + sys::EResult::EResultPhoneActivityLimitExceeded => SteamError::PhoneActivityLimitExceeded, + sys::EResult::EResultRefundToWallet => SteamError::RefundToWallet, + sys::EResult::EResultEmailSendFailure => SteamError::EmailSendFailure, + sys::EResult::EResultNotSettled => SteamError::NotSettled, + sys::EResult::EResultNeedCaptcha => SteamError::NeedCaptcha, + sys::EResult::EResultGSLTDenied => SteamError::GSLTDenied, + sys::EResult::EResultGSOwnerDenied => SteamError::GSOwnerDenied, + sys::EResult::EResultInvalidItemType => SteamError::InvalidItemType, + sys::EResult::EResultIPBanned => SteamError::IPBanned, + sys::EResult::EResultGSLTExpired => SteamError::GSLTExpired, + sys::EResult::EResultInsufficientFunds => SteamError::InsufficientFunds, + sys::EResult::EResultTooManyPending => SteamError::TooManyPending, + sys::EResult::EResultNoSiteLicensesFound => SteamError::NoSiteLicensesFound, + sys::EResult::EResultWGNetworkSendExceeded => SteamError::WGNetworkSendExceeded, _ => unreachable!(), } } diff --git a/src/friends.rs b/src/friends.rs index 2604fa6..b5dcdaa 100644 --- a/src/friends.rs +++ b/src/friends.rs @@ -70,7 +70,7 @@ impl <Manager> Friends<Manager> { } let mut friends = Vec::with_capacity(count as usize); for idx in 0 .. count { - let friend = SteamId(sys::SteamAPI_ISteamFriends_GetFriendByIndex(self.friends, idx, flags.bits() as _)); + let friend = SteamId(sys::SteamAPI_ISteamFriends_GetFriendByIndex(self.friends, idx, flags.bits() as _).0); friends.push(Friend { id: friend, friends: self.friends, @@ -92,7 +92,7 @@ impl <Manager> Friends<Manager> { pub fn request_user_information(&self, user: SteamId, name_only: bool) { unsafe { - sys::SteamAPI_ISteamFriends_RequestUserInformation(self.friends, user.0, name_only as u8); + sys::SteamAPI_ISteamFriends_RequestUserInformation(self.friends, sys::CSteamID(user.0), name_only as u8); } } @@ -107,7 +107,7 @@ impl <Manager> Friends<Manager> { /// Opens up an invite dialog for the given lobby pub fn activate_invite_dialog(&self, lobby: LobbyId) { unsafe { - sys::SteamAPI_ISteamFriends_ActivateGameOverlayInviteDialog(self.friends, lobby.0); + sys::SteamAPI_ISteamFriends_ActivateGameOverlayInviteDialog(self.friends, sys::CSteamID(lobby.0)); } } } @@ -141,8 +141,8 @@ unsafe impl Callback for PersonaStateChange { unsafe fn from_raw(raw: *mut libc::c_void) -> Self { let val = &mut *(raw as *mut sys::PersonaStateChange_t); PersonaStateChange { - steam_id: SteamId(val.get_m_ulSteamID()), - flags: PersonaChange::from_bits_truncate(val.get_m_nChangeFlags() as i32), + steam_id: SteamId(val.m_ulSteamID), + flags: PersonaChange::from_bits_truncate(val.m_nChangeFlags as i32), } } } @@ -160,8 +160,8 @@ unsafe impl Callback for GameLobbyJoinRequested { unsafe fn from_raw(raw: *mut libc::c_void) -> Self { let val = &mut *(raw as *mut sys::GameLobbyJoinRequested_t); GameLobbyJoinRequested { - lobby_steam_id: LobbyId(val.get_m_steamIDLobby()), - friend_steam_id: SteamId(val.get_m_steamIDFriend()), + lobby_steam_id: LobbyId(val.m_steamIDLobby.0), + friend_steam_id: SteamId(val.m_steamIDFriend.0), } } } @@ -185,7 +185,7 @@ impl <Manager> Friend<Manager> { pub fn name(&self) -> String { unsafe { - let name = sys::SteamAPI_ISteamFriends_GetFriendPersonaName(self.friends, self.id.0); + let name = sys::SteamAPI_ISteamFriends_GetFriendPersonaName(self.friends, sys::CSteamID(self.id.0)); let name = CStr::from_ptr(name); name.to_string_lossy().into_owned() } @@ -193,15 +193,15 @@ impl <Manager> Friend<Manager> { pub fn state(&self) -> FriendState { unsafe { - let state = sys::SteamAPI_ISteamFriends_GetFriendPersonaState(self.friends, self.id.0); + let state = sys::SteamAPI_ISteamFriends_GetFriendPersonaState(self.friends, sys::CSteamID(self.id.0)); match state { - sys::EPersonaState_k_EPersonaStateOffline => FriendState::Offline, - sys::EPersonaState_k_EPersonaStateOnline => FriendState::Online, - sys::EPersonaState_k_EPersonaStateBusy => FriendState::Busy, - sys::EPersonaState_k_EPersonaStateAway => FriendState::Away, - sys::EPersonaState_k_EPersonaStateSnooze => FriendState::Snooze, - sys::EPersonaState_k_EPersonaStateLookingToPlay => FriendState::LookingToPlay, - sys::EPersonaState_k_EPersonaStateLookingToTrade => FriendState::LookingToTrade, + sys::EPersonaState::EPersonaStateOffline => FriendState::Offline, + sys::EPersonaState::EPersonaStateOnline => FriendState::Online, + sys::EPersonaState::EPersonaStateBusy => FriendState::Busy, + sys::EPersonaState::EPersonaStateAway => FriendState::Away, + sys::EPersonaState::EPersonaStateSnooze => FriendState::Snooze, + sys::EPersonaState::EPersonaStateLookingToPlay => FriendState::LookingToPlay, + sys::EPersonaState::EPersonaStateLookingToTrade => FriendState::LookingToTrade, _ => unreachable!(), } } @@ -210,14 +210,14 @@ impl <Manager> Friend<Manager> { /// Returns information about the game the player is current playing if any pub fn game_played(&self) -> Option<FriendGame> { unsafe { - let mut info = sys::create_empty_FriendGameInfo_t(); - if sys::SteamAPI_ISteamFriends_GetFriendGamePlayed(self.friends, self.id.0, &mut info) != 0 { + let mut info: sys::FriendGameInfo_t = std::mem::uninitialized(); + if sys::SteamAPI_ISteamFriends_GetFriendGamePlayed(self.friends, sys::CSteamID(self.id.0), &mut info) != 0 { Some(FriendGame { - game: GameId(info.get_m_gameID()), - game_address: info.get_m_unGameIP().into(), - game_port: info.get_m_usGamePort(), - query_port: info.get_m_usQueryPort(), - lobby: LobbyId(info.get_m_steamIDLobby()), + game: GameId(info.m_gameID.0), + game_address: info.m_unGameIP.into(), + game_port: info.m_usGamePort, + query_port: info.m_usQueryPort, + lobby: LobbyId(info.m_steamIDLobby.0), }) } else { None @@ -229,7 +229,7 @@ impl <Manager> Friend<Manager> { pub fn small_avatar(&self) -> Option<Vec<u8>> { unsafe { let utils = sys::steam_rust_get_utils(); - let img = sys::SteamAPI_ISteamFriends_GetSmallFriendAvatar(self.friends, self.id.0); + let img = sys::SteamAPI_ISteamFriends_GetSmallFriendAvatar(self.friends, sys::CSteamID(self.id.0)); if img == 0 { return None; } @@ -252,7 +252,7 @@ impl <Manager> Friend<Manager> { pub fn medium_avatar(&self) -> Option<Vec<u8>> { unsafe { let utils = sys::steam_rust_get_utils(); - let img = sys::SteamAPI_ISteamFriends_GetMediumFriendAvatar(self.friends, self.id.0); + let img = sys::SteamAPI_ISteamFriends_GetMediumFriendAvatar(self.friends, sys::CSteamID(self.id.0)); if img == 0 { return None; } @@ -76,7 +76,7 @@ struct Inner<Manager> { struct Callbacks { callbacks: Vec<*mut libc::c_void>, - call_results: HashMap<sys::SteamAPICall, *mut libc::c_void>, + call_results: HashMap<sys::SteamAPICall_t, *mut libc::c_void>, } unsafe impl <Manager: Send + Sync> Send for Inner<Manager> {} diff --git a/src/matchmaking.rs b/src/matchmaking.rs index 0f3c17b..6788450 100644 --- a/src/matchmaking.rs +++ b/src/matchmaking.rs @@ -58,9 +58,9 @@ impl <Manager> Matchmaking<Manager> { cb(if io_error { Err(SteamError::IOFailure) } else { - let mut out = Vec::with_capacity(v.get_m_nLobbiesMatching() as usize); - for idx in 0 .. v.get_m_nLobbiesMatching() { - out.push(LobbyId(sys::SteamAPI_ISteamMatchmaking_GetLobbyByIndex(sys::steam_rust_get_matchmaking(), idx as _))); + let mut out = Vec::with_capacity(v.m_nLobbiesMatching as usize); + for idx in 0 .. v.m_nLobbiesMatching { + out.push(LobbyId(sys::SteamAPI_ISteamMatchmaking_GetLobbyByIndex(sys::steam_rust_get_matchmaking(), idx as _).0)); } Ok(out) }) @@ -84,10 +84,10 @@ impl <Manager> Matchmaking<Manager> { assert!(max_members <= 250); // Steam API limits unsafe { let ty = match ty { - LobbyType::Private => sys::ELobbyType_k_ELobbyTypePrivate, - LobbyType::FriendsOnly => sys::ELobbyType_k_ELobbyTypeFriendsOnly, - LobbyType::Public => sys::ELobbyType_k_ELobbyTypePublic, - LobbyType::Invisible => sys::ELobbyType_k_ELobbyTypeInvisible, + LobbyType::Private => sys::ELobbyType::ELobbyTypePrivate, + LobbyType::FriendsOnly => sys::ELobbyType::ELobbyTypeFriendsOnly, + LobbyType::Public => sys::ELobbyType::ELobbyTypePublic, + LobbyType::Invisible => sys::ELobbyType::ELobbyTypeInvisible, }; let api_call = sys::SteamAPI_ISteamMatchmaking_CreateLobby(self.mm, ty, max_members as _); register_call_result::<sys::LobbyCreated_t, _, _>( @@ -95,10 +95,10 @@ impl <Manager> Matchmaking<Manager> { move |v, io_error| { cb(if io_error { Err(SteamError::IOFailure) - } else if v.get_m_eResult() != sys::EResult_k_EResultOK { - Err(v.get_m_eResult().into()) + } else if v.m_eResult != sys::EResult::EResultOK { + Err(v.m_eResult.into()) } else { - Ok(LobbyId(v.get_m_ulSteamIDLobby())) + Ok(LobbyId(v.m_ulSteamIDLobby)) }) }); } @@ -109,16 +109,16 @@ impl <Manager> Matchmaking<Manager> { where F: FnMut(Result<LobbyId, ()>) + 'static + Send { unsafe { - let api_call = sys::SteamAPI_ISteamMatchmaking_JoinLobby(self.mm, lobby.0); + let api_call = sys::SteamAPI_ISteamMatchmaking_JoinLobby(self.mm, sys::CSteamID(lobby.0)); register_call_result::<sys::LobbyEnter_t, _, _>( &self.inner, api_call, CALLBACK_BASE_ID + 4, move |v, io_error| { cb(if io_error { Err(()) - } else if v.get_m_EChatRoomEnterResponse() != 1 { + } else if v.m_EChatRoomEnterResponse != 1 { Err(()) } else { - Ok(LobbyId(v.get_m_ulSteamIDLobby())) + Ok(LobbyId(v.m_ulSteamIDLobby)) }) }); } @@ -127,14 +127,14 @@ impl <Manager> Matchmaking<Manager> { /// Exits the passed lobby pub fn leave_lobby(&self, lobby: LobbyId) { unsafe { - sys::SteamAPI_ISteamMatchmaking_LeaveLobby(self.mm, lobby.0); + sys::SteamAPI_ISteamMatchmaking_LeaveLobby(self.mm, sys::CSteamID(lobby.0)); } } /// Returns the steam id of the current owner of the passed lobby pub fn lobby_owner(&self, lobby: LobbyId) -> SteamId { unsafe { - SteamId(sys::SteamAPI_ISteamMatchmaking_GetLobbyOwner(self.mm, lobby.0)) + SteamId(sys::SteamAPI_ISteamMatchmaking_GetLobbyOwner(self.mm, sys::CSteamID(lobby.0)).0) } } @@ -143,7 +143,7 @@ impl <Manager> Matchmaking<Manager> { /// Useful if you are not currently in the lobby pub fn lobby_member_count(&self, lobby: LobbyId) -> usize { unsafe { - let count = sys::SteamAPI_ISteamMatchmaking_GetNumLobbyMembers(self.mm, lobby.0); + let count = sys::SteamAPI_ISteamMatchmaking_GetNumLobbyMembers(self.mm, sys::CSteamID(lobby.0)); count as usize } } @@ -151,11 +151,11 @@ impl <Manager> Matchmaking<Manager> { /// Returns a list of members currently in the lobby pub fn lobby_members(&self, lobby: LobbyId) -> Vec<SteamId> { unsafe { - let count = sys::SteamAPI_ISteamMatchmaking_GetNumLobbyMembers(self.mm, lobby.0); + let count = sys::SteamAPI_ISteamMatchmaking_GetNumLobbyMembers(self.mm, sys::CSteamID(lobby.0)); let mut members = Vec::with_capacity(count as usize); for idx in 0 .. count { members.push(SteamId( - sys::SteamAPI_ISteamMatchmaking_GetLobbyMemberByIndex(self.mm, lobby.0, idx) + sys::SteamAPI_ISteamMatchmaking_GetLobbyMemberByIndex(self.mm, sys::CSteamID(lobby.0), idx).0 )) } members diff --git a/src/networking.rs b/src/networking.rs index 258abda..032b03e 100644 --- a/src/networking.rs +++ b/src/networking.rs @@ -31,14 +31,14 @@ impl <Manager> Networking<Manager> { /// Should only be called in response to a `P2PSessionRequest`. pub fn accept_p2p_session(&self, user: SteamId) { unsafe { - sys::SteamAPI_ISteamNetworking_AcceptP2PSessionWithUser(self.net, user.0); + sys::SteamAPI_ISteamNetworking_AcceptP2PSessionWithUser(self.net, sys::CSteamID(user.0)); } } /// Closes the p2p connection between the given user pub fn close_p2p_session(&self, user: SteamId) { unsafe { - sys::SteamAPI_ISteamNetworking_CloseP2PSessionWithUser(self.net, user.0); + sys::SteamAPI_ISteamNetworking_CloseP2PSessionWithUser(self.net, sys::CSteamID(user.0)); } } @@ -47,12 +47,12 @@ impl <Manager> Networking<Manager> { pub fn send_p2p_packet(&self, remote: SteamId, send_type: SendType, data: &[u8]) -> bool { unsafe { let send_type = match send_type { - SendType::Unreliable => sys::EP2PSend_k_EP2PSendUnreliable, - SendType::UnreliableNoDelay => sys::EP2PSend_k_EP2PSendUnreliableNoDelay, - SendType::Reliable => sys::EP2PSend_k_EP2PSendReliable, - SendType::ReliableWithBuffering => sys::EP2PSend_k_EP2PSendReliableWithBuffering, + SendType::Unreliable => sys::EP2PSend::EP2PSendUnreliable, + SendType::UnreliableNoDelay => sys::EP2PSend::EP2PSendUnreliableNoDelay, + SendType::Reliable => sys::EP2PSend::EP2PSendReliable, + SendType::ReliableWithBuffering => sys::EP2PSend::EP2PSendReliableWithBuffering, }; - sys::SteamAPI_ISteamNetworking_SendP2PPacket(self.net, remote.0, data.as_ptr() as *const _, data.len() as u32, send_type, 0) != 0 + sys::SteamAPI_ISteamNetworking_SendP2PPacket(self.net, sys::CSteamID(remote.0), data.as_ptr() as *const _, data.len() as u32, send_type, 0) != 0 } } @@ -78,9 +78,9 @@ impl <Manager> Networking<Manager> { pub fn read_p2p_packet(&self, buf: &mut [u8]) -> Option<(SteamId, usize)> { unsafe { let mut size = 0; - let mut remote = 0; + let mut remote = sys::CSteamID(0); if sys::SteamAPI_ISteamNetworking_ReadP2PPacket(self.net, buf.as_mut_ptr() as *mut _, buf.len() as _, &mut size, &mut remote, 0) != 0 { - Some((SteamId(remote), size as usize)) + Some((SteamId(remote.0), size as usize)) } else { None } @@ -97,13 +97,13 @@ pub struct P2PSessionRequest { } unsafe impl Callback for P2PSessionRequest { - const ID: i32 = sys::P2PSessionRequest_t_k_iCallback as i32; + const ID: i32 = 1202; const SIZE: i32 = ::std::mem::size_of::<sys::P2PSessionRequest_t>() as i32; unsafe fn from_raw(raw: *mut libc::c_void) -> Self { let val = &mut *(raw as *mut sys::P2PSessionRequest_t); P2PSessionRequest { - remote: SteamId(val.get_m_steamIDRemote()), + remote: SteamId(val.m_steamIDRemote.0), } } } diff --git a/src/server.rs b/src/server.rs index 6a01b7f..a7afbb1 100644 --- a/src/server.rs +++ b/src/server.rs @@ -62,9 +62,9 @@ impl Server { let version = CString::new(version).unwrap(); let raw_ip: u32 = ip.into(); let server_mode = match server_mode { - ServerMode::NoAuthentication => sys::EServerMode_eServerModeNoAuthentication, - ServerMode::Authentication => sys::EServerMode_eServerModeAuthentication, - ServerMode::AuthenticationAndSecure => sys::EServerMode_eServerModeAuthenticationAndSecure, + ServerMode::NoAuthentication => sys::EServerMode::ServerModeNoAuthentication, + ServerMode::Authentication => sys::EServerMode::ServerModeAuthentication, + ServerMode::AuthenticationAndSecure => sys::EServerMode::ServerModeAuthenticationAndSecure, }; if sys::steam_rust_game_server_init( raw_ip, steam_port, @@ -109,7 +109,7 @@ impl Server { /// Returns the steam id of the current server pub fn steam_id(&self) -> SteamId { unsafe { - SteamId(sys::SteamAPI_ISteamGameServer_GetSteamID(self.server)) + SteamId(sys::SteamAPI_ISteamGameServer_GetSteamID(self.server).0) } } @@ -158,16 +158,15 @@ impl Server { let res = sys::SteamAPI_ISteamGameServer_BeginAuthSession( self.server, ticket.as_ptr() as *const _, ticket.len() as _, - user.0 + sys::CSteamID(user.0) ); Err(match res { - sys::EBeginAuthSessionResult_k_EBeginAuthSessionResultOK => return Ok(()), - sys::EBeginAuthSessionResult_k_EBeginAuthSessionResultInvalidTicket => AuthSessionError::InvalidTicket, - sys::EBeginAuthSessionResult_k_EBeginAuthSessionResultDuplicateRequest => AuthSessionError::DuplicateRequest, - sys::EBeginAuthSessionResult_k_EBeginAuthSessionResultInvalidVersion => AuthSessionError::InvalidVersion, - sys::EBeginAuthSessionResult_k_EBeginAuthSessionResultGameMismatch => AuthSessionError::GameMismatch, - sys::EBeginAuthSessionResult_k_EBeginAuthSessionResultExpiredTicket => AuthSessionError::ExpiredTicket, - _ => unreachable!(), + sys::EBeginAuthSessionResult::EBeginAuthSessionResultOK => return Ok(()), + sys::EBeginAuthSessionResult::EBeginAuthSessionResultInvalidTicket => AuthSessionError::InvalidTicket, + sys::EBeginAuthSessionResult::EBeginAuthSessionResultDuplicateRequest => AuthSessionError::DuplicateRequest, + sys::EBeginAuthSessionResult::EBeginAuthSessionResultInvalidVersion => AuthSessionError::InvalidVersion, + sys::EBeginAuthSessionResult::EBeginAuthSessionResultGameMismatch => AuthSessionError::GameMismatch, + sys::EBeginAuthSessionResult::EBeginAuthSessionResultExpiredTicket => AuthSessionError::ExpiredTicket, }) } } @@ -179,7 +178,7 @@ impl Server { /// the specified entity. pub fn end_authentication_session(&self, user: SteamId) { unsafe { - sys::SteamAPI_ISteamGameServer_EndAuthSession(self.server, user.0); + sys::SteamAPI_ISteamGameServer_EndAuthSession(self.server, sys::CSteamID(user.0)); } } @@ -251,7 +250,7 @@ fn test() { println!("{:?}", server.steam_id()); - let _cb = server.register_callback(|v: AuthSessionTicketResponse| println!("{:?}", v)); + let _cb = server.register_callback(|v: AuthSessionTicketResponse| println!("Got response: {:?}", v.result)); let _cb = server.register_callback(|v: ValidateAuthTicketResponse| println!("{:?}", v)); let id = server.steam_id(); diff --git a/src/user.rs b/src/user.rs index 3263ba6..a57ae51 100644 --- a/src/user.rs +++ b/src/user.rs @@ -11,7 +11,7 @@ impl <Manager> User<Manager> { /// Returns the steam id of the current user pub fn steam_id(&self) -> SteamId { unsafe { - SteamId(sys::SteamAPI_ISteamUser_GetSteamID(self.user)) + SteamId(sys::SteamAPI_ISteamUser_GetSteamID(self.user).0) } } @@ -60,16 +60,15 @@ impl <Manager> User<Manager> { let res = sys::SteamAPI_ISteamUser_BeginAuthSession( self.user, ticket.as_ptr() as *const _, ticket.len() as _, - user.0 + sys::CSteamID(user.0) ); Err(match res { - sys::EBeginAuthSessionResult_k_EBeginAuthSessionResultOK => return Ok(()), - sys::EBeginAuthSessionResult_k_EBeginAuthSessionResultInvalidTicket => AuthSessionError::InvalidTicket, - sys::EBeginAuthSessionResult_k_EBeginAuthSessionResultDuplicateRequest => AuthSessionError::DuplicateRequest, - sys::EBeginAuthSessionResult_k_EBeginAuthSessionResultInvalidVersion => AuthSessionError::InvalidVersion, - sys::EBeginAuthSessionResult_k_EBeginAuthSessionResultGameMismatch => AuthSessionError::GameMismatch, - sys::EBeginAuthSessionResult_k_EBeginAuthSessionResultExpiredTicket => AuthSessionError::ExpiredTicket, - _ => unreachable!(), + sys::EBeginAuthSessionResult::EBeginAuthSessionResultOK => return Ok(()), + sys::EBeginAuthSessionResult::EBeginAuthSessionResultInvalidTicket => AuthSessionError::InvalidTicket, + sys::EBeginAuthSessionResult::EBeginAuthSessionResultDuplicateRequest => AuthSessionError::DuplicateRequest, + sys::EBeginAuthSessionResult::EBeginAuthSessionResultInvalidVersion => AuthSessionError::InvalidVersion, + sys::EBeginAuthSessionResult::EBeginAuthSessionResultGameMismatch => AuthSessionError::GameMismatch, + sys::EBeginAuthSessionResult::EBeginAuthSessionResultExpiredTicket => AuthSessionError::ExpiredTicket, }) } } @@ -81,7 +80,7 @@ impl <Manager> User<Manager> { /// the specified entity. pub fn end_authentication_session(&self, user: SteamId) { unsafe { - sys::SteamAPI_ISteamUser_EndAuthSession(self.user, user.0); + sys::SteamAPI_ISteamUser_EndAuthSession(self.user, sys::CSteamID(user.0)); } } } @@ -111,7 +110,7 @@ fn test() { let (client, single) = Client::init().unwrap(); let user = client.user(); - let _cb = client.register_callback(|v: AuthSessionTicketResponse| println!("{:?}", v)); + let _cb = client.register_callback(|v: AuthSessionTicketResponse| println!("Got response: {:?}", v.result)); let _cb = client.register_callback(|v: ValidateAuthTicketResponse| println!("{:?}", v)); let id = user.steam_id(); @@ -138,13 +137,11 @@ fn test() { /// A handle for an authentication ticket that can be used to cancel /// it. -#[derive(Debug)] pub struct AuthTicket(pub(crate) sys::HAuthTicket); /// Called when generating a authentication session ticket. /// /// This can be used to verify the ticket was created successfully. -#[derive(Debug)] pub struct AuthSessionTicketResponse { /// The ticket in question pub ticket: AuthTicket, @@ -159,11 +156,11 @@ unsafe impl Callback for AuthSessionTicketResponse { unsafe fn from_raw(raw: *mut libc::c_void) -> Self { let val = &mut *(raw as *mut sys::GetAuthSessionTicketResponse_t); AuthSessionTicketResponse { - ticket: AuthTicket(val.get_m_hAuthTicket()), - result: if val.get_m_eResult() == sys::EResult_k_EResultOK { + ticket: AuthTicket(val.m_hAuthTicket), + result: if val.m_eResult == sys::EResult::EResultOK { Ok(()) } else { - Err(val.get_m_eResult().into()) + Err(val.m_eResult.into()) } } } @@ -190,20 +187,19 @@ unsafe impl Callback for ValidateAuthTicketResponse { unsafe fn from_raw(raw: *mut libc::c_void) -> Self { let val = &mut *(raw as *mut sys::ValidateAuthTicketResponse_t); ValidateAuthTicketResponse { - steam_id: SteamId(val.get_m_SteamID()), - owner_steam_id: SteamId(val.get_m_OwnerSteamID()), - response: match val.get_m_eAuthSessionResponse() { - sys::EAuthSessionResponse_k_EAuthSessionResponseOK => Ok(()), - sys::EAuthSessionResponse_k_EAuthSessionResponseUserNotConnectedToSteam => Err(AuthSessionValidateError::UserNotConnectedToSteam), - sys::EAuthSessionResponse_k_EAuthSessionResponseNoLicenseOrExpired => Err(AuthSessionValidateError::NoLicenseOrExpired), - sys::EAuthSessionResponse_k_EAuthSessionResponseVACBanned => Err(AuthSessionValidateError::VACBanned), - sys::EAuthSessionResponse_k_EAuthSessionResponseLoggedInElseWhere => Err(AuthSessionValidateError::LoggedInElseWhere), - sys::EAuthSessionResponse_k_EAuthSessionResponseVACCheckTimedOut => Err(AuthSessionValidateError::VACCheckTimedOut), - sys::EAuthSessionResponse_k_EAuthSessionResponseAuthTicketCanceled => Err(AuthSessionValidateError::AuthTicketCancelled), - sys::EAuthSessionResponse_k_EAuthSessionResponseAuthTicketInvalidAlreadyUsed => Err(AuthSessionValidateError::AuthTicketInvalidAlreadyUsed), - sys::EAuthSessionResponse_k_EAuthSessionResponseAuthTicketInvalid => Err(AuthSessionValidateError::AuthTicketInvalid), - sys::EAuthSessionResponse_k_EAuthSessionResponsePublisherIssuedBan => Err(AuthSessionValidateError::PublisherIssuedBan), - _ => unreachable!(), + steam_id: SteamId(val.m_SteamID.0), + owner_steam_id: SteamId(val.m_OwnerSteamID.0), + response: match val.m_eAuthSessionResponse { + sys::EAuthSessionResponse::EAuthSessionResponseOK => Ok(()), + sys::EAuthSessionResponse::EAuthSessionResponseUserNotConnectedToSteam => Err(AuthSessionValidateError::UserNotConnectedToSteam), + sys::EAuthSessionResponse::EAuthSessionResponseNoLicenseOrExpired => Err(AuthSessionValidateError::NoLicenseOrExpired), + sys::EAuthSessionResponse::EAuthSessionResponseVACBanned => Err(AuthSessionValidateError::VACBanned), + sys::EAuthSessionResponse::EAuthSessionResponseLoggedInElseWhere => Err(AuthSessionValidateError::LoggedInElseWhere), + sys::EAuthSessionResponse::EAuthSessionResponseVACCheckTimedOut => Err(AuthSessionValidateError::VACCheckTimedOut), + sys::EAuthSessionResponse::EAuthSessionResponseAuthTicketCanceled => Err(AuthSessionValidateError::AuthTicketCancelled), + sys::EAuthSessionResponse::EAuthSessionResponseAuthTicketInvalidAlreadyUsed => Err(AuthSessionValidateError::AuthTicketInvalidAlreadyUsed), + sys::EAuthSessionResponse::EAuthSessionResponseAuthTicketInvalid => Err(AuthSessionValidateError::AuthTicketInvalid), + sys::EAuthSessionResponse::EAuthSessionResponsePublisherIssuedBan => Err(AuthSessionValidateError::PublisherIssuedBan), } } } diff --git a/src/user_stats.rs b/src/user_stats.rs index 33b92a1..745b76a 100644 --- a/src/user_stats.rs +++ b/src/user_stats.rs @@ -23,8 +23,8 @@ impl <Manager> UserStats<Manager> { cb(if io_error { Err(SteamError::IOFailure) } else { - Ok(if v.get_m_bLeaderboardFound() != 0 { - Some(Leaderboard(v.get_m_hSteamLeaderboard())) + Ok(if v.m_bLeaderboardFound != 0 { + Some(Leaderboard(v.m_hSteamLeaderboard.0)) } else { None }) @@ -40,14 +40,14 @@ impl <Manager> UserStats<Manager> { let name = CString::new(name).unwrap(); let sort_method = match sort_method { - LeaderboardSortMethod::Ascending => sys::ELeaderboardSortMethod_k_ELeaderboardSortMethodAscending, - LeaderboardSortMethod::Descending => sys::ELeaderboardSortMethod_k_ELeaderboardSortMethodDescending, + LeaderboardSortMethod::Ascending => sys::ELeaderboardSortMethod::ELeaderboardSortMethodAscending, + LeaderboardSortMethod::Descending => sys::ELeaderboardSortMethod::ELeaderboardSortMethodDescending, }; let display_type = match display_type { - LeaderboardDisplayType::Numeric => sys::ELeaderboardDisplayType_k_ELeaderboardDisplayTypeNumeric, - LeaderboardDisplayType::TimeSeconds => sys::ELeaderboardDisplayType_k_ELeaderboardDisplayTypeTimeSeconds, - LeaderboardDisplayType::TimeMilliSeconds => sys::ELeaderboardDisplayType_k_ELeaderboardDisplayTypeTimeMilliSeconds, + LeaderboardDisplayType::Numeric => sys::ELeaderboardDisplayType::ELeaderboardDisplayTypeNumeric, + LeaderboardDisplayType::TimeSeconds => sys::ELeaderboardDisplayType::ELeaderboardDisplayTypeTimeSeconds, + LeaderboardDisplayType::TimeMilliSeconds => sys::ELeaderboardDisplayType::ELeaderboardDisplayTypeTimeMilliSeconds, }; let api_call = sys::SteamAPI_ISteamUserStats_FindOrCreateLeaderboard(self.user_stats, name.as_ptr() as *const _, sort_method, display_type); @@ -57,8 +57,8 @@ impl <Manager> UserStats<Manager> { cb(if io_error { Err(SteamError::IOFailure) } else { - Ok(if v.get_m_bLeaderboardFound() != 0 { - Some(Leaderboard(v.get_m_hSteamLeaderboard())) + Ok(if v.m_bLeaderboardFound != 0 { + Some(Leaderboard(v.m_hSteamLeaderboard.0)) } else { None }) @@ -72,22 +72,22 @@ impl <Manager> UserStats<Manager> { { unsafe { let method = match method { - UploadScoreMethod::KeepBest => sys::ELeaderboardUploadScoreMethod_k_ELeaderboardUploadScoreMethodKeepBest, - UploadScoreMethod::ForceUpdate => sys::ELeaderboardUploadScoreMethod_k_ELeaderboardUploadScoreMethodForceUpdate, + UploadScoreMethod::KeepBest => sys::ELeaderboardUploadScoreMethod::ELeaderboardUploadScoreMethodKeepBest, + UploadScoreMethod::ForceUpdate => sys::ELeaderboardUploadScoreMethod::ELeaderboardUploadScoreMethodForceUpdate, }; - let api_call = sys::SteamAPI_ISteamUserStats_UploadLeaderboardScore(self.user_stats, leaderboard.0, method, score, details.as_ptr(), details.len() as _); + let api_call = sys::SteamAPI_ISteamUserStats_UploadLeaderboardScore(self.user_stats, sys::SteamLeaderboard_t(leaderboard.0), method, score, details.as_ptr(), details.len() as _); register_call_result::<sys::LeaderboardScoreUploaded_t , _, _>( &self.inner, api_call, CALLBACK_BASE_ID + 6, move |v, io_error| { cb(if io_error { Err(SteamError::IOFailure) } else { - Ok(if v.get_m_bSuccess() != 0 { + Ok(if v.m_bSuccess != 0 { Some(LeaderboardScoreUploaded { - score: v.get_m_nScore(), - was_changed: v.get_m_bScoreChanged() != 0, - global_rank_new: v.get_m_nGlobalRankNew() as _, - global_rank_previous: v.get_m_nGlobalRankPrevious() as _, + score: v.m_nScore, + was_changed: v.m_bScoreChanged != 0, + global_rank_new: v.m_nGlobalRankNew as _, + global_rank_previous: v.m_nGlobalRankPrevious as _, }) } else { None @@ -108,11 +108,11 @@ impl <Manager> UserStats<Manager> { { unsafe { let request = match request { - LeaderboardDataRequest::Global => sys::ELeaderboardDataRequest_k_ELeaderboardDataRequestGlobal, - LeaderboardDataRequest::GlobalAroundUser => sys::ELeaderboardDataRequest_k_ELeaderboardDataRequestGlobalAroundUser, - LeaderboardDataRequest::Friends => sys::ELeaderboardDataRequest_k_ELeaderboardDataRequestFriends, + LeaderboardDataRequest::Global => sys::ELeaderboardDataRequest::ELeaderboardDataRequestGlobal, + LeaderboardDataRequest::GlobalAroundUser => sys::ELeaderboardDataRequest::ELeaderboardDataRequestGlobalAroundUser, + LeaderboardDataRequest::Friends => sys::ELeaderboardDataRequest::ELeaderboardDataRequestFriends, }; - let api_call = sys::SteamAPI_ISteamUserStats_DownloadLeaderboardEntries(self.user_stats, leaderboard.0, request, start as _, end as _); + let api_call = sys::SteamAPI_ISteamUserStats_DownloadLeaderboardEntries(self.user_stats, sys::SteamLeaderboard_t(leaderboard.0), request, start as _, end as _); let user_stats = self.user_stats as isize; register_call_result::<sys::LeaderboardScoresDownloaded_t , _, _>( &self.inner, api_call, CALLBACK_BASE_ID + 5, @@ -120,19 +120,19 @@ impl <Manager> UserStats<Manager> { cb(if io_error { Err(SteamError::IOFailure) } else { - let len = v.get_m_cEntryCount(); + let len = v.m_cEntryCount; let mut entries = Vec::with_capacity(len as usize); for idx in 0 .. len { - let mut entry = sys::create_empty_LeaderboardEntry_t(); + let mut entry: sys::LeaderboardEntry_t = std::mem::uninitialized(); let mut details = Vec::with_capacity(max_details_len); - sys::SteamAPI_ISteamUserStats_GetDownloadedLeaderboardEntry(user_stats as *mut _, v.get_m_hSteamLeaderboardEntries(), idx, &mut entry, details.as_mut_ptr(), max_details_len as _); - details.set_len(entry.get_m_cDetails() as usize); + sys::SteamAPI_ISteamUserStats_GetDownloadedLeaderboardEntry(user_stats as *mut _, v.m_hSteamLeaderboardEntries, idx, &mut entry, details.as_mut_ptr(), max_details_len as _); + details.set_len(entry.m_cDetails as usize); entries.push(LeaderboardEntry { - user: SteamId(entry.get_m_steamIDUser()), - global_rank: entry.get_m_nGlobalRank(), - score: entry.get_m_nScore(), + user: SteamId(entry.m_steamIDUser.0), + global_rank: entry.m_nGlobalRank, + score: entry.m_nScore, details, }) } diff --git a/src/utils.rs b/src/utils.rs index 43e167b..34ba6c9 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -18,7 +18,7 @@ impl <Manager> Utils<Manager> { /// Returns the app ID of the current process pub fn app_id(&self) -> AppId { unsafe { - AppId(sys::SteamAPI_ISteamUtils_GetAppID(self.utils)) + AppId(sys::SteamAPI_ISteamUtils_GetAppID(self.utils).0) } } @@ -39,10 +39,10 @@ impl <Manager> Utils<Manager> { pub fn set_overlay_notification_position(&self, position: NotificationPosition) { unsafe { let position = match position { - NotificationPosition::TopLeft => sys::ENotificationPosition_k_EPositionTopLeft, - NotificationPosition::TopRight => sys::ENotificationPosition_k_EPositionTopRight, - NotificationPosition::BottomLeft => sys::ENotificationPosition_k_EPositionBottomLeft, - NotificationPosition::BottomRight => sys::ENotificationPosition_k_EPositionBottomRight, + NotificationPosition::TopLeft => sys::ENotificationPosition::EPositionTopLeft, + NotificationPosition::TopRight => sys::ENotificationPosition::EPositionTopRight, + NotificationPosition::BottomLeft => sys::ENotificationPosition::EPositionBottomLeft, + NotificationPosition::BottomRight => sys::ENotificationPosition::EPositionBottomRight, }; sys::SteamAPI_ISteamUtils_SetOverlayNotificationPosition(self.utils, position); } diff --git a/steamworks-sys/Cargo.toml b/steamworks-sys/Cargo.toml index 168d2fb..e46410d 100644 --- a/steamworks-sys/Cargo.toml +++ b/steamworks-sys/Cargo.toml @@ -19,12 +19,12 @@ docs-only = [] [dependencies] -libc = "0.2.36" +libc = "0.2.50" [build-dependencies] -cc = "1.0.4" -bindgen = "0.36.0" -serde = "1.0.37" -serde_derive = "1.0.37" -serde_json = "1.0.14" +cc = "1.0.31" +bindgen = {git = "https://github.com/rust-lang/rust-bindgen.git"} # "0.48.1" +serde = "1.0.89" +serde_derive = "1.0.89" +serde_json = "1.0.39" diff --git a/steamworks-sys/build.rs b/steamworks-sys/build.rs index 38ee072..c68259c 100755 --- a/steamworks-sys/build.rs +++ b/steamworks-sys/build.rs @@ -6,13 +6,28 @@ extern crate serde_derive; #[derive(Deserialize)] struct SteamApi { + typedefs: Vec<SteamTypedef>, structs: Vec<SteamStruct>, enums: Vec<SteamEnum>, } +#[derive(Deserialize)] +struct SteamTypedef { + typedef: String, + #[serde(rename = "type")] + ty: String, +} #[derive(Deserialize)] struct SteamEnum { enumname: String, + values: Vec<SteamEnumValue>, +} + + +#[derive(Deserialize)] +struct SteamEnumValue { + name: String, + value: String, } #[derive(Deserialize)] @@ -32,12 +47,12 @@ struct SteamField { fn main() {} #[cfg(not(feature = "docs-only"))] -fn main() { +fn main() -> Result<(), Box<dyn std::error::Error>> { use std::env; use std::path::{Path, PathBuf}; - use std::io::Write; - use std::fmt::Write as FWrite; - use std::fs::File; + use std::fmt::Write as _; + use std::fs::{self, File}; + use std::borrow::Cow; let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); let sdk_loc = env::var("STEAM_SDK_LOCATION") @@ -46,6 +61,7 @@ fn main() { let triple = env::var("TARGET").unwrap(); let mut lib = "steam_api"; + let mut packing = 8; let path = if triple.contains("windows") { if triple.contains("i686") { sdk_loc.join("redistributable_bin/") @@ -54,12 +70,14 @@ fn main() { sdk_loc.join("redistributable_bin/win64") } } else if triple.contains("linux") { + packing = 4; if triple.contains("i686") { sdk_loc.join("redistributable_bin/linux32") } else { sdk_loc.join("redistributable_bin/linux64") } } else if triple.contains("darwin") { + packing = 4; sdk_loc.join("redistributable_bin/osx64") } else { panic!("Unsupported OS"); @@ -67,30 +85,24 @@ fn main() { println!("cargo:rustc-link-search={}", path.display()); println!("cargo:rustc-link-lib=dylib={}", lib); - let mut builder = bindgen::builder() - .header("wrapper.hpp") - .clang_arg(format!("-I{}", sdk_loc.join("public/steam").display())) - .ctypes_prefix("libc") - .rustfmt_bindings(false); - // Steamworks uses packed structs making them hard to work // with normally - let steam_api: SteamApi = serde_json::from_reader(File::open(sdk_loc.join("public/steam/steam_api.json")).unwrap()) - .unwrap(); + let steam_api: SteamApi = serde_json::from_reader(File::open(sdk_loc.join("public/steam/steam_api.json"))?)?; - let mut cpp_wrapper = String::from(r#" -#include <steam_api.h> -#include <steam_gameserver.h> -#include <stdint.h> -extern "C" { - "#); + let mut bindings = r##" +use libc::*; +"##.to_owned(); - fn field_type_fix(fty: &str) -> (&str, String){ + fn c_to_rust<'a>(fty: &'a str) -> Option<(&'a str, Cow<'a, str>)> { + // Generics + if fty == "T *" { + return None; + } let fty = { if fty.contains("enum") { - fty.trim_left_matches("enum ") + fty.trim_start_matches("enum ") } else if fty.contains("struct") { - fty.trim_left_matches("struct ") + fty.trim_start_matches("struct ") } else if fty == "_Bool" { "bool" } else { @@ -98,173 +110,136 @@ extern "C" { } }; let fty_rust = if fty == "const char*" || fty == "*const char" || fty == "const char *" { - "*const libc::c_char".to_owned() + "*const libc::c_char".into() } else if fty == "char*" { - "*mut libc::c_char".to_owned() + "*mut libc::c_char".into() } else if fty == "const char **" { - "*mut *const libc::c_char".to_owned() + "*mut *const libc::c_char".into() }else if fty.ends_with("*") { if fty.starts_with("const") { - let trimmed = fty.trim_left_matches("const ").trim_right_matches("*"); - format!("*const {}", trimmed) + let trimmed = fty.trim_start_matches("const ").trim_end_matches("*").trim(); + format!("*const {}", c_to_rust(trimmed)?.1).into() } else { - let trimmed = fty.trim_right_matches("*"); - format!("*mut {}", trimmed) + let trimmed = fty.trim_end_matches("*").trim(); + format!("*mut {}", c_to_rust(trimmed)?.1).into() } } else if fty.contains("[") { - panic!("Unsupported field type array") - } else if fty == "class CSteamID" { - "u64".to_owned() - } else if fty == "class CGameID" { - "u64".to_owned() - } else if fty == "int" { - "libc::c_int".to_owned() - } else if fty == "float" { - "libc::c_float".to_owned() - } else if fty == "double" { - "libc::c_double".to_owned() + let num_start = fty.chars().position(|v| v == '[').unwrap_or(0); + let num_end = fty.chars().position(|v| v == ']').unwrap_or(0); + format!("[{}; {}]", c_to_rust(&fty[..num_start].trim())?.1, &fty[num_start + 1 .. num_end]).into() + } else if fty.contains("(") { + eprintln!("Unsupported field type function pointer: {:?}", fty); + return None; } else { - fty.to_owned() + match fty { + "int" => "c_int".into(), + "float" => "c_float".into(), + "double" => "c_double".into(), + "void" => "c_void".into(), + "uint8" => "u8".into(), + "int8" => "i8".into(), + "uint16" => "u16".into(), + "int16" => "i16".into(), + "uint32" => "u32".into(), + "int32" => "i32".into(), + "uint64" => "u64".into(), + "int64" => "i64".into(), + "lint64" => "i64".into(), + "ulint64" => "u64".into(), + "intp" => "isize".into(), + "uintp" => "usize".into(), + "class CSteamID" => "CSteamID".into(), + "class CGameID" => "CGameID".into(), + val if val.contains("class") => return None, + val => val.into(), + } }; - (fty, fty_rust) + + Some((fty, fty_rust)) } - for &SteamStruct{struct_: ref ty, ref fields} in &steam_api.structs { - if ty.contains("::") || !ty.ends_with("_t") || fields.iter().any(|v| v.fieldtype.contains('[')) - || ty.chars().next().map_or(true, |v| v.is_lowercase()) - || ty.starts_with("GSStats") - { + for def in steam_api.typedefs { + if def.typedef.chars().next().map_or(true, |v| v.is_lowercase()) { continue; } - builder = builder.whitelist_type(ty) - .opaque_type(ty); - - // Make a raw constructor - writeln!(cpp_wrapper, r#"{ty} __rust_helper_raw__{ty}() {{ - {ty} created_type = {{}}; - return created_type; - }}"#, ty = ty).unwrap(); - builder = builder.raw_line(format!(r#" - extern "C" {{ - fn __rust_helper_raw__{ty}() -> {ty}; - }} - pub unsafe fn create_empty_{ty}() -> {ty} {{ - __rust_helper_raw__{ty}() - }} - "#, ty = ty)); - // Make a typed constructor - let mut typed_constr_extern = String::new(); - let mut typed_constr_wrap = String::new(); - write!(cpp_wrapper, r#"{ty} __rust_helper_typed__{ty}("#, ty = ty).unwrap(); - write!(typed_constr_extern, r#"extern "C" {{ - fn __rust_helper_typed__{ty}("#, ty = ty).unwrap(); - write!(typed_constr_wrap, r#"pub unsafe fn create_{ty}("#, ty = ty).unwrap(); - for (idx, &SteamField{fieldname: ref fname, fieldtype: ref fty}) in fields.iter().enumerate() { - let (fty, fty_rust) = field_type_fix(fty); - write!(cpp_wrapper, "{} {}", fty, fname).unwrap(); - write!(typed_constr_extern, "{}: {},", fname, fty_rust).unwrap(); - write!(typed_constr_wrap, "{}: {},", fname, fty_rust).unwrap(); - if idx != fields.len() - 1 { - cpp_wrapper.push(','); + if let Some(rty) = c_to_rust(&def.ty) { + if def.typedef == rty.1 || def.typedef.contains("::") { + continue; } + writeln!(bindings, r#" +#[repr(transparent)] +#[derive(PartialEq, Eq, Hash, Clone, Copy)] +pub struct {}(pub {});"#, def.typedef, rty.1)?; + } else { + eprintln!("Could not typedef {:?}", def.typedef); } + } - write!(cpp_wrapper, r#") {{ - {ty} created_type = {{}}; - "#, ty = ty).unwrap(); - write!(typed_constr_extern, r#") -> {ty}; - }}"#, ty = ty).unwrap(); - write!(typed_constr_wrap, r#") -> {ty} {{ - __rust_helper_typed__{ty}("#, ty = ty).unwrap(); - for &SteamField{fieldname: ref fname, ..} in fields.iter() { - write!(cpp_wrapper, "created_type.{fname} = {fname};", fname = fname).unwrap(); - write!(typed_constr_wrap, "{},", fname).unwrap(); + for e in steam_api.enums { + if e.enumname.contains("::") { + continue; + } + writeln!(bindings, r#" +#[repr(C)] +#[derive(PartialEq, Eq, Hash, Clone, Copy)] +pub enum {} {{"#, e.enumname)?; + + for v in e.values { + // Known duplicate + if v.name == "k_EWorkshopFileTypeFirst" { + continue; + } + writeln!(bindings, r#" {} = {},"#, v.name.trim_start_matches("k_"), v.value)?; } - writeln!(cpp_wrapper, r#" - return created_type; - }}"#).unwrap(); - writeln!(typed_constr_wrap, r#") - }}"#).unwrap(); - builder = builder.raw_line(typed_constr_extern); - builder = builder.raw_line(typed_constr_wrap); + writeln!(bindings, r#"}}"#)?; + } - for &SteamField{fieldname: ref fname, fieldtype: ref fty} in fields.iter() { - let (fty, fty_rust) = field_type_fix(fty); - builder = builder.whitelist_type(fty); - // Generate getters/setters for fields - if fty == "class CSteamID" { - writeln!(cpp_wrapper, r#" - uint64_t __rust_helper_getter__{ty}_{fname}(const {ty}* from) {{ - return from->{fname}.ConvertToUint64(); - }} - void __rust_helper_setter__{ty}_{fname}({ty}* to, uint64_t val) {{ - to->{fname}.SetFromUint64(val); - }} - "#, ty = ty, fname = fname).unwrap(); - } else if fty == "class CGameID" { - writeln!(cpp_wrapper, r#" - uint64_t __rust_helper_getter__{ty}_{fname}(const {ty}* from) {{ - return from->{fname}.ToUint64(); - }} - void __rust_helper_setter__{ty}_{fname}({ty}* to, uint64_t val) {{ - to->{fname}.Set(val); - }} - "#, ty = ty, fname = fname).unwrap(); + 'structs: + for s in steam_api.structs { + if s.struct_ == "CSteamID" || s.struct_ == "CGameID" || s.struct_.contains("::") { + continue; + } + // TODO: Remove special case for SteamUGCDetails_t + let derive = if !s.fields.iter().any(|v| + v.fieldtype == "float" + || v.fieldtype == "double" + || v.fieldtype == "struct SteamUGCDetails_t" + || v.fieldtype.contains('[')) + { + "#[derive(Clone, Copy, PartialEq, Eq, Hash)]" + } else { + "#[derive(Clone, Copy)]" + }; + let mut s_builder = String::new(); + writeln!(s_builder, r#" +#[repr(C, packed({}))] +{} +pub struct {} {{"#, packing, derive, s.struct_)?; + + for f in s.fields { + if let Some(rty) = c_to_rust(&f.fieldtype) { + writeln!(s_builder, " pub {}: {},", f.fieldname, rty.1)?; } else { - writeln!(cpp_wrapper, r#" - {fty} __rust_helper_getter__{ty}_{fname}(const {ty}* from) {{ - return from->{fname}; - }} - void __rust_helper_setter__{ty}_{fname}({ty}* to, {fty} val) {{ - to->{fname} = val; - }} - "#, ty = ty, fty = fty, fname = fname).unwrap(); - }; - - builder = builder.raw_line(format!(r#" - extern "C" {{ - fn __rust_helper_getter__{ty}_{fname}(from: *const {ty}) -> {fty_rust}; - fn __rust_helper_setter__{ty}_{fname}(from: *mut {ty}, val: {fty_rust}); - }} - impl {ty} {{ - pub unsafe fn get_{fname}(&self) -> {fty_rust} {{ - __rust_helper_getter__{ty}_{fname}(self) - }} - pub unsafe fn set_{fname}(&mut self, val: {fty_rust}) {{ - __rust_helper_setter__{ty}_{fname}(self, val) - }} - }} - "#, ty = ty, fty_rust = fty_rust, fname = fname)) + continue 'structs; + } } - } - for e in steam_api.enums { - builder = builder.whitelist_type(e.enumname); - } - builder = builder.whitelist_type("EServerMode"); - cpp_wrapper.push_str("}"); + writeln!(s_builder, r#"}}"#)?; + + bindings.push_str(&s_builder); + } - File::create(out_path.join("steam_gen.cpp")) - .unwrap() - .write_all(cpp_wrapper.as_bytes()) - .unwrap(); + // fs::write("/tmp/steam-bindings.rs", &bindings)?; + fs::write(out_path.join("bindings.rs"), bindings)?; - // panic!("{}", out_path.join("steam_gen.cpp").display()); cc::Build::new() .cpp(true) .include(sdk_loc.join("public/steam")) .file("src/lib.cpp") - .file(out_path.join("steam_gen.cpp")) .compile("steamrust"); - let bindings = builder - .generate() - .unwrap(); - // panic!("{}", bindings.to_string()); - bindings - .write_to_file(out_path.join("bindings.rs")) - .expect("Couldn't write bindings!"); + Ok(()) }
\ No newline at end of file diff --git a/steamworks-sys/src/lib.rs b/steamworks-sys/src/lib.rs index e9473f1..4f064a5 100644 --- a/steamworks-sys/src/lib.rs +++ b/steamworks-sys/src/lib.rs @@ -6,41 +6,47 @@ extern crate libc; include!(concat!(env!("OUT_DIR"), "/bindings.rs")); -use libc::{ - c_char, - c_void, - c_int, -}; - -#[repr(C)] +#[repr(transparent)] pub struct ISteamClient(c_void); -#[repr(C)] +#[repr(transparent)] pub struct ISteamUtils(c_void); -#[repr(C)] +#[repr(transparent)] pub struct ISteamApps(c_void); -#[repr(C)] +#[repr(transparent)] pub struct ISteamFriends(c_void); -#[repr(C)] +#[repr(transparent)] pub struct ISteamMatchmaking(c_void); -#[repr(C)] +#[repr(transparent)] pub struct ISteamUser(c_void); -#[repr(C)] +#[repr(transparent)] pub struct ISteamUserStats(c_void); -#[repr(C)] +#[repr(transparent)] pub struct ISteamGameServer(c_void); -#[repr(C)] +#[repr(transparent)] pub struct ISteamNetworking(c_void); -pub type HSteamPipe = i32; -pub type AppId = u32; -pub type SteamAPICall = u64; +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct CSteamID(pub u64); +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct CGameID(pub u64); + + +#[repr(C)] +pub enum EServerMode { + ServerModeInvalid = 0, + ServerModeNoAuthentication = 1, + ServerModeAuthentication = 2, + ServerModeAuthenticationAndSecure = 3, +} #[repr(C)] pub struct CallbackData { pub param_size: c_int, pub userdata: *mut c_void, pub run: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void), - pub run_extra: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void, u8, SteamAPICall), + pub run_extra: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void, u8, SteamAPICall_t), pub dealloc: unsafe extern "C" fn(*mut c_void, *mut c_void), } @@ -73,8 +79,8 @@ extern "C" { pub fn SteamAPI_RunCallbacks(); pub fn SteamAPI_RegisterCallback(pCallback: *mut c_void, id: c_int); pub fn SteamAPI_UnregisterCallback(pCallback: *mut c_void); - pub fn SteamAPI_RegisterCallResult(pCallback: *mut c_void, api_call: SteamAPICall); - pub fn SteamAPI_UnregisterCallResult(pCallback: *mut c_void, api_call: SteamAPICall); + pub fn SteamAPI_RegisterCallResult(pCallback: *mut c_void, api_call: SteamAPICall_t); + pub fn SteamAPI_UnregisterCallResult(pCallback: *mut c_void, api_call: SteamAPICall_t); pub fn SteamAPI_RestartAppIfNecessary(app_id: u32) -> u8; pub fn SteamGameServer_Shutdown(); @@ -84,74 +90,74 @@ extern "C" { pub fn SteamAPI_ISteamClient_BReleaseSteamPipe(instance: *mut ISteamClient, pipe: HSteamPipe) -> u8; pub fn SteamAPI_ISteamClient_ConnectToGlobalUser(instance: *mut ISteamClient, pipe: HSteamPipe) -> HSteamUser; - pub fn SteamAPI_ISteamUtils_GetAppID(instance: *mut ISteamUtils) -> u32; + pub fn SteamAPI_ISteamUtils_GetAppID(instance: *mut ISteamUtils) -> AppId_t; pub fn SteamAPI_ISteamUtils_GetSteamUILanguage(instance: *mut ISteamUtils) -> *const c_char; - pub fn SteamAPI_ISteamUtils_IsAPICallCompleted(instance: *mut ISteamUtils, api_call: SteamAPICall, failed: *mut bool) -> u8; + pub fn SteamAPI_ISteamUtils_IsAPICallCompleted(instance: *mut ISteamUtils, api_call: SteamAPICall_t, failed: *mut bool) -> u8; pub fn SteamAPI_ISteamUtils_SetOverlayNotificationPosition(instance: *mut ISteamUtils, position: ENotificationPosition); pub fn SteamAPI_ISteamUtils_GetImageSize(instance: *mut ISteamUtils, image: c_int, width: *mut u32, height: *mut u32) -> u8; pub fn SteamAPI_ISteamUtils_GetImageRGBA(instance: *mut ISteamUtils, image: c_int, dest: *mut u8, dest_size: c_int) -> u8; - pub fn SteamAPI_ISteamApps_BIsAppInstalled(instance: *mut ISteamApps, app_id: AppId) -> u8; - pub fn SteamAPI_ISteamApps_BIsDlcInstalled(instance: *mut ISteamApps, app_id: AppId) -> u8; - pub fn SteamAPI_ISteamApps_BIsSubscribedApp(instance: *mut ISteamApps, app_id: AppId) -> u8; + pub fn SteamAPI_ISteamApps_BIsAppInstalled(instance: *mut ISteamApps, app_id: AppId_t) -> u8; + pub fn SteamAPI_ISteamApps_BIsDlcInstalled(instance: *mut ISteamApps, app_id: AppId_t) -> u8; + pub fn SteamAPI_ISteamApps_BIsSubscribedApp(instance: *mut ISteamApps, app_id: AppId_t) -> u8; pub fn SteamAPI_ISteamApps_BIsSubscribedFromFreeWeekend(instance: *mut ISteamApps) -> u8; pub fn SteamAPI_ISteamApps_BIsVACBanned(instance: *mut ISteamApps) -> u8; pub fn SteamAPI_ISteamApps_BIsCybercafe(instance: *mut ISteamApps) -> u8; pub fn SteamAPI_ISteamApps_BIsLowViolence(instance: *mut ISteamApps) -> u8; pub fn SteamAPI_ISteamApps_BIsSubscribed(instance: *mut ISteamApps) -> u8; pub fn SteamAPI_ISteamApps_GetAppBuildId(instance: *mut ISteamApps) -> c_int; - pub fn SteamAPI_ISteamApps_GetAppInstallDir(instance: *mut ISteamApps, app_id: AppId, folder: *const c_char, buffer_size: u32) -> u32; - pub fn SteamAPI_ISteamApps_GetAppOwner(instance: *mut ISteamApps) -> u64; + pub fn SteamAPI_ISteamApps_GetAppInstallDir(instance: *mut ISteamApps, app_id: AppId_t, folder: *const c_char, buffer_size: u32) -> u32; + pub fn SteamAPI_ISteamApps_GetAppOwner(instance: *mut ISteamApps) -> CSteamID; pub fn SteamAPI_ISteamApps_GetAvailableGameLanguages(instance: *mut ISteamApps) -> *const c_char; pub fn SteamAPI_ISteamApps_GetCurrentBetaName(instance: *mut ISteamApps, name: *const c_char, buffer_size: c_int) -> u8; pub fn SteamAPI_ISteamApps_GetCurrentGameLanguage(instance: *mut ISteamApps) -> *const c_char; pub fn SteamAPI_ISteamFriends_GetFriendCount(instance: *mut ISteamFriends, flags: c_int) -> c_int; - pub fn SteamAPI_ISteamFriends_GetFriendByIndex(instance: *mut ISteamFriends, friend: c_int, flags: c_int) -> u64; - pub fn SteamAPI_ISteamFriends_GetFriendPersonaName(instance: *mut ISteamFriends, friend: u64) -> *const c_char; - pub fn SteamAPI_ISteamFriends_GetFriendPersonaState(instance: *mut ISteamFriends, friend: u64) -> EPersonaState; - pub fn SteamAPI_ISteamFriends_RequestUserInformation(instance: *mut ISteamFriends, user_id: u64, name_only: u8) -> u8; + pub fn SteamAPI_ISteamFriends_GetFriendByIndex(instance: *mut ISteamFriends, friend: c_int, flags: c_int) -> CSteamID; + pub fn SteamAPI_ISteamFriends_GetFriendPersonaName(instance: *mut ISteamFriends, friend: CSteamID) -> *const c_char; + pub fn SteamAPI_ISteamFriends_GetFriendPersonaState(instance: *mut ISteamFriends, friend: CSteamID) -> EPersonaState; + pub fn SteamAPI_ISteamFriends_RequestUserInformation(instance: *mut ISteamFriends, user_id: CSteamID, name_only: u8) -> u8; pub fn SteamAPI_ISteamFriends_ActivateGameOverlayToWebPage(instance: *mut ISteamFriends, url: *const c_char); pub fn SteamAPI_ISteamFriends_GetPersonaName(instance: *mut ISteamFriends) -> *const c_char; - pub fn SteamAPI_ISteamFriends_ActivateGameOverlayInviteDialog(instance: *mut ISteamFriends, lobby: u64); - pub fn SteamAPI_ISteamFriends_GetSmallFriendAvatar(instance: *mut ISteamFriends, friend: u64) -> c_int; - pub fn SteamAPI_ISteamFriends_GetMediumFriendAvatar(instance: *mut ISteamFriends, friend: u64) -> c_int; - pub fn SteamAPI_ISteamFriends_GetFriendGamePlayed(instance: *mut ISteamFriends, friend: u64, game_info: *mut FriendGameInfo_t) -> u8; - - pub fn SteamAPI_ISteamMatchmaking_CreateLobby(instance: *mut ISteamMatchmaking, lobby_ty: ELobbyType, max_members: c_int) -> SteamAPICall; - pub fn SteamAPI_ISteamMatchmaking_RequestLobbyList(instance: *mut ISteamMatchmaking) -> SteamAPICall; - pub fn SteamAPI_ISteamMatchmaking_GetLobbyByIndex(instance: *mut ISteamMatchmaking, lobby: c_int) -> u64; - pub fn SteamAPI_ISteamMatchmaking_LeaveLobby(instance: *mut ISteamMatchmaking, lobby: u64); - pub fn SteamAPI_ISteamMatchmaking_JoinLobby(instance: *mut ISteamMatchmaking, lobby: u64) -> SteamAPICall; - pub fn SteamAPI_ISteamMatchmaking_GetLobbyOwner(instance: *mut ISteamMatchmaking, lobby: u64) -> u64; - pub fn SteamAPI_ISteamMatchmaking_GetNumLobbyMembers(instance: *mut ISteamMatchmaking, lobby: u64) -> c_int; - pub fn SteamAPI_ISteamMatchmaking_GetLobbyMemberByIndex(instance: *mut ISteamMatchmaking, lobby: u64, member: c_int) -> u64; - - pub fn SteamAPI_ISteamNetworking_AcceptP2PSessionWithUser(instance: *mut ISteamNetworking, remote: u64) -> u8; - pub fn SteamAPI_ISteamNetworking_CloseP2PSessionWithUser(instance: *mut ISteamNetworking, remote: u64) -> u8; - pub fn SteamAPI_ISteamNetworking_SendP2PPacket(instance: *mut ISteamNetworking, remote: u64, data: *const c_void, data_len: u32, send_type: EP2PSend, channel: c_int) -> u8; + pub fn SteamAPI_ISteamFriends_ActivateGameOverlayInviteDialog(instance: *mut ISteamFriends, lobby: CSteamID); + pub fn SteamAPI_ISteamFriends_GetSmallFriendAvatar(instance: *mut ISteamFriends, friend: CSteamID) -> c_int; + pub fn SteamAPI_ISteamFriends_GetMediumFriendAvatar(instance: *mut ISteamFriends, friend: CSteamID) -> c_int; + pub fn SteamAPI_ISteamFriends_GetFriendGamePlayed(instance: *mut ISteamFriends, friend: CSteamID, game_info: *mut FriendGameInfo_t) -> u8; + + pub fn SteamAPI_ISteamMatchmaking_CreateLobby(instance: *mut ISteamMatchmaking, lobby_ty: ELobbyType, max_members: c_int) -> SteamAPICall_t; + pub fn SteamAPI_ISteamMatchmaking_RequestLobbyList(instance: *mut ISteamMatchmaking) -> SteamAPICall_t; + pub fn SteamAPI_ISteamMatchmaking_GetLobbyByIndex(instance: *mut ISteamMatchmaking, lobby: c_int) -> CSteamID; + pub fn SteamAPI_ISteamMatchmaking_LeaveLobby(instance: *mut ISteamMatchmaking, lobby: CSteamID); + pub fn SteamAPI_ISteamMatchmaking_JoinLobby(instance: *mut ISteamMatchmaking, lobby: CSteamID) -> SteamAPICall_t; + pub fn SteamAPI_ISteamMatchmaking_GetLobbyOwner(instance: *mut ISteamMatchmaking, lobby: CSteamID) -> CSteamID; + pub fn SteamAPI_ISteamMatchmaking_GetNumLobbyMembers(instance: *mut ISteamMatchmaking, lobby: CSteamID) -> c_int; + pub fn SteamAPI_ISteamMatchmaking_GetLobbyMemberByIndex(instance: *mut ISteamMatchmaking, lobby: CSteamID, member: c_int) -> CSteamID; + + pub fn SteamAPI_ISteamNetworking_AcceptP2PSessionWithUser(instance: *mut ISteamNetworking, remote: CSteamID) -> u8; + pub fn SteamAPI_ISteamNetworking_CloseP2PSessionWithUser(instance: *mut ISteamNetworking, remote: CSteamID) -> u8; + pub fn SteamAPI_ISteamNetworking_SendP2PPacket(instance: *mut ISteamNetworking, remote: CSteamID, data: *const c_void, data_len: u32, send_type: EP2PSend, channel: c_int) -> u8; pub fn SteamAPI_ISteamNetworking_IsP2PPacketAvailable(instance: *mut ISteamNetworking, msg_size: *mut u32, channel: c_int) -> u8; - pub fn SteamAPI_ISteamNetworking_ReadP2PPacket(instance: *mut ISteamNetworking, data: *mut c_void, data_len: u32, msg_size: *mut u32, remote: *mut u64, channel: c_int) -> u8; + pub fn SteamAPI_ISteamNetworking_ReadP2PPacket(instance: *mut ISteamNetworking, data: *mut c_void, data_len: u32, msg_size: *mut u32, remote: *mut CSteamID, channel: c_int) -> u8; - pub fn SteamAPI_ISteamUser_GetSteamID(instance: *mut ISteamUser) -> u64; + pub fn SteamAPI_ISteamUser_GetSteamID(instance: *mut ISteamUser) -> CSteamID; pub fn SteamAPI_ISteamUser_GetAuthSessionTicket(instance: *mut ISteamUser, ticket: *mut c_void, max_ticket: c_int, ticket_size: *mut u32) -> HAuthTicket; - pub fn SteamAPI_ISteamUser_BeginAuthSession(instance: *mut ISteamUser, ticket: *const c_void, ticket_size: *mut u32, steam_id: u64) -> EBeginAuthSessionResult; - pub fn SteamAPI_ISteamUser_EndAuthSession(instance: *mut ISteamUser, steam_id: u64); + pub fn SteamAPI_ISteamUser_BeginAuthSession(instance: *mut ISteamUser, ticket: *const c_void, ticket_size: *mut u32, steam_id: CSteamID) -> EBeginAuthSessionResult; + pub fn SteamAPI_ISteamUser_EndAuthSession(instance: *mut ISteamUser, steam_id: CSteamID); pub fn SteamAPI_ISteamUser_CancelAuthTicket(instance: *mut ISteamUser, auth_ticket: HAuthTicket); - pub fn SteamAPI_ISteamUserStats_FindLeaderboard(instance: *mut ISteamUserStats, name: *const c_char) -> SteamAPICall; - pub fn SteamAPI_ISteamUserStats_FindOrCreateLeaderboard(instance: *mut ISteamUserStats, name: *const c_char, sort_method: ELeaderboardSortMethod, display_type: ELeaderboardDisplayType) -> SteamAPICall; - pub fn SteamAPI_ISteamUserStats_UploadLeaderboardScore(instance: *mut ISteamUserStats, leaderboard: u64, method: ELeaderboardUploadScoreMethod, score: i32, details: *const i32, details_count: c_int) -> SteamAPICall; - pub fn SteamAPI_ISteamUserStats_DownloadLeaderboardEntries(instance: *mut ISteamUserStats, leaderboard: u64, data_request: ELeaderboardDataRequest, start: c_int, end: c_int) -> SteamAPICall; + pub fn SteamAPI_ISteamUserStats_FindLeaderboard(instance: *mut ISteamUserStats, name: *const c_char) -> SteamAPICall_t; + pub fn SteamAPI_ISteamUserStats_FindOrCreateLeaderboard(instance: *mut ISteamUserStats, name: *const c_char, sort_method: ELeaderboardSortMethod, display_type: ELeaderboardDisplayType) -> SteamAPICall_t; + pub fn SteamAPI_ISteamUserStats_UploadLeaderboardScore(instance: *mut ISteamUserStats, leaderboard: SteamLeaderboard_t, method: ELeaderboardUploadScoreMethod, score: i32, details: *const i32, details_count: c_int) -> SteamAPICall_t; + pub fn SteamAPI_ISteamUserStats_DownloadLeaderboardEntries(instance: *mut ISteamUserStats, leaderboard: SteamLeaderboard_t, data_request: ELeaderboardDataRequest, start: c_int, end: c_int) -> SteamAPICall_t; pub fn SteamAPI_ISteamUserStats_GetDownloadedLeaderboardEntry(instance: *mut ISteamUserStats, entries: SteamLeaderboardEntries_t, index: c_int, entry: *mut LeaderboardEntry_t, details: *mut i32, details_max: c_int) -> u8; pub fn SteamAPI_ISteamGameServer_LogOnAnonymous(instance: *mut ISteamGameServer); pub fn SteamAPI_ISteamGameServer_SetProduct(instance: *mut ISteamGameServer, product: *const c_char); pub fn SteamAPI_ISteamGameServer_SetGameDescription(instance: *mut ISteamGameServer, description: *const c_char); pub fn SteamAPI_ISteamGameServer_SetDedicatedServer(instance: *mut ISteamGameServer, dedicated: u8); - pub fn SteamAPI_ISteamGameServer_GetSteamID(instance: *mut ISteamGameServer) -> u64; + pub fn SteamAPI_ISteamGameServer_GetSteamID(instance: *mut ISteamGameServer) -> CSteamID; pub fn SteamAPI_ISteamGameServer_GetAuthSessionTicket(instance: *mut ISteamGameServer, ticket: *mut c_void, max_ticket: c_int, ticket_size: *mut u32) -> HAuthTicket; - pub fn SteamAPI_ISteamGameServer_BeginAuthSession(instance: *mut ISteamGameServer, ticket: *const c_void, ticket_size: *mut u32, steam_id: u64) -> EBeginAuthSessionResult; - pub fn SteamAPI_ISteamGameServer_EndAuthSession(instance: *mut ISteamGameServer, steam_id: u64); + pub fn SteamAPI_ISteamGameServer_BeginAuthSession(instance: *mut ISteamGameServer, ticket: *const c_void, ticket_size: *mut u32, steam_id: CSteamID) -> EBeginAuthSessionResult; + pub fn SteamAPI_ISteamGameServer_EndAuthSession(instance: *mut ISteamGameServer, steam_id: CSteamID); pub fn SteamAPI_ISteamGameServer_CancelAuthTicket(instance: *mut ISteamGameServer, auth_ticket: HAuthTicket); -} +}
\ No newline at end of file |