private void ComputeGravityAlignedOrientation(out MatrixD resultOrientationStorage)
        {
            // Y axis
            bool     inGravityField = true;
            Vector3D upVector       = -MyGravityProviderSystem.CalculateTotalGravityInPoint(Position);

            if (upVector.LengthSquared() < MyMathConstants.EPSILON)
            {
                upVector = m_lastUpVec;
                m_lastOrientationWeight = 1;
                inGravityField          = false;
            }
            else
            {
                m_lastUpVec = upVector;
            }
            upVector.Normalize();
            // X axis
            Vector3D rightVector = m_lastRightVec - Vector3D.Dot(m_lastRightVec, upVector) * upVector;

            if (rightVector.LengthSquared() < MyMathConstants.EPSILON)
            {
                rightVector = m_orientation.Right - Vector3D.Dot(m_orientation.Right, upVector) * upVector;
                // backup behavior if singularity happens
                if (rightVector.LengthSquared() < MyMathConstants.EPSILON)
                {
                    rightVector = m_orientation.Forward - Vector3D.Dot(m_orientation.Forward, upVector) * upVector;
                }
                // backup behavior if singularity happens
            }
            rightVector.Normalize();
            m_lastRightVec = rightVector;
            // Z axis
            Vector3D forwardVector;

            Vector3D.Cross(ref upVector, ref rightVector, out forwardVector);

            resultOrientationStorage         = MatrixD.Identity;
            resultOrientationStorage.Right   = rightVector;
            resultOrientationStorage.Up      = upVector;
            resultOrientationStorage.Forward = forwardVector;
            resultOrientationStorage         = MatrixD.CreateFromAxisAngle(Vector3D.Right, m_pitch) * resultOrientationStorage *
                                               MatrixD.CreateFromAxisAngle(upVector, m_yaw);
            upVector    = resultOrientationStorage.Up;
            rightVector = resultOrientationStorage.Right;
            resultOrientationStorage.Right = Math.Cos(m_roll) * rightVector + Math.Sin(m_roll) * upVector;
            resultOrientationStorage.Up    = -Math.Sin(m_roll) * rightVector + Math.Cos(m_roll) * upVector;

            if (inGravityField && m_lastOrientationWeight > 0)
            {
                m_lastOrientationWeight = Math.Max(0, m_lastOrientationWeight - MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS);

                resultOrientationStorage = MatrixD.Slerp(resultOrientationStorage, m_lastOrientation,
                                                         MathHelper.SmoothStepStable(m_lastOrientationWeight));
            }
            if (!inGravityField)
            {
                m_lastOrientation = resultOrientationStorage;
            }
        }
Example #2
0
        void UpdateTreadmill()
        {
            if (!IsControlled)
            {
                return;
            }

            MatrixD matrix = cockpit.WorldMatrix;

            matrix *= MatrixD.CreateFromAxisAngle(matrix.Right, MathHelper.ToRadians(5));

            treadmillCounter += treadmillUVOffset;

            if (treadmillCounter > 1)
            {
                treadmillCounter = 0;
            }

            Vector2 offset = new Vector2(treadmillCounter, 0);

            MyTransparentGeometry.AddBillboardOriented(
                MyStringId.GetOrCompute("Treadmill"),
                Color.White.ToVector4(),
                cockpit.GetPosition() + (cockpit.WorldMatrix.Up * -0.948f) + (cockpit.WorldMatrix.Forward * -0.2f),
                matrix.Backward,
                matrix.Right,
                0.6f,
                0.25f,
                Vector2.Zero + offset);
        }
        public override void Draw()
        {
            if (MyAPIGateway.Multiplayer.IsServer)
            {
                return;
            }

            foreach (var effect in _enabledEffects)
            {
                var rotatingParticle = effect.Value;

                if (rotatingParticle.Effect == null)
                {
                    rotatingParticle.Play();
                    continue;
                }

                //Rotate the particle emitter every tick
                var angle = Vector3D.Rotate(rotatingParticle.InitialMatrix.Translation - rotatingParticle.CenterMatrix.Translation,
                                            MatrixD.CreateFromAxisAngle(rotatingParticle.CenterMatrix.Up, rotatingParticle.CurrentAngle));

                var finalPos = rotatingParticle.CenterMatrix.Translation + Vector3D.Normalize(angle) * rotatingParticle.Radius;
                var finalUp  = Vector3D.Normalize(rotatingParticle.CenterMatrix.Translation - finalPos);

                //Final matrix
                rotatingParticle.Effect.WorldMatrix = MatrixD.CreateWorld(finalPos, finalUp, rotatingParticle.Effect.WorldMatrix.Up);

                //Increase the angle every tick
                rotatingParticle.CurrentAngle += 0.5f;
            }
        }
        protected override MatrixD GetEffectMatrix(float muzzleOffset)
        {
            if (m_raycastComponent.HitCubeGrid == null || m_raycastComponent.HitBlock == null || !(Owner is MyCharacter))
            {
                return(MatrixD.CreateWorld(m_gunBase.GetMuzzleWorldPosition(), WorldMatrix.Forward, WorldMatrix.Up));
            }

            var headMatrix = Owner.GetHeadMatrix(true);
            var aimPoint   = m_raycastComponent.HitPosition;
            var dist       = Vector3.Dot(aimPoint - m_gunBase.GetMuzzleWorldPosition(), headMatrix.Forward);

            dist -= 0.1f;
            var target = m_gunBase.GetMuzzleWorldPosition() + headMatrix.Forward * (dist * muzzleOffset) + headMatrix.Up * 0.04f;

            MatrixD matrix = MatrixD.CreateWorld(dist > 0 && muzzleOffset == 0 ? m_gunBase.GetMuzzleWorldPosition() : target, WorldMatrix.Forward, WorldMatrix.Up);

            //var normal = ((MyCharacter) CharacterInventory.Owner).AimedPointNormal;

            Vector3D right = Vector3D.TransformNormal(matrix.Right, MatrixD.CreateFromAxisAngle(matrix.Up, -MathHelper.ToRadians(45)));

            right = MyUtilRandomVector3ByDeviatingVector.GetRandom(right, MyUtils.GetRandomFloat(0, 0.35f));
            Vector3D up      = Vector3D.Cross(right, matrix.Forward);
            Vector3D forward = Vector3D.Cross(up, right);

            return(MatrixD.CreateWorld(matrix.Translation, forward, up));
            //matrix = Matrix.CreateFromAxisAngle(matrix.Up, -MathHelper.ToRadians(75)) * matrix;
            //return Matrix.CreateWorld(matrix.Translation, matrix.Forward, Vector3.Reflect(matrix.Forward, normal));
        }
Example #5
0
        public void UpdateLightPosition()
        {
            if (m_light != null)
            {
                MyCharacter character = m_skinnedEntity as MyCharacter;

                m_lightLocalPosition = character.Definition.LightOffset;

                MatrixD headMatrix     = character.GetHeadMatrix(false, true, false);
                MatrixD headMatrixAnim = character.GetHeadMatrix(false, true, true, true);

                if (m_oldReflectorAngle != MyCharacter.REFLECTOR_DIRECTION)
                {
                    m_oldReflectorAngle    = MyCharacter.REFLECTOR_DIRECTION;
                    m_reflectorAngleMatrix = MatrixD.CreateFromAxisAngle(headMatrix.Forward, MathHelper.ToRadians(MyCharacter.REFLECTOR_DIRECTION));
                }

                m_light.ReflectorDirection = Vector3.Transform(headMatrix.Forward, m_reflectorAngleMatrix);
                m_light.ReflectorUp        = headMatrix.Up;
                m_light.ReflectorTexture   = "Textures\\Lights\\dual_reflector_2.dds";
                m_light.ReflectorColor     = MyCharacter.REFLECTOR_COLOR;
                m_light.UpdateReflectorRangeAndAngle(MyCharacter.REFLECTOR_CONE_ANGLE, MyCharacter.REFLECTOR_RANGE);
                m_light.Position = Vector3D.Transform(m_lightLocalPosition, headMatrixAnim);
                m_light.UpdateLight();

                Matrix[] boneMatrices = character.BoneAbsoluteTransforms;

                if (m_leftGlare != null)
                {
                    MatrixD leftGlareMatrix = m_reflectorAngleMatrix * MatrixD.Normalize(boneMatrices[m_leftLightIndex]) * m_skinnedEntity.PositionComp.WorldMatrix;

                    m_leftGlare.Position           = leftGlareMatrix.Translation;
                    m_leftGlare.Range              = 1;
                    m_leftGlare.ReflectorDirection = -leftGlareMatrix.Up;//, m_reflectorAngleMatrix);
                    m_leftGlare.ReflectorUp        = leftGlareMatrix.Forward;
                    m_leftGlare.GlareIntensity     = m_light.Intensity;
                    m_leftGlare.GlareSize          = m_lightGlareSize;
                    m_leftGlare.GlareQuerySize     = 0.1f;
                    m_leftGlare.GlareMaxDistance   = MyCharacter.LIGHT_GLARE_MAX_DISTANCE;
                    m_leftGlare.UpdateLight();
                }

                if (m_rightGlare != null)
                {
                    MatrixD rightGlareMatrix = m_reflectorAngleMatrix * MatrixD.Normalize(boneMatrices[m_rightLightIndex]) * m_skinnedEntity.PositionComp.WorldMatrix;
                    m_rightGlare.Position           = rightGlareMatrix.Translation;
                    m_rightGlare.Range              = 1;
                    m_rightGlare.ReflectorDirection = -rightGlareMatrix.Up;
                    m_rightGlare.ReflectorUp        = rightGlareMatrix.Forward;
                    m_rightGlare.GlareIntensity     = m_light.Intensity;
                    m_rightGlare.GlareSize          = m_lightGlareSize;
                    m_rightGlare.GlareQuerySize     = 0.1f;
                    m_rightGlare.GlareMaxDistance   = MyCharacter.LIGHT_GLARE_MAX_DISTANCE;
                    m_rightGlare.UpdateLight();
                }
            }
        }
        private MatrixD FindRotationMatrix(MyObjectBuilder_CubeGrid cubeGrid)
        {
            var resultMatrix = MatrixD.Identity;
            var cockpits     = cubeGrid.CubeBlocks.OfType <MyObjectBuilder_Cockpit>()
                               .Where(blk =>
            {
                return(!(blk is MyObjectBuilder_CryoChamber) &&
                       blk.SubtypeName.IndexOf("bathroom", StringComparison.InvariantCultureIgnoreCase) == -1);
            })
                               .ToList();

            MyObjectBuilder_CubeBlock referenceBlock = cockpits.Find(blk => blk.IsMainCockpit) ?? cockpits.FirstOrDefault();



            if (referenceBlock == null)
            {
                var remoteControls = cubeGrid.CubeBlocks.OfType <MyObjectBuilder_RemoteControl>().ToList();
                referenceBlock = remoteControls.Find(blk => blk.IsMainCockpit) ?? remoteControls.FirstOrDefault();
            }

            if (referenceBlock == null)
            {
                referenceBlock = cubeGrid.CubeBlocks.OfType <MyObjectBuilder_LandingGear>().FirstOrDefault();
            }



            if (referenceBlock != null)
            {
                if (referenceBlock.BlockOrientation.Up == Base6Directions.Direction.Right)
                {
                    resultMatrix *= MatrixD.CreateFromAxisAngle(Vector3D.Forward, MathHelper.ToRadians(-90));
                }
                else if (referenceBlock.BlockOrientation.Up == Base6Directions.Direction.Left)
                {
                    resultMatrix *= MatrixD.CreateFromAxisAngle(Vector3D.Forward, MathHelper.ToRadians(90));
                }
                else if (referenceBlock.BlockOrientation.Up == Base6Directions.Direction.Down)
                {
                    resultMatrix *= MatrixD.CreateFromAxisAngle(Vector3D.Forward, MathHelper.ToRadians(180));
                }
                else if (referenceBlock.BlockOrientation.Up == Base6Directions.Direction.Forward)
                {
                    resultMatrix *= MatrixD.CreateFromAxisAngle(Vector3D.Left, MathHelper.ToRadians(-90));
                }
                else if (referenceBlock.BlockOrientation.Up == Base6Directions.Direction.Backward)
                {
                    resultMatrix *= MatrixD.CreateFromAxisAngle(Vector3D.Left, MathHelper.ToRadians(90));
                }
            }



            return(resultMatrix);
        }
        private void CalculateGridPosition(Vector3D Target)
        {
            List <MyObjectBuilder_CubeGrid> TotalGrids = new List <MyObjectBuilder_CubeGrid>();
            List <MyObjectBuilder_Cockpit>  cockpits   = new List <MyObjectBuilder_Cockpit>();
            Vector3D forwardVector = Vector3D.Zero;


            Hangar.Debug("Total Grids to be pasted: " + _grids.Count());

            //Attempt to get gravity/Artificial gravity to align the grids to


            //Here you can adjust the offset from the surface and rotation.
            //Unfortunatley we move the grid again after this to find a free space around the character. Perhaps later i can incorporate that into
            //LordTylus's existing grid checkplament method
            float gravityRotation = 0f;

            Vector3 gravityDirectionalVector = MyGravityProviderSystem.CalculateNaturalGravityInPoint(Target);

            if (gravityDirectionalVector == Vector3.Zero)
            {
                gravityDirectionalVector = MyGravityProviderSystem.CalculateArtificialGravityInPoint(Target);
            }
            Vector3D upDirectionalVector;

            if (gravityDirectionalVector != Vector3.Zero)
            {
                Hangar.Debug("Attempting to correct grid orientation!");
                gravityDirectionalVector.Normalize();
                upDirectionalVector = -gravityDirectionalVector;

                if (forwardVector == Vector3D.Zero)
                {
                    forwardVector = Vector3D.CalculatePerpendicularVector(gravityDirectionalVector);
                    if (gravityRotation != 0f)
                    {
                        MatrixD matrixa = MatrixD.CreateFromAxisAngle(upDirectionalVector, gravityRotation);
                        forwardVector = Vector3D.Transform(forwardVector, matrixa);
                    }
                }
            }
            else if (forwardVector == Vector3D.Zero)
            {
                forwardVector       = Vector3D.Right;
                upDirectionalVector = Vector3D.Up;
            }
            else
            {
                upDirectionalVector = Vector3D.CalculatePerpendicularVector(-forwardVector);
            }

            BeginAlignToGravity(_grids, Target, forwardVector, upDirectionalVector);
        }
Example #8
0
 public void UpdateLightPosition()
 {
     if (m_light != null)
     {
         MatrixD specMatrix = MatrixD.CreateWorld(Position, m_orientation.Forward, m_orientation.Up);
         m_reflectorAngleMatrix     = MatrixD.CreateFromAxisAngle(specMatrix.Backward, MathHelper.ToRadians(MyCharacter.REFLECTOR_DIRECTION));
         m_light.ReflectorDirection = Vector3.Transform(specMatrix.Forward, m_reflectorAngleMatrix);
         m_light.ReflectorUp        = specMatrix.Up;
         m_light.Position           = Position;
         m_light.UpdateLight();
     }
 }
Example #9
0
 private void UpdateLightPosition()
 {
     if (this.m_light != null)
     {
         MatrixD xd = MatrixD.CreateWorld(base.Position, base.m_orientation.Forward, base.m_orientation.Up);
         this.m_reflectorAngleMatrix     = (Matrix)MatrixD.CreateFromAxisAngle(xd.Backward, (double)MathHelper.ToRadians(MyCharacter.REFLECTOR_DIRECTION));
         this.m_light.ReflectorDirection = Vector3.Transform((Vector3)xd.Forward, this.m_reflectorAngleMatrix);
         this.m_light.ReflectorUp        = (Vector3)xd.Up;
         this.m_light.Position           = base.Position;
         this.m_light.UpdateLight();
     }
 }
Example #10
0
        /// <summary>
        ///     Calculates the current sun direction.
        /// </summary>
        /// <returns>Returns the sun direction vector.</returns>
        public Vector3D CalculateSunDirection()
        {
            if (_enabled)
            {
                const float predict = 16f * 100 / 1000;
                var         vector3 = Vector3D.Transform(_baseSunDirection, MatrixD.CreateFromAxisAngle(_sunRotationAxis, 6.2831859588623 * ((ElapsedGameTime.TotalSeconds + predict) / Speed)));
                vector3.Normalize();

                return(vector3);
            }

            return(_baseSunDirection);
        }
Example #11
0
        private void ComputeGravityAlignedOrientation(out MatrixD resultOrientationStorage)
        {
            Vector3D vectord3;
            bool     flag = true;
            Vector3D up   = -MyGravityProviderSystem.CalculateTotalGravityInPoint(base.Position);

            if (up.LengthSquared() >= 9.9999997473787516E-06)
            {
                this.m_lastUpVec = up;
            }
            else
            {
                up = this.m_lastUpVec;
                this.m_lastOrientationWeight = 1f;
                flag = false;
            }
            up.Normalize();
            Vector3D right = this.m_lastRightVec - (Vector3D.Dot(this.m_lastRightVec, up) * up);

            if (right.LengthSquared() < 9.9999997473787516E-06)
            {
                right = base.m_orientation.Right - (Vector3D.Dot(base.m_orientation.Right, up) * up);
                if (right.LengthSquared() < 9.9999997473787516E-06)
                {
                    right = base.m_orientation.Forward - (Vector3D.Dot(base.m_orientation.Forward, up) * up);
                }
            }
            right.Normalize();
            this.m_lastRightVec = right;
            Vector3D.Cross(ref up, ref right, out vectord3);
            resultOrientationStorage         = MatrixD.Identity;
            resultOrientationStorage.Right   = right;
            resultOrientationStorage.Up      = up;
            resultOrientationStorage.Forward = vectord3;
            resultOrientationStorage         = (MatrixD.CreateFromAxisAngle(Vector3D.Right, this.m_pitch) * resultOrientationStorage) * MatrixD.CreateFromAxisAngle(up, this.m_yaw);
            up    = resultOrientationStorage.Up;
            right = resultOrientationStorage.Right;
            resultOrientationStorage.Right = (Vector3D)((Math.Cos(this.m_roll) * right) + (Math.Sin(this.m_roll) * up));
            resultOrientationStorage.Up    = (Vector3D)((-Math.Sin(this.m_roll) * right) + (Math.Cos(this.m_roll) * up));
            if (flag && (this.m_lastOrientationWeight > 0f))
            {
                this.m_lastOrientationWeight     = Math.Max((float)0f, (float)(this.m_lastOrientationWeight - 0.01666667f));
                resultOrientationStorage         = MatrixD.Slerp(resultOrientationStorage, this.m_lastOrientation, MathHelper.SmoothStepStable(this.m_lastOrientationWeight));
                resultOrientationStorage         = MatrixD.Orthogonalize(resultOrientationStorage);
                resultOrientationStorage.Forward = Vector3D.Cross(resultOrientationStorage.Up, resultOrientationStorage.Right);
            }
            if (!flag)
            {
                this.m_lastOrientation = resultOrientationStorage;
            }
        }
Example #12
0
        /// <summary>
        ///     Calculates the current sun direction.
        /// </summary>
        /// <returns>Returns the sun direction vector.</returns>
        public Vector3D CalculateSunDirection()
        {
            using (Mod.PROFILE ? Profiler.Measure(nameof(SunTracker), nameof(CalculateSunDirection)) : null) {
                if (_enabled)
                {
                    var vector3 = Vector3D.Transform(_baseSunDirection, MatrixD.CreateFromAxisAngle(_sunRotationAxis, 6.283186f * (ElapsedGameTime.TotalSeconds / Speed)));
                    vector3.Normalize();

                    return(vector3);
                }

                return(_baseSunDirection);
            }
        }
        /// <summary>
        /// Calculate propper direction for meteorits. Everytime above horizon.
        /// </summary>
        /// <param name="direction"></param>
        /// <returns></returns>
        private static Vector3 GetCorrectedDirection(Vector3 direction)
        {
            var currDir = direction;

            if (m_currentTarget == null)
            {
                return(currDir);
            }

            var tgtPos = m_currentTarget.Value.Center;

            MyMeteorShower.m_tgtPos = tgtPos;

            if (!MyGravityProviderSystem.IsPositionInNaturalGravity(tgtPos))
            {
                return(currDir);
            }

            var pltTgtDir = -Vector3D.Normalize(MyGravityProviderSystem.CalculateNaturalGravityInPoint(tgtPos));
            var tmpVec    = Vector3D.Normalize(Vector3D.Cross(pltTgtDir, currDir));
            var mirror    = Vector3D.Normalize(Vector3D.Cross(tmpVec, pltTgtDir));

            MyMeteorShower.m_mirrorDir = mirror;
            MyMeteorShower.m_pltTgtDir = pltTgtDir;
            MyMeteorShower.m_normalSun = tmpVec;

            double horizonRatio = pltTgtDir.Dot(currDir);

            //below down horizon
            if (horizonRatio < -HORIZON_ANGLE_FROM_ZENITH_RATIO)
            {
                return(Vector3D.Reflect(-currDir, mirror));
            }

            // between below and above horizon (prohi
            if (horizonRatio < HORIZON_ANGLE_FROM_ZENITH_RATIO)
            {
                MatrixD tmpMat = MatrixD.CreateFromAxisAngle(tmpVec, -Math.Asin(HORIZON_ANGLE_FROM_ZENITH_RATIO));
                return(Vector3D.Transform(mirror, tmpMat));
            }

            // above 20 Degree above horizon
            return(currDir);
        }
Example #14
0
        public override MatrixD GetHeadMatrix(bool includeY, bool includeX = true, bool forceHeadAnim = false, bool forceHeadBone = false)
        {
            var world = PositionComp.WorldMatrix;

            float headX = m_headLocalXAngle;
            float headY = m_headLocalYAngle;

            if (!includeX)
            {
                headX = DEFAULT_FPS_CAMERA_X_ANGLE;
            }

            MatrixD matrixRotation = MatrixD.CreateFromAxisAngle(Vector3D.Right, MathHelper.ToRadians(headX));

            if (includeY)
            {
                matrixRotation = matrixRotation * Matrix.CreateFromAxisAngle(Vector3.Up, MathHelper.ToRadians(headY));
            }

            world = matrixRotation * world;
            Vector3D headPosition = world.Translation;

            if (m_headLocalPosition != Vector3.Zero)
            {
                headPosition = Vector3D.Transform(m_headLocalPosition + m_playerHeadSpring, PositionComp.WorldMatrix);
            }
            else if (Pilot != null)
            {
                var headMatrix = Pilot.GetHeadMatrix(includeY, includeX, forceHeadAnim, IsInFirstPersonView);
                headPosition = headMatrix.Translation + headMatrix.Backward * 0.15f + m_playerHeadSpring;
            }

            world.Translation = headPosition;
            if (MyDebugDrawSettings.ENABLE_DEBUG_DRAW && MyDebugDrawSettings.DEBUG_DRAW_CHARACTER_MISC)
            {
                VRageRender.MyRenderProxy.DebugDrawSphere(world.Translation, 0.05f, Color.Yellow, 1f, false);
                VRageRender.MyRenderProxy.DebugDrawText3D(world.Translation, "Cockpit camera", Color.Yellow, 0.5f, false);
            }

            return(world);
        }
        MyDetectedEntityInfo ModAPI.Ingame.IMyCameraBlock.Raycast(double distance, float pitch, float yaw)
        {
            if (pitch > BlockDefinition.RaycastConeLimit || yaw > BlockDefinition.RaycastConeLimit)
            {
                return(new MyDetectedEntityInfo());
            }

            pitch = MathHelper.ToRadians(pitch);
            yaw   = MathHelper.ToRadians(yaw);

            var forwardDir  = this.WorldMatrix.Forward;
            var pitchMatrix = MatrixD.CreateFromAxisAngle(this.WorldMatrix.Right, pitch);
            //right hand rule!
            var      yawMatrix = MatrixD.CreateFromAxisAngle(this.WorldMatrix.Down, yaw);
            Vector3D direction;
            Vector3D intermediateDirection;

            Vector3D.RotateAndScale(ref forwardDir, ref pitchMatrix, out intermediateDirection);
            Vector3D.RotateAndScale(ref intermediateDirection, ref yawMatrix, out direction);

            return(Raycast(distance, direction));
        }
Example #16
0
        void UpdateMatrix()
        {
            try
            {
                if (!lcd.IsFunctional || !lcd.IsWorking)
                {
                    return;
                }

                subpart = Entity.GetSubpart("top");
                if (subpart != null)
                {
                    var pos = subpart.PositionComp.LocalMatrix;
                    var rot = MatrixD.CreateFromAxisAngle(pos.Up, MathHelper.ToRadians(-rotation));

                    var tr = pos.Translation;
                    pos             = pos * rot;
                    pos.Translation = tr;

                    subpart.PositionComp.LocalMatrix = pos;
                }

                if (lcd != null)
                {
                    var pos = lcd.PositionComp.LocalMatrix;
                    var rot = MatrixD.CreateFromAxisAngle(pos.Up, MathHelper.ToRadians(rotation));

                    var tr = pos.Translation;
                    pos             = pos * rot;
                    pos.Translation = tr;

                    lcd.PositionComp.LocalMatrix = pos;
                }
            }
            catch
            {
            }
        }
        public void UpdateLightPosition()
        {
            if (m_light != null)
            {
                MyCharacter character = m_skinnedEntity as MyCharacter;

                m_lightLocalPosition = character.Definition.LightOffset;

                MatrixD headMatrix     = character.GetHeadMatrix(false, true, false);
                MatrixD headMatrixAnim = character.GetHeadMatrix(false, true, true, true);

                if (m_oldReflectorAngle != MyCharacter.REFLECTOR_DIRECTION)
                {
                    m_oldReflectorAngle    = MyCharacter.REFLECTOR_DIRECTION;
                    m_reflectorAngleMatrix = MatrixD.CreateFromAxisAngle(headMatrix.Forward, MathHelper.ToRadians(MyCharacter.REFLECTOR_DIRECTION));
                }

                m_light.ReflectorDirection = Vector3.Transform(headMatrix.Forward, m_reflectorAngleMatrix);
                m_light.ReflectorUp        = headMatrix.Up;
                m_light.Position           = Vector3D.Transform(m_lightLocalPosition, headMatrixAnim);
                m_light.UpdateLight();

                Matrix[] boneMatrices = character.BoneAbsoluteTransforms;

                if (m_leftLightIndex != -1)
                {
                    MatrixD leftGlareMatrix = m_reflectorAngleMatrix * MatrixD.Normalize(boneMatrices[m_leftLightIndex]) * m_skinnedEntity.PositionComp.WorldMatrix;
                    m_leftGlarePosition = leftGlareMatrix.Translation;
                }

                if (m_rightLightIndex != -1)
                {
                    MatrixD rightGlareMatrix = m_reflectorAngleMatrix * MatrixD.Normalize(boneMatrices[m_rightLightIndex]) * m_skinnedEntity.PositionComp.WorldMatrix;
                    m_rightGlarePosition = rightGlareMatrix.Translation;
                }
            }
        }
Example #18
0
        private void CompileTurret(WeaponComponent comp, bool reset = false)
        {
            var c = 0;

            foreach (var m in Structure.WeaponSystems)
            {
                MyEntity muzzlePart = null;
                if (Parts.NameToEntity.TryGetValue(m.Key.String, out muzzlePart) || m.Value.DesignatorWeapon)
                {
                    var azimuthPartName = comp.BaseType == Turret?string.IsNullOrEmpty(m.Value.AzimuthPartName.String) ? "MissileTurretBase1" : m.Value.AzimuthPartName.String : m.Value.AzimuthPartName.String;

                    var elevationPartName = comp.BaseType == Turret?string.IsNullOrEmpty(m.Value.ElevationPartName.String) ? "MissileTurretBarrels" : m.Value.ElevationPartName.String : m.Value.ElevationPartName.String;

                    var weapon = Weapons[c];

                    var muzzlePartName = m.Key.String;
                    if (m.Value.DesignatorWeapon)
                    {
                        muzzlePart     = weapon.ElevationPart.Entity;
                        muzzlePartName = elevationPartName;
                    }

                    weapon.MuzzlePart.Entity = muzzlePart;
                    weapon.HeatingParts      = new List <MyEntity> {
                        weapon.MuzzlePart.Entity
                    };

                    if (muzzlePartName != "None")
                    {
                        var muzzlePartLocation = comp.Session.GetPartLocation("subpart_" + muzzlePartName, muzzlePart.Parent.Model);

                        var muzzlePartPosTo   = MatrixD.CreateTranslation(-muzzlePartLocation);
                        var muzzlePartPosFrom = MatrixD.CreateTranslation(muzzlePartLocation);

                        weapon.MuzzlePart.ToTransformation        = muzzlePartPosTo;
                        weapon.MuzzlePart.FromTransformation      = muzzlePartPosFrom;
                        weapon.MuzzlePart.PartLocalLocation       = muzzlePartLocation;
                        weapon.MuzzlePart.Entity.NeedsWorldMatrix = true;
                    }

                    if (weapon.AiOnlyWeapon)
                    {
                        var azimuthPart   = weapon.AzimuthPart.Entity;
                        var elevationPart = weapon.ElevationPart.Entity;
                        if (azimuthPart != null && azimuthPartName != "None" && weapon.System.TurretMovement != WeaponSystem.TurretType.ElevationOnly)
                        {
                            var azimuthPartLocation = comp.Session.GetPartLocation("subpart_" + azimuthPartName, azimuthPart.Parent.Model);
                            var partDummy           = comp.Session.GetPartDummy("subpart_" + azimuthPartName, azimuthPart.Parent.Model);
                            if (partDummy == null)
                            {
                                Log.Line($"partDummy null: name:{azimuthPartName} - azimuthPartParentNull:{azimuthPart.Parent == null}, I am crashing now Dave.");
                                continue;
                            }

                            var azPartPosTo  = MatrixD.CreateTranslation(-azimuthPartLocation);
                            var azPrtPosFrom = MatrixD.CreateTranslation(azimuthPartLocation);

                            var fullStepAzRotation = azPartPosTo * MatrixD.CreateFromAxisAngle(partDummy.Matrix.Up, -m.Value.AzStep) * azPrtPosFrom;

                            var rFullStepAzRotation = MatrixD.Invert(fullStepAzRotation);

                            weapon.AzimuthPart.RotationAxis = partDummy.Matrix.Up;

                            weapon.AzimuthPart.ToTransformation    = azPartPosTo;
                            weapon.AzimuthPart.FromTransformation  = azPrtPosFrom;
                            weapon.AzimuthPart.FullRotationStep    = fullStepAzRotation;
                            weapon.AzimuthPart.RevFullRotationStep = rFullStepAzRotation;
                            weapon.AzimuthPart.PartLocalLocation   = azimuthPartLocation;
                            //weapon.AzimuthPart.Entity.NeedsWorldMatrix = true;
                        }
                        else
                        {
                            weapon.AzimuthPart.RotationAxis        = Vector3.Zero;
                            weapon.AzimuthPart.ToTransformation    = MatrixD.Zero;
                            weapon.AzimuthPart.FromTransformation  = MatrixD.Zero;
                            weapon.AzimuthPart.FullRotationStep    = MatrixD.Zero;
                            weapon.AzimuthPart.RevFullRotationStep = MatrixD.Zero;
                            weapon.AzimuthPart.PartLocalLocation   = Vector3.Zero;
                            //weapon.AzimuthPart.Entity.NeedsWorldMatrix = true;
                        }

                        if (elevationPart != null && elevationPartName != "None" && weapon.System.TurretMovement != WeaponSystem.TurretType.AzimuthOnly)
                        {
                            var elevationPartLocation = comp.Session.GetPartLocation("subpart_" + elevationPartName, elevationPart.Parent.Model);
                            var partDummy             = comp.Session.GetPartDummy("subpart_" + elevationPartName, elevationPart.Parent.Model);
                            if (partDummy == null)
                            {
                                Log.Line($"partDummy null: name:{elevationPartName} - azimuthPartParentNull:{elevationPart.Parent == null}, I am crashing now Dave.");
                                continue;
                            }
                            var elPartPosTo   = MatrixD.CreateTranslation(-elevationPartLocation);
                            var elPartPosFrom = MatrixD.CreateTranslation(elevationPartLocation);

                            var fullStepElRotation = elPartPosTo * MatrixD.CreateFromAxisAngle(partDummy.Matrix.Left, m.Value.ElStep) * elPartPosFrom;

                            var rFullStepElRotation = MatrixD.Invert(fullStepElRotation);

                            weapon.ElevationPart.RotationAxis        = partDummy.Matrix.Left;
                            weapon.ElevationPart.ToTransformation    = elPartPosTo;
                            weapon.ElevationPart.FromTransformation  = elPartPosFrom;
                            weapon.ElevationPart.FullRotationStep    = fullStepElRotation;
                            weapon.ElevationPart.RevFullRotationStep = rFullStepElRotation;
                            weapon.ElevationPart.PartLocalLocation   = elevationPartLocation;
                            //weapon.ElevationPart.Entity.NeedsWorldMatrix = true;
                        }
                        else if (elevationPartName == "None")
                        {
                            weapon.ElevationPart.RotationAxis        = Vector3.Zero;
                            weapon.ElevationPart.ToTransformation    = MatrixD.Zero;
                            weapon.ElevationPart.FromTransformation  = MatrixD.Zero;
                            weapon.ElevationPart.FullRotationStep    = MatrixD.Zero;
                            weapon.ElevationPart.RevFullRotationStep = MatrixD.Zero;
                            weapon.ElevationPart.PartLocalLocation   = Vector3.Zero;
                            //weapon.ElevationPart.Entity.NeedsWorldMatrix = true;
                        }
                    }

                    var barrelCount = m.Value.Barrels.Length;

                    if (m.Key.String != "Designator")
                    {
                        weapon.MuzzlePart.Entity.PositionComp.OnPositionChanged += weapon.PositionChanged;
                        weapon.MuzzlePart.Entity.OnMarkForClose += weapon.EntPartClose;
                    }
                    else
                    {
                        if (weapon.ElevationPart.Entity != null)
                        {
                            weapon.ElevationPart.Entity.PositionComp.OnPositionChanged += weapon.PositionChanged;
                            weapon.ElevationPart.Entity.OnMarkForClose += weapon.EntPartClose;
                        }
                        else
                        {
                            weapon.AzimuthPart.Entity.PositionComp.OnPositionChanged += weapon.PositionChanged;
                            weapon.AzimuthPart.Entity.OnMarkForClose += weapon.EntPartClose;
                        }
                    }

                    for (int i = 0; i < barrelCount; i++)
                    {
                        var barrel = m.Value.Barrels[i];

                        weapon.MuzzleIdToName.Add(i, barrel);
                        if (weapon.Muzzles[i] == null)
                        {
                            weapon.Dummies[i] = new Dummy(weapon.MuzzlePart.Entity, weapon, barrel);
                            weapon.Muzzles[i] = new Muzzle(i, comp.Session);
                        }
                        else
                        {
                            weapon.Dummies[i].Entity = weapon.MuzzlePart.Entity;
                        }
                    }

                    for (int i = 0; i < m.Value.HeatingSubparts.Length; i++)
                    {
                        var      partName = m.Value.HeatingSubparts[i];
                        MyEntity ent;
                        if (Parts.NameToEntity.TryGetValue(partName, out ent))
                        {
                            weapon.HeatingParts.Add(ent);
                            try
                            {
                                ent.SetEmissiveParts("Heating", Color.Transparent, 0);
                            }
                            catch (Exception ex) { Log.Line($"Exception no emmissive Found: {ex}"); }
                        }
                    }

                    //was run only on weapon first build, needs to run every reset as well
                    try
                    {
                        foreach (var emissive in weapon.System.WeaponEmissiveSet)
                        {
                            if (emissive.Value.EmissiveParts == null)
                            {
                                continue;
                            }

                            foreach (var part in emissive.Value.EmissiveParts)
                            {
                                Parts.SetEmissiveParts(part, Color.Transparent, 0);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        //cant check for emissives so may be null ref
                    }

                    if (weapon.Comp.FunctionalBlock.Enabled)
                    {
                        if (weapon.AnimationsSet.ContainsKey(EventTriggers.TurnOn))
                        {
                            weapon.Comp.Session.FutureEvents.Schedule(weapon.TurnOnAV, null, 4);
                        }
                        else
                        if (weapon.AnimationsSet.ContainsKey(EventTriggers.TurnOff))
                        {
                            weapon.Comp.Session.FutureEvents.Schedule(weapon.TurnOffAv, null, 4);
                        }
                    }

                    c++;
                }
            }
        }
Example #19
0
        private bool CalculateGridPosition()
        {
            List <MyObjectBuilder_CubeGrid> TotalGrids = new List <MyObjectBuilder_CubeGrid>();
            List <MyObjectBuilder_Cockpit>  cockpits   = new List <MyObjectBuilder_Cockpit>();
            Vector3D direction = _PlayerPosition;



            //Get all cockpit blkocks on the grid
            foreach (var shipBlueprint in _ShipBlueprints)
            {
                TotalGrids.AddRange(shipBlueprint.CubeGrids.ToList());
                foreach (MyObjectBuilder_CubeGrid grid in shipBlueprint.CubeGrids)
                {
                    cockpits.AddRange(grid.CubeBlocks.OfType <MyObjectBuilder_Cockpit>().ToList());
                }
            }

            MyObjectBuilder_CubeGrid[] array = TotalGrids.ToArray();
            if (array.Length == 0)
            {
                //Simple grid/objectbuilder null check. If there are no gridys then why continue?
                return(false);
            }
            Hangar.Debug("Total Grids to be pasted: " + array.Count());

            if (cockpits.Count > 0)
            {
                //Main.Debug("Cockpits found!");
                foreach (MyObjectBuilder_Cockpit Block in cockpits)
                {
                    if (Block.IsMainCockpit)
                    {
                        Hangar.Debug("Main cockpit found! Attempting to Align!");
                        direction = new Vector3D(Block.Orientation.x, Block.Orientation.y, Block.Orientation.z);
                        break;
                    }
                }
            }
            else
            {
                Hangar.Debug("No Cockpits. Continuing based off of grid pivot point!");
            }


            //Attempt to get gravity/Artificial gravity to align the grids to
            Vector3D position = _PlayerPosition;

            //Here you can adjust the offset from the surface and rotation.
            //Unfortunatley we move the grid again after this to find a free space around the character. Perhaps later i can incorporate that into
            //LordTylus's existing grid checkplament method
            float gravityOffset   = 0f;
            float gravityRotation = 0f;

            Vector3 vector = MyGravityProviderSystem.CalculateNaturalGravityInPoint(position);

            if (vector == Vector3.Zero)
            {
                vector = MyGravityProviderSystem.CalculateArtificialGravityInPoint(position);
            }
            Vector3D vector3D;

            if (vector != Vector3.Zero)
            {
                Hangar.Debug("Attempting to correct grid orientation!");
                vector.Normalize();
                vector3D  = -vector;
                position += vector * gravityOffset;
                if (direction == Vector3D.Zero)
                {
                    direction = Vector3D.CalculatePerpendicularVector(vector);
                    if (gravityRotation != 0f)
                    {
                        MatrixD matrixa = MatrixD.CreateFromAxisAngle(vector3D, gravityRotation);
                        direction = Vector3D.Transform(direction, matrixa);
                    }
                }
            }
            else if (direction == Vector3D.Zero)
            {
                direction = Vector3D.Right;
                vector3D  = Vector3D.Up;
            }
            else
            {
                vector3D = Vector3D.CalculatePerpendicularVector(-direction);
            }


            return(BeginAlignToGravity(array, position, direction, vector3D));
        }
Example #20
0
        public static void DrawHighlightBox(MatrixD matrix, float scale, float lineWidth, MyStringId material, Color colorFace, Color colorWire, BlendTypeEnum blendType)
        {
            // optimized box draw compared to MySimpleObjectDraw.DrawTransparentBox; also allows consistent edge thickness
            MyQuadD     quad;
            Vector3D    p;
            MatrixD     m;
            var         halfScale     = (scale * 0.5f);
            float       lineLength    = scale;
            const float ROTATE_90_RAD = (90f / 180f * MathHelper.Pi); // 90deg in radians

            p = matrix.Translation + matrix.Forward * halfScale;
            if (IsFaceVisible(p, matrix.Forward))
            {
                MyUtils.GenerateQuad(out quad, ref p, halfScale, halfScale, ref matrix);
                MyTransparentGeometry.AddQuad(material, ref quad, colorFace, ref p, blendType: blendType);
            }

            p = matrix.Translation + matrix.Backward * halfScale;
            if (IsFaceVisible(p, matrix.Backward))
            {
                MyUtils.GenerateQuad(out quad, ref p, halfScale, halfScale, ref matrix);
                MyTransparentGeometry.AddQuad(material, ref quad, colorFace, ref p, blendType: blendType);
            }

            p = matrix.Translation + matrix.Left * halfScale;
            m = matrix * MatrixD.CreateFromAxisAngle(matrix.Up, ROTATE_90_RAD);
            if (IsFaceVisible(p, matrix.Left))
            {
                MyUtils.GenerateQuad(out quad, ref p, halfScale, halfScale, ref m);
                MyTransparentGeometry.AddQuad(material, ref quad, colorFace, ref p, blendType: blendType);
            }

            p = matrix.Translation + matrix.Right * halfScale;
            if (IsFaceVisible(p, matrix.Right))
            {
                MyUtils.GenerateQuad(out quad, ref p, halfScale, halfScale, ref m);
                MyTransparentGeometry.AddQuad(material, ref quad, colorFace, ref p, blendType: blendType);
            }

            m = matrix * MatrixD.CreateFromAxisAngle(matrix.Left, ROTATE_90_RAD);
            p = matrix.Translation + matrix.Up * halfScale;
            if (IsFaceVisible(p, matrix.Up))
            {
                MyUtils.GenerateQuad(out quad, ref p, halfScale, halfScale, ref m);
                MyTransparentGeometry.AddQuad(material, ref quad, colorFace, ref p, blendType: blendType);
            }

            p = matrix.Translation + matrix.Down * halfScale;
            if (IsFaceVisible(p, matrix.Down))
            {
                MyUtils.GenerateQuad(out quad, ref p, halfScale, halfScale, ref m);
                MyTransparentGeometry.AddQuad(material, ref quad, colorFace, ref p, blendType: blendType);
            }

            var upHalf      = (matrix.Up * halfScale);
            var rightHalf   = (matrix.Right * halfScale);
            var forwardHalf = (matrix.Forward * halfScale);

            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + upHalf + -rightHalf + matrix.Forward * halfScale, matrix.Backward, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + upHalf + rightHalf + matrix.Forward * halfScale, matrix.Backward, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + -upHalf + -rightHalf + matrix.Forward * halfScale, matrix.Backward, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + -upHalf + rightHalf + matrix.Forward * halfScale, matrix.Backward, lineLength, lineWidth, blendType: blendType);

            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + forwardHalf + -rightHalf + matrix.Up * halfScale, matrix.Down, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + forwardHalf + rightHalf + matrix.Up * halfScale, matrix.Down, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + -forwardHalf + -rightHalf + matrix.Up * halfScale, matrix.Down, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + -forwardHalf + rightHalf + matrix.Up * halfScale, matrix.Down, lineLength, lineWidth, blendType: blendType);

            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + forwardHalf + -upHalf + matrix.Right * halfScale, matrix.Left, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + forwardHalf + upHalf + matrix.Right * halfScale, matrix.Left, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + -forwardHalf + -upHalf + matrix.Right * halfScale, matrix.Left, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + -forwardHalf + upHalf + matrix.Right * halfScale, matrix.Left, lineLength, lineWidth, blendType: blendType);
        }
        private bool CalculateGridPosition()
        {
            List <MyObjectBuilder_CubeGrid> TotalGrids = new List <MyObjectBuilder_CubeGrid>();
            List <MyObjectBuilder_Cockpit>  cockpits   = new List <MyObjectBuilder_Cockpit>();
            Vector3D forwardVector = Vector3D.Zero;



            //Get all cockpit blkocks on the grid
            foreach (var shipBlueprint in _ShipBlueprints)
            {
                TotalGrids.AddRange(shipBlueprint.CubeGrids.ToList());
            }

            MyObjectBuilder_CubeGrid[] array = TotalGrids.ToArray();
            if (array.Length == 0)
            {
                //Simple grid/objectbuilder null check. If there are no gridys then why continue?
                return(false);
            }
            Hangar.Debug("Total Grids to be pasted: " + array.Count());

            //Attempt to get gravity/Artificial gravity to align the grids to
            Vector3D position = _PlayerPosition;

            //Here you can adjust the offset from the surface and rotation.
            //Unfortunatley we move the grid again after this to find a free space around the character. Perhaps later i can incorporate that into
            //LordTylus's existing grid checkplament method
            float gravityOffset   = 0f;
            float gravityRotation = 0f;

            Vector3 gravityDirectionalVector = MyGravityProviderSystem.CalculateNaturalGravityInPoint(position);

            if (gravityDirectionalVector == Vector3.Zero)
            {
                gravityDirectionalVector = MyGravityProviderSystem.CalculateArtificialGravityInPoint(position);
            }
            Vector3D upDirectionalVector;

            if (gravityDirectionalVector != Vector3.Zero)
            {
                Hangar.Debug("Attempting to correct grid orientation!");
                gravityDirectionalVector.Normalize();
                upDirectionalVector = -gravityDirectionalVector;
                position           += gravityDirectionalVector * gravityOffset;
                if (forwardVector == Vector3D.Zero)
                {
                    forwardVector = Vector3D.CalculatePerpendicularVector(gravityDirectionalVector);
                    if (gravityRotation != 0f)
                    {
                        MatrixD matrixa = MatrixD.CreateFromAxisAngle(upDirectionalVector, gravityRotation);
                        forwardVector = Vector3D.Transform(forwardVector, matrixa);
                    }
                }
            }
            else if (forwardVector == Vector3D.Zero)
            {
                forwardVector       = Vector3D.Right;
                upDirectionalVector = Vector3D.Up;
            }
            else
            {
                upDirectionalVector = Vector3D.CalculatePerpendicularVector(-forwardVector);
            }

            return(BeginAlignToGravity(array, forwardVector, upDirectionalVector));
        }
Example #22
0
        public unsafe void MoveAndRotate(ref Vector3 moveIndicator, ref Vector2 rotationIndicator, float roll, bool canRotate)
        {
            MyCharacterProxy characterProxy = base.Character.Physics.CharacterProxy;

            this.ThrustComp.ControlThrust = Vector3.Zero;
            base.Character.SwitchAnimation(MyCharacterMovementEnum.Flying, true);
            base.Character.SetCurrentMovementState(MyCharacterMovementEnum.Flying);
            MyCharacterMovementFlags movementFlags = base.Character.MovementFlags;
            MyCharacterMovementFlags flags2        = base.Character.MovementFlags;

            this.IsFlying = !(moveIndicator.LengthSquared() == 0f);
            HkCharacterStateType type = (characterProxy != null) ? characterProxy.GetState() : HkCharacterStateType.HK_CHARACTER_ON_GROUND;

            if ((type == HkCharacterStateType.HK_CHARACTER_IN_AIR) || (type == ((HkCharacterStateType)5)))
            {
                base.Character.PlayCharacterAnimation("Jetpack", MyBlendOption.Immediate, MyFrameOption.Loop, 0.2f, 1f, false, null, false);
                base.Character.CanJump = true;
            }
            MatrixD worldMatrix = base.Character.WorldMatrix;

            if (canRotate)
            {
                MatrixD identity = MatrixD.Identity;
                MatrixD xd3      = MatrixD.Identity;
                MatrixD xd4      = MatrixD.Identity;
                if (Math.Abs(rotationIndicator.X) > float.Epsilon)
                {
                    if (base.Character.Definition.VerticalPositionFlyingOnly)
                    {
                        base.Character.SetHeadLocalXAngle(base.Character.HeadLocalXAngle - (rotationIndicator.X * base.Character.RotationSpeed));
                    }
                    else
                    {
                        identity = MatrixD.CreateFromAxisAngle(worldMatrix.Right, (double)((-rotationIndicator.X * base.Character.RotationSpeed) * 0.02f));
                    }
                }
                if (Math.Abs(rotationIndicator.Y) > float.Epsilon)
                {
                    xd3 = MatrixD.CreateFromAxisAngle(worldMatrix.Up, (double)((-rotationIndicator.Y * base.Character.RotationSpeed) * 0.02f));
                }
                if (!base.Character.Definition.VerticalPositionFlyingOnly && (Math.Abs(roll) > float.Epsilon))
                {
                    xd4 = MatrixD.CreateFromAxisAngle(worldMatrix.Forward, (double)(roll * 0.02f));
                }
                float    y      = base.Character.ModelCollision.BoundingBoxSizeHalf.Y;
                MatrixD  xd7    = worldMatrix.GetOrientation() * ((identity * xd3) * xd4);
                MatrixD *xdPtr1 = (MatrixD *)ref xd7;
                xdPtr1.Translation         = (base.Character.Physics.GetWorldMatrix().Translation + (worldMatrix.Up * y)) - (xd7.Up * y);
                base.Character.WorldMatrix = xd7;
                base.Character.ClearShapeContactPoints();
            }
            Vector3 position = moveIndicator;

            if (base.Character.Definition.VerticalPositionFlyingOnly)
            {
                float  num2 = Math.Sign(base.Character.HeadLocalXAngle);
                double x    = Math.Abs(MathHelper.ToRadians(base.Character.HeadLocalXAngle));
                double y    = 1.95;
                double num5 = Math.Pow(x, y) * (x / Math.Pow((double)MathHelper.ToRadians((float)89f), y));
                position = (Vector3)Vector3D.Transform(position, MatrixD.CreateFromAxisAngle(Vector3D.Right, num2 * num5));
            }
            if (!Vector3.IsZero(position))
            {
                position.Normalize();
            }
            MyJetpackThrustComponent thrustComp = this.ThrustComp;

            thrustComp.ControlThrust += position * this.ForceMagnitude;
        }
Example #23
0
        static void ProcessDebugMessages()
        {
            bool clearPersistent = false;

            m_persistentDebugMessagesTemp.Clear();
            var linesBatch        = MyLinesRenderer.CreateBatch();
            var noDepthLinesBatch = MyLinesRenderer.CreateBatch();

            noDepthLinesBatch.IgnoreDepth = true;
            var lines2D = MyLinesRenderer.CreateBatch();

            lines2D.IgnoreDepth = true;

            while (m_debugDrawMessages.Count > 0)
            {
                MyRenderMessageBase debugDrawMessage = m_debugDrawMessages.Dequeue();
                if (debugDrawMessage.IsPersistent)
                {
                    m_persistentDebugMessagesTemp.Add(debugDrawMessage);
                }

                MyRenderMessageEnum messageType = debugDrawMessage.MessageType;

                switch (messageType)
                {
                case MyRenderMessageEnum.DebugDrawLine3D:
                {
                    MyRenderMessageDebugDrawLine3D message = (MyRenderMessageDebugDrawLine3D)debugDrawMessage;

                    if (message.DepthRead)
                    {
                        linesBatch.Add(message.PointFrom - MyRender11.Environment.Matrices.CameraPosition, message.PointTo - MyRender11.Environment.Matrices.CameraPosition, message.ColorFrom, message.ColorTo);
                    }
                    else
                    {
                        noDepthLinesBatch.Add(message.PointFrom - MyRender11.Environment.Matrices.CameraPosition, message.PointTo - MyRender11.Environment.Matrices.CameraPosition, message.ColorFrom, message.ColorTo);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawLine2D:
                {
                    MyRenderMessageDebugDrawLine2D message = (MyRenderMessageDebugDrawLine2D)debugDrawMessage;

                    var matrix = message.Projection ?? Matrix.CreateOrthographicOffCenter(0, MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y, 0, 0, -1);

                    if (!lines2D.CustomViewProjection.HasValue || (lines2D.CustomViewProjection.HasValue && lines2D.CustomViewProjection.Value != matrix))
                    {
                        lines2D.Commit();
                        lines2D                      = MyLinesRenderer.CreateBatch();
                        lines2D.IgnoreDepth          = true;
                        lines2D.CustomViewProjection = matrix;
                    }

                    var p0 = new Vector3(message.PointFrom.X, message.PointFrom.Y, 0);
                    var p1 = new Vector3(message.PointTo.X, message.PointTo.Y, 0);
                    lines2D.Add(p0, p1, message.ColorFrom, message.ColorTo);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawPoint:
                {
                    MyRenderMessageDebugDrawPoint message = (MyRenderMessageDebugDrawPoint)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    var scale = 0.125f;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyRender11.Environment.Matrices.Projection).Z : borderDepth;

                    var clipPosition = Vector3D.Transform(message.Position, MyRender11.Environment.Matrices.ViewProjectionAt0);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    //Debug.Assert(MyRender11.UseComplementaryDepthBuffer);

                    Vector3 position = (Vector3)(message.Position - MyRender11.Environment.Matrices.CameraPosition);

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        batch.Add(position + Vector3.UnitX * scale, position - Vector3.UnitX * scale, message.Color);
                        batch.Add(position + Vector3.UnitY * scale, position - Vector3.UnitY * scale, message.Color);
                        batch.Add(position + Vector3.UnitZ * scale, position - Vector3.UnitZ * scale, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawSphere:
                {
                    MyRenderMessageDebugDrawSphere message = (MyRenderMessageDebugDrawSphere)debugDrawMessage;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyRender11.Environment.Matrices.Projection).Z : borderDepth;

                    Vector3D position = message.Position - MyRender11.Environment.Matrices.CameraPosition;

                    var clipPosition = Vector3D.Transform(position, MyRender11.Environment.Matrices.ViewProjectionAt0);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                        batch.AddSphereRing(new BoundingSphere(position, message.Radius), message.Color, Matrix.Identity);
                        batch.AddSphereRing(new BoundingSphere(position, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));
                        batch.AddSphereRing(new BoundingSphere(position, message.Radius), message.Color, Matrix.CreateRotationZ(MathHelper.PiOver2));
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawAABB:
                {
                    MyRenderMessageDebugDrawAABB message = (MyRenderMessageDebugDrawAABB)debugDrawMessage;

                    BoundingBox aabb = (BoundingBox)message.AABB;
                    aabb.Translate(-MyRender11.Environment.Matrices.CameraPosition);

                    if (message.DepthRead)
                    {
                        linesBatch.AddBoundingBox(aabb, message.Color);
                    }
                    else
                    {
                        noDepthLinesBatch.AddBoundingBox(aabb, message.Color);
                    }

                    if (message.Shaded)
                    {
                        unsafe
                        {
                            Vector3 *points = stackalloc Vector3[8];

                            aabb.GetCornersUnsafe(points);

                            MyPrimitivesRenderer.Draw6FacedConvexZ(points, message.Color, message.Alpha);
                        }
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDraw6FaceConvex:
                {
                    MyRenderMessageDebugDraw6FaceConvex convex = (MyRenderMessageDebugDraw6FaceConvex)debugDrawMessage;

                    if (convex.Fill)
                    {
                        MyPrimitivesRenderer.Draw6FacedConvex(convex.Vertices, convex.Color, convex.Alpha);
                    }
                    else
                    {
                        if (convex.DepthRead)
                        {
                            linesBatch.Add6FacedConvexWorld(convex.Vertices, convex.Color);
                        }
                        else
                        {
                            noDepthLinesBatch.Add6FacedConvexWorld(convex.Vertices, convex.Color);
                        }
                    }
                    break;
                }


                case MyRenderMessageEnum.DebugDrawCone:
                {
                    MyRenderMessageDebugDrawCone message = (MyRenderMessageDebugDrawCone)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    var axis = message.DirectionVector;
                    axis.Normalize();

                    var apex = message.Translation + message.DirectionVector;

                    var steps    = 32;
                    var stepsRcp = (float)(Math.PI * 2 / steps);
                    for (int i = 0; i < 32; i++)
                    {
                        float a0 = i * stepsRcp;
                        float a1 = (i + 1) * stepsRcp;

                        var A = message.Translation + Vector3D.Transform(message.BaseVector, MatrixD.CreateFromAxisAngle(axis, a0)) - MyRender11.Environment.Matrices.CameraPosition;
                        var B = message.Translation + Vector3D.Transform(message.BaseVector, MatrixD.CreateFromAxisAngle(axis, a1)) - MyRender11.Environment.Matrices.CameraPosition;

                        batch.Add(A, B, message.Color);
                        batch.Add(A, apex, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawAxis:
                {
                    MyRenderMessageDebugDrawAxis message = (MyRenderMessageDebugDrawAxis)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    Vector3 position = message.Matrix.Translation - MyRender11.Environment.Matrices.CameraPosition;

                    if (message.SkipScale)
                    {
                        batch.Add(position, position + Vector3.Normalize(message.Matrix.Right) * message.AxisLength, Color.Red);
                        batch.Add(position, position + Vector3.Normalize(message.Matrix.Up) * message.AxisLength, Color.Green);
                        batch.Add(position, position + Vector3.Normalize(message.Matrix.Forward) * message.AxisLength, Color.Blue);
                    }
                    else
                    {
                        batch.Add(position, position + message.Matrix.Right * message.AxisLength, Color.Red);
                        batch.Add(position, position + message.Matrix.Up * message.AxisLength, Color.Green);
                        batch.Add(position, position + message.Matrix.Forward * message.AxisLength, Color.Blue);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawOBB:
                {
                    MyRenderMessageDebugDrawOBB message = (MyRenderMessageDebugDrawOBB)debugDrawMessage;

                    Vector3D[] cornersD = new Vector3D[8];
                    MatrixD    matrix   = (MatrixD)message.Matrix;
                    new MyOrientedBoundingBoxD(matrix).GetCorners(cornersD, 0);

                    Vector3[] corners = new Vector3[8];
                    for (int i = 0; i < 8; i++)
                    {
                        corners[i] = (cornersD[i] - MyRender11.Environment.Matrices.CameraPosition);
                    }

                    if (message.DepthRead)
                    {
                        linesBatch.Add6FacedConvex(corners, message.Color);
                    }
                    else
                    {
                        noDepthLinesBatch.Add6FacedConvex(corners, message.Color);
                    }

                    MyPrimitivesRenderer.Draw6FacedConvexZ(corners, message.Color, message.Alpha);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawFrustrum:
                {
                    MyRenderMessageDebugDrawFrustrum message = (MyRenderMessageDebugDrawFrustrum)debugDrawMessage;

                    Vector3[] corners = new Vector3[8];

                    Matrix m = message.Frustrum.Matrix;

                    m.Translation -= MyRender11.Environment.Matrices.CameraPosition;

                    message.Frustrum.Matrix = m;

                    message.Frustrum.GetCorners(corners);

                    if (message.DepthRead)
                    {
                        linesBatch.Add6FacedConvex(corners, message.Color);
                    }
                    else
                    {
                        noDepthLinesBatch.Add6FacedConvex(corners, message.Color);
                    }

                    MyPrimitivesRenderer.Draw6FacedConvexZ(corners, message.Color, message.Alpha);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawCylinder:
                {
                    MyRenderMessageDebugDrawCylinder message = (MyRenderMessageDebugDrawCylinder)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    var steps    = 32;
                    var stepsRcp = (float)(Math.PI * 2 / steps);
                    for (int i = 0; i < 32; i++)
                    {
                        float a0 = i * stepsRcp;
                        float a1 = (i + 1) * stepsRcp;

                        Vector3D A = new Vector3D(Math.Cos(a0), 1.0f, Math.Sin(a0)) * 0.5f;
                        Vector3D B = new Vector3D(Math.Cos(a1), 1.0f, Math.Sin(a1)) * 0.5f;
                        Vector3D C = A - Vector3D.UnitY;
                        Vector3D D = B - Vector3D.UnitY;

                        A = Vector3D.Transform(A, message.Matrix);
                        B = Vector3D.Transform(B, message.Matrix);
                        C = Vector3D.Transform(C, message.Matrix);
                        D = Vector3D.Transform(D, message.Matrix);

                        A -= MyRender11.Environment.Matrices.CameraPosition;
                        B -= MyRender11.Environment.Matrices.CameraPosition;
                        C -= MyRender11.Environment.Matrices.CameraPosition;
                        D -= MyRender11.Environment.Matrices.CameraPosition;

                        batch.Add(A, B, message.Color);
                        batch.Add(A, C, message.Color);
                        batch.Add(C, D, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawTriangle:
                {
                    MyRenderMessageDebugDrawTriangle message = (MyRenderMessageDebugDrawTriangle)debugDrawMessage;

                    MyPrimitivesRenderer.DrawTriangle(message.Vertex0 - MyRender11.Environment.Matrices.CameraPosition,
                                                      message.Vertex1 - MyRender11.Environment.Matrices.CameraPosition,
                                                      message.Vertex2 - MyRender11.Environment.Matrices.CameraPosition, message.Color);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawTriangles:
                {
                    MyRenderMessageDebugDrawTriangles message = (MyRenderMessageDebugDrawTriangles)debugDrawMessage;

                    for (int i = 0; i < message.Indices.Count; i += 3)
                    {
                        var v0 = Vector3D.Transform(message.Vertices[message.Indices[i + 0]], message.WorldMatrix) - MyRender11.Environment.Matrices.CameraPosition;
                        var v1 = Vector3D.Transform(message.Vertices[message.Indices[i + 1]], message.WorldMatrix) - MyRender11.Environment.Matrices.CameraPosition;
                        var v2 = Vector3D.Transform(message.Vertices[message.Indices[i + 2]], message.WorldMatrix) - MyRender11.Environment.Matrices.CameraPosition;

                        MyPrimitivesRenderer.DrawTriangle(v0, v1, v2, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawMesh:
                {
                    MyPrimitivesRenderer.DebugMesh(debugDrawMessage as MyRenderMessageDebugDrawMesh);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawCapsule:
                {
                    MyRenderMessageDebugDrawCapsule message = (MyRenderMessageDebugDrawCapsule)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    batch.AddSphereRing(new BoundingSphere(message.P0 - MyRender11.Environment.Matrices.CameraPosition, message.Radius), message.Color, Matrix.Identity);
                    batch.AddSphereRing(new BoundingSphere(message.P0 - MyRender11.Environment.Matrices.CameraPosition, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));
                    batch.AddSphereRing(new BoundingSphere(message.P1 - MyRender11.Environment.Matrices.CameraPosition, message.Radius), message.Color, Matrix.Identity);
                    batch.AddSphereRing(new BoundingSphere(message.P1 - MyRender11.Environment.Matrices.CameraPosition, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));

                    batch.Add(message.P0 - MyRender11.Environment.Matrices.CameraPosition, message.P1 - MyRender11.Environment.Matrices.CameraPosition, message.Color);


                    break;
                }

                case MyRenderMessageEnum.DebugDrawText2D:
                {
                    MyRenderMessageDebugDrawText2D message = (MyRenderMessageDebugDrawText2D)debugDrawMessage;

                    var text = new StringBuilder(message.Text);

                    MySpritesRenderer.DrawText(message.Coord, text, message.Color, message.Scale, message.Align);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawText3D:
                {
                    MyRenderMessageDebugDrawText3D message = (MyRenderMessageDebugDrawText3D)debugDrawMessage;

                    Vector3D position = message.Coord;

                    var worldToClip = MyRender11.Environment.Matrices.ViewProjectionD;
                    if (message.CustomViewProjection != -1)
                    {
                        if (!MyRenderProxy.BillboardsViewProjectionRead.ContainsKey(message.CustomViewProjection))
                        {
                            break;
                        }

                        var i = message.CustomViewProjection;

                        var scaleX  = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Width / (float)MyRender11.ViewportResolution.X;
                        var scaleY  = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Height / (float)MyRender11.ViewportResolution.Y;
                        var offsetX = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.OffsetX / (float)MyRender11.ViewportResolution.X;
                        var offsetY = (MyRender11.ViewportResolution.Y - MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.OffsetY - MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Height)
                                      / (float)MyRender11.ViewportResolution.Y;

                        var viewportTransformation = new Matrix(
                            scaleX, 0, 0, 0,
                            0, scaleY, 0, 0,
                            0, 0, 1, 0,
                            offsetX, offsetY, 0, 1
                            );

                        worldToClip = MyRenderProxy.BillboardsViewProjectionRead[message.CustomViewProjection].ViewAtZero * MyRenderProxy.BillboardsViewProjectionRead[message.CustomViewProjection].Projection * viewportTransformation;
                    }

                    var clipPosition = Vector3D.Transform(position, ref worldToClip);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyRender11.Environment.Matrices.Projection).Z : borderDepth;

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        MySpritesRenderer.DrawText(new Vector2((float)clipPosition.X, (float)clipPosition.Y) * MyRender11.ViewportResolution,
                                                   new StringBuilder(message.Text), message.Color, message.Scale, message.Align);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawModel:
                {
                    MyRenderMessageDebugDrawModel message = (MyRenderMessageDebugDrawModel)debugDrawMessage;


                    break;
                }

                case MyRenderMessageEnum.DebugDrawPlane:
                {
                    MyRenderMessageDebugDrawPlane message = (MyRenderMessageDebugDrawPlane)debugDrawMessage;


                    break;
                }

                case MyRenderMessageEnum.DebugWaitForPresent:
                {
                    MyRenderMessageDebugWaitForPresent rMessage = (MyRenderMessageDebugWaitForPresent)debugDrawMessage;
                    MyRenderProxy.RenderThread.DebugAddWaitingForPresent(rMessage.WaitHandle);
                    break;
                }

                case MyRenderMessageEnum.DebugClearPersistentMessages:
                {
                    MyRenderMessageDebugClearPersistentMessages rMessage = (MyRenderMessageDebugClearPersistentMessages)debugDrawMessage;
                    clearPersistent = true;
                    break;
                }

                default:
                {
                    break;
                }
                }
            }

            linesBatch.Commit();
            noDepthLinesBatch.Commit();
            lines2D.Commit();

            foreach (var message in m_persistentDebugMessagesTemp)
            {
                if (clearPersistent && m_currentPersistentDebugMessages.Remove(message))
                {
                    continue;
                }

                m_debugDrawMessages.Enqueue(message);
                m_currentPersistentDebugMessages.Add(message);
            }
        }
        /// <summary>
        /// Draws a frustum representing the valid scanning range, a line representing the last raycast,
        /// and a sphere representing the last raycast hit.
        /// </summary>
        private void DrawDebug()
        {
            MyRenderProxy.DebugDrawLine3D(m_lastRay.Start, m_lastRay.End, Color.Orange, Color.Orange, false);
            if (m_lastRay.Hit.HasValue)
            {
                MyRenderProxy.DebugDrawSphere(m_lastRay.Hit.Value, 1, Color.Orange, 1, false);
            }

            double distance = m_lastRay.Distance / Math.Cos(MathHelper.ToRadians(BlockDefinition.RaycastConeLimit));

            //calculate the extremes of the scan area and draw the thing manually
            Vector3D[] corners = new Vector3D[4];

            var startPos   = this.WorldMatrix.Translation;
            var forwardDir = this.WorldMatrix.Forward;

            float    pitch       = MathHelper.ToRadians(-BlockDefinition.RaycastConeLimit);
            float    yaw         = MathHelper.ToRadians(-BlockDefinition.RaycastConeLimit);
            var      pitchMatrix = MatrixD.CreateFromAxisAngle(this.WorldMatrix.Right, pitch);
            var      yawMatrix   = MatrixD.CreateFromAxisAngle(this.WorldMatrix.Down, yaw);
            Vector3D direction;
            Vector3D intermediateDirection;

            Vector3D.RotateAndScale(ref forwardDir, ref pitchMatrix, out intermediateDirection);
            Vector3D.RotateAndScale(ref intermediateDirection, ref yawMatrix, out direction);

            corners[0] = startPos + direction * distance;

            pitch       = MathHelper.ToRadians(-BlockDefinition.RaycastConeLimit);
            yaw         = MathHelper.ToRadians(BlockDefinition.RaycastConeLimit);
            pitchMatrix = MatrixD.CreateFromAxisAngle(this.WorldMatrix.Right, pitch);
            yawMatrix   = MatrixD.CreateFromAxisAngle(this.WorldMatrix.Down, yaw);
            Vector3D.RotateAndScale(ref forwardDir, ref pitchMatrix, out intermediateDirection);
            Vector3D.RotateAndScale(ref intermediateDirection, ref yawMatrix, out direction);

            corners[1] = startPos + direction * distance;

            pitch       = MathHelper.ToRadians(BlockDefinition.RaycastConeLimit);
            yaw         = MathHelper.ToRadians(BlockDefinition.RaycastConeLimit);
            pitchMatrix = MatrixD.CreateFromAxisAngle(this.WorldMatrix.Right, pitch);
            yawMatrix   = MatrixD.CreateFromAxisAngle(this.WorldMatrix.Down, yaw);
            Vector3D.RotateAndScale(ref forwardDir, ref pitchMatrix, out intermediateDirection);
            Vector3D.RotateAndScale(ref intermediateDirection, ref yawMatrix, out direction);

            corners[2] = startPos + direction * distance;

            pitch       = MathHelper.ToRadians(BlockDefinition.RaycastConeLimit);
            yaw         = MathHelper.ToRadians(-BlockDefinition.RaycastConeLimit);
            pitchMatrix = MatrixD.CreateFromAxisAngle(this.WorldMatrix.Right, pitch);
            yawMatrix   = MatrixD.CreateFromAxisAngle(this.WorldMatrix.Down, yaw);
            Vector3D.RotateAndScale(ref forwardDir, ref pitchMatrix, out intermediateDirection);
            Vector3D.RotateAndScale(ref intermediateDirection, ref yawMatrix, out direction);

            corners[3] = startPos + direction * distance;

            MyRenderProxy.DebugDrawLine3D(startPos, corners[0], Color.Blue, Color.Blue, false);
            MyRenderProxy.DebugDrawLine3D(startPos, corners[1], Color.Blue, Color.Blue, false);
            MyRenderProxy.DebugDrawLine3D(startPos, corners[2], Color.Blue, Color.Blue, false);
            MyRenderProxy.DebugDrawLine3D(startPos, corners[3], Color.Blue, Color.Blue, false);

            MyRenderProxy.DebugDrawLine3D(corners[0], corners[1], Color.Blue, Color.Blue, false);
            MyRenderProxy.DebugDrawLine3D(corners[1], corners[2], Color.Blue, Color.Blue, false);
            MyRenderProxy.DebugDrawLine3D(corners[2], corners[3], Color.Blue, Color.Blue, false);
            MyRenderProxy.DebugDrawLine3D(corners[3], corners[0], Color.Blue, Color.Blue, false);
        }
Example #25
0
        public void MoveAndRotate(ref Vector3 moveIndicator, ref Vector2 rotationIndicator, float roll, bool canRotate)
        {
            var characterPhysics = Character.Physics;
            var characterProxy   = characterPhysics.CharacterProxy;

            ThrustComp.ControlThrust = Vector3.Zero;

            const MyCharacterMovementEnum newMovementState = MyCharacterMovementEnum.Flying;

            Character.SwitchAnimation(newMovementState);

            Character.SetCurrentMovementState(newMovementState);

            bool wantsFlyDown = (Character.MovementFlags & MyCharacterMovementFlags.FlyDown) == MyCharacterMovementFlags.FlyDown;
            bool wantsFlyUp   = (Character.MovementFlags & MyCharacterMovementFlags.FlyUp) == MyCharacterMovementFlags.FlyUp;

            IsFlying = moveIndicator.LengthSquared() != 0;

            var proxyState = characterProxy != null?characterProxy.GetState() : 0;

            if ((proxyState == HkCharacterStateType.HK_CHARACTER_IN_AIR || (int)proxyState == MyCharacter.HK_CHARACTER_FLYING))
            {
                Character.PlayCharacterAnimation("Jetpack", MyBlendOption.Immediate, MyFrameOption.Loop, 0.2f);

                Character.CanJump = true;
            }

            MatrixD WorldMatrix    = Character.WorldMatrix;
            float   RotationSpeed  = Character.RotationSpeed;
            float   RotationFactor = 0.02f;

            if (canRotate)
            {
                MatrixD rotationXMatrix = MatrixD.Identity;
                MatrixD rotationYMatrix = MatrixD.Identity;
                MatrixD rotationZMatrix = MatrixD.Identity;

                if (Math.Abs(rotationIndicator.X) > float.Epsilon)
                {
                    if (Character.Definition.VerticalPositionFlyingOnly)
                    {
                        Character.SetHeadLocalXAngle(Character.HeadLocalXAngle - rotationIndicator.X * Character.RotationSpeed);
                    }
                    else
                    {
                        rotationXMatrix = MatrixD.CreateFromAxisAngle(WorldMatrix.Right, -rotationIndicator.X * RotationSpeed * RotationFactor);
                    }
                }

                if (Math.Abs(rotationIndicator.Y) > float.Epsilon)
                {
                    rotationYMatrix = MatrixD.CreateFromAxisAngle(WorldMatrix.Up, -rotationIndicator.Y * RotationSpeed * RotationFactor);
                }

                if (!Character.Definition.VerticalPositionFlyingOnly)
                {
                    if (Math.Abs(roll) > float.Epsilon)
                    {
                        rotationZMatrix = MatrixD.CreateFromAxisAngle(WorldMatrix.Forward, roll * RotationFactor);
                    }
                }

                // Rotation center is at the middle of the character, who is 2 meters high.
                float rotationHeight = Character.ModelCollision.BoundingBoxSizeHalf.Y;

                MatrixD  physicsMatrix = Character.Physics.GetWorldMatrix();
                Vector3D translation   = physicsMatrix.Translation + WorldMatrix.Up * rotationHeight;

                // Compute rotation
                MatrixD fullRotation  = rotationXMatrix * rotationYMatrix * rotationZMatrix;
                MatrixD rotatedMatrix = WorldMatrix.GetOrientation();
                rotatedMatrix             = rotatedMatrix * fullRotation;
                rotatedMatrix.Translation = translation - rotatedMatrix.Up * rotationHeight;

                // Update game character
                Character.WorldMatrix = rotatedMatrix;

                // Update physics character
                rotatedMatrix.Translation = physicsMatrix.Translation;
                Character.PositionComp.SetWorldMatrix(rotatedMatrix, Character.Physics);
                Character.ClearShapeContactPoints();
            }

            Vector3 moveDirection = moveIndicator;

            if (Character.Definition.VerticalPositionFlyingOnly)
            {
                float  angleSign     = Math.Sign(Character.HeadLocalXAngle);
                double headAngle     = Math.Abs(MathHelper.ToRadians(Character.HeadLocalXAngle));
                double exponent      = 1.95;
                double smoothedAngle = Math.Pow(headAngle, exponent);
                smoothedAngle *= headAngle / Math.Pow(MathHelper.ToRadians(MyCharacter.MAX_HEAD_LOCAL_X_ANGLE), exponent);
                MatrixD rotationMatrix = MatrixD.CreateFromAxisAngle(Vector3D.Right, angleSign * smoothedAngle);
                moveDirection = Vector3D.Transform(moveDirection, rotationMatrix);
            }

            if (!Vector3.IsZero(moveDirection))
            {
                moveDirection.Normalize();
            }

            ThrustComp.ControlThrust          += moveDirection * ForceMagnitude;
            ThrustComp.ControlThrustMagnitude += Vector3.One;
        }
Example #26
0
 public override void UpdateAfterSimulation()
 {
     try
     {
         if (MyAPIGateway.Multiplayer.IsServer && MyAPIGateway.Utilities.IsDedicated)
         {
             return;                     // no reason to run this on a dedicated server's side
         }
         var block = Entity as IMyCubeBlock;
         var data  = blockFanData[block.BlockDefinition.SubtypeId];
         if (first)
         {
             first     = false;
             lodDistSq = data.lodDistance * data.lodDistance;
         }
         if (!block.IsFunctional || Vector3D.DistanceSquared(block.WorldMatrix.Translation, MyAPIGateway.Session.Camera.WorldMatrix.Translation) > lodDistSq)
         {
             RemoveFan();
             return;
         }
         if (fan == null)
         {
             fan = SpawnPrefab(data.fanModel);
             if (fan == null)
             {
                 return;
             }
         }
         // sync fan color
         if (++skip % 30 == 0 && Vector3.DistanceSquared(lastColor, block.Render.ColorMaskHsv) > 0)
         {
             skip = 0;
             (fan as IMyCubeGrid).ColorBlocks(Vector3I.Zero, Vector3I.Zero, block.Render.ColorMaskHsv);
             lastColor = block.Render.ColorMaskHsv;
         }
         if (block is Ingame.IMyAirVent)
         {
             var airVent = block as Ingame.IMyAirVent;
             if (airVent.IsWorking)
             {
                 if (airVent.IsDepressurizing == true)
                 {
                     spin = Math.Min(spin + SPINUP_STEP, SPIN_THRUST);
                 }
                 else if (airVent.IsDepressurizing == false)
                 {
                     spin = Math.Max(spin - SPINDOWN_STEP, SPIN_REVERSE);
                 }
             }
             else
             {
                 if (airVent.IsDepressurizing == true)
                 {
                     spin = Math.Max(spin - SPINDOWN_STEP, SPIN_OFF);
                 }
                 else if (airVent.IsDepressurizing == false)
                 {
                     spin = Math.Min(spin + SPINUP_STEP, SPIN_OFF);
                 }
             }
         }
         var matrix = block.WorldMatrix;
         angle -= spin;
         if (data.tiltAxis.HasValue)
         {
             var axis = block.WorldMatrix.GetDirectionVector(data.tiltAxis.Value);
             matrix *= MatrixD.CreateFromAxisAngle(axis, MathHelper.ToRadians(data.tiltAngle));
         }
         matrix            *= MatrixD.CreateFromAxisAngle(matrix.Forward, MathHelper.ToRadians(angle));
         matrix.Translation = block.WorldMatrix.Translation;
         if (data.offset.HasValue)
         {
             matrix.Translation += block.WorldMatrix.Left * data.offset.Value.X + block.WorldMatrix.Up * data.offset.Value.Y + block.WorldMatrix.Forward * data.offset.Value.Z;
         }
         fan.SetWorldMatrix(matrix);
     }
     catch (Exception e)
     {
         MyLog.Default.WriteLineAndConsole(e.ToString());
         MyAPIGateway.Utilities.ShowNotification(e.Message, 3000, MyFontEnum.Red);
     }
 }
        public void MoveAndRotate(ref Vector3 moveIndicator, ref Vector2 rotationIndicator, bool canRotate)
        {
            var characterPhysics = Character.Physics;
            var characterProxy   = characterPhysics.CharacterProxy;

            ThrustComp.ControlThrust = Vector3.Zero;

            const MyCharacterMovementEnum newMovementState = MyCharacterMovementEnum.Flying;

            Character.SwitchAnimation(newMovementState);

            Character.SetCurrentMovementState(newMovementState);

            bool wantsFlyDown = (Character.MovementFlags & MyCharacterMovementFlags.FlyDown) == MyCharacterMovementFlags.FlyDown;
            bool wantsFlyUp   = (Character.MovementFlags & MyCharacterMovementFlags.FlyUp) == MyCharacterMovementFlags.FlyUp;

            IsFlying = moveIndicator.LengthSquared() != 0;

            var proxyState = characterProxy != null?characterProxy.GetState() : 0;

            if ((proxyState == HkCharacterStateType.HK_CHARACTER_IN_AIR || (int)proxyState == MyCharacter.HK_CHARACTER_FLYING))
            {
                Character.PlayCharacterAnimation("Jetpack", MyBlendOption.Immediate, MyFrameOption.Loop, 0.2f);

                Character.CanJump = true;
            }

            if (canRotate && rotationIndicator.X != 0)
            {
                MatrixD  rotationMatrix = Character.WorldMatrix.GetOrientation();
                Vector3D translation    = Character.WorldMatrix.Translation + Character.WorldMatrix.Up;

                if (Character.Definition.VerticalPositionFlyingOnly)
                {
                    Character.SetHeadLocalXAngle(MathHelper.Clamp(Character.HeadLocalXAngle - rotationIndicator.X * Character.RotationSpeed, MyCharacter.MIN_HEAD_LOCAL_X_ANGLE, MyCharacter.MAX_HEAD_LOCAL_X_ANGLE));
                }
                else
                {
                    rotationMatrix = rotationMatrix * MatrixD.CreateFromAxisAngle(Character.WorldMatrix.Right, rotationIndicator.X * -0.02 * Character.RotationSpeed);
                }

                rotationMatrix.Translation = translation - rotationMatrix.Up;

                //Enable if we want limit character rotation in collisions
                //if (m_shapeContactPoints.Count < 2)
                {
                    Character.WorldMatrix = rotationMatrix;
                    Character.ClearShapeContactPoints();
                }
            }

            Vector3 moveDirection = moveIndicator;

            if (Character.Definition.VerticalPositionFlyingOnly)
            {
                float  angleSign     = Math.Sign(Character.HeadLocalXAngle);
                double headAngle     = Math.Abs(MathHelper.ToRadians(Character.HeadLocalXAngle));
                double exponent      = 1.95;
                double smoothedAngle = Math.Pow(headAngle, exponent);
                smoothedAngle *= headAngle / Math.Pow(MathHelper.ToRadians(MyCharacter.MAX_HEAD_LOCAL_X_ANGLE), exponent);
                MatrixD rotationMatrix = MatrixD.CreateFromAxisAngle(Vector3D.Right, angleSign * smoothedAngle);
                moveDirection = Vector3D.Transform(moveDirection, rotationMatrix);
            }

            if (wantsFlyUp || wantsFlyDown)
            {
                moveDirection += (wantsFlyUp ? 1 : -1) * Vector3.Up;
            }

            if (!Vector3.IsZero(moveDirection))
            {
                moveDirection.Normalize();
            }

            ThrustComp.ControlThrust = moveDirection * ForceMagnitude;
        }
Example #28
0
        internal static unsafe void Render()
        {
            if (m_cloudLayers.Count == 0)
            {
                return;
            }

            var immediateContext = MyImmediateRC.RC;

            immediateContext.VertexShader.Set(m_proxyVs);
            immediateContext.PixelShader.Set(m_cloudPs);
            immediateContext.SetInputLayout(m_proxyIL);

            immediateContext.SetRasterizerState(MyRasterizerStateManager.NocullRasterizerState);
            immediateContext.SetBlendState(MyBlendStateManager.BlendTransparent);
            immediateContext.SetDepthStencilState(MyDepthStencilStateManager.DepthTestReadOnly);

            var cb = MyCommon.GetObjectCB(sizeof(CloudsConstants));

            immediateContext.AllShaderStages.SetConstantBuffer(1, cb);
            immediateContext.PixelShader.SetSamplers(0, MySamplerStateManager.CloudSampler);

            immediateContext.SetRtv(MyGBuffer.Main.DepthStencil, MyDepthStencilAccess.ReadOnly, MyGBuffer.Main.LBuffer);

            m_cloudLayers.OrderByDescending(x =>
            {
                MyCloudLayer cloudLayer         = x.Value;
                Vector3D cameraToLayer          = cloudLayer.CenterPoint - MyRender11.Environment.Matrices.CameraPosition;
                Vector3D layerToCameraDirection = -Vector3D.Normalize(cameraToLayer);
                return((cameraToLayer + layerToCameraDirection * cloudLayer.Altitude).Length());
            });

            foreach (var cloudLayer in m_cloudLayers)
            {
                var modifiableData       = m_modifiableCloudLayerData[cloudLayer.Key];
                int currentGameplayFrame = MyRender11.GameplayFrameCounter;
                var increment            = cloudLayer.Value.AngularVelocity * (float)(currentGameplayFrame - modifiableData.LastGameplayFrameUpdate) / 10.0f;
                modifiableData.RadiansAroundAxis += increment; // Constant for backward compatibility
                if (modifiableData.RadiansAroundAxis >= 2 * Math.PI)
                {
                    modifiableData.RadiansAroundAxis -= 2 * Math.PI;
                }

                modifiableData.LastGameplayFrameUpdate = currentGameplayFrame;

                double   scaledAltitude           = cloudLayer.Value.Altitude;
                Vector3D centerPoint              = cloudLayer.Value.CenterPoint;
                Vector3D cameraPosition           = MyRender11.Environment.Matrices.CameraPosition;
                double   cameraDistanceFromCenter = (centerPoint - cameraPosition).Length();

                if (cloudLayer.Value.ScalingEnabled)
                {
                    double threshold = cloudLayer.Value.Altitude * 0.95;
                    if (cameraDistanceFromCenter > threshold)
                    {
                        scaledAltitude = MathHelper.Clamp(scaledAltitude * (1 - MathHelper.Clamp((cameraDistanceFromCenter - threshold) / (threshold * 1.5), 0.0, 1.0)), cloudLayer.Value.MinScaledAltitude, cloudLayer.Value.Altitude);
                    }
                }

                MatrixD worldMatrix = MatrixD.CreateScale(scaledAltitude) * MatrixD.CreateFromAxisAngle(cloudLayer.Value.RotationAxis, (float)modifiableData.RadiansAroundAxis);
                worldMatrix.Translation  = cloudLayer.Value.CenterPoint;
                worldMatrix.Translation -= MyRender11.Environment.Matrices.CameraPosition;

                float layerAlpha = 1.0f;

                double currentRelativeAltitude = (cameraDistanceFromCenter - cloudLayer.Value.MinScaledAltitude) / (cloudLayer.Value.MaxPlanetHillRadius - cloudLayer.Value.MinScaledAltitude);
                if (cloudLayer.Value.FadeOutRelativeAltitudeStart > cloudLayer.Value.FadeOutRelativeAltitudeEnd)
                {
                    layerAlpha = (float)MathHelper.Clamp(1.0 - (cloudLayer.Value.FadeOutRelativeAltitudeStart - currentRelativeAltitude) / (cloudLayer.Value.FadeOutRelativeAltitudeStart - cloudLayer.Value.FadeOutRelativeAltitudeEnd), 0.0, 1.0);
                }
                else if (cloudLayer.Value.FadeOutRelativeAltitudeStart < cloudLayer.Value.FadeOutRelativeAltitudeEnd)
                {
                    layerAlpha = (float)MathHelper.Clamp(1.0 - (currentRelativeAltitude - cloudLayer.Value.FadeOutRelativeAltitudeStart) / (cloudLayer.Value.FadeOutRelativeAltitudeEnd - cloudLayer.Value.FadeOutRelativeAltitudeStart), 0.0, 1.0);
                }

                Vector4 layerColor = new Vector4(1, 1, 1, layerAlpha);

                var constants = new CloudsConstants();
                constants.World    = MatrixD.Transpose(worldMatrix);
                constants.ViewProj = MatrixD.Transpose(MyRender11.Environment.Matrices.ViewProjectionAt0);
                constants.Color    = layerColor;

                var mapping = MyMapping.MapDiscard(cb);
                mapping.WriteAndPosition(ref constants);
                mapping.Unmap();

                MeshId        sphereMesh = cloudLayer.Value.Mesh;
                LodMeshId     lodMesh    = MyMeshes.GetLodMesh(sphereMesh, 0);
                MyMeshBuffers buffers    = lodMesh.Buffers;
                immediateContext.SetVertexBuffer(0, buffers.VB0.Buffer, buffers.VB0.Stride);
                immediateContext.SetVertexBuffer(1, buffers.VB1.Buffer, buffers.VB1.Stride);
                immediateContext.SetIndexBuffer(buffers.IB.Buffer, buffers.IB.Format);

                immediateContext.PixelShader.SetSrv(0, cloudLayer.Value.TextureInfo.ColorMetalTexture);
                immediateContext.PixelShader.SetSrv(1, cloudLayer.Value.TextureInfo.AlphaTexture);
                immediateContext.PixelShader.SetSrv(2, cloudLayer.Value.TextureInfo.NormalGlossTexture);

                immediateContext.DrawIndexed(lodMesh.Info.IndicesNum, 0, 0);
            }

            immediateContext.PixelShader.SetSrv(0, null);
            immediateContext.PixelShader.SetSrv(1, null);
            immediateContext.PixelShader.SetSrv(2, null);
            immediateContext.SetDepthStencilState(null);
            immediateContext.SetBlendState(null);
            immediateContext.SetRasterizerState(null);
            immediateContext.SetRtv(null);
        }
Example #29
0
        private bool CalculateGridPosition(Vector3D Target)
        {
            Vector3D forwardVector = Vector3D.Zero;


            //Hangar.Debug("Total Grids to be pasted: " + _grids.Count());

            //Attempt to get gravity/Artificial gravity to align the grids to


            //Here you can adjust the offset from the surface and rotation.
            //Unfortunatley we move the grid again after this to find a free space around the character. Perhaps later i can incorporate that into
            //LordTylus's existing grid checkplament method
            float gravityRotation = 0f;

            Vector3 gravityDirectionalVector = MyGravityProviderSystem.CalculateNaturalGravityInPoint(Target);

            bool AllowAlignToNatrualGravity = false;

            if (AllowAlignToNatrualGravity && gravityDirectionalVector == Vector3.Zero)
            {
                gravityDirectionalVector = MyGravityProviderSystem.CalculateArtificialGravityInPoint(Target);
            }


            if (gravityDirectionalVector == Vector3.Zero)
            {
                return(false);
            }


            //Calculate and apply grid rotation
            Vector3D upDirectionalVector;

            if (gravityDirectionalVector != Vector3.Zero)
            {
                gravityDirectionalVector.Normalize();
                upDirectionalVector = -gravityDirectionalVector;

                if (forwardVector == Vector3D.Zero)
                {
                    forwardVector = Vector3D.CalculatePerpendicularVector(gravityDirectionalVector);
                    if (gravityRotation != 0f)
                    {
                        MatrixD matrixa = MatrixD.CreateFromAxisAngle(upDirectionalVector, gravityRotation);
                        forwardVector = Vector3D.Transform(forwardVector, matrixa);
                    }
                }
            }
            else if (forwardVector == Vector3D.Zero)
            {
                forwardVector       = Vector3D.Right;
                upDirectionalVector = Vector3D.Up;
            }
            else
            {
                upDirectionalVector = Vector3D.CalculatePerpendicularVector(-forwardVector);
            }

            BeginAlignToGravity(Target, forwardVector, upDirectionalVector);
            return(true);
        }