Esempio n. 1
0
        /// <summary>
        /// Sets the world matrix.
        /// </summary>
        /// <param name="worldMatrix">The world matrix.</param>
        /// <param name="source">The source object that caused this change or null when not important.</param>
        public override void SetWorldMatrix(MatrixD worldMatrix, object source = null, bool forceUpdate = false)
        {
            if (Entity.Parent != null && source != Entity.Parent)
            {
                return;
            }
            MyUtils.AssertIsValid(worldMatrix);

            if (Scale != null)
            {
                MyUtils.Normalize(ref worldMatrix, out worldMatrix);
                worldMatrix = MatrixD.CreateScale(Scale.Value) * worldMatrix;
            }
            if (m_worldMatrix.EqualsFast(ref worldMatrix) && !forceUpdate)
            {
                return;
            }

            if (this.Container.Entity.Parent == null)
            {
                m_localMatrix = worldMatrix;
            }
            else
            {
                m_localMatrix = (Matrix)(worldMatrix * this.Container.Entity.Parent.WorldMatrixInvScaled);
            }
            this.m_worldMatrix = worldMatrix;

            OnWorldPositionChanged(source);

            if (this.Container.Entity.InScene && source != m_syncObject && ShouldSync && this.Container.Entity.Parent == null)
            {
                m_syncObject.MarkPhysicsDirty();
            }
        }
Esempio n. 2
0
        public void UpdateFrustumCorners()
        {
            //Set camera data
            m_camera.FarClip     = 1000.0f;
            m_camera.NearClip    = 1.0f;
            m_camera.AspectRatio = MyRenderCamera.AspectRatio;
            m_camera.FieldOfView = MyRenderCamera.FieldOfView;

            //camera.WorldMatrix = Matrix.CreateWorld(MyCamera.Position, MyCamera.ForwardVector, MyCamera.UpVector);
            m_camera.ViewMatrix       = MyRenderCamera.ViewMatrix;
            m_camera.ProjectionMatrix = MyRenderCamera.ProjectionMatrix;

            // Get corners of the main camera's bounding frustum
            MatrixD cameraTransform, viewMatrix;

            m_camera.GetWorldMatrix(out cameraTransform);
            MyUtils.AssertIsValid(cameraTransform);
            m_camera.GetViewMatrix(out viewMatrix);
            m_camera.BoundingFrustum.GetCorners(m_frustumCornersWS);
            Vector3D.Transform(m_frustumCornersWS, ref viewMatrix, m_frustumCornersVS);
            for (int i = 0; i < 4; i++)
            {
                m_farFrustumCornersVS[i] = (Vector3)m_frustumCornersVS[i + 4];
            }
        }
        public void Start(MyParticleGeneration generation)
        {
            System.Diagnostics.Debug.Assert(Life > 0);

            m_elapsedTime        = 0;
            m_normalizedTime     = 0.0f;
            m_elapsedTimeDivider = VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS / Life;
            m_generation         = generation;

            MyUtils.AssertIsValid(StartPosition);
            MyUtils.AssertIsValid(Angle);
            MyUtils.AssertIsValid(Velocity);
            MyUtils.AssertIsValid(RotationSpeed);

            m_actualPosition   = StartPosition;
            m_previousPosition = m_actualPosition;
            m_actualAngle      = Angle;

            if (PivotRotation != null && PivotDistance != null)
            {
                Vector3 rotation;
                float   distance;
                PivotRotation.GetInterpolatedValue <Vector3>(0, out rotation);
                PivotDistance.GetInterpolatedValue <float>(0, out distance);
                Quaternion rotationQ = Quaternion.CreateFromYawPitchRoll(MathHelper.ToRadians(rotation.Y), MathHelper.ToRadians(rotation.X), MathHelper.ToRadians(rotation.Z));
                m_actualPivot = Vector3.Transform(Vector3.Forward, rotationQ) * distance;
            }
        }
Esempio n. 4
0
        private MyEntity CreateFromObjectBuilder(MyMwcObjectBuilder_Base objectBuilder)
        {
            if (objectBuilder.GetObjectBuilderType() == MyMwcObjectBuilderTypeEnum.VoxelMap)
            {
                MyMwcObjectBuilder_VoxelMap voxelMapObjectBuilder = objectBuilder as MyMwcObjectBuilder_VoxelMap;
                return(MyEntities.CreateFromObjectBuilderAndAdd(null, voxelMapObjectBuilder, Matrix.Identity));
            }
            else if (objectBuilder.GetObjectBuilderType() == MyMwcObjectBuilderTypeEnum.VoxelMap_Neighbour)
            {
                //  Voxel map neighbours are handled in its static classe, so ignore it here
            }
            else
            {
                if (objectBuilder is MyMwcObjectBuilder_Object3dBase || objectBuilder is MyMwcObjectBuilder_InfluenceSphere)
                {
                    MyEntity temporaryEntity = null;
                    Matrix   matrix          = Matrix.Identity;

                    if (objectBuilder is MyMwcObjectBuilder_Object3dBase)
                    {
                        var object3d = objectBuilder as MyMwcObjectBuilder_Object3dBase;

                        matrix = Matrix.CreateWorld(object3d.PositionAndOrientation.Position, object3d.PositionAndOrientation.Forward, object3d.PositionAndOrientation.Up);
                        MyUtils.AssertIsValid(matrix);
                    }

                    temporaryEntity = MyEntities.CreateFromObjectBuilderAndAdd(null, objectBuilder, matrix);

                    MyEntities.TestEntityAfterInsertionForCollision(temporaryEntity);
                    return(temporaryEntity);
                }
            }
            return(null);
        }
Esempio n. 5
0
        //  Add billboard for one frame only. This billboard isn't particle (it doesn't survive this frame, doesn't have update/draw methods, etc).
        //  This billboard isn't facing the camera. It's always oriented in specified direction. May be used as thrusts, or inner light of reflector.
        //  It's used by other classes when they want to draw some billboard (e.g. rocket thrusts, reflector glare).
        public static void AddBillboardOriented(string material,
                                                Vector4 color, Vector3D origin, Vector3 leftVector, Vector3 upVector, float radius,
                                                int customViewProjection = -1, float reflection = 0)
        {
            Debug.Assert(material != null);
            if (!IsEnabled)
            {
                return;
            }

            MyUtils.AssertIsValid(origin);
            MyUtils.AssertIsValid(leftVector);
            MyUtils.AssertIsValid(upVector);
            MyUtils.AssertIsValid(radius);
            MyDebug.AssertDebug(radius > 0);

            //VRageRender.MyBillboard billboard = new VRageRender.MyBillboard();// m_preallocatedBillboards.Allocate();
            VRageRender.MyBillboard billboard = VRageRender.MyRenderProxy.BillboardsPoolWrite.Allocate();
            if (billboard == null)
            {
                return;
            }

            MyQuadD quad;

            MyUtils.GetBillboardQuadOriented(out quad, ref origin, radius, ref leftVector, ref upVector);

            CreateBillboard(billboard, ref quad, material, ref color, ref origin, customViewProjection, reflection);
            billboard.BlendType = MyBillboard.BlenType.Standard;

            VRageRender.MyRenderProxy.AddBillboard(billboard);
        }
Esempio n. 6
0
        public static bool AddQuad(string material, ref MyQuadD quad, ref Color color, ref Vector3D vctPos, int priority = 0, int customViewProjection = -1)
        {
            Debug.Assert(material != null);
            if (!IsEnabled)
            {
                return(false);
            }

            MyUtils.AssertIsValid(quad.Point0);
            MyUtils.AssertIsValid(quad.Point1);
            MyUtils.AssertIsValid(quad.Point2);
            MyUtils.AssertIsValid(quad.Point3);

            //VRageRender.MyBillboard billboard = m_preallocatedBillboards.Allocate();
            //VRageRender.MyBillboard billboard = new VRageRender.MyBillboard();
            VRageRender.MyBillboard billboard = VRageRender.MyRenderProxy.BillboardsPoolWrite.Allocate();
            if (billboard == null)
            {
                return(false);
            }

            billboard.Priority = priority;

            CreateBillboard(billboard, ref quad, material, ref color, ref vctPos, false, false, false, customViewProjection);

            VRageRender.MyRenderProxy.AddBillboard(billboard);

            return(true);
        }
Esempio n. 7
0
        public static void UpdateLightsForEffect(List <MyRenderLight> renderLights)
        {
            m_renderLights.Clear();

            const float RADIUS_FOR_LIGHTS = 400;

            BoundingSphereD sphere             = new BoundingSphereD(MyRenderCamera.Position, RADIUS_FOR_LIGHTS);
            int             maxLightsForEffect = MyLightsConstants.MAX_LIGHTS_FOR_EFFECT;

            MyUtils.AssertIsValid(sphere.Center);
            MyUtils.AssertIsValid(sphere.Radius);


            //  If number of lights with influence is more than max number of lights allowed in the effect, we sort them by distance (or we can do it by some priority)
            if (renderLights.Count > maxLightsForEffect)
            {
                m_sortLightsComparer.BoundingSphere = sphere;
                renderLights.Sort(m_sortLightsComparer);
            }
            else
            {
                maxLightsForEffect = renderLights.Count;
            }

            for (int i = 0; i < maxLightsForEffect; i++)
            {
                m_renderLights.Add(renderLights[i]);
            }
        }
Esempio n. 8
0
        public static bool AddAttachedQuad(string material, ref MyQuadD quad, Vector4 color, ref Vector3D vctPos, int renderObjectID)
        {
            Debug.Assert(material != null);
            if (!IsEnabled)
            {
                return(false);
            }

            MyUtils.AssertIsValid(quad.Point0);
            MyUtils.AssertIsValid(quad.Point1);
            MyUtils.AssertIsValid(quad.Point2);
            MyUtils.AssertIsValid(quad.Point3);

            //VRageRender.MyBillboard billboard = m_preallocatedBillboards.Allocate();
            //VRageRender.MyBillboard billboard = new VRageRender.MyBillboard();
            VRageRender.MyBillboard billboard = VRageRender.MyRenderProxy.BillboardsPoolWrite.Allocate();
            if (billboard == null)
            {
                return(false);
            }

            CreateBillboard(billboard, ref quad, material, ref color, ref vctPos);
            billboard.ParentID  = renderObjectID;
            billboard.BlendType = MyBillboard.BlenType.Standard;

            VRageRender.MyRenderProxy.AddBillboard(billboard);

            return(true);
        }
Esempio n. 9
0
        /// <summary>
        /// Applies the impulse.
        /// </summary>
        /// <param name="dir">The dir.</param>
        /// <param name="pos">The pos.</param>
        public void ApplyImpulse(Vector3 dir, Vector3 pos)
        {
            MyUtils.AssertIsValid(dir);
            MyUtils.AssertIsValid(pos);

            this.rigidBody.ApplyImpulse(dir, pos);
        }
Esempio n. 10
0
 public void SetViewMatrix(ref MatrixD viewMatrix)
 {
     MyUtils.AssertIsValid(viewMatrix);
     this.m_viewMatrix = viewMatrix;
     MatrixD.Invert(ref viewMatrix, out m_worldMatrix);
     MyUtils.AssertIsValid(m_worldMatrix);
     Update();
 }
Esempio n. 11
0
        /// <summary>
        /// Sets the world matrix.
        /// </summary>
        /// <param name="worldMatrix">The world matrix.</param>
        /// <param name="source">The source object that caused this change or null when not important.</param>
        public override void SetWorldMatrix(MatrixD worldMatrix, object source = null, bool forceUpdate = false)
        {
            if (Entity.Parent != null && source != Entity.Parent)
            {
                return;
            }
            MyUtils.AssertIsValid(worldMatrix);

            if (Scale != null)
            {
                //ProfilerShort.Begin("Scale");
                MyUtils.Normalize(ref worldMatrix, out worldMatrix);
                worldMatrix = MatrixD.CreateScale(Scale.Value) * worldMatrix;
                //ProfilerShort.End();
            }
            if (m_worldMatrix.EqualsFast(ref worldMatrix) && !forceUpdate)
            {
                return;
            }

            //MatrixD localMatrix;


            //m_previousWorldMatrix = this.m_worldMatrix;

            if (this.Container.Entity.Parent == null)
            {
                m_localMatrix = worldMatrix;
            }
            else
            {
                //MatrixD matParentInv = MatrixD.Invert();
                m_localMatrix = (Matrix)(worldMatrix * this.Container.Entity.Parent.WorldMatrixInvScaled);
            }
            this.m_worldMatrix = worldMatrix;

            //ProfilerShort.Begin("EqualsFast");
            //if (/*!m_localMatrix.EqualsFast(ref localMatrix) ||*/ !m_previousWorldMatrix.EqualsFast(ref worldMatrix))
            {
                //ProfilerShort.BeginNextBlock("UpdateWM");
                //m_localMatrixChanged = true;
                //this.m_localMatrix = localMatrix;
                OnWorldPositionChanged(source);
                //ProfilerShort.BeginNextBlock("sync");
                if (MyPerGameSettings.MultiplayerEnabled)
                {
                    if (this.Container.Entity.InScene && source != m_syncObject && ShouldSync && this.Container.Entity.Parent == null)
                    {
                        m_syncObject.MarkPhysicsDirty();
                    }
                }
            }
            //ProfilerShort.End();
        }
Esempio n. 12
0
        //  This method is like a constructor (which we can't use because billboards are allocated from a pool).
        //  It starts/initializes a billboard. Refs used only for optimalization
        public static void CreateBillboard(VRageRender.MyBillboard billboard, ref MyQuadD quad, string material,
                                           ref Vector4 color, ref Vector3D origin, Vector2 uvOffset, int customViewProjection = -1, float reflectivity = 0)
        {
            System.Diagnostics.Debug.Assert(material != null);

            if (string.IsNullOrEmpty(material) || !MyTransparentMaterials.ContainsMaterial(material))
            {
                material = "ErrorMaterial";
                color    = Vector4.One;
            }

            billboard.Material = material;

            MyUtils.AssertIsValid(quad.Point0);
            MyUtils.AssertIsValid(quad.Point1);
            MyUtils.AssertIsValid(quad.Point2);
            MyUtils.AssertIsValid(quad.Point3);


            //  Billboard vertices
            billboard.Position0 = quad.Point0;
            billboard.Position1 = quad.Point1;
            billboard.Position2 = quad.Point2;
            billboard.Position3 = quad.Point3;

            billboard.UVOffset = uvOffset;
            billboard.UVSize   = Vector2.One;

            //  Distance for sorting
            //  IMPORTANT: Must be calculated before we do color and alpha misting, because we need distance there
            Vector3D cameraPosition = customViewProjection == -1 ? MyTransparentGeometry.Camera.Translation : VRageRender.MyRenderProxy.BillboardsViewProjectionWrite[customViewProjection].CameraPosition;

            billboard.DistanceSquared = (float)Vector3D.DistanceSquared(cameraPosition, origin);

            //  Color
            billboard.Color          = color;
            billboard.ColorIntensity = 1;
            billboard.Reflectivity   = reflectivity;

            billboard.CustomViewProjection      = customViewProjection;
            billboard.ParentID                  = -1;
            billboard.SoftParticleDistanceScale = 1;

            //  Alpha depends on distance to camera. Very close bilboards are more transparent, so player won't see billboard errors or rotating billboards
            var mat = MyTransparentMaterials.GetMaterial(billboard.Material);

            if (mat.AlphaMistingEnable)
            {
                billboard.Color *= MathHelper.Clamp(((float)Math.Sqrt(billboard.DistanceSquared) - mat.AlphaMistingStart) / (mat.AlphaMistingEnd - mat.AlphaMistingStart), 0, 1);
            }

            billboard.Color *= mat.Color;
        }
Esempio n. 13
0
        public void SetViewMatrix(MatrixD viewMatrix)
        {
            MyUtils.AssertIsValid(viewMatrix);

            MatrixD inverted = MatrixD.Invert(viewMatrix);

            Position              = inverted.Translation;
            m_orientation         = MatrixD.Identity;
            m_orientation.Right   = inverted.Right;
            m_orientation.Up      = inverted.Up;
            m_orientation.Forward = inverted.Forward;
        }
Esempio n. 14
0
        public virtual void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            ProfilerShort.Begin("MyEntity.Init(objectBuilder)");
            MarkedForClose = false;
            Closed         = false;
            this.Render.PersistentFlags = MyPersistentEntityFlags2.CastShadows;
            if (objectBuilder != null)
            {
                if (objectBuilder.EntityDefinitionId.HasValue)
                {
                    DefinitionId = objectBuilder.EntityDefinitionId;
                    InitFromDefinition(objectBuilder, DefinitionId.Value);
                }

                if (objectBuilder.PositionAndOrientation.HasValue)
                {
                    var     posAndOrient = objectBuilder.PositionAndOrientation.Value;
                    MatrixD matrix       = MatrixD.CreateWorld(posAndOrient.Position, posAndOrient.Forward, posAndOrient.Up);
                    MyUtils.AssertIsValid(matrix);

                    PositionComp.SetWorldMatrix((MatrixD)matrix);
                    if (MyPerGameSettings.LimitedWorld)
                    {
                        ClampToWorld();
                    }
                }
                // Do not copy EntityID if it gets overwritten later. It might
                // belong to some existing entity that we're making copy of.
                if (objectBuilder.EntityId != 0)
                {
                    this.EntityId = objectBuilder.EntityId;
                }
                this.Name = objectBuilder.Name;
                this.Render.PersistentFlags = objectBuilder.PersistentFlags;

                this.Components.Deserialize(objectBuilder.ComponentContainer);
            }

            AllocateEntityID();

            this.InScene = false;

            MyEntities.SetEntityName(this, false);

            if (SyncFlag)
            {
                CreateSync();
            }
            GameLogic.Init(objectBuilder);
            ProfilerShort.End();
        }
Esempio n. 15
0
        /// <summary>
        /// Applies external force to the physics object.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="force">The force.</param>
        /// <param name="position">The position.</param>
        /// <param name="torque">The torque.</param>
        public void AddForce(MyPhysicsForceType type, Vector3?force, Vector3?position, Vector3?torque)
        {
            MyUtils.AssertIsValid(force);
            MyUtils.AssertIsValid(position);
            MyUtils.AssertIsValid(torque);

            switch (type)
            {
            case MyPhysicsForceType.ADD_BODY_FORCE_AND_BODY_TORQUE:
            {
                Matrix tempM = rigidBody.Matrix;
                tempM.Translation = Vector3.Zero;

                if (force != null && !MyMwcUtils.IsZero(force.Value))
                {
                    Vector3 tmpForce = Vector3.Transform(force.Value, tempM);

                    this.rigidBody.ApplyForce(tmpForce);
                }

                if (torque != null && !MyMwcUtils.IsZero(torque.Value))
                {
                    Vector3 tmpTorque = Vector3.Transform(torque.Value, tempM);

                    this.rigidBody.ApplyTorque(tmpTorque);
                }
            }
            break;

            case MyPhysicsForceType.APPLY_WORLD_IMPULSE_AND_WORLD_ANGULAR_IMPULSE:
            {
                if (force.HasValue && position.HasValue)
                {
                    this.rigidBody.ApplyImpulse(force.Value, position.Value);
                }

                if (torque.HasValue)
                {
                    this.rigidBody.ApplyTorque(torque.Value);
                }
            }
            break;

            default:
            {
                Debug.Fail("Unhandled enum!");
            }
            break;
            }
        }
Esempio n. 16
0
        public bool Update()
        {
            m_elapsedTime += VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;

            if (m_elapsedTime >= Life)
            {
                return(false);
            }

            m_normalizedTime += m_elapsedTimeDivider;

            m_velocity += m_generation.GetEffect().Gravity *m_generation.Gravity *VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;

            m_previousPosition  = m_actualPosition;
            m_actualPosition.X += Velocity.X * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;
            m_actualPosition.Y += Velocity.Y * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;
            m_actualPosition.Z += Velocity.Z * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;

            if (PivotRotation != null && PivotDistance != null)
            {
                MyTransparentGeometry.StartParticleProfilingBlock("Pivot calculation");

                Vector3 rotation;
                float   distance;
                PivotRotation.GetInterpolatedValue <Vector3>(m_normalizedTime, out rotation);
                PivotDistance.GetInterpolatedValue <float>(m_normalizedTime, out distance);
                Quaternion rotationQ = Quaternion.CreateFromYawPitchRoll(MathHelper.ToRadians(rotation.Y), MathHelper.ToRadians(rotation.X), MathHelper.ToRadians(rotation.Z));
                m_actualPivot = Vector3.Transform(Vector3.Forward, rotationQ) * distance;

                MyTransparentGeometry.EndParticleProfilingBlock();
            }

            if (Acceleration != null)
            {
                MyTransparentGeometry.StartParticleProfilingBlock("Acceleration calculation");

                Acceleration.GetInterpolatedValue <Vector3>(m_normalizedTime, out m_actualAcceleration);
                Velocity += m_actualAcceleration * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;

                MyTransparentGeometry.EndParticleProfilingBlock();
            }

            m_actualAngle += RotationSpeed * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;

            MyUtils.AssertIsValid(m_actualPosition);
            MyUtils.AssertIsValid(m_actualAngle);

            return(true);
        }
Esempio n. 17
0
        //  This method is like a constructor (which we can't use because billboards are allocated from a pool).
        //  It starts/initializes a billboard. Refs used only for optimalization
        public void Start(ref MyQuad quad, MyTransparentMaterialEnum materialEnum, MyTransparentMaterialEnum blendMaterial, float textureBlendRatio,
                          ref Vector4 color, ref Vector3 origin, Vector2 uvOffset, bool colorize = false, bool near = false, bool lowres = false)
        {
            MaterialEnum      = materialEnum;
            BlendMaterial     = blendMaterial;
            BlendTextureRatio = textureBlendRatio;

            MyUtils.AssertIsValid(quad.Point0);
            MyUtils.AssertIsValid(quad.Point1);
            MyUtils.AssertIsValid(quad.Point2);
            MyUtils.AssertIsValid(quad.Point3);


            //  Billboard vertexes
            Position0 = quad.Point0;
            Position1 = quad.Point1;
            Position2 = quad.Point2;
            Position3 = quad.Point3;

            UVOffset = uvOffset;

            EnableColorize = colorize;

            if (EnableColorize)
            {
                Size = (Position0 - Position2).Length();
            }

            //  Distance for sorting
            //  IMPORTANT: Must be calculated before we do color and alpha misting, because we need distance there
            DistanceSquared = Vector3.DistanceSquared(MyCamera.Position, origin);

            //  Color
            Color = color;

            Near   = near;
            Lowres = lowres;

            //  Alpha depends on distance to camera. Very close bilboards are more transparent, so player won't see billboard errors or rotating billboards
            var mat = MyTransparentMaterialConstants.GetMaterialProperties(MaterialEnum);

            if (mat.AlphaMistingEnable)
            {
                Color *= MathHelper.Clamp(((float)Math.Sqrt(DistanceSquared) - mat.AlphaMistingStart) / (mat.AlphaMistingEnd - mat.AlphaMistingStart), 0, 1);
            }

            ContainedBillboards.Clear();
        }
        public void Start(MyParticleGeneration generation)
        {
            System.Diagnostics.Debug.Assert(Life > 0);

            m_elapsedTime        = 0;
            m_normalizedTime     = 0.0f;
            m_elapsedTimeDivider = MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS / Life;
            m_generation         = generation;

            MyUtils.AssertIsValid(StartPosition);
            MyUtils.AssertIsValid(Angle);
            MyUtils.AssertIsValid(Velocity);
            MyUtils.AssertIsValid(RotationSpeed);

            m_actualPosition = StartPosition;
            m_actualAngle    = Angle;
        }
Esempio n. 19
0
        //  This method adds lights information into specified effect.
        //  Method gets lights that could have influence on bounding sphere (it is assumed this will be bounding sphere of a phys object or voxel render cell).
        //  Lights that are far from bounding sphere are ignored. But near lights are taken to second step, where we sort them by distance and priority
        //  and set them to the effect.
        //  We assume RemoveKilled() was called before this method, so here we don't check if light isn't killed.
        public static void UpdateEffect(MyEffectDynamicLightingBase effect, ref BoundingSphere boundingSphere, bool subtractCameraPosition)
        {
            MyUtils.AssertIsValid(boundingSphere.Center);
            MyUtils.AssertIsValid(boundingSphere.Radius);

            // Reason to remove this condition: when updating effect with same bounding sphere, it could return different result when some light died (effect ended) before second request
            //if (m_lastBoundingSphere != boundingSphere)
            {
                UpdateSortedLights(ref boundingSphere, true);
                m_lastBoundingSphere = boundingSphere;

                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //  Now in 'm_sortedLights' we have only lights that intersects bounding sphere in SAP list
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                m_lightsCount = m_sortedLights.Count;
                int maxLightsForEffect = MyLightsConstants.MAX_LIGHTS_FOR_EFFECT;

                //  If number of lights with influence is more than max number of lights allowed in the effect, we sort them by distance (or we can do it by some priority)
                if (m_sortedLights.Count > maxLightsForEffect)
                {
                    m_sortLightsComparer.BoundingSphere = boundingSphere;
                    m_sortedLights.Sort(m_sortLightsComparer);
                    m_lightsCount = maxLightsForEffect;
                }
            }

            //  Set lights to effect, but not more than effect can handle
            for (int i = 0; i < m_lightsCount; i++)
            {
                SetLightToEffect(effect, i, m_sortedLights[i], subtractCameraPosition);
            }

            effect.SetDynamicLightsCount(m_lightsCount);


            Vector4 sunColor = MySunWind.GetSunColor();

            effect.SetSunColor(new Vector3(sunColor.X, sunColor.Y, sunColor.Z));
            effect.SetDirectionToSun(MyGuiScreenGamePlay.Static.GetDirectionToSunNormalized());
            effect.SetSunIntensity(MySector.SunProperties.SunIntensity);

            Vector3 ambientColor = MyRender.AmbientColor * MyRender.AmbientMultiplier;

            effect.SetAmbientColor(ambientColor * (MyRenderConstants.RenderQualityProfile.ForwardRender ? 6.5f : 1.0f));
        }
        /// <summary>
        /// Sets the world matrix.
        /// </summary>
        /// <param name="worldMatrix">The world matrix.</param>
        /// <param name="source">The source object that caused this change or null when not important.</param>
        public override void SetWorldMatrix(MatrixD worldMatrix, object source = null)
        {
            MyUtils.AssertIsValid(worldMatrix);

            ProfilerShort.Begin("Scale");
            if (Scale != null)
            {
                MyUtils.Normalize(ref worldMatrix, out worldMatrix);
                worldMatrix = MatrixD.CreateScale(Scale.Value) * worldMatrix;
            }
            ProfilerShort.End();
            MatrixD localMatrix;

            if (this.Container.Entity.Parent == null)
            {
                m_previousParentWorldMatrix = this.m_worldMatrix;
                this.m_worldMatrix          = worldMatrix;
                localMatrix = worldMatrix;
            }
            else
            {
                MatrixD matParentInv = MatrixD.Invert(this.Container.Entity.Parent.WorldMatrix);
                localMatrix = (Matrix)(worldMatrix * matParentInv);
            }

            ProfilerShort.Begin("EqualsFast");
            if (!m_localMatrix.EqualsFast(ref localMatrix) || !m_previousParentWorldMatrix.EqualsFast(ref worldMatrix))
            {
                ProfilerShort.BeginNextBlock("UpdateWM");
                m_localMatrixChanged = true;
                this.m_localMatrix   = localMatrix;
                UpdateWorldMatrix(source);
                ProfilerShort.BeginNextBlock("sync");
                if (MyPerGameSettings.MultiplayerEnabled)
                {
                    if (this.Container.Entity.InScene && source != m_syncObject && ShouldSync && this.Container.Entity.Parent == null)
                    {
                        m_syncObject.UpdatePosition();
                    }
                }
            }
            ProfilerShort.End();
        }
Esempio n. 21
0
        public void Start(MyParticleGeneration generation)
        {
            System.Diagnostics.Debug.Assert(Life > 0);

            m_elapsedTime        = 0;
            m_normalizedTime     = 0.0f;
            m_elapsedTimeDivider = VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS / Life;
            m_generation         = generation;

            MyUtils.AssertIsValid(StartPosition);
            MyUtils.AssertIsValid(Angle);
            MyUtils.AssertIsValid(Velocity);

            m_actualPosition   = StartPosition;
            m_previousPosition = m_actualPosition;
            m_actualAngle      = new Vector3(MathHelper.ToRadians(Angle.X), MathHelper.ToRadians(Angle.Y), MathHelper.ToRadians(Angle.Z));

            if (Pivot != null)
            {
                Pivot.GetInterpolatedValue <Vector3>(0, out m_actualPivot);
            }

            if (PivotRotation != null)
            {
                PivotRotation.GetInterpolatedValue <Vector3>(0, out m_actualPivotRotation);
            }

            m_arrayIndex = -1;
            if (ArrayIndex != null)
            {
                ArrayIndex.GetInterpolatedValue <int>(m_normalizedTime, out m_arrayIndex);

                int     arrayOffset = m_generation.ArrayOffset;
                Vector3 arraySize   = m_generation.ArraySize;

                if (arraySize.X > 0 && arraySize.Y > 0)
                {
                    int arrayModulo = m_generation.ArrayModulo == 0 ? (int)arraySize.X * (int)arraySize.Y : m_generation.ArrayModulo;
                    m_arrayIndex = arrayOffset + m_arrayIndex % arrayModulo;
                }
            }
        }
        public bool Update()
        {
            m_elapsedTime += MyConstants.PHYSICS_STEP_SIZE_IN_SECONDS;

            if (m_elapsedTime >= Life)
            {
                return(false);
            }

            m_normalizedTime += m_elapsedTimeDivider;

            m_actualPosition.X += Velocity.X * MyConstants.PHYSICS_STEP_SIZE_IN_SECONDS;
            m_actualPosition.Y += Velocity.Y * MyConstants.PHYSICS_STEP_SIZE_IN_SECONDS;
            m_actualPosition.Z += Velocity.Z * MyConstants.PHYSICS_STEP_SIZE_IN_SECONDS;

            m_actualAngle += RotationSpeed * MyConstants.PHYSICS_STEP_SIZE_IN_SECONDS;

            MyUtils.AssertIsValid(m_actualPosition);
            MyUtils.AssertIsValid(m_actualAngle);

            return(true);
        }
Esempio n. 23
0
        public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            ProfilerShort.Begin("MyEntity.Init(objectBuilder)");
            if (objectBuilder != null)
            {
                if (objectBuilder.PositionAndOrientation.HasValue)
                {
                    var     posAndOrient = objectBuilder.PositionAndOrientation.Value;
                    MatrixD matrix       = MatrixD.CreateWorld(posAndOrient.Position, posAndOrient.Forward, posAndOrient.Up);
                    MyUtils.AssertIsValid(matrix);

                    Container.Entity.PositionComp.SetWorldMatrix(matrix);
                }
                // Do not copy EntityID if it gets overwritten later. It might
                // belong to some existing entity that we're making copy of.
                if (objectBuilder.EntityId != 0)
                {
                    Container.Entity.EntityId = objectBuilder.EntityId;
                }
                Container.Entity.Name = objectBuilder.Name;
                Container.Entity.Render.PersistentFlags = objectBuilder.PersistentFlags;
            }

            AllocateEntityID();

            Container.Entity.InScene = false;

            MyEntities.SetEntityName(m_entity, false);

            if (m_entity.SyncFlag)
            {
                m_entity.CreateSync();
            }
            GameLogic.Init(objectBuilder);
            ProfilerShort.End();
        }
Esempio n. 24
0
 public static void SetPosition(Vector3D value)
 {
     MyUtils.AssertIsValid(value);
     Position = value;
 }
Esempio n. 25
0
        public bool Update()
        {
            m_elapsedTime += VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;

            if (m_elapsedTime >= Life)
            {
                return(false);
            }

            m_normalizedTime += m_elapsedTimeDivider;

            m_velocity += m_generation.GetEffect().Gravity *m_generation.Gravity *VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;

            m_previousPosition  = m_actualPosition;
            m_actualPosition.X += Velocity.X * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;
            m_actualPosition.Y += Velocity.Y * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;
            m_actualPosition.Z += Velocity.Z * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;

            if (Pivot != null)
            {
                MyTransparentGeometry.StartParticleProfilingBlock("Pivot calculation");

                Pivot.GetInterpolatedValue <Vector3>(m_normalizedTime, out m_actualPivot);

                MyTransparentGeometry.EndParticleProfilingBlock();
            }

            if (Acceleration != null)
            {
                MyTransparentGeometry.StartParticleProfilingBlock("Acceleration calculation");

                Acceleration.GetInterpolatedValue <Vector3>(m_normalizedTime, out m_actualAcceleration);

                Matrix transform = Matrix.Identity;

                if (m_generation.AccelerationReference == MyAccelerationReference.Camera)
                {
                    transform = MyTransparentGeometry.Camera;
                }
                else if (m_generation.AccelerationReference == MyAccelerationReference.Local)
                {
                }
                else if ((m_generation.AccelerationReference == MyAccelerationReference.Velocity))
                {
                    Vector3 actualVelocity = (Vector3)(m_actualPosition - m_previousPosition);

                    if (actualVelocity.LengthSquared() < 0.00001f)
                    {
                        m_actualAcceleration = Vector3.Zero;
                    }
                    else
                    {
                        transform = Matrix.CreateFromDir(Vector3.Normalize(actualVelocity));
                    }
                }
                else if ((m_generation.AccelerationReference == MyAccelerationReference.Gravity))
                {
                    if (m_generation.GetEffect().Gravity.LengthSquared() < 0.00001f)
                    {
                        m_actualAcceleration = Vector3.Zero;
                    }
                    else
                    {
                        transform = Matrix.CreateFromDir(Vector3.Normalize(m_generation.GetEffect().Gravity));
                    }
                }
                else
                {
                    System.Diagnostics.Debug.Fail("Unknown RotationReference enum");
                }

                m_actualAcceleration = Vector3.TransformNormal(m_actualAcceleration, transform);

                Velocity += m_actualAcceleration * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;

                MyTransparentGeometry.EndParticleProfilingBlock();
            }

            if (RotationSpeed != null)
            {
                Vector3 rotationSpeed;
                RotationSpeed.GetInterpolatedValue <Vector3>(m_normalizedTime, out rotationSpeed);
                m_actualAngle += new Vector3(MathHelper.ToRadians(rotationSpeed.X), MathHelper.ToRadians(rotationSpeed.Y), MathHelper.ToRadians(rotationSpeed.Z)) * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;
            }

            if (PivotRotation != null)
            {
                Vector3 pivotRotation;
                PivotRotation.GetInterpolatedValue <Vector3>(m_normalizedTime, out pivotRotation);
                m_actualPivotRotation += pivotRotation;
            }

            if (ArrayIndex != null)
            {
                ArrayIndex.GetInterpolatedValue <int>(m_normalizedTime, out m_arrayIndex);
            }

            MyUtils.AssertIsValid(m_actualPosition);
            MyUtils.AssertIsValid(m_actualAngle);

            return(true);
        }
Esempio n. 26
0
 public void SetWorldMatrix(ref MatrixD worldMatrix)
 {
     this.m_worldMatrix = worldMatrix;
     MyUtils.AssertIsValid(m_worldMatrix);
     Update();
 }
        private void CreateParticle(Vector3D interpolatedEffectPosition)
        {
            MyAnimatedParticle particle = MyTransparentGeometry.AddAnimatedParticle();

            if (particle == null)
            {
                return;
            }

            particle.Type = (MyParticleTypeEnum)ParticleType.GetValue <int>();

            MyUtils.AssertIsValid(m_effect.WorldMatrix);

            Vector3D startOffset;

            m_emitter.CalculateStartPosition(m_effect.GetElapsedTime(), MatrixD.CreateWorld(interpolatedEffectPosition, m_effect.WorldMatrix.Forward, m_effect.WorldMatrix.Up), m_effect.UserEmitterScale * m_effect.UserScale, out startOffset, out particle.StartPosition);

            Vector3D particlePosition = particle.StartPosition;

            m_AABB = m_AABB.Include(ref particlePosition);

            Life.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out particle.Life);
            float lifeVar = LifeVar;

            if (lifeVar > 0)
            {
                particle.Life = MathHelper.Max(MyUtils.GetRandomFloat(particle.Life - lifeVar, particle.Life + lifeVar), 0.1f);
            }

            Vector3 vel;

            Velocity.GetInterpolatedValue <Vector3>(m_effect.GetElapsedTime(), out vel);
            vel.X            *= m_effect.UserScale;
            vel.Y            *= m_effect.UserScale;
            vel.Z            *= m_effect.UserScale;
            particle.Velocity = vel;

            if (VelocityDir == MyVelocityDirEnum.FromEmitterCenter)
            {
                if (!MyUtils.IsZero(startOffset - particle.StartPosition))
                {
                    float length = particle.Velocity.Length();
                    particle.Velocity = MyUtils.Normalize(particle.StartPosition - (Vector3D)startOffset) * length;
                }
            }
            particle.Velocity = Vector3D.TransformNormal(particle.Velocity, GetEffect().WorldMatrix);

            Angle.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out particle.Angle);
            float angleVar = AngleVar;

            if (angleVar > 0)
            {
                particle.Angle = MyUtils.GetRandomFloat(particle.Angle - AngleVar, particle.Angle + AngleVar);
            }

            RotationSpeed.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out particle.RotationSpeed);
            float rotationSpeedVar = RotationSpeedVar;

            if (rotationSpeedVar > 0)
            {
                particle.RotationSpeed = MyUtils.GetRandomFloat(particle.RotationSpeed - RotationSpeedVar, particle.RotationSpeed + RotationSpeedVar);
            }

            float radiusVar;

            RadiusVar.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out radiusVar);
            float lodRadius = 1.0f;

            if (GetEffect().EnableLods)
            {
                LODRadius.GetInterpolatedValue <float>(GetEffect().Distance, out lodRadius);
            }

            Radius.GetInterpolatedKeys(m_effect.GetElapsedTime(),
                                       radiusVar,
                                       (EnableCustomRadius.GetValue <bool>() ? m_effect.UserRadiusMultiplier : 1.0f)
                                       * lodRadius
                                       * GetEffect().UserScale,
                                       particle.Radius);

            if (particle.Type != MyParticleTypeEnum.Point)
            {
                Thickness.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out particle.Thickness);
            }

            particle.Thickness *= lodRadius;

            float colorVar;

            ColorVar.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out colorVar);
            Color.GetInterpolatedKeys(m_effect.GetElapsedTime(), colorVar, 1.0f, particle.Color);

            Material.GetInterpolatedKeys(m_effect.GetElapsedTime(), 0, 1.0f, particle.Material);

            particle.Flags  = 0;
            particle.Flags |= BlendTextures.GetValue <bool>() ? MyAnimatedParticle.ParticleFlags.BlendTextures : 0;
            particle.Flags |= GetEffect().IsInFrustum ? MyAnimatedParticle.ParticleFlags.IsInFrustum : 0;

            particle.Start(this);

            m_particles.Add(particle);
        }