This commit is contained in:
Даниил Заикин
2026-06-17 20:44:53 +03:00
parent 9d153773c2
commit b133e7c656
1880 changed files with 244545 additions and 0 deletions
@@ -0,0 +1,215 @@
using System;
using UnityEngine;
using Blocks.Common;
using Unity.Properties;
using UnityEngine.UIElements;
using Blocks.Sessions.Common;
using Unity.Services.Multiplayer;
using System.Collections.Generic;
namespace Blocks.Sessions
{
[UxmlElement]
public partial class SessionBrowserElement : ListView
{
private const string k_JoinButtonText = "JOIN";
private const string k_RefreshButtonText = "REFRESH LIST";
private const string k_NoSessionFoundText = "No sessions found";
private const string k_SessionNameLabel = "SessionNameLabel";
private const string k_SessionPlayerCountLabel = "SessionPlayerCountLabel";
private int m_MaxSessionsDisplayed = 20;
private SessionSettings m_SessionSettings;
private SessionBrowserViewModel m_ViewModel;
private List<DataBinding> m_DataBindings;
private Button m_RefreshButton;
private Button m_JoinSessionButton;
[CreateProperty, UxmlAttribute]
public SessionSettings SessionSettings
{
get => m_SessionSettings;
set
{
if (m_SessionSettings == value)
return;
m_SessionSettings = value;
if (panel != null)
{
UpdateBindingSources();
}
}
}
[CreateProperty, UxmlAttribute]
public int MaxSessionsDisplayed
{
get => m_MaxSessionsDisplayed;
set => m_MaxSessionsDisplayed = value;
}
public SessionBrowserElement()
{
virtualizationMethod = CollectionVirtualizationMethod.FixedHeight;
fixedItemHeight = 56f;
// required for making each element inheriting an indexed array item for the data source path
// if not set, you need to specify the datasource path manually in the bindItem callback for each item
bindingSourceSelectionMode = BindingSourceSelectionMode.AutoAssign;
AddToClassList(BlocksTheme.ScrollView);
AddToClassList(BlocksTheme.SpaceBottom);
makeNoneElement = MakeNoneElement;
makeItem = MakeDefaultItem;
makeFooter = MakeFooter;
RegisterCallback<AttachToPanelEvent>(OnAttachToPanelEvent);
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanelEvent);
}
private VisualElement MakeFooter()
{
var buttonsContainer = new VisualElement();
buttonsContainer.AddToClassList(BlocksTheme.ContainerHorizontal);
buttonsContainer.AddToClassList(BlocksTheme.ContainerAlignedRight);
m_JoinSessionButton = new Button { text = k_JoinButtonText };
m_JoinSessionButton.AddToClassList(BlocksTheme.Button);
m_JoinSessionButton.AddToClassList(BlocksTheme.SpaceRight);
buttonsContainer.Add(m_JoinSessionButton);
m_RefreshButton = new Button { text = k_RefreshButtonText };
m_RefreshButton.AddToClassList(BlocksTheme.Button);
buttonsContainer.Add(m_RefreshButton);
return buttonsContainer;
}
private void OnRefreshButtonClicked()
{
ClearSelection();
// fire and forget, so we don't block the UI thread
_ = m_ViewModel?.UpdateSessionListAsync(MaxSessionsDisplayed);
}
private void JoinSession()
{
if (!m_ViewModel.SelectedAndAvailable)
{
Debug.LogError("Selected session is no longer selected.");
return;
}
// fire and forget, so we don't block the UI thread
_ = m_ViewModel.JoinSessionAsync(SessionSettings.ToJoinSessionOptions());
}
private void UpdateBindingSources()
{
CleanupBindings();
m_ViewModel = new SessionBrowserViewModel(SessionSettings?.sessionType);
foreach (var dataBinding in m_DataBindings)
{
dataBinding.dataSource = m_ViewModel;
}
}
private void CleanupBindings()
{
m_ViewModel?.Dispose();
m_ViewModel = null;
foreach (var dataBinding in m_DataBindings)
{
dataBinding.dataSource = null;
}
}
private void OnDetachFromPanelEvent(DetachFromPanelEvent evt)
{
CleanupBindings();
m_RefreshButton.clicked -= OnRefreshButtonClicked;
m_RefreshButton.ClearBinding(nameof(SessionBrowserViewModel.CanRefresh));
m_JoinSessionButton.clicked -= JoinSession;
m_JoinSessionButton.ClearBinding(nameof(enabledSelf));
ClearBindings();
}
private void OnAttachToPanelEvent(AttachToPanelEvent evt)
{
m_DataBindings = new List<DataBinding>();
var listBinding = new DataBinding { dataSourcePath = new PropertyPath(nameof(SessionBrowserViewModel.Sessions)), bindingMode = BindingMode.ToTarget };
SetBinding(new BindingId(nameof(ListView.itemsSource)), listBinding);
m_DataBindings.Add(listBinding);
var selectionBinding = new DataBinding { dataSourcePath = new PropertyPath(nameof(SessionBrowserViewModel.SelectedSessionIndex)), bindingMode = BindingMode.TwoWay };
SetBinding(new BindingId(nameof(ListView.selectedIndex)), selectionBinding);
m_DataBindings.Add(selectionBinding);
var joinSessionBinding = new DataBinding { dataSourcePath = new PropertyPath(nameof(SessionBrowserViewModel.SelectedAndAvailable)), bindingMode = BindingMode.ToTarget };
m_JoinSessionButton.SetBinding(new BindingId(nameof(enabledSelf)), joinSessionBinding);
m_DataBindings.Add(joinSessionBinding);
m_JoinSessionButton.clicked += JoinSession;
var refreshBinding = new DataBinding { dataSourcePath = new PropertyPath(nameof(SessionBrowserViewModel.CanRefresh)), bindingMode = BindingMode.ToTarget };
m_RefreshButton.SetBinding(new BindingId(nameof(enabledSelf)), refreshBinding);
m_DataBindings.Add(refreshBinding);
m_RefreshButton.clicked += OnRefreshButtonClicked;
UpdateBindingSources();
}
private static VisualElement MakeNoneElement()
{
var label = new Label(k_NoSessionFoundText);
label.AddToClassList(BlocksTheme.Label);
label.AddToClassList(BlocksTheme.SpaceLeft);
return label;
}
private static VisualElement MakeDefaultItem()
{
var container = new VisualElement();
container.AddToClassList(BlocksTheme.ContainerHorizontal);
container.AddToClassList(BlocksTheme.ScrollViewElement);
container.AddToClassList(BlocksTheme.ContainerSpaceBetween);
var sessionNameLabel = new Label { name = k_SessionNameLabel };
sessionNameLabel.AddToClassList(BlocksTheme.Label);
sessionNameLabel.AddToClassList(BlocksTheme.SpaceLeft);
container.Add(sessionNameLabel);
var db = new DataBinding
{
dataSourcePath = PropertyPath.FromName(nameof(SessionInfoViewModel.Name)),
bindingMode = BindingMode.ToTarget,
updateTrigger = BindingUpdateTrigger.OnSourceChanged
};
sessionNameLabel.SetBinding(nameof(Label.text), db);
var sessionPlayerCountLabel = new Label { name = k_SessionPlayerCountLabel };
sessionPlayerCountLabel.AddToClassList(BlocksTheme.Label);
sessionPlayerCountLabel.AddToClassList(BlocksTheme.SpaceRight);
container.Add(sessionPlayerCountLabel);
var sessionPlayerCountBinding = new DataBinding { bindingMode = BindingMode.ToTarget };
// register a local converter to display relevant session properties as a formatted string
sessionPlayerCountBinding.sourceToUiConverters
.AddConverter((ref SessionInfoViewModel session) => $"{session.MaxPlayers - session.AvailableSlots}/{session.MaxPlayers} Players");
sessionPlayerCountLabel.SetBinding(nameof(Label.text), sessionPlayerCountBinding);
return container;
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 203f2c9355eb4514f9062db88d0512e1
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/SessionBrowser/SessionBrowserElement.cs
uploadId: 814574
@@ -0,0 +1,274 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Unity.Properties;
using Unity.Services.Core;
using Unity.Services.Multiplayer;
using UnityEngine;
using UnityEngine.UIElements;
namespace Blocks.Sessions
{
public class SessionBrowserViewModel : INotifyBindablePropertyChanged, IDataSourceViewHashProvider, IDisposable
{
private SessionObserver m_SessionObserver;
private ServiceObserver<IMultiplayerService> m_ServiceObserver;
private long m_UpdateVersion;
private bool m_SelectedAndAvailable;
private bool m_CanRefresh;
private int m_SelectedSessionIndex;
private ISession m_Session;
private List<SessionInfoViewModel> m_Sessions;
[CreateProperty]
public List<SessionInfoViewModel> Sessions
{
get => m_Sessions;
set
{
if (m_Sessions == value)
{
return;
}
m_Sessions = value;
++m_UpdateVersion;
Notify();
}
}
[CreateProperty]
public int SelectedSessionIndex
{
get => m_SelectedSessionIndex;
set
{
if (value >= 0 && value < Sessions.Count)
{
m_SelectedSessionIndex = value;
SelectedAndAvailable = true;
}
else
{
SelectedAndAvailable = false;
}
}
}
public string GetSelectedSessionId()
{
if (SelectedSessionIndex >= 0 && SelectedSessionIndex < Sessions.Count)
{
return Sessions[SelectedSessionIndex].Id;
}
return null;
}
[CreateProperty]
public bool SelectedAndAvailable
{
get => m_SelectedAndAvailable;
set
{
var newValue = value;
if (value && m_Session != null && m_Session.Id == GetSelectedSessionId())
{
newValue = false;
}
if (m_SelectedAndAvailable != newValue)
{
m_SelectedAndAvailable = newValue;
++m_UpdateVersion;
Notify();
}
}
}
[CreateProperty]
public bool CanRefresh
{
get => m_CanRefresh;
set
{
if (m_CanRefresh == value)
{
return;
}
m_CanRefresh = value;
++m_UpdateVersion;
Notify();
}
}
public SessionBrowserViewModel(string sessionType)
{
Sessions = new List<SessionInfoViewModel>();
m_SessionObserver = new SessionObserver(sessionType);
m_SessionObserver.SessionAdded += OnSessionAdded;
if (m_SessionObserver.Session != null)
{
OnSessionAdded(m_SessionObserver.Session);
}
// This can be null while in edit mode and needs to be checked before creating the Observer.
if (UnityServices.Instance != null)
{
m_ServiceObserver = new ServiceObserver<IMultiplayerService>();
if (m_ServiceObserver.Service != null)
{
CanRefresh = true;
}
else
{
CanRefresh = false;
m_ServiceObserver.Initialized += OnServicesInitialized;
}
}
}
public async Task JoinSessionAsync(JoinSessionOptions options)
{
try
{
await MultiplayerService.Instance.JoinSessionByIdAsync(GetSelectedSessionId(), options);
}
catch (Exception exception)
{
Debug.LogException(exception);
}
}
void OnServicesInitialized(IMultiplayerService service)
{
m_ServiceObserver.Initialized -= OnServicesInitialized;
CanRefresh = true;
}
internal async Task UpdateSessionListAsync(int numberOfMaxSessions)
{
// if there is no connection to MultiplayerService, do not try to refresh
if (!CanRefresh)
{
Debug.LogWarning("Cannot refresh session list." +
"Multiplayer Services are not initialized." +
"You can initialize them with default settings by adding a " +
"ServicesInitialization and PlayerAuthentication components in your scene.");
return;
}
try
{
CanRefresh = false;
var queryResult = await MultiplayerService.Instance
.QuerySessionsAsync(new QuerySessionsOptions
{
SortOptions = new List<SortOption>
{
new (SortOrder.Descending,SortField.Name)
}
});
// properly dispose the sessionInfo view models first
foreach (var session in Sessions)
{
session.Dispose();
}
Sessions.Clear();
for (var i = 0; (i < Math.Min(queryResult.Sessions.Count, numberOfMaxSessions)); i++)
{
Sessions.Add(new SessionInfoViewModel(queryResult.Sessions[i]));
}
++m_UpdateVersion;
CanRefresh = true;
// reset selection
SelectedSessionIndex = -1;
}
catch (Exception ex)
{
Debug.LogError($"Failed to update session list: {ex.Message}");
}
}
private void OnSessionAdded(ISession newSession)
{
m_Session = newSession;
m_Session.RemovedFromSession += OnSessionRemoved;
m_Session.Deleted += OnSessionRemoved;
if (m_Session.Id == GetSelectedSessionId())
{
SelectedAndAvailable = false;
}
}
private void OnSessionRemoved()
{
var lastSessionId = m_Session.Id;
CleanupSession();
if (lastSessionId == GetSelectedSessionId())
{
SelectedAndAvailable = true;
}
}
private void CleanupSession()
{
m_Session.RemovedFromSession -= OnSessionRemoved;
m_Session.Deleted -= OnSessionRemoved;
m_Session = null;
}
public async Task<ISession> JoinSessionByIdAsync(JoinSessionOptions joinSessionOptions)
{
return await MultiplayerService.Instance.JoinSessionByIdAsync(GetSelectedSessionId(), joinSessionOptions);
}
public void Dispose()
{
if (m_SessionObserver != null)
{
m_SessionObserver.SessionAdded -= OnSessionAdded;
m_SessionObserver.Dispose();
m_SessionObserver = null;
}
if (m_ServiceObserver != null)
{
m_ServiceObserver.Dispose();
m_ServiceObserver = null;
}
if (m_Session != null)
{
CleanupSession();
}
}
/// <summary>
/// This method is used by UIToolkit to determine if any data bound to the UI has changed.
/// Instead of hashing the data, an m_UpdateVersion counter is incremented when changes occur.
/// </summary>
public long GetViewHashCode() => m_UpdateVersion;
/// <summary>
/// Suggested implementation of INotifyBindablePropertyChanged from UIToolkit.
/// </summary>
public event EventHandler<BindablePropertyChangedEventArgs> propertyChanged;
private void Notify([CallerMemberName] string property = null)
{
propertyChanged?.Invoke(this, new BindablePropertyChangedEventArgs(property));
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: fbab5cc94e2a7ab4cad1d3a5f9174b61
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/SessionBrowser/SessionBrowserViewModel.cs
uploadId: 814574
@@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.Properties;
using Unity.Services.Multiplayer;
using UnityEngine.UIElements;
namespace Blocks.Sessions
{
/// <summary>
/// Provides a DataBinding compatible representation of a <c>Session</c> associated information.
/// </summary>
public class SessionInfoViewModel : ISessionInfo,
INotifyBindablePropertyChanged, IDataSourceViewHashProvider, IDisposable
{
private const string k_Unavailalble = "N/A";
private ISession _session;
private ISessionInfo _sessionInfo;
private long _updateVersion;
public SessionInfoViewModel(ISessionInfo sessionInfo)
{
_sessionInfo = sessionInfo;
}
public SessionInfoViewModel(ISession session)
{
_session = session;
_session.Changed += OnSessionChanged;
_session.SessionHostChanged += OnSessionHostChanged;
_session.SessionPropertiesChanged += OnSessionPropertiesChanged;
// should we attempt to query the associated info?
}
/// <inheritdoc/>
[CreateProperty]
public string Name
=> _sessionInfo?.Name ?? _session?.Name;
/// <inheritdoc/>
[CreateProperty]
public string Id
=> _sessionInfo?.Id ?? _session?.Id;
/// <inheritdoc/>
[CreateProperty]
public string Upid
=> _sessionInfo?.Upid ?? k_Unavailalble;
/// <inheritdoc/>
[CreateProperty]
public string HostId
=> _sessionInfo?.HostId ?? _session?.Host;
/// <inheritdoc/>
[CreateProperty]
public int AvailableSlots
=> _sessionInfo?.AvailableSlots ?? _session?.AvailableSlots ?? 0;
/// <inheritdoc/>
[CreateProperty]
public int MaxPlayers
=> _sessionInfo?.MaxPlayers ?? _session?.MaxPlayers ?? 0;
/// <inheritdoc/>
[CreateProperty]
public bool IsLocked
=> _sessionInfo?.IsLocked ?? _session?.IsLocked ?? true;
/// <inheritdoc/>
[CreateProperty]
public bool HasPassword
=> _sessionInfo?.HasPassword ?? _session?.HasPassword ?? true;
/// <inheritdoc/>
[CreateProperty]
public DateTime LastUpdated
=> _sessionInfo?.LastUpdated ?? DateTime.UnixEpoch;
/// <inheritdoc/>
[CreateProperty]
public DateTime Created
=> _sessionInfo?.Created ?? DateTime.UnixEpoch;
/// <inheritdoc/>
[CreateProperty]
public IReadOnlyDictionary<string, SessionProperty> Properties
=> _sessionInfo?.Properties ?? _session?.Properties;
private void OnSessionHostChanged(string obj)
{
_updateVersion++;
Notify(nameof(HostId));
}
private void OnSessionPropertiesChanged()
{
_updateVersion++;
Notify(nameof(Properties));
}
private void OnSessionChanged()
{
_updateVersion++;
Notify(nameof(Name));
Notify(nameof(LastUpdated));
Notify(nameof(HasPassword));
Notify(nameof(IsLocked));
Notify(nameof(MaxPlayers));
Notify(nameof(AvailableSlots));
}
public void Dispose()
{
if (_session != null)
{
_session.Changed -= OnSessionChanged;
_session.SessionHostChanged -= OnSessionHostChanged;
_session.SessionPropertiesChanged -= OnSessionPropertiesChanged;
}
_session = null;
_sessionInfo = null;
}
/// <summary>
/// This method is used by UIToolkit to determine if any data bound to the UI has changed.
/// Instead of hashing the data, an m_UpdateVersion counter is incremented when changes occur.
/// </summary>
public long GetViewHashCode() => _updateVersion;
/// <summary>
/// Suggested implementation of INotifyBindablePropertyChanged from UIToolkit.
/// </summary>
public event EventHandler<BindablePropertyChangedEventArgs> propertyChanged;
private void Notify([CallerMemberName] string property = null)
{
propertyChanged?.Invoke(this, new BindablePropertyChangedEventArgs(property));
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: e83d0589eebc4c059679b6f84b0775af
timeCreated: 1761317686
AssetOrigin:
serializedVersion: 1
productId: 341930
packageName: Unity Building Block - Multiplayer Session
packageVersion: 1.0
assetPath: Assets/Blocks/MultiplayerSession/Runtime/SessionBrowser/SessionInfoViewModel.cs
uploadId: 814574