Exemplo n.º 1
0
        // "main" scene constructor. The constructor is called by the server when the scene is created.
        //
        public Main(ISceneHost scene)
        {
            _scene = scene;
            _env = _scene.GetComponent<IEnvironment>();
            _log = _scene.GetComponent<ILogger>();
            _log.Debug("server", "starting configuration");

            // we configure the functions that will be called by the Connecting, Connected and Disconnected events.
            // Connecting is called when a client tries to connect to the server. Please use this event to prevent player form accessing the server.
            // Connected is called when a client is already connected.
            // Disconnected is called when a client is already disconnected.
            _scene.Connecting.Add(OnConnecting);
            _scene.Connected.Add(OnConnected);
            _scene.Disconnected.Add(OnDisconnect);

            // We configure the routes and procedure the client can use.
            // A route is used for "one-shot" messages that don't need response such as position updates.
            // Produres send a response to the client. It's better to use them when client have to wait for a response from the server such as being hit.
            // Procedures use more bandwidth than regular routes.
            //
            // In our case, the server mostly has procedures as the client always needs to wait for a response from the server since it controls the game.
            _scene.AddProcedure("play", OnPlay);
            _scene.AddProcedure("click", OnClick);
            _scene.AddProcedure("update_leaderBoard", OnUpdateLeaderBoard);

            // this route is only used by the client to disconnect from the game (not the server) because it doesn't have to wait for the server to stop playing.
            _scene.AddRoute("exit", OnExit);

            //The starting and shutdown event are called when the scene is launched and shut down. these are useful if you need to initiate the server logic or save the game state before going down.
            _scene.Starting.Add(OnStarting);
            _scene.Shuttingdown.Add(OnShutdown);

            _log.Debug("server", "configuration complete");
        }
        public void AdjustScene(ISceneHost scene)
        {
            var steamConfig = scene.GetComponent<IEnvironment>().Configuration.steam;

            //_authenticator = new SteamUserTicketAuthenticator( steamConfig.apiKey, steamConfig.appId);

            _authenticator = new SteamUserTicketAuthenticatorMockup();
        }
 public InterpolatorScene(ISceneHost scene)
 {
     _scene = scene;
     _log = _scene.GetComponent<ILogger>();
     _env = _scene.GetComponent<IEnvironment>();
     Chat = ChatServerExtensions.AddChat(_scene);
     replicator.Init(_scene);
 }
        public Test(ISceneHost scene)
        {
            _scene = scene;
            _scene.GetComponent<ILogger>().Debug("server", "starting configuration");

            _scene.AddProcedure("test_rpc", onTest);
               _scene.GetComponent<ILogger>().Debug("server", "configuration complete");
        }
Exemplo n.º 5
0
 private void SceneCreated(ISceneHost scene)
 {
     if (scene.Template != SCENE_TEMPLATE)
     {
         var index = scene.DependencyResolver.Resolve <UserSessionCache>();
         scene.Connected.Add(index.OnConnected, 1000);
         scene.Disconnected.Add(args => index.OnDisconnected(args.Peer));
     }
 }
 public TurnBasedGame(ISceneHost scene, ILogger logger, IUserSessions sessions, IEnumerable <ITurnBaseGameEventHandler> handlers)
 {
     _scene    = scene;
     _logger   = logger;
     _sessions = sessions;
     _handlers = handlers;
     scene.Connected.Add(OnConnected);
     scene.Disconnected.Add(OnDisconnected);
 }
Exemplo n.º 7
0
        public void Initialize(ISceneHost scene)
        {
            var config = scene.DependencyResolver.Resolve <IConfiguration>();

            logger = scene.DependencyResolver.Resolve <ILogger>();

            config.SettingsChanged += (s, e) => ApplyConfiguration(config);
            ApplyConfiguration(config);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Listen to messages on the specified route, and output instances of T using the scene serializer.
        /// </summary>
        /// <typeparam name="TData">Type into which message contents should be deserialized.</typeparam>
        /// <param name="scene">The scene to listen to.</param>
        /// <param name="route">A string describing the route to listen to.</param>
        /// <returns>An observable instance providing the messages.</returns>
        public static IObservable <TData> OnMessage <TData>(this ISceneHost scene, string route)
        {
            return(scene.OnMessage(route).Select(packet =>
            {
                var value = packet.Serializer().Deserialize <TData>(packet.Stream);

                return value;
            }));
        }
Exemplo n.º 9
0
        public void Initialize(ISceneHost scene)
        {
            var environment = scene.DependencyResolver.Resolve <IEnvironment>();

            _logger = scene.DependencyResolver.Resolve <ILogger>();
            ApplyConfig(environment, scene);

            environment.ConfigurationChanged += (sender, e) => ApplyConfig(environment, scene);
        }
Exemplo n.º 10
0
 public ChatServer(ISceneHost scene)
 {
     _scene = scene;
     _env   = _scene.GetComponent <IEnvironment>();
     _scene.AddProcedure("GetUsersInfos", OnGetUsersInfos);
     _scene.AddRoute("UpdateInfo", OnUpdateInfo);
     _scene.AddRoute("chat", OnMessageReceived);
     _scene.Connected.Add(OnConnected);
     _scene.Disconnected.Add(OnDisconnected);
 }
 public ChatServer(ISceneHost scene)
 {
     _scene = scene;
     _env = _scene.GetComponent<IEnvironment>();
     _scene.AddProcedure("GetUsersInfos", OnGetUsersInfos);
     _scene.AddRoute("UpdateInfo", OnUpdateInfo);
     _scene.AddRoute("chat", OnMessageReceived);
     _scene.Connected.Add(OnConnected);
     _scene.Disconnected.Add(OnDisconnected);
 }
 internal RequestContext(T peer, ISceneHost scene, ushort id, bool ordered, Stream inputStream, CancellationTokenSource cts)
 {
     _cts = cts;
     CancellationToken = cts.Token;
     this._scene       = scene;
     this.id           = id;
     this._ordered     = ordered;
     this._peer        = peer;
     this.InputStream  = inputStream;
 }
Exemplo n.º 13
0
        public bool IsClicked(float player_x, float player_y, long time, ISceneHost scene)
        {
            float dist = 0.3f;

            float updated_x = x + (vx * (time - creationTime) / 1000);
            float updated_y = y + (vy * (time - creationTime) / 1000);

            if (updated_x - dist < player_x && player_x < updated_x + dist && updated_y - dist < player_y && player_y < updated_y + dist)
                return (true);
            return (false);
        }
Exemplo n.º 14
0
 private Task ValidatePseudo(string pseudo, ISceneHost scene)
 {
     if (pseudo == null ||
         pseudo.Length < 3 ||
         pseudo.Length > 15 ||
         !System.Text.RegularExpressions.Regex.IsMatch(pseudo, "^[a-zA-Z0-9_]*$", System.Text.RegularExpressions.RegexOptions.Compiled))
     {
         throw new ClientException("Pseudo not valid");
     }
     return(Task.FromResult(true));
 }
 public void Init(ISceneHost scene)
 {
     _scene = scene;
     _env = _scene.GetComponent<IEnvironment>();
     _log = _scene.GetComponent<ILogger>();
     _scene.AddProcedure("RegisterObject", OnRegisterObject);
     _scene.AddRoute("RemoveObject", OnRemoveObject);
     _scene.AddRoute("UpdateSynchedObject", OnUpdateObject);
     _scene.Connected.Add(OnClientConnected);
     _scene.Disconnected.Add(OnClientDisconnected);
 }
Exemplo n.º 16
0
        /// <summary>
        /// Broadcasts an object to all clients
        /// </summary>
        /// <typeparam name="TData">The type of object to send.</typeparam>
        /// <param name="scene">The scene on which to broadcast.</param>
        /// <param name="route">The target route on the scene peers.</param>
        /// <param name="data">The data that will be serialized then sent.</param>
        /// <param name="priority">The priority level.</param>
        /// <param name="reliability">The reliability level.</param>
        public static void Broadcast <TData>(this ISceneHost scene, string route, TData data, PacketPriority priority = PacketPriority.HIGH_PRIORITY, PacketReliability reliability = PacketReliability.RELIABLE_ORDERED)
        {
            var peersBySerializer = scene.RemotePeers.ToLookup(peer => peer.Serializer().Name);

            foreach (var group in peersBySerializer)
            {
                scene.Send(new MatchArrayFilter(group), route, s =>
                {
                    group.First().Serializer().Serialize(data, s);
                }, priority, reliability);
            }
        }
Exemplo n.º 17
0
        private void SceneDependenciesRegistration(IDependencyBuilder builder, ISceneHost scene)
        {
            string kind;

            if (scene.Metadata.TryGetValue(METADATA_KEY, out kind))
            {
                GameFinderConfig config;
                if (Configs.TryGetValue(kind, out config))
                {
                    config.RegisterDependencies(builder);
                }
            }
        }
Exemplo n.º 18
0
        private void SceneDependenciesRegistration(IDependencyBuilder builder, ISceneHost scene)
        {
            string kind;

            if (scene.Metadata.TryGetValue(METADATA_KEY, out kind))
            {
                MatchmakingConfig config;
                if (Configs.TryGetValue(kind, out config))
                {
                    config.RegisterDependencies(builder);
                }
            }
            builder.Register <MatchmakingService>().As <IMatchmakingService>().InstancePerScene();
        }
Exemplo n.º 19
0
        private async Task ValidateKey(string key, ISceneHost scene)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ClientException("Invalid key");
            }
            var serialsService = scene.DependencyResolver.Resolve <ISerialsService>();
            var sk             = await serialsService.Get(key);

            if (sk == null || sk.Status != KeyStatus.Available)
            {
                throw new ClientException("Invalid key");
            }
        }
Exemplo n.º 20
0
 /// <summary>
 /// Adds a procedure to the scene.
 /// </summary>
 /// <remarks>
 /// Procedures provide an asynchronous request/response pattern on top of scenes using the RPC plugin.
 /// Procedures can be called by remote peers using the `rpc` method. They support multiple partial responses in a single request.
 /// </remarks>
 /// <param name="scene">The scene to add the procedure to.</param>
 /// <param name="route">The route of the procedure</param>
 /// <param name="handler">A method that implement the procedure logic</param>
 /// <param name="ordered">True if order of the partial responses should be preserved when sent to the client, false otherwise.</param>
 public static void AddProcedure(this ISceneHost scene, string route, Func <Stormancer.Plugins.RequestContext <IScenePeerClient>, Task> handler, bool ordered = true)
 {
     scene.Starting.Add(_ =>
     {
         var rpcService = scene.DependencyResolver.Resolve <Stormancer.Plugins.RpcService>();
         scene.DependencyResolver.Resolve <ILogger>().Trace("rpc", $"Adding procedure in starting event'{route}'");
         if (rpcService == null)
         {
             throw new NotSupportedException("RPC plugin not available.");
         }
         rpcService.AddProcedure(route, handler, ordered);
         return(Task.FromResult(true));
     });
 }
        public GameSessionService(
            ISceneHost scene,
            IUserSessions sessions,
            IConfiguration configuration,
            IEnvironment environment,
            IDelegatedTransports pools,
            ILogger logger,
            Func <IEnumerable <IGameSessionEventHandler> > eventHandlers)
        {
            _scene         = scene;
            _sessions      = sessions;
            _configuration = configuration;
            _logger        = logger;
            _environment   = environment;
            _pools         = pools;

            _eventHandlers = eventHandlers;

            scene.Shuttingdown.Add(args =>
            {
                _logger.Log(LogLevel.Trace, "gameserver", $"Shutting down gamesession scene {_scene.Id}.", new { _scene.Id, Port = _port });

                try
                {
                    if (_gameServerProcess != null && !_gameServerProcess.HasExited)
                    {
                        _gameServerProcess.Close();
                        _gameServerProcess = null;
                    }
                }
                catch { }
                finally
                {
                    _portLease?.Dispose();
                }
                _logger.Log(LogLevel.Trace, "gameserver", $"gamesession scene {_scene.Id} shut down.", new
                {
                    _scene.Id,
                    Port = _port
                });

                return(Task.FromResult(true));
            });
            scene.Connecting.Add(this.PeerConnecting);
            scene.Connected.Add(this.PeerConnected);
            scene.Disconnected.Add((args) => this.PeerDisconnecting(args.Peer));
            scene.AddRoute("player.ready", ReceivedReady, _ => _);
            scene.AddRoute("player.faulted", ReceivedFaulted, _ => _);
        }
 public StickyPlatformsServer(ISceneHost scene)
 {
     mScene = scene;
     scene.AddProcedure("joinGame", joinGameProcedure);
     scene.AddProcedure("getPlayerList", ctx =>
     {
         ctx.SendValue(mPlayers.Values.Where(player => player.hp > 0));
         return(Task.FromResult(true));
     });
     scene.Disconnected.Add(onDisconnect);
     scene.AddRoute("spawn", onPlayerSpawn, _ => _);
     scene.AddRoute("updateHp", updateHp, _ => _);
     scene.AddRoute("updatePhysics", updatePhysics, _ => _);
     scene.AddRoute("updateKeys", updateKeys, _ => _);
 }
Exemplo n.º 23
0
 public MatchmakingService(IEnumerable <IMatchmakingDataExtractor> extractors,
                           IMatchmaker matchmaker,
                           IMatchmakingResolver resolver,
                           IUserSessions sessions,
                           //   MatchmakingPeerService peerService,
                           ILogger logger, ISceneHost scene)
 {
     this._extractors = extractors;
     this._matchmaker = matchmaker;
     this._resolver   = resolver;
     this._sessions   = sessions;
     _logger          = logger;
     this._scene      = scene;
     //     _peerService = peerService;
 }
Exemplo n.º 24
0
        public UserSessions(IUserService userService,
                            IPeerUserIndex peerUserIndex,
                            IUserPeerIndex userPeerIndex,
                            IEnumerable <IUserSessionEventHandler> eventHandlers,
                            IEnumerable <IAuthenticationProvider> authProviders,
                            ISceneHost scene, ILogger logger)
        {
            _userService   = userService;
            _peerUserIndex = peerUserIndex;
            _userPeerIndex = userPeerIndex;
            _eventHandlers = eventHandlers;
            _scene         = scene;
            _authProviders = authProviders;

            this.logger = logger;
        }
Exemplo n.º 25
0
        public GameScene(ISceneHost scene)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Diagnostics.Debugger.Break();
            }
            _scene = scene;

            _scene.Connected.Add(OnConnected);
            _scene.Disconnected.Add(OnDisconnected);
            _scene.AddRoute("position.update", OnPositionUpdate);
            _scene.AddProcedure("getShipInfos", OnGetShipInfos);
            _scene.AddProcedure("ship.killCount", OnGetShipKillCount);
            _scene.AddProcedure("skill", UseSkill);
            _scene.Starting.Add(OnStarting);
            _scene.Shuttingdown.Add(OnShutdown);
        }
Exemplo n.º 26
0
        private void ApplyConfig(IEnvironment environment, ISceneHost scene)
        {
            var steamConfig = environment.Configuration.steam;

            _steamService = scene.DependencyResolver.Resolve <ISteamService>();
            if (steamConfig?.usemockup != null && (bool)(steamConfig.usemockup))
            {
                _authenticator = new SteamUserTicketAuthenticatorMockup();
            }
            else
            {
                _authenticator =

                    new SteamUserTicketAuthenticator(_steamService);
            }
            _vacEnabled = steamConfig?.vac != null && (bool)steamConfig.vac;
        }
Exemplo n.º 27
0
        public GameScene(ISceneHost host, World world, PlaybackManager playbackManager, Texture2D turnIndicator, Action <Dictionary <Guid, ShipCommands> > onSubmit)
        {
            _host               = host;
            _turnStart          = world;
            _onSubmit           = onSubmit;
            _playbackManager    = playbackManager;
            this._turnIndicator = turnIndicator;
            _commands           = new Dictionary <Guid, ShipCommands>();

            _submitButton            = new Button(Resources.SubmitButton, Resources.SubmitButtonHover, host.ScreenWidth - 100 - 10, host.ScreenHeight - 70, 100);
            _submitButton.OnMouseUp += OnSubmit;

            _previewButton            = new Button(Resources.PlayButton, Resources.PlayButtonHover, host.ScreenWidth - 100 - 10 - 100 - 10, host.ScreenHeight - 70, 100);
            _previewButton.OnMouseUp += OnPreview;

            _playbackButton            = new Button(Resources.ReplayButton, Resources.ReplayButtonHover, host.ScreenWidth - 100 - 10 - 100 - 10 - 100 - 10, host.ScreenHeight - 70, 100);
            _playbackButton.OnMouseUp += OnPlayback;
        }
Exemplo n.º 28
0
 public AuthenticationService(
     Func <IEnumerable <IAuthenticationEventHandler> > handlers,
     IEnumerable <IAuthenticationProvider> providers,
     UserManagementConfig config,
     IUserService users,
     IUserSessions sessions,
     ILogger logger,
     ISceneHost scene
     )
 {
     _config        = config;
     _logger        = logger;
     _authProviders = providers;
     _users         = users;
     _sessions      = sessions;
     _handlers      = handlers;
     _scene         = scene;
 }
Exemplo n.º 29
0
        public server(ISceneHost scene)
        {
            _scene = scene;
            _scene.GetComponent <ILogger>().Debug("server", "starting configuration");
            _env = _scene.GetComponent <IEnvironment>();
            _scene.Connecting.Add(onConnecting);
            _scene.Connected.Add(onConnected);
            _scene.Disconnected.Add(onDisconnected);

            _scene.AddRoute("enable_action", OnEnableAction);
            _scene.AddRoute("disable_action", OnDisableAction);

            _scene.AddRoute("firing_weapon", onFiringWeapon);
            _scene.AddRoute("chat", onReceivingMessage);

            _scene.Starting.Add(onStarting);
            _scene.Shuttingdown.Add(onShutdown);
            _scene.GetComponent <ILogger>().Debug("server", "configuration complete");
        }
Exemplo n.º 30
0
        void IScene.Attach(ISceneHost host)
        {
            this.Host = host;

            Device device = host.Device;

            if (device == null)
            {
                throw new Exception("Scene host device is null");
            }

            ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Simple.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);

            this.SimpleEffect = new Effect(device, shaderBytes);

            EffectTechnique technique = this.SimpleEffect.GetTechniqueByIndex(0);;
            EffectPass      pass      = technique.GetPassByIndex(0);

            this.VertexLayout = new InputLayout(device, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });

            this.VertexStream = new DataStream(3 * 32, true, true);
            this.VertexStream.WriteRange(new[] {
                new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
            });
            this.VertexStream.Position = 0;

            this.Vertices = new Buffer(device, this.VertexStream, new BufferDescription()
            {
                BindFlags      = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = 3 * 32,
                Usage          = ResourceUsage.Default
            }
                                       );

            device.Flush();
        }
Exemplo n.º 31
0
        public static TesterBehavior AddTesterBehaviorToScene(ISceneHost scene)
        {
            var result = new TesterBehavior(scene);

            scene.Starting.Add(result.OnStarting);

            scene.Connected.Add(result.OnConnected);
            scene.Disconnected.Add(result.OnDisconnected);

            scene.AddRoute("echo", result.OnEcho);
            scene.AddRoute("transfert", result.OnTransfert);
            scene.AddRoute("broadcast", result.OnBroadcast);

            scene.AddProcedure("rpc", result.OnRpc);
            scene.AddProcedure("rpcping", result.OnRpcPing);

            scene.Shuttingdown.Add(result.OnShutDown);

            return result;
        }
Exemplo n.º 32
0
        public static TesterBehavior AddTesterBehaviorToScene(ISceneHost scene)
        {
            var result = new TesterBehavior(scene);

            scene.Starting.Add(result.OnStarting);

            scene.Connected.Add(result.OnConnected);
            scene.Disconnected.Add(result.OnDisconnected);

            scene.AddRoute("echo", result.OnEcho);
            scene.AddRoute("transfert", result.OnTransfert);
            scene.AddRoute("broadcast", result.OnBroadcast);

            scene.AddProcedure("rpc", result.OnRpc);
            scene.AddProcedure("rpcping", result.OnRpcPing);

            scene.Shuttingdown.Add(result.OnShutDown);

            return(result);
        }
Exemplo n.º 33
0
        public  server(ISceneHost scene)
        {
            _scene = scene;
            _scene.GetComponent<ILogger>().Debug("server", "starting configuration");
            _env = _scene.GetComponent<IEnvironment>();
            _scene.Connecting.Add(onConnecting);
            _scene.Connected.Add(onConnected);
            _scene.Disconnected.Add(onDisconnected);

            _scene.AddRoute("enable_action", OnEnableAction);
            _scene.AddRoute("disable_action", OnDisableAction);

            _scene.AddRoute("firing_weapon", onFiringWeapon);
            _scene.AddRoute("chat", onReceivingMessage);

            _scene.Starting.Add(onStarting);
            _scene.Shuttingdown.Add(onShutdown);
            _scene.GetComponent<ILogger>().Debug("server", "configuration complete");

        }
Exemplo n.º 34
0
        private void SceneCreated(ISceneHost scene)
        {
            string kind;

            if (scene.Metadata.TryGetValue(METADATA_KEY, out kind))
            {
                scene.AddController <GameFinderController>();
                var logger = scene.DependencyResolver.Resolve <ILogger>();
                try
                {
                    var gameFinderService = scene.DependencyResolver.Resolve <IGameFinderService>();

                    //Start gameFinder
                    scene.RunTask(gameFinderService.Run);
                }
                catch (Exception ex)
                {
                    logger.Log(LogLevel.Error, "plugins.gameFinder", $"An exception occured when creating scene {scene.Id}.", ex);
                    throw;
                }
            }
        }
Exemplo n.º 35
0
        void IScene.Attach(ISceneHost host)
        {
            this.Host      = host;
            keyboardInput  = new InputDevices.KeyboardInputDevice();
            gamepadInput   = new InputDevices.GamepadInputDevice();
            navigatorInput = new InputDevices.NavigatorInputDevice();

            _device = host.Device;

            if (_device == null)
            {
                throw new Exception("Scene host device is null");
            }

            graphicsDevice = SharpDX.Toolkit.Graphics.GraphicsDevice.New(_device);
            customEffect   = Headset.GetCustomEffect(graphicsDevice);

            MediaDecoder.Instance.OnContentChanged += ContentChanged;

            projectionMatrix = Matrix.PerspectiveFovRH((float)(72f * Math.PI / 180f), (float)16f / 9f, 0.0001f, 50.0f);
            worldMatrix      = Matrix.Identity;

            //primitive = GraphicTools.CreateGeometry(projectionMode, graphicsDevice);

            _device.ImmediateContext.Flush();
            ResetRotation();


            var devices = SharpDX.RawInput.Device.GetDevices();

            devices.ForEach(dev =>
            {
                if (dev.DeviceType == SharpDX.RawInput.DeviceType.Mouse)
                {
                    SharpDX.RawInput.Device.RegisterDevice(SharpDX.Multimedia.UsagePage.Generic, SharpDX.Multimedia.UsageId.GenericMouse, SharpDX.RawInput.DeviceFlags.None, dev.Handle);
                }
                Console.WriteLine($"Scene::Attach DX device: {dev.DeviceName} :: {dev.DeviceType}");
            });
        }
Exemplo n.º 36
0
        /// <summary>
        /// Attaches the host (the DPFcanvas in the window) to this to access its resources
        /// </summary>
        /// <param name="host"></param>
        public void Attach(ISceneHost host)
        {
            try
            {
                this._host = host;

                // Assure that a device is set.
                if (host.Device == null)
                {
                    throw new Exception("Scene host device is null");
                }

                SetupRenderer();
                FSMain.CreateRenderables();

                Initialized = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Exemplo n.º 37
0
        void IScene.Attach(ISceneHost host)
        {
            this.Host = host;

            Device device = host.Device;
            if (device == null)
                throw new Exception("Scene host device is null");

            ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Simple.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
            this.SimpleEffect = new Effect(device, shaderBytes);

            EffectTechnique technique = this.SimpleEffect.GetTechniqueByIndex(0); ;
            EffectPass pass = technique.GetPassByIndex(0);

            this.VertexLayout = new InputLayout(device, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) 
            });

            this.VertexStream = new DataStream(3 * 32, true, true);
            this.VertexStream.WriteRange(new[] {
                new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
            });
            this.VertexStream.Position = 0;

            this.Vertices = new Buffer(device, this.VertexStream, new BufferDescription()
                {
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = 3 * 32,
                    Usage = ResourceUsage.Default
                }
            );

            device.Flush();
        }
Exemplo n.º 38
0
 private void RegisterSceneDependencies(IDependencyBuilder b, ISceneHost scene)
 {
     if (scene.Template == SCENE_TEMPLATE)
     {
         b.Register <UserSessions>().As <IUserSessions>();
         b.Register <UserPeerIndex>().As <IUserPeerIndex>().SingleInstance();
         b.Register <PeerUserIndex>().As <IPeerUserIndex>().SingleInstance();
         b.Register <DeviceIdentifierAuthenticationProvider>().As <IAuthenticationProvider>();
         b.Register <AdminImpersonationAuthenticationProvider>().As <IAuthenticationProvider>();
         b.Register <CredentialsRenewer>().AsSelf().As <IAuthenticationEventHandler>().SingleInstance();
     }
     else
     {
         b.Register <UserSessionsProxy>(dr => new UserSessionsProxy(
                                            dr.Resolve <ISceneHost>(),
                                            dr.Resolve <ISerializer>(),
                                            dr.Resolve <IEnvironment>(),
                                            dr.Resolve <IServiceLocator>(),
                                            dr.Resolve <UserSessionCache>()))
         .As <IUserSessions>().InstancePerRequest();
     }
 }
Exemplo n.º 39
0
        public void Attach(ISceneHost host)
        {
            this.Host = host;

            Device device = host.Device;
            if (device == null)
                throw new Exception("Scene host device is null");

            try
            {
                ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Shaders\\Particle.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
                this.ParticleEffect = new Effect(device, shaderBytes);
            }
            catch
            { }

            try
            {
                ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Shaders\\Shape.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
                this.ShapeEffect = new Effect(device, shaderBytes);
            }
            catch
            { }

            try
            {
                ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Shaders\\Line.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
                this.LineEffect = new Effect(device, shaderBytes);
            }
            catch
            { }

            EffectTechnique technique = this.ParticleEffect.GetTechniqueByIndex(0);
            EffectPass pass = technique.GetPassByIndex(0);

            this.ParticleLayout = new InputLayout(device, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0),
                new InputElement("POSITION", 1, Format.R32G32_Float, 8, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });

            this.ShapeLayout = new InputLayout(device, this.ShapeEffect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0)
            });

            this.LineLayout = new InputLayout(device, this.LineEffect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0)
            });

            ParticleProjection = ParticleEffect.GetVariableByName("Projection").AsVector();
            ParticleCamera = ParticleEffect.GetVariableByName("Camera").AsVector();

            ShapeCamera = ShapeEffect.GetVariableByName("Camera").AsVector();
            ShapeProjection = ShapeEffect.GetVariableByName("Projection").AsVector();
            ShapeColor = ShapeEffect.GetVariableByName("Color").AsVector();
            ShapePosition = ShapeEffect.GetVariableByName("Position").AsVector();

            ParticlePass = ParticleEffect.GetTechniqueByIndex(0).GetPassByIndex(0);
            ShapePass = ShapeEffect.GetTechniqueByIndex(0).GetPassByIndex(0);

            DataStream lines = new DataStream(linesCount * 8, true, true);
            for (int i = 0; i < linesCount; i++)
                lines.Write(new Vector2(-1.0f + (float)i / (float)linesCount * 2.0f, 0));

            lines.Position = 0;

            Disposer.RemoveAndDispose(ref this.LineBuffer);

            this.LineBuffer = new Buffer(device, lines, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = linesCount * 8,
                Usage = ResourceUsage.Default
            });

            Disposer.RemoveAndDispose(ref lines);

            device.Flush();

            Initialized = true;
        }
 public void AdjustScene(ISceneHost scene)
 {
 }
        private async Task CreateAccount(RequestContext<IScenePeerClient> p, ISceneHost scene)
        {
            try
            {
                var userService = scene.GetComponent<IUserService>();
                var rq = p.ReadObject<CreateAccountRequest>();

                scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.provider.loginpassword", "Creating user " + rq.Login + ".", rq.Login);
                ValidateLoginPassword(rq.Login, rq.Password);

                var user = await userService.GetUserByClaim(PROVIDER_NAME, "login", rq.Login);

                if (user != null)
                {
                    scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.provider.loginpassword", "User with login " + rq.Login + " already exists.", rq.Login);

                    throw new ClientException("An user with this login already exist.");
                }

                user = await userService.GetUser(p.RemotePeer);
                if (user == null)
                {
                    try
                    {
                        var uid = PROVIDER_NAME + "-" + rq.Login;
                        user = await userService.CreateUser(uid, JObject.Parse(rq.UserData));
                    }
                    catch (Exception ex)
                    {
                        scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.provider.loginpassword", "Couldn't create user " + rq.Login + ".", ex);

                        throw new ClientException("Couldn't create account : " + ex.Message);
                    }
                }

                var salt = GenerateSaltValue();

                try
                {
                    await userService.AddAuthentication(user, PROVIDER_NAME, JObject.FromObject(new
                    {
                        login = rq.Login,
                        email = rq.Email,
                        salt = salt,
                        password = HashPassword(rq.Password, salt),
                        validated = false,
                    }));
                }
                catch (Exception ex)
                {
                    scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.provider.loginpassword", "Couldn't link account " + rq.Login + ".", ex);

                    throw new ClientException("Couldn't link account : " + ex.Message);
                }

                scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.provider.loginpassword", "Creating user " + rq.Login + ".", rq.Login);
                p.SendValue(new LoginResult
                {
                    Success = true
                });


            }
            catch (Exception ex)
            {
                p.SendValue(new LoginResult { ErrorMsg = ex.Message, Success = false });
            }
        }
Exemplo n.º 42
0
 public static ChatServer AddChat(this ISceneHost scene)
 {
     return(new ChatServer(scene));
 }
Exemplo n.º 43
0
        /// <summary>
        /// Attaches the host (the DPFcanvas in the window) to this to access its resources
        /// </summary>
        /// <param name="host"></param>
        public void Attach(ISceneHost host)
        {
            try
            {
                this._host = host;

                // Assure that a device is set.
                if (host.Device == null)
                    throw new Exception("Scene host device is null");

                SetupRenderer();
                FSMain.CreateRenderables();

                Initialized = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Exemplo n.º 44
0
        public RTypeMainLobby(ISceneHost scene)
        {
            m_scene = scene;
            m_log = m_scene.GetComponent<ILogger>();
            m_env = m_scene.GetComponent<IEnvironment>();
            connectClientAPI();

            m_scene.Connecting.Add(onConnecting);
            m_scene.Connected.Add(onConnected);
            m_scene.Shuttingdown.Add(onShuttingDown);
            m_scene.Disconnected.Add(onDisconnected);

            m_scene.AddProcedure("GetListGames", onGetListGames);
            m_scene.AddProcedure("JoinGame", onJoinGame);
            m_scene.AddRoute("UpdateGame", onUpdateGame);
            m_scene.AddRoute("GetReady", onGetReady);
            m_scene.AddRoute("CreateGame", onCreateGame);
            m_scene.AddRoute("DestroyGame", onDestroyGame);
            m_scene.AddRoute("QuitGame", onQuitGame);
        }
        private void AuthenticatorSceneFactory(ISceneHost scene)
        {
            scene.AddProcedure("login", async p =>
            {
                scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "Logging in an user.", null);

                var accessor = scene.DependencyResolver.Resolve<Management.ManagementClientAccessor>();
                var authenticationCtx = p.ReadObject<Dictionary<string, string>>();
                var result = new LoginResult();
                var userService = scene.DependencyResolver.Resolve<IUserService>();

                foreach (var provider in _config.AuthenticationProviders)
                {
                    var authResult = await provider.Authenticate(authenticationCtx, userService);
                    if (authResult == null)
                    {
                        continue;
                    }

                    if (authResult.Success)
                    {
                        scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "Authentication successful.", authResult);

                        result.Success = true;
                        var client = await accessor.GetApplicationClient();
                        result.Token = await client.CreateConnectionToken(_config.OnRedirect(authResult), _config.UserDataSelector(authResult));
                        userService.SetUid(p.RemotePeer, authResult.AuthenticatedId);
                        break;
                    }
                    else
                    {
                        scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "Authentication failed.", authResult);

                        result.ErrorMsg = authResult.ReasonMsg;
                        break;
                    }
                }
                if (!result.Success)
                {
                    if (result.ErrorMsg == null)
                    {
                        result.ErrorMsg = "No authentication provider able to handle these credentials were found.";
                    }
                }

                if (result.Success)
                {
                    scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "User logged in.", null);
                }
                else
                {
                    scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "User failed to log in.", null);
                }
                p.SendValue(result);
            });

            foreach (var provider in _config.AuthenticationProviders)
            {
                provider.AdjustScene(scene);
            }
        }
Exemplo n.º 46
0
        void IScene.Attach(ISceneHost host)
        {
            
            this.Host = host;

            Device device = host.Device;
            if (device == null)
                throw new Exception("Scene host device is null");

            Uri executablePath = new Uri(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            String shaderPath = System.IO.Path.GetDirectoryName(executablePath.LocalPath) + "\\Shaders\\";

            if (videoPlayerViewModel.DecodedVideoFormat == VideoLib.VideoPlayer.DecodedVideoFormat.YUV420P)
            {
                shaderPath += "YUVtoRGB.fx";
            }
            else
            {
                shaderPath += "Simple.fx";
            }

            try
            {            
                ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile(shaderPath, "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);             
                this.SimpleEffect = new Effect(device, shaderBytes);             
            }
            catch (Exception e)
            {              
                System.Diagnostics.Debug.Print(e.Message);
                throw new Exception("Error compiling: " + shaderPath);
            }

            EffectTechnique technique = this.SimpleEffect.GetTechniqueByIndex(0); 
            EffectPass pass = technique.GetPassByIndex(0);

            this.VertexLayout = new InputLayout(device, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),  
                new InputElement("TEXCOORD", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0)
                //new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0)  
               
            });

            int bytesPerVertexInfo = 4 * 8;          
            nrVertices = 4;

            this.VertexStream = new DataStream(bytesPerVertexInfo * nrVertices, true, true);
            this.VertexStream.WriteRange(new[] 
                {
                    new Vector4(-1.0f, 1.0f, 0.5f, 1.0f),
                    new Vector4(0.0f, 0.0f, 0.0f, 0.0f),

                    new Vector4(1.0f, -1.0f, 0.5f, 1.0f),
                    new Vector4(1.0f, 1.0f, 0.0f, 0.0f),

                    new Vector4(-1.0f, -1.0f, 0.5f, 1.0f),
                    new Vector4(0.0f, 1.0f, 0.0f, 0.0f),

                    new Vector4(1.0f, 1.0f, 0.5f, 1.0f),
                    new Vector4(1.0f, 0.0f, 0.0f, 0.0f)
                }
            );
            
            this.VertexStream.Position = 0;

            this.Vertices = new Buffer(device, this.VertexStream, new BufferDescription()
                {
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = bytesPerVertexInfo * nrVertices,
                    Usage = ResourceUsage.Default
                }
            );

            nrIndices = 4;
            int indicesSizeBytes = nrIndices * sizeof(Int32);

            IndexStream = new DataStream(indicesSizeBytes, true, true);
            IndexStream.WriteRange<int>(new[] 
                {
                    3,1,0,2
                }
            );

            this.IndexStream.Position = 0;

            this.Indices = new Buffer(device, this.IndexStream, new BufferDescription()
                {
                    BindFlags = BindFlags.IndexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = indicesSizeBytes,
                    Usage = ResourceUsage.Default
                }
            );
  
            device.Flush();         
        }
Exemplo n.º 47
0
 private TesterBehavior(ISceneHost scene)
 {
     _scene = scene;
 }
Exemplo n.º 48
0
 public void setScene(ISceneHost scene)
 {
     _scene = scene;
 }
Exemplo n.º 49
0
        public RTypeMainGame(ISceneHost scene)
        {
            m_running = false;
            m_started = false;
            m_game = null;
            m_nbPlayer = 0;
            m_scene = scene;
            m_log = m_scene.GetComponent<ILogger>();
            m_env = m_scene.GetComponent<IEnvironment>();

            m_scene.Starting.Add(onStarting);
            m_scene.Shuttingdown.Add(onShutdown);
            m_scene.Connecting.Add(onConnecting);
            m_scene.Connected.Add(onConnected);
            m_scene.Disconnected.Add(onDisconnected);

            m_scene.AddRoute("PosUpdate", onPosUpdate);
            m_scene.AddRoute("Fire", onFire);
            m_scene.AddRoute("GameInfos", onGetGameInfos);
            m_scene.AddRoute("Collision", onGetCollision);
            m_scene.AddRoute("OutOfScreen", onEntityOutOfScreen);
        }
Exemplo n.º 50
0
 public void OnResize(ISceneHost host)
 {
 }
 public void setScene(ISceneHost scene)
 {
     _scene = scene;
 }
Exemplo n.º 52
0
 /// <inheritdoc />
 protected Scene(string id, string name, ISceneHost host = null)
     : base(id, name, host ?? HomeBase <THome> .Current.GetDefaultSceneHost(name))
 {
 }
 public void AdjustScene(ISceneHost scene)
 {
     scene.AddProcedure("provider.loginpassword.createAccount", p => CreateAccount(p, scene));
 }