/// <summary>
 /// Copies main parameters from this component to the specified instance.
 /// </summary>
 /// <param name="camera">The camera to receive copied parameters from this instance.</param>
 /// <exception cref="System.ArgumentNullException">camera</exception>
 public void CopyTo(CameraComponent camera)
 {
     if (camera == null) throw new ArgumentNullException("camera");
     camera.Projection = Projection;
     camera.VerticalFieldOfView = VerticalFieldOfView;
     camera.OrthographicSize = OrthographicSize;
     camera.NearClipPlane = NearPlane;
     camera.FarClipPlane = FarPlane;
     // TODO: Aspect ratio
 }
Пример #2
0
        /// <summary>
        /// Sets up the base camera to start off the scene manager.
        /// </summary>
        /// <remarks>This will likely be temporary until we are reading in a camera from the editor.</remarks>
        public void SetupBaseCamera()
        {
            CameraComponent sceneMgrCamera = EntityLoader.LoadComponent(this.sceneMgrRootEntity,
                                                                        ComponentType.CameraComponent, this.content,
                                                                        "Entities/ComponentDefinitions/Camera/StandardCamera")
                                             as CameraComponent;

            // Lets create a free-cam
            CreateAndStartFreeMovingCamera();

            // Set our camera's position
            this.sceneMgrRootEntity.Position = new Vector3(800, 220, 780);

            // Set our camera's look-at point
            this.sceneMgrRootEntity.LookAt(new Vector3(900, 220, 700));
        }
Пример #3
0
        //---------------------------------------------------------------------------

        private bool IsValidDistance()
        {
            foreach (Camera cam in EntityManager.Get().Find <Camera>())
            {
                TransformComponent transform = cam.GetComponent <TransformComponent>();
                CameraComponent    camera    = cam.GetComponent <CameraComponent>();
                if (transform != null && camera != null)
                {
                    if (Vector2.Distance(transform.Location.To2D(), Center.To2D()) <= Math.Sqrt(Math.Pow(camera.Width, 2) + Math.Pow(camera.Height, 2)) / 2)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
        public void SerializeAndDeserialize(AspectRatioBehavior aspectRatioBehavior)
        {
            // Arrange
            var component = new CameraComponent
            {
                AspectRatioBehavior = aspectRatioBehavior,
                ViewRectangle       = new Vector2(12.34, 56.78)
            };

            // Act
            var actual = SerializeAndDeserialize(component);

            // Assert
            Assert.That(actual.AspectRatioBehavior, Is.EqualTo(component.AspectRatioBehavior));
            Assert.That(actual.ViewRectangle, Is.EqualTo(component.ViewRectangle));
        }
Пример #5
0
        public static void SetNearClipPlane(float value)
        {
            List <Entity> entities = ComponentManager.Instance.GetAllEntitiesWithComponentType <CameraComponent>();

            foreach (Entity enitity in entities)
            {
                CameraComponent c = ComponentManager.Instance.GetEntityComponent <CameraComponent>(enitity);

                if (value <= 0)
                {
                    c.nearClipPlane = 1f;
                }

                c.nearClipPlane = value;
            }
        }
Пример #6
0
        protected override float ComputeScreenCoverage(CameraComponent camera, Vector3 position, Vector3 direction, float width, float height)
        {
            // http://stackoverflow.com/questions/21648630/radius-of-projected-sphere-in-screen-space
            var     targetPosition = new Vector4(position, 1.0f);
            Vector4 projectedTarget;

            Vector4.Transform(ref targetPosition, ref camera.ViewProjectionMatrix, out projectedTarget);

            var d           = Math.Abs(projectedTarget.W) + 0.00001f;
            var r           = Radius;
            var coTanFovBy2 = camera.ProjectionMatrix.M22;
            var pr          = r * coTanFovBy2 / (Math.Sqrt(d * d - r * r) + 0.00001f);

            // Size on screen
            return((float)pr * Math.Max(width, height));
        }
Пример #7
0
        protected PreviewFromEntity(string modelEffectName = EditorGraphicsCompositorHelper.EditorForwardShadingEffect)
        {
            this.modelEffectName = modelEffectName;
            var cameraComponent = new CameraComponent();

            // create the entity preview scene
            entityScene = new Scene();

            // setup the camera
            CameraScript = new CameraUpdateScript();
            camera       = new Entity("Preview Camera")
            {
                cameraComponent, CameraScript
            };
            entityScene.Entities.Add(camera);
        }
Пример #8
0
        public static bool ScreenPositionToWorldPositionRaycast(Vector2 screenPos, CameraComponent camera, Simulation simulation, out ClickResult clickResult)
        {
            Matrix invViewProj = Matrix.Invert(camera.ViewProjectionMatrix);

            Vector3 sPos;

            sPos.X = screenPos.X * 2f - 1f;
            sPos.Y = 1f - screenPos.Y * 2f;

            sPos.Z = 0f;
            var vectorNear = Vector3.Transform(sPos, invViewProj);

            vectorNear /= vectorNear.W;

            sPos.Z = 1f;
            var vectorFar = Vector3.Transform(sPos, invViewProj);

            vectorFar /= vectorFar.W;

            clickResult.ClickedEntity = null;
            clickResult.WorldPosition = Vector3.Zero;
            clickResult.HitResult     = new HitResult();

            var minDistance = float.PositiveInfinity;

            List <HitResult> result = new List <HitResult>();

            simulation.RaycastPenetrating(vectorNear.XYZ(), vectorFar.XYZ(), result);
            foreach (var hitResult in result)
            {
                var staticBody = hitResult.Collider;
                if (staticBody != null)
                {
                    var distance = (vectorNear.XYZ() - hitResult.Point).LengthSquared();
                    if (distance < minDistance)
                    {
                        minDistance               = distance;
                        clickResult.HitResult     = hitResult;
                        clickResult.WorldPosition = hitResult.Point;
                        clickResult.ClickedEntity = hitResult.Collider.Entity;
                    }
                }
            }

            return(clickResult.ClickedEntity != null);
        }
Пример #9
0
        public async Task AwaitSpawnAsync(CancellationToken cancellationToken = default)
        {
            var camera = Engine.GetService <CameraManager>().Camera;

            cameraComponent               = camera.gameObject.AddComponent <CameraComponent>();
            cameraComponent.Shader        = glitchShader;
            cameraComponent.GlitchTexture = glitchTexture;
            cameraComponent.Intensity     = Intensity;

            await new WaitForSeconds(Duration);
            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }

            Engine.GetService <SpawnManager>()?.DestroySpawnedObject(gameObject.name);
        }
Пример #10
0
        public void Update(GameTime gameTime)
        {
            //get the camera entity
            Entity camera = ComponentManager.Instance.GetFirstEntityOfType <CameraComponent>();

            //get the camera component
            CameraComponent c = ComponentManager.Instance.GetEntityComponent <CameraComponent>(camera);

            //update the bounding frustum
            c.cameraFrustrum = new BoundingFrustum(c.viewMatrix * c.projectionMatrix);

            if (c.targetEntity != null)
            {
                List <Entity> elist = ComponentManager.Instance.GetAllEntitiesWithComponentType <ModelComponent>();
                Entity        e     = ComponentManager.Instance.GetEntityWithTag(c.targetEntity, elist);

                //set the camera behind the target object
                Vector3 pos = c.camChasePosition;

                //get transform component from the entity the camera i following
                TransformComponent t = ComponentManager.Instance.GetEntityComponent <TransformComponent>(e);

                //get the rotation
                pos = Vector3.Transform(pos, Matrix.CreateFromQuaternion(t.Rotation));

                //move the camera to the object position
                pos += t.Position;

                c.position = pos;

                //update the camera up position
                Vector3 cameraUp = new Vector3(0, 1, 0);
                cameraUp = Vector3.Transform(cameraUp, Matrix.CreateFromQuaternion(t.Rotation));

                //update the view
                c.viewMatrix = Matrix.CreateLookAt(pos, t.Position, cameraUp);

                //update the projection
                // c.projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, c.aspectRatio, c.nearClipPlane, c.farClipPlane);
            }
            //Else, a static camera that looks at origo is set up.
            else
            {
                c.viewMatrix = Matrix.CreateLookAt(c.position, c.target, c.upDirection);
            }
        }
Пример #11
0
            public void UpdateComponents()
            {
                cameraComponent = Entity.Get <CameraComponent>();
                if (cameraComponent != null)
                {
                    var maxPitch = MathUtil.PiOverTwo - 0.01f;
                    pitch = MathUtil.Clamp(pitch, -maxPitch, maxPitch);

                    var offset         = new Vector3(0, 0, distance);
                    var cameraPosition = target + Vector3.Transform(offset, Quaternion.RotationYawPitchRoll(yaw, pitch, 0));

                    Entity.Transform.UseTRS       = false;
                    Entity.Transform.LocalMatrix  = Matrix.Invert(Matrix.LookAtRH(cameraPosition, target, Vector3.UnitY));
                    cameraComponent.FarClipPlane  = 2.5f * Math.Max(distance, previousBoundingSphere.Radius);
                    cameraComponent.NearClipPlane = cameraComponent.FarClipPlane / 1000f;
                }
            }
Пример #12
0
    void updateCamera(Entity e)
    {
        SmoothCameraComponent smoothCamera = e.smoothCamera;
        CameraComponent       camera       = e.camera;
        FollowTargetComponent target       = e.followTarget;
        Vector2 targetPosition             = target.target.position.pos;

        Vector3 cameraPosition = camera.camera.transform.position;

        temp.x = cameraPosition.x + (targetPosition.x - cameraPosition.x) * LERP_FACTOR;

        Vector2 position = e.position.pos;

        snapCamera(e, position);
        e.position.pos.Set(position);
        camera.camera.transform.position = new Vector3(temp.x, position.y, smoothCamera.offset.z);
    }
Пример #13
0
        public void Update(GraphicsDevice graphicsDevice, CameraComponent camera)
        {
            if (_materials == null || _ocean == null || Model == null || Model.Model == null)
                return;

            if (_isDirty)
            {
                Model.Model.Materials.Clear();
                foreach (var material in _materials)
                {
                    Model.Model.Materials.Add(new MaterialInstance(material)
                    {
                        IsShadowCaster = false
                    });
                }
            }
        }
Пример #14
0
        public void Update(GameTime gameTime)
        {
            foreach (ulong m in ComponentManager.GetAllEntitiesWithComp <CameraComponent>())
            {
                TransformComponent transform = ComponentManager.GetComponent <TransformComponent>(m);
                CameraComponent    curCam    = ComponentManager.GetComponent <CameraComponent>(m);

                Vector3 offSet = new Vector3(0, 0.5f, 0.6f);
                curCam.cameraPosition  = Vector3.Transform(offSet, Matrix.CreateFromQuaternion(transform.qRot));
                curCam.cameraPosition += transform.position;

                Vector3 up = Vector3.Transform(Vector3.Up, transform.qRot);

                curCam.viewMatrix       = Matrix.CreateLookAt(curCam.cameraPosition, transform.position, up);
                curCam.projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.AspectRatio, 0.2f, 500f);
            }
        }
Пример #15
0
    private void Turning(PlayerComponent playerComponent, ICameraData cameraData)
    {
        CameraComponent cameraComponent = entityDatabase.QueryType <CameraComponent>();

        Ray        camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit floorHit;

        if (Physics.Raycast(camRay, out floorHit, cameraData.camRayLength, cameraComponent.floorMask))
        {
            Transform transform     = playerComponent.entity.GetComponent <TransformComponent>().transform;
            Vector3   playerToMouse = floorHit.point - transform.position;
            playerToMouse.y = 0f;

            Quaternion newRotation = Quaternion.LookRotation(playerToMouse);
            playerComponent.rigidBody.MoveRotation(newRotation);
        }
    }
Пример #16
0
            public void Update(Entity entity, CameraComponent camera)
            {
                AspectRatio   = camera.AspectRatio;
                FrustumHeight = 2 * (float)Math.Tan(MathUtil.DegreesToRadians(camera.VerticalFieldOfView) / 2);

                // extract the world matrix of the UI entity
                var worldMatrix = entity.Get <TransformComponent>().WorldMatrix;

                // rotate the UI element perpendicular to the camera view vector, if billboard is activated
                var uiComponent = entity.Get <UIComponent>();

                if (!uiComponent.IsFullScreen && uiComponent.IsBillboard)
                {
                    Matrix viewInverse;
                    Matrix.Invert(ref camera.ViewMatrix, out viewInverse);

                    // remove scale of the camera
                    viewInverse.Row1 /= viewInverse.Row1.XYZ().Length();
                    viewInverse.Row2 /= viewInverse.Row2.XYZ().Length();

                    // set the scale of the object
                    viewInverse.Row1 *= worldMatrix.Row1.XYZ().Length();
                    viewInverse.Row2 *= worldMatrix.Row2.XYZ().Length();

                    // set the adjusted world matrix
                    worldMatrix.Row1 = viewInverse.Row1;
                    worldMatrix.Row2 = viewInverse.Row2;
                    worldMatrix.Row3 = viewInverse.Row3;
                }

                // Rotation of Pi along 0x to go from UI space to world space
                worldMatrix.Row2 = -worldMatrix.Row2;
                worldMatrix.Row3 = -worldMatrix.Row3;

                // If the UI component is not drawn fullscreen it should be drawn as a quad with world sizes corresponding to its actual size
                if (!uiComponent.IsFullScreen)
                {
                    worldMatrix = Matrix.Scaling(uiComponent.Size / uiComponent.Resolution) * worldMatrix;
                }

                ProjectionMatrix = camera.ProjectionMatrix;
                Matrix.Multiply(ref worldMatrix, ref camera.ViewMatrix, out ViewMatrix);
                Matrix.Invert(ref ViewMatrix, out ViewMatrixInverse);
                Matrix.Multiply(ref ViewMatrix, ref ProjectionMatrix, out ViewProjectionMatrix);
            }
Пример #17
0
        protected override void Initialize()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            _netAgent = new NetworkAgent(AgentRole.Client, "Umbra");

            EntitySystem.BlackBoard.SetEntry("Game", this);
            EntitySystem.BlackBoard.SetEntry("ContentManager", Content);
            EntitySystem.BlackBoard.SetEntry("SpriteBatch", spriteBatch);
            EntitySystem.BlackBoard.SetEntry("GraphicsDevice", GraphicsDevice);
            EntitySystem.BlackBoard.SetEntry("ContentManager", Content);
            EntitySystem.BlackBoard.SetEntry("NetworkAgent", _netAgent);

            _entityWorld = new EntityWorld();

            // create camera
            Vector3 camPosition = new Vector3(0, 10, 5);
            Matrix  camRotation = Matrix.CreateFromAxisAngle(new Vector3(1, 0, 0), MathHelper.ToRadians(-65.0f));
            float   aspectRatio = (float)GraphicsDevice.Viewport.Width / GraphicsDevice.Viewport.Height;

            CameraComponent cameraComponent = new CameraComponent(camPosition, camRotation, aspectRatio);

            Entity cameraEntity = _entityWorld.CreateEntity();

            cameraEntity.AddComponent(cameraComponent);

            EntitySystem.BlackBoard.SetEntry("Camera", cameraComponent);

            //// TEMP ////
            Map    map       = new Map(100, 100);
            Entity mapEntity = _entityWorld.CreateEntity();

            mapEntity.AddComponent(new TileMapComponent(map));

            EntitySystem.BlackBoard.SetEntry("Map", map);
            //// TEMP ////

            _entityWorld.InitializeAll(new[] { GetType().Assembly });

            CrawEntityManager.Instance.Initialize(_entityWorld, new ClientEntityFactory(_entityWorld));

            _netAgent.Connect("127.0.0.1");

            base.Initialize();
        }
Пример #18
0
        private void UpdateFrustum(CameraComponent camera)
        {
            var projectionToView = camera.ProjectionMatrix;

            projectionToView.Invert();

            // Compute frustum-dependent variables (common for all shadow maps)
            var projectionToWorld = camera.ViewProjectionMatrix;

            projectionToWorld.Invert();

            // Transform Frustum corners in World Space (8 points) - algorithm is valid only if the view matrix does not do any kind of scale/shear transformation
            for (int i = 0; i < 8; ++i)
            {
                Vector3.TransformCoordinate(ref FrustumBasePoints[i], ref projectionToWorld, out frustumCornersWS[i]);
                Vector3.TransformCoordinate(ref FrustumBasePoints[i], ref projectionToView, out frustumCornersVS[i]);
            }
        }
Пример #19
0
            public void Update(Entity entity, Vector3 virtualResolution)
            {
                var nearPlane   = virtualResolution.Z / 2;
                var farPlane    = nearPlane + virtualResolution.Z;
                var zOffset     = nearPlane + virtualResolution.Z / 2;
                var aspectRatio = virtualResolution.X / virtualResolution.Y;
                var verticalFov = (float)Math.Atan2(virtualResolution.Y / 2, zOffset) * 2;

                var cameraComponent = new CameraComponent(nearPlane, farPlane)
                {
                    AspectRatio         = aspectRatio,
                    VerticalFieldOfView = MathUtil.RadiansToDegrees(verticalFov),
                    ViewMatrix          = Matrix.LookAtRH(new Vector3(0, 0, zOffset), Vector3.Zero, Vector3.UnitY),
                    ProjectionMatrix    = Matrix.PerspectiveFovRH(verticalFov, aspectRatio, nearPlane, farPlane),
                };

                Update(entity, cameraComponent);
            }
Пример #20
0
        public void createGameEntities()
        {
            ulong              id        = ComponentManager.GetNewId();
            ChopperComponent   chopper   = new ChopperComponent();
            TransformComponent transform = new TransformComponent(new Vector3(200.0f, 300.0f, 100.0f), 0f, 10f);

            Model           model  = Content.Load <Model>(@"Models/Chopper");
            CameraComponent camera = new CameraComponent(graphics.GraphicsDevice, cameraPosition, Vector3.Zero, Vector3.Up, id);

            ComponentManager.StoreComponent(id, camera);
            ComponentManager.StoreComponent(id, new ModelComponent(model, CHOPPER_SCALE, CHOPPER_TRANSLATION,
                                                                   0f, 0f, MathHelper.PiOver2, true)
            {
                world = Matrix.Identity
            });
            ComponentManager.StoreComponent(id, transform);
            ComponentManager.StoreComponent(id, chopper);
        }
Пример #21
0
        /// <summary>
        /// Converts the screen position to a <see cref="RaySegment"/> in world coordinates.
        /// </summary>
        /// <param name="cameraComponent"></param>
        /// <param name="position"></param>
        /// <param name="result"><see cref="RaySegment"/>, starting at near plain and ending at the far plain.</param>
        /// <exception cref="ArgumentNullException">If the cameraComponent argument is <see langword="null"/>.</exception>
        /// <remarks>
        /// This method does not update the <see cref="CameraComponent.ViewMatrix"/> or <see cref="CameraComponent.ProjectionMatrix"/> before performing the transformation.
        /// If the <see cref="CameraComponent"/> or it's containing <see cref="Entity"/> <see cref="TransformComponent"/>has been modified since the last frame you may need to call the <see cref="CameraComponent.Update()"/> method first.
        /// </remarks>
        public static void ScreenToWorldRaySegment(this CameraComponent cameraComponent, ref Vector2 position, out RaySegment result)
        {
            if (cameraComponent == null)
            {
                throw new ArgumentNullException(nameof(cameraComponent));
            }

            Matrix.Invert(ref cameraComponent.ViewProjectionMatrix, out var inverseViewProjection);

            ScreenToClipSpace(ref position, out var clipSpace);

            Vector3.TransformCoordinate(ref clipSpace, ref inverseViewProjection, out var near);

            clipSpace.Z = 1f;
            Vector3.TransformCoordinate(ref clipSpace, ref inverseViewProjection, out var far);

            result = new RaySegment(near, far);
        }
        public void CameraComponentTerminateTest()
        {
            CameraComponent           target          = new CameraComponent();
            PrivateObject             obj             = new PrivateObject(target);
            Mock <ILogger>            loggerMock      = new Mock <ILogger>();
            Mock <IExecutableContext> execContextMock = new Mock <IExecutableContext>();
            Mock <IMessageRouter>     msgRouterMock   = new Mock <IMessageRouter>();

            execContextMock.Setup(f => f.MessageRouter).Returns(msgRouterMock.Object);
            obj.SetFieldOrProperty("mLogger", loggerMock.Object);
            obj.SetFieldOrProperty("mContext", execContextMock.Object);
            obj.SetFieldOrProperty("mName", "TESTNAME");

            target.Terminate();

            loggerMock.Verify(f => f.Terminate(), Times.Once());
            msgRouterMock.Verify(f => f.DeregisterTopic("TESTNAME", target), Times.Once());
        }
Пример #23
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            AIParams.SetUpAIParams(Path.Combine(Directory.GetCurrentDirectory(), "AIConfig.txt"));

            device      = graphics.GraphicsDevice;
            spriteBatch = new SpriteBatch(device);

            world = new World(this);


            _windowWidth  = 1000; // GraphicsDevice.DisplayMode.Width / 2;
            _windowHeight = 600;  // GraphicsDevice.DisplayMode.Height / 2;

            // Setup frame buffer.
            graphics.SynchronizeWithVerticalRetrace = false;
            graphics.PreferredBackBufferWidth       = _windowWidth;
            graphics.PreferredBackBufferHeight      = _windowHeight;
            graphics.PreferMultiSampling            = true;
            graphics.ApplyChanges();

            // Setup the initial input states.
            currentKeyboardState = Keyboard.GetState();

            // Setup Fog
            // NOTE: migration to XNA 4.0
            // NOTE: graphics.GraphicsDevice.RenderState.FogStart = Settings.FOG_START;
            // NOTE: graphics.GraphicsDevice.RenderState.FogEnd = Settings.FOG_END;
            // NOTE: graphics.GraphicsDevice.RenderState.FogDensity = Settings.FOG_DENSITY;
            // NOTE: graphics.GraphicsDevice.RenderState.FogColor = Settings.FOG_COLOR;
            // NOTE: graphics.GraphicsDevice.RenderState.FogTableMode = Settings.FOG_MODE;
            // NOTE: graphics.GraphicsDevice.RenderState.FogVertexMode = Settings.FOG_MODE;

            HUD      = new ScreenOutput.HUD();
            _console = new ScreenOutput.Console();
            cursor   = new Cursor(this, device, spriteBatch);
            Components.Add(cursor);
            camera = new CameraComponent(this);
            Components.Add(camera);

            // NOTE: migration to XNA 4.0 basicEffect = new BasicEffect(graphics.GraphicsDevice, null);
            basicEffect = new BasicEffect(graphics.GraphicsDevice);

            base.Initialize();
        }
Пример #24
0
        public void LoadScene()
        {
            IEnumerable <IEntity> renderableEntities = _entityManager.GetEntitiesWithComponents <RenderableComponent>();

            renderableEntities.ForEach(SetupRenderableEntity);

            IEnumerable <IEntity> cameraEntities = _entityManager.GetEntitiesWithComponents <CameraComponent>();

            cameraEntities.ForEach(SetupCamera);

            _entityManager.GetEntities().ForEach(entity =>
            {
                entity.GetComponents().ForEach(component =>
                {
                    component.OnLoaded();
                });
            });

            if (!_context.IsEditor)
            {
                // Set the current Active Camera
                _entityManager.GetEntitiesWithComponents <CameraComponent>().ForEach(entity =>
                {
                    CameraComponent cameraComponent = entity.GetComponent <CameraComponent>();
                    if (cameraComponent.ActiveCamera)
                    {
                        var vp = _context.GetRenderWindow().addViewport(cameraComponent.Camera);
                        vp.setBackgroundColour(new ColourValue(.1f, .3f, .3f));
                    }
                });
            }

            MeshPtr meshPtr  = MeshManager.getSingleton().createPlane("background", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, new Plane(VectorUtils.Vector3.UNIT_Y, 0f), 800, 600, 4, 4, true, 1, 4, 4, VectorUtils.Vector3.UNIT_Z);
            var     floorEnt = _sceneManager.createEntity("background", "background");

            floorEnt.setMaterial(MaterialManager.getSingleton().getByName("Color_009"));

            var floorNode = _sceneManager.getRootSceneNode().createChildSceneNode();

            floorNode.setPosition(new Vector3(0f, -3f, 0f));
            floorNode.attachObject(floorEnt);

            meshPtr.Dispose();
        }
Пример #25
0
    public void Execute()
    {
        float           deltaTime   = _time.GetSingleEntity().time.deltaTime;
        CameraComponent camera      = _camera.GetSingleEntity().camera;
        bool            wasFirstOne = false;

        foreach (Entity e in _group.GetEntities())
        {
            if (wasFirstOne)
            {
                e.isDestroyEntity = true;
                return;
            }

            CameraShakeProperties componentProperties = e.cameraShake.properties;

            componentProperties.time -= deltaTime;
            if (componentProperties.time < 0.0f)
            {
                e.isDestroyEntity = true;
            }
            else
            {
                if (!componentProperties.velocityCalculated)
                {
                    componentProperties.velocity = componentProperties.totalOffsetX * 4.0f / componentProperties.totalTime;
                }
                Vector3 originalPosition = camera.camera.transform.position;
                componentProperties.offsetX += componentProperties.direction * componentProperties.velocity * deltaTime;

                if (componentProperties.offsetX >= componentProperties.totalOffsetX)
                {
                    componentProperties.direction = -1;
                }
                else if (componentProperties.offsetX <= -componentProperties.totalOffsetX)
                {
                    componentProperties.direction = 1;
                }

                camera.camera.transform.position = new Vector3(originalPosition.x + componentProperties.offsetX, originalPosition.y, originalPosition.z);
                wasFirstOne = true;
            }
        }
    }
Пример #26
0
        /// <summary>
        /// Resolves camera to the one contained in slot <see cref="Camera"/>.
        /// </summary>
        protected virtual CameraComponent ResolveCamera(RenderContext renderContext)
        {
            if (Camera == null && !cameraSlotResolutionFailed)
            {
                Logger.Warning($"{nameof(SceneCameraRenderer)} [{Id}] has no camera set. Make sure to set camera to the renderer via the Graphic Compositor Editor.");
            }

            cameraSlotResolutionFailed = Camera == null;
            if (cameraSlotResolutionFailed)
            {
                return(null);
            }

            var camera = Camera?.Camera;

            if (camera == null && !cameraResolutionFailed)
            {
                // no slot set, try to set one automatically
                SceneSystem        ss = renderContext.Services.GetService <SceneSystem>();
                GraphicsCompositor gc = ss?.GraphicsCompositor;
                if (gc != null)
                {
                    foreach (Entity e in ss.SceneInstance.RootScene.Entities)
                    {
                        CameraComponent cam = e.Get <CameraComponent>();
                        if (cam != null)
                        {
                            cam.Slot = gc.Cameras[0].ToSlotId();
                            camera   = cam;
                            break;
                        }
                    }
                }

                if (camera == null)
                {
                    Logger.Warning($"{nameof(SceneCameraRenderer)} [{Id}] has no camera assigned to its {nameof(CameraComponent.Slot)}[{Camera.Name}]. Make sure a camera is enabled and assigned to the corresponding {nameof(CameraComponent.Slot)}.");
                }
            }

            cameraResolutionFailed = camera == null;

            return(camera);
        }
Пример #27
0
        public void PerformAction(Keys key, String entityName)
        {
            List <Entity>   entities = SceneManager.Instance.GetActiveSceneEntities();
            CameraComponent c        = ComponentManager.Instance.GetEntityComponent <CameraComponent>(ComponentManager.Instance.GetEntityWithTag("camera", entities));

            switch (entityName)
            {
            case "player":
                Entity             ent = ComponentManager.Instance.GetEntityWithTag("player", entities);
                TransformComponent t   = ComponentManager.Instance.GetEntityComponent <TransformComponent>(ent);
                PlayerComponent    p   = ComponentManager.Instance.GetEntityComponent <PlayerComponent>(ent);
                switch (key)
                {
                case Keys.W:
                    t.Position += p.CharDirectionNormal * MOVEMENT;
                    break;

                case Keys.A:
                    t.Position = p.CharDirectionNormal;
                    break;

                case Keys.S:
                    //t.Position = ;
                    break;

                case Keys.D:
                    t.Position = new Vector3(MOVEMENT, 0, 0);
                    break;

                case Keys.L:
                    t.Position = new Vector3(MOVEMENT, 0, 0);
                    break;

                case Keys.Right:
                    t.Position = new Vector3(MOVEMENT, 0, 0);
                    break;
                }
                c.LookAt = t.Position;
                break;

            default:
                break;
            }
        }
Пример #28
0
        public CubemapRendererBase(GraphicsDevice device, int outputSize, PixelFormat outputFormat, bool needDepthStencil)
        {
            OutputTextureSize   = outputSize;
            OutputTextureFormat = outputFormat;

            Camera = new CameraComponent
            {
                UseCustomProjectionMatrix = true,
                UseCustomViewMatrix       = true,
            };
            Camera.ProjectionMatrix = Matrix.PerspectiveFovRH(MathUtil.DegreesToRadians(90.0f), 1.0f, Camera.NearClipPlane, Camera.FarClipPlane);

            // We can't render directly to the texture cube before feature level 10.1, so let's render to a standard render target and copy instead
            renderTarget = Texture.New2D(device, OutputTextureSize, OutputTextureSize, outputFormat, TextureFlags.RenderTarget);
            if (needDepthStencil)
            {
                depthStencil = Texture.New2D(device, OutputTextureSize, OutputTextureSize, PixelFormat.D24_UNorm_S8_UInt, TextureFlags.DepthStencil);
            }
        }
Пример #29
0
        public SkiUiScene(Action invalidateSurface, Func <Node, CameraComponent, Action, SkiUiComponent> createUiComponent)
        {
            _invalidateSurface = invalidateSurface;

            _canvasComponent = new CanvasComponent();
            _cameraGroup     = _canvasComponent.CreateCameraGroup();
            _camera          = _scene.RootNode
                               .CreateChild()
                               .AddComponent(new CameraComponent(_cameraGroup, 0));
            _scene.RootNode.AddComponent(_canvasComponent);

            UiComponent = _scene.RootNode
                          .CreateChild()
                          .AddComponent(createUiComponent(_scene.RootNode, _camera, InvalidateSurface))
                          .AddToCamera(_camera);

            _scene.Start();
            InvalidateSurface();
        }
Пример #30
0
        private void SetupCamera(IEntity entity)
        {
            CameraComponent cameraComponent = entity.GetComponent <CameraComponent>();

            Camera camera = _sceneManager.createCamera("Camera" /*TODO Name From Component*/);

            cameraComponent.Camera = camera;

            PositionComponent transformComponent = entity.GetComponent <PositionComponent>();

            SceneNode camnode = _sceneManager.getRootSceneNode().createChildSceneNode();

            camnode.setPosition(transformComponent.Position);
            camnode.yaw(new Radian(0f));
            camnode.pitch(new Radian(-1.2f));

            cameraComponent.SceneNode = camnode;
            camnode.attachObject(camera);
        }
Пример #31
0
        protected override float ComputeScreenCoverage(CameraComponent camera, Vector3 position, Vector3 direction, float width, float height)
        {
            // http://stackoverflow.com/questions/21648630/radius-of-projected-sphere-in-screen-space
            // Use a sphere at target point to compute the screen coverage. This is a very rough approximation.
            // We compute the sphere at target point where the size of light is the largest
            // TODO: Check if we can improve this calculation with a better model
            var     targetPosition = new Vector4(position + direction * Range, 1.0f);
            Vector4 projectedTarget;

            Vector4.Transform(ref targetPosition, ref camera.ViewProjectionMatrix, out projectedTarget);

            var d           = Math.Abs(projectedTarget.W) + 0.00001f;
            var r           = Range * Math.Sin(MathUtil.DegreesToRadians(AngleOuter / 2.0f));
            var coTanFovBy2 = camera.ProjectionMatrix.M22;
            var pr          = r * coTanFovBy2 / (Math.Sqrt(d * d - r * r) + 0.00001f);

            // Size on screen
            return((float)pr * Math.Max(width, height));
        }
Пример #32
0
        /// <summary>
        /// Draws this tile using the given the camera
        /// </summary>
        /// <param name="c"></param>
        public void Draw(CameraComponent c)
        {
            if (IsEmpty()) return;
            Matrix[] transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);

            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect be in mesh.Effects)
                {
                    be.EnableDefaultLighting();
                    be.Projection = c.ProjectionMatrix;
                    be.View = c.ViewMatrix;
                    be.World = GetWorld() * mesh.ParentBone.Transform;
                }

                mesh.Draw();
            }
        }
Пример #33
0
 public static bool InRange(Character c, CameraComponent cam)
 {
     return Math.Abs(c.getX() - cam.Position.X) < Constants.TILE_SIZE * 30;
 }
Пример #34
0
        /// <summary>
        /// Calculate camera view parameters based on the entity bounding box.
        /// </summary>
        /// <param name="entity">The entity that we want to display</param>
        /// <param name="up">The vector representing the up of the entity</param>
        /// <param name="front">The vector representing the front of the entity</param>
        /// <param name="cameraComponent">The camera component used to render to object</param>
        /// <returns>Appropriate view parameters that can be used to display the entity</returns>
        public static ViewParameters CalculateViewParameters(Entity entity, Vector3 up, Vector3 front, CameraComponent cameraComponent)
        {
            var upAxis = up.Length() < MathUtil.ZeroTolerance ? Vector3.UnitY : Vector3.Normalize(up);

            // if we ensure that the whole object bounding box seen under the view vector in the frustum,
            // most of the time it results in object occupying only ~ 1/4 * 1/4 of the screen space.
            // So instead we decided to approximate the object with a bounding sphere (taking the risk that some of the objects are a little bit out of the screen)
            var boundingSphere = CalculateBoundingSpere(entity);

            // calculate the min distance from the object to see it entirely
            var minimunDistance = Math.Max(
                boundingSphere.Radius / (2f * (float)Math.Tan(cameraComponent.VerticalFieldOfView * cameraComponent.AspectRatio / 2f)),
                boundingSphere.Radius / (2f * (float)Math.Tan(cameraComponent.VerticalFieldOfView / 2f)));

            var distance = 1.2f * (minimunDistance + boundingSphere.Radius); // set the view distance such that the object can be seen entirely 
            var parameters = new ViewParameters(upAxis)
            {
                Target = boundingSphere.Center + entity.Transform.Position, // use of center of the bounding box as camera target
                Distance = distance,
                FarPlane = distance
            };

            return parameters;
        }
Пример #35
0
 private void DrawProjectiles(CameraComponent c)
 {
     foreach (Projectile proj in projectiles)
     {
         if (proj != null)
         {
             proj.Draw(c);
         }
     }
 }
Пример #36
0
 private void DrawExperience(CameraComponent c)
 {
     foreach (ExperienceOrb exp in expOrbs)
     {
         if (exp != null)
         {
             exp.Draw(c);
         }
     }
 }
Пример #37
0
	public bool AttachPlayerCamera( Transform playerTransform, float fTime)
	{
		if ( null == playerTransform)
		{
			Debug.LogError( "CameraMgr::AttachCharCamera() [ null == playerTransform ]");
			return false;
		}
		m_PlayerTransform = playerTransform;

		GameObject goMainCamera = GameObject.FindWithTag( "MainCamera");

		if( null == goMainCamera)
		{
			Debug.LogError( "CameraMgr::AttachCharCamera() [ Main camera gameobject not found ]");
			return false;
		}

		m_CameraComponent = goMainCamera.GetComponent< CameraComponent > ();
		if( null == m_CameraComponent)
			m_CameraComponent = goMainCamera.AddComponent< CameraComponent > ();

		m_mainCamera = goMainCamera.GetComponent<Camera>();
		if( null == m_mainCamera)
		{
			Debug.LogError( "CameraMgr::AttachCharCamera() [ Main camera not found ]");
			return false;
		}

		m_mainCamera.nearClipPlane = 1f;
		m_mainCamera.farClipPlane = 1000f;

		if( 0.0f >= fTime)
		{
			Debug.LogError( "CameraMgr::StartCameraZoom() [ 0.0f >= fTime] ");
			return false;
		}

		SetCameraData( m_CameraData[( int)eCAMERA_STATE.NORMAL], fTime);
		
		if( true == TerrainMgr.Instance.IsCurMapType( eMAP_TYPE.Pvp ) )
		{
			m_MinZoomInDistance = -8f;
			SetZoomData( m_MinZoomInDistance );		
			SetZoom( m_MinZoomInDistance );
		}
		else			
		{
			m_MinZoomInDistance = 0f;
			SetZoomData( getZoomData );		
			SetZoom( getZoomData );
		}

		return true;
	}