예제 #1
0
        public Basis Execute(Matrix matrix)
        {
            var basis = new Basis();
            var row = matrix.GetRow(0);
            for (int i = 0; i < row.rows; i++)
            {
                if (row[i] == 0)
                {
                    var v = new Vector(row.rows);
                    v[i] = 1;
                    basis.Add(v);
                }
                else
                {
                    bool sign = row[i] > 0;
                    for (int j = i + 1; j < row.rows; j++)
                    {
                        if (row[j] != 0 && row[j] > 0 ^ sign)
                        {
                            var lcm = MathExtensions.LCM(Math.Abs((int)row[i]), Math.Abs((int)row[j]));
                            var v = new Vector(row.rows);
                            v[i] = (lcm / Math.Abs((int)row[i]));
                            v[j] = (lcm / Math.Abs((int)row[j]));
                            basis.Add(v);
                        }
                    }
                }
            }

            return ExcecuteRound(matrix, basis, 1);
        }
예제 #2
0
 private Basis ExcecuteRound(Matrix matrix, Basis basis, int rowIndex)
 {
     var currentRow = matrix.GetRow(rowIndex);
     var currentRes = new Vector(basis.Count);
     for (int i = 0; i < basis.Count; i++)
     {
         currentRes[i] = (int)(basis[i].Transpose() * currentRow)[0, 0];
     }
     var newBasis = Compose(basis, currentRes);
     if (rowIndex == matrix.rows-1)
         return newBasis;
     return ExcecuteRound(matrix, newBasis, rowIndex + 1);
 }
예제 #3
0
    void UpdateMovementInput()
    {
        direction = Vector3.Zero;

        Basis headDirection   = head.GetGlobalTransform().basis;
        Basis cameraDirection = camera.GetGlobalTransform().basis;

        if (flyMode)
        {
            CalculateFlyDirection(cameraDirection);
        }
        else
        {
            CalculateMoveDirection(cameraDirection, headDirection);
        }

        direction = direction.Normalized();

        isWalking = Input.IsActionPressed("move_walk");

        if (Input.IsActionJustPressed("jump") && alowJumpInput)
        {
            canJump = true;
        }
        else if (Input.IsActionJustPressed("jump") && airJumpsLeft > 0)
        {
            canJump = true;
            airJumpsLeft--;
        }
        else
        {
            canJump = false;
        }

        if (Input.IsActionJustPressed("fly_mode"))
        {
            flyMode = !flyMode;
        }
    }
예제 #4
0
        public IActionResult UpdateRounds(Basis model)
        {
            if (model.RoundCount <= 0)
            {
                ModelState.AddModelError(nameof(model.RoundCount), "轮数必须为正整数。");
            }

            if (model.GameCount <= 0)
            {
                ModelState.AddModelError(nameof(model.GameCount), "局数必须为正整数。");
            }

            if (ModelState.IsValid)
            {
                FacadeService.Facade.SetBasisRoundAndGame(model.RoundCount, model.GameCount);
                OperationMessageAccessor.Messages.Add(OperationMessageLevel.Success, "操作成功",
                                                      "比赛轮次信息已经更新。以前的轮次信息已经被清除。");
                return(RedirectToAction("Basis", "Manage"));
            }

            return(View("Basis", model));
        }
예제 #5
0
        /// <summary>
        /// Uses information from <paramref name="config"/> to create
        /// <see cref="SinglePhaseField"/>s for <see cref="Density"/>,
        /// <see cref="Momentum"/> and <see cref="Energy"/>.
        /// </summary>
        /// <param name="gridData">The omnipresent grid data</param>
        /// <param name="config">CNS specific control options</param>
        public CNSFieldSet(GridData gridData, CNSControl config)
        {
            this.gridData = gridData;
            this.config   = config;

            int numberOfDimensions = CNSEnvironment.NumberOfDimensions;

            SinglePhaseField[] momentumFields = new SinglePhaseField[numberOfDimensions];
            Basis momentumBasis = new Basis(gridData, config.MomentumDegree);

            // Mandatory fields
            Density = new SinglePhaseField(
                new Basis(gridData, config.DensityDegree),
                Variables.Density);

            for (int d = 0; d < numberOfDimensions; d++)
            {
                string variableName = Variables.Momentum[d];
                momentumFields[d] = new SinglePhaseField(momentumBasis, variableName);
            }
            Momentum = new VectorField <DGField>(momentumFields);

            Energy = new SinglePhaseField(
                new Basis(gridData, config.EnergyDegree), Variables.Energy);

            // Derived fields
            foreach (var fieldConfig in config.VariableFields)
            {
                DerivedVariable key = fieldConfig.Key as DerivedVariable;
                if (key == null)
                {
                    continue;
                }

                SinglePhaseField field = new SinglePhaseField(
                    new Basis(gridData, fieldConfig.Value), key);
                DerivedFields.Add(key, field);
            }
        }
예제 #6
0
 private Basis Compose(Basis basis, Vector items)
 {
     var newBasis = new Basis();
     for (int i = 0; i < items.rows; i++)
     {
         if (items[i] == 0)
             newBasis.Add(basis[i]);
         else
         {
             bool sign = items[i] > 0;
             for (int j = i + 1; j < items.rows; j++)
             {
                 if (items[j] != 0 && items[j] > 0 ^ sign)
                 {
                     var lcm = MathExtensions.LCM(Math.Abs((int)items[i]), Math.Abs((int)items[j]));
                     newBasis.Add((lcm / Math.Abs((int)items[i])) * basis[i] + (lcm / Math.Abs((int)items[j])) * basis[j]);
                 }
             }
         }
     }
     return newBasis;
 }
예제 #7
0
        private void UpdatePatchRecoveryFilter()
        {
            Basis B   = m_FilteredVelocity[0].Basis;
            var   CC1 = LsTrk.Regions.GetNearFieldMask(0);

            if (this.Config.UsePatchRecoveryFiltering)
            {
                var filterDom = m_CC0.Union(CC1);
                if (this.Filter == null)
                {
                    this.Filter = new L2PatchRecovery(B, B, filterDom, RestrictToCellMask: false);
                }
                else
                {
                    this.Filter.UpdateDomain(filterDom, RestrictToCellMask: false);
                }
            }
            else
            {
                this.Filter = null;
            }
        }
예제 #8
0
파일: IBMUtility.cs 프로젝트: xyuan/BoSSS
        internal static double GetMassMatrixDeterminant(ImmersedSpeciesMap speciesMap, CoordinateMapping mapping, CellMask cellMask)
        {
            BlockMsrMatrix massMatrix = speciesMap.GetMassMatrixFactory(mapping).MassMatrix;
            Basis          maxBasis   = mapping.BasisS.ElementAtMax(b => b.Degree);

            MultidimensionalArray subMatrix = MultidimensionalArray.Create(
                cellMask.NoOfItemsLocally + 1, maxBasis.Length, cellMask.NoOfItemsLocally + 1, maxBasis.Length);
            int cellIndex = 0;

            foreach (Chunk chunk in cellMask)
            {
                for (int i = 0; i < chunk.Len; i++)
                {
                    //IMatrix block = massMatrix.GetBlock(i + chunk.i0);
                    MultidimensionalArray block = GetBlock(massMatrix, i + chunk.i0);
                    for (int j = 0; j < maxBasis.Length; j++)
                    {
                        for (int k = 0; k < maxBasis.Length; k++)
                        {
                            subMatrix[cellIndex, j, cellIndex, k] = block[j, k];
                        }
                    }

                    cellIndex++;
                }
            }

            for (int j = 0; j < maxBasis.Length; j++)
            {
                subMatrix[cellIndex, j, cellIndex, j] = 1.0;
            }

            subMatrix = subMatrix.ResizeShallow(
                (cellMask.NoOfItemsLocally + 1) * maxBasis.Length,
                (cellMask.NoOfItemsLocally + 1) * maxBasis.Length);

            return(subMatrix.cond());
        }
예제 #9
0
        public LocalSolver_Geometric(Basis __LevelSetBasis_Geometric)
        {
            LevelSetBasis_Geometric = __LevelSetBasis_Geometric;
            GridDat = (GridData)(LevelSetBasis_Geometric.GridDat);

            int D = this.GridDat.SpatialDimension;

            if (D != 2)
            {
                throw new NotImplementedException("Geometric solver currently only implemented for 2D.");
            }

            if (!(this.GridDat.Edges.EdgeRefElements.Count() == 1 && this.GridDat.Edges.EdgeRefElements.First().GetType() == typeof(Foundation.Grid.RefElements.Line)))
            {
                throw new NotImplementedException();
            }


            double[] _EdgeNodes = GenericBlas.Linspace(-1, 1, Math.Max(10, (this.LevelSetBasis_Geometric.Degree + 1) * 2));
            int      NN         = _EdgeNodes.Length;

            this.EdgeNodes = new NodeSet(GridDat.Edges.EdgeRefElements[0], NN, 1);
            EdgeNodes.ExtractSubArrayShallow(-1, 0).SetVector(_EdgeNodes);
            this.EdgeNodes.LockForever();

            DaRuleS         = this.GridDat.Grid.RefElements.Select(Kref => Kref.GetQuadratureRule(this.LevelSetBasis_Geometric.Degree * 2)).ToArray();
            QuadNodesGlobal = DaRuleS.Select(rule => MultidimensionalArray.Create(rule.NoOfNodes, D)).ToArray();

            int NNKmax = 4;

            PhiEvalBuffer   = new MultidimensionalArray[NNKmax];
            CellNodesGlobal = new MultidimensionalArray[NNKmax];
            for (int i = 0; i < NNKmax; i++)
            {
                PhiEvalBuffer[i]   = MultidimensionalArray.Create(1, NN);
                CellNodesGlobal[i] = MultidimensionalArray.Create(NN, D);
            }
        }
예제 #10
0
        /// <summary>
        /// Creation of DG fields.
        /// </summary>
        protected override void CreateFields()
        {
            int GridDeg = this.Grid.Cells.Select(cl => this.Grid.GetRefElement(cl.Type).GetInterpolationDegree(cl.Type)).Max();
            int D       = this.GridData.SpatialDimension;

            if (this.Grid.GetRefElement(this.Grid.Cells[0].Type) == Square.Instance ||
                this.Grid.GetRefElement(this.Grid.Cells[0].Type) == Cube.Instance)
            {
                // hack: otherwise DG deg gets to high
                GridDeg = (int)Math.Round(Math.Pow(GridDeg, 1.0 / D));
            }

            Basis b = new Basis(this.GridData, 2 + GridDeg);


            Console.WriteLine("Grid degree is " + GridDeg + " => Using DG order: " + b.Degree);


            f1 = new SinglePhaseField(b, "f1");
            f2 = new SinglePhaseField(b, "f2");
            Laplace_f1_Numerical  = new SinglePhaseField(b, "Laplace_f1_Numerical");
            Laplace_f2_Numerical  = new SinglePhaseField(b, "Laplace_f2_Numerical");
            Laplace_f1_Analytical = new SinglePhaseField(b, "Laplace_f1_Analytical");
            Laplace_f2_Analytical = new SinglePhaseField(b, "Laplace_f2_Analytical");

            f1Gradient_Analytical = new SinglePhaseField[D];
            f2Gradient_Analytical = new SinglePhaseField[D];
            f1Gradient_Numerical  = new SinglePhaseField[D];
            f2Gradient_Numerical  = new SinglePhaseField[D];

            for (int d = 0; d < D; d++)
            {
                f1Gradient_Analytical[d] = new SinglePhaseField(b, string.Format("df1_dx{0}_Analytical", d));
                f2Gradient_Analytical[d] = new SinglePhaseField(b, string.Format("df2_dx{0}_Analytical", d));
                f1Gradient_Numerical[d]  = new SinglePhaseField(b, string.Format("df1_dx{0}_Numerical", d));
                f2Gradient_Numerical[d]  = new SinglePhaseField(b, string.Format("df2_dx{0}_Numerical", d));
            }
        }
예제 #11
0
        public static void RestrictionOfSystemOpTest()
        {
            Basis B1 = new Basis(grid, 0), B2 = new Basis(grid, 2);
            var   Map = new UnsetteledCoordinateMapping(B1, B2);

            var Lev0Basis = new AggregationGridBasis(B2, TestProgram.MgSeq[0]);
            var Lev1Basis = new AggregationGridBasis(B2, TestProgram.MgSeq[1]);


            var Lev0 = new MultigridMapping(Map, new AggregationGridBasis[] { Lev0Basis, Lev0Basis }, new int[] { B1.Degree, B2.Degree });
            var Lev1 = new MultigridMapping(Map, new AggregationGridBasis[] { Lev1Basis, Lev1Basis }, new int[] { B1.Degree, B2.Degree });


            int[] I0col = Lev0.GetSubvectorIndices(new int[] { 0 });
            int[] I1col = Lev0.GetSubvectorIndices(new int[] { 1 });
            int[] I0row = Lev1.GetSubvectorIndices(new int[] { 0 });
            int[] I1row = Lev1.GetSubvectorIndices(new int[] { 1 });

            var RestMtx = Lev1.FromOtherLevelMatrix(Lev0);

            MsrMatrix Rest00 = new MsrMatrix(I0row.Length, I0col.Length, 1, 1);

            RestMtx.WriteSubMatrixTo(Rest00, I0row, default(int[]), I0col, default(int[]));
            MsrMatrix Rest01 = new MsrMatrix(I0row.Length, I1col.Length, 1, 1);

            RestMtx.WriteSubMatrixTo(Rest01, I0row, default(int[]), I1col, default(int[]));
            MsrMatrix Rest10 = new MsrMatrix(I1row.Length, I0col.Length, 1, 1);

            RestMtx.WriteSubMatrixTo(Rest10, I1row, default(int[]), I0col, default(int[]));
            MsrMatrix Rest11 = new MsrMatrix(I1row.Length, I1col.Length, 1, 1);

            RestMtx.WriteSubMatrixTo(Rest11, I1row, default(int[]), I1col, default(int[]));

            Debug.Assert(Rest10.InfNorm() == 0.0);
            Debug.Assert(Rest01.InfNorm() == 0.0);
            Debug.Assert(Rest00.InfNorm() != 0.0);
            Debug.Assert(Rest11.InfNorm() != 0.0);
        }
예제 #12
0
파일: SolverUtils.cs 프로젝트: xyuan/BoSSS
        /// <summary>
        /// computes the index of the
        /// 0-th DG coordinate (see <see cref="SetRefPtPressure_Matrix"/>, <see cref="SetRefPtPressure_Rhs"/>)
        /// from a position <paramref name="Point"/> vector.
        /// </summary>
        /// <param name="map">the mapping which defines how cell indices translate.</param>
        /// <param name="iVar">the index of the pressure variable in the mapping <paramref name="map"/>.</param>
        /// <param name="Point">position vector</param>
        static public int GetIndexOfPressureReferencePoint(double[] Point, UnsetteledCoordinateMapping map, int iVar)
        {
            using (new FuncTrace()) {
                var GridDat = map.GridDat;

                Basis PressureBasis = map.BasisS[iVar];
                int   D             = GridDat.SpatialDimension;

                long GlobalID, GlobalIndex;
                bool IsInside, onthisProc;
                GridDat.LocatePoint(Point, out GlobalID, out GlobalIndex, out IsInside, out onthisProc);

                int iRowGl = -111;
                if (onthisProc)
                {
                    int jCell = (int)GlobalIndex - GridDat.CellPartitioning.i0;
                    iRowGl = (int)map.GlobalUniqueCoordinateIndex_FromGlobal(iVar, GlobalIndex, 0);
                }
                iRowGl = iRowGl.MPIMax();

                return(iRowGl);
            }
        }
예제 #13
0
        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="GridDat"></param>
        /// <param name="Temperature"></param>
        /// <param name="EoS"></param>
        /// <param name="edgeTagNames"></param>
        public NusseltNumber(IGridData GridDat, SinglePhaseField Temperature, MaterialLaw EoS, string[] edgeTagNames)
        {
            this.GridDat     = GridDat;
            this.Temperature = Temperature;

            //Basis BasisDerivative = new Basis(GridDat, Temperature.Basis.Degree - 1);
            Basis BasisDerivative = new Basis(GridDat, Temperature.Basis.Degree);

            dTdx = new SinglePhaseField(BasisDerivative);
            dTdy = new SinglePhaseField(BasisDerivative);

            NusseltIntegrals = new EdgeIntegral[edgeTagNames.Length];
            Nusselt          = new double[edgeTagNames.Length];

            for (int bc = 0; bc < edgeTagNames.Length; bc++)
            {
                NusseltIntegrals[bc] = new EdgeIntegral((BoSSS.Foundation.Grid.Classic.GridData)GridDat,
                                                        edgeTagNames[bc],
                                                        new NusseltFlux2D(EoS),
                                                        new CoordinateMapping(dTdx, dTdy, Temperature),
                                                        20);
            }
        }
예제 #14
0
        /// <summary>
        /// Factory for some stationary level sets
        /// </summary>
        /// <param name="surf">To be replaced by the level set class....</param>
        /// <param name="specification">Switch for the different types of surfaces: Sphere, Torus or Plane</param>
        /// <param name="b">Basis for the level set</param>
        /// <param name="context">The context object</param>
        /// <param name="deltax">Parameter for the signum approximation, should correspond to the maximal side length in case of a Cartesian grid </param>
        public static void ProduceSurface(out Surface surf, String specification, Basis b, GridData context, double deltax)
        {
            switch (specification)
            {
            /* By default: a unit sphere is created.*/
            case "Sphere":
                surf = new Sphere(context, b, deltax, 1.0);
                break;

            /* By default: a torus with major radius 1.0 and minor radius 0.25 is created.*/
            case "Torus":
                surf = new Torus(context, b, deltax, 1.0, 0.25);
                break;

            case "Plane":
                surf = new Plane(context, b, deltax);
                break;

            default: Console.WriteLine("This option is not implemented. Please select Sphere,Torus or Plane.");
                surf = null;
                break;
            }
        }
예제 #15
0
        /// <summary>
        /// Determines the total curvature which is twice the mean curvature
        /// Please pay attention to the sign of this expression!
        /// </summary>
        /// <param name="Output">Field representing the total curvature</param>
        /// <param name="optionalCellMask">
        /// Cell Mask for the derivatives and their accumulation regarding the
        /// curvature
        /// </param>
        public void ComputeTotalCurvature(SinglePhaseField Output, CellMask optionalCellMask)
        {
            if (this.m_Basis.Degree <= 1)
            {
                throw new ArgumentException("For correct computation of these level set quantities, the level set has to be at least of degree 2!");
            }

            Basis basisForNormalVec = new Basis(this.GridDat, this.m_Basis.Degree - 1);
            Basis basisForCurvature = new Basis(this.GridDat, this.m_Basis.Degree - 2);

            Func <Basis, string, SinglePhaseField> fac          = (Basis b, string id) => new SinglePhaseField(b, id);
            VectorField <SinglePhaseField>         normalVector = new VectorField <SinglePhaseField>(this.GridDat.SpatialDimension, basisForNormalVec, fac);

            ComputeNormal(normalVector, optionalCellMask);
            VectorField <SinglePhaseField> secondDerivatives = new VectorField <SinglePhaseField>(this.GridDat.SpatialDimension, basisForCurvature, fac);

            Output.Clear();
            for (int i = 0; i < normalVector.Dim; i++)
            {
                secondDerivatives[i].Derivative(1.0, normalVector[i], i, optionalCellMask);
                Output.Acc(-1.0, secondDerivatives[i], optionalCellMask);
            }
        }
예제 #16
0
        /***************************************************/

        /***************************************************/
        /**** Constructors                              ****/
        /***************************************************/

        public MeshDisplacement(IComparable objectId,
                                IComparable nodeId,
                                IComparable meshFaceId,
                                IComparable resultCase,
                                double timeStep,
                                MeshResultLayer meshResultLayer,
                                double layerPosition,
                                MeshResultSmoothingType smoothing,
                                Basis orientation,
                                double uXX,
                                double uYY,
                                double uZZ,
                                double rXX,
                                double rYY,
                                double rZZ) : base(objectId, nodeId, meshFaceId, resultCase, timeStep, meshResultLayer, layerPosition, smoothing, orientation)
        {
            UXX = uXX;
            UYY = uYY;
            UZZ = uZZ;
            RXX = rXX;
            RYY = rYY;
            RZZ = rZZ;
        }
예제 #17
0
    public static CustomSymbol CreateSymbol(List <Vector3> points)
    {
        List <Vector3> correctedCountPoints = CorrectPointsCount(points);
        Vector3        spellCenter          = SymbolsHelper.CalculateSymbolCenter(correctedCountPoints);

        Basis basisBasedOnPlayerSight       = CreateBasisBasedOnPlayerSight(spellCenter, Player.instance.headCollider.transform.position);
        Basis basisToProjectPointsToXyPlane = CreateBasisToProjectPointsToXyPlane(basisBasedOnPlayerSight);

        List <Vector3> poitnsProjectedToPlaneInPlayerSightBasis = MathHelper.ProjectPointsToPlane(correctedCountPoints, spellCenter, basisBasedOnPlayerSight.Forward);
        List <Vector3> pointsProjectedToXyPlane = ProjectPointsToXyPlane(poitnsProjectedToPlaneInPlayerSightBasis, spellCenter, basisToProjectPointsToXyPlane);
        List <Vector3> resizedPoints            = ResizeShapeToFitRecognitionSquare(pointsProjectedToXyPlane);

        SymbolAnalyzerResult result = SymbolAnalyzer.Instance.Analyze(resizedPoints);

        CustomSymbol newSymbol = new CustomSymbol();

        newSymbol.Type        = result.IsPassed() ? result.SymbolType : SymbolType.Unrecognized;
        newSymbol.Center      = spellCenter;
        newSymbol.Orientation = basisBasedOnPlayerSight;
        newSymbol.Size        = SymbolsHelper.GetWidthAndHeightOfShape(pointsProjectedToXyPlane).MaxDimension;

        return(newSymbol);
    }
예제 #18
0
    private void Fly(float delta)
    {
        //Reset direction
        Direction = Vector3.Zero;

        //Get the rotation of the head
        Basis aim = _Camera.GlobalTransform.basis;

        //Get input and set direction
        Direction += aim.z * Vinput;
        Direction += aim.x * Hinput;
        Direction += aim.y * Linput;
        Direction  = Direction.Normalized();

        //Set target speed
        Vector3 target = Direction * FullSpeedFly;

        //Calculate velocity
        Velocity = Velocity.LinearInterpolate(target, AccelerationFly * delta);

        //Move Player
        GlobalTranslate(Velocity);
    }
예제 #19
0
        public void SetLimiter(int[] limDeg)
        {
            if (limDeg == null)
            {
                this.Nlim = null;
            }
            else
            {
                int J = this.Domain.GridData.iLogicalCells.NoOfLocalUpdatedCells;
                if (limDeg.Length != J)
                {
                    throw new ArgumentException();
                }

                var _Nlim = new int[J];

                Basis B      = this.m_bInput.Degree > this.m_bOutput.Degree ? this.m_bInput : this.m_bOutput;
                int[] DegToN = (B.Degree + 1).ForLoop(deg => B.Polynomials[0].Where(p => p.AbsoluteDegree <= deg).Count());

                int degMax = B.Degree;
                for (int j = 0; j < J; j++)
                {
                    if (limDeg[j] > degMax)
                    {
                        throw new ArgumentOutOfRangeException();
                    }

                    if (limDeg[j] >= 0)
                    {
                        _Nlim[j] = DegToN[limDeg[j]];
                        Debug.Assert(_Nlim[j] > 0);
                    }
                }

                this.Nlim = _Nlim;
            }
        }
예제 #20
0
        unsafe public static void Laplacian(ref int GridRef,
                                            ref int DgDegree,

                                            out int ierr)
        {
            try {
                // grid, etc
                // =========

                GridData grd = null;// (GridData)(Infrastructure.GetObject(GridRef));

                var b   = new Basis(grd, DgDegree);
                var map = new UnsetteledCoordinateMapping(b);

                var L  = new Laplace(1.3, grd.Cells.cj);
                var op = new SpatialOperator(1, 0, 1, QuadOrderFunc.Linear(), "T", "c1");
                op.EquationComponents["c1"].Add(L);
                op.Commit();

                // evaluate operator
                // =================

                var      Mtx = new BlockMsrMatrix(map, map);
                double[] B   = new double[map.LocalLength];

                var eval = op.GetMatrixBuilder(map, null, map);
                eval.ComputeMatrix(Mtx, B);

                // return data
                // ===========

                throw new NotImplementedException("todo");
            } catch (Exception e) {
                ierr = Infrastructure.ErrorHandler(e);
            }
            ierr = 0;
        }
예제 #21
0
파일: IBMUtility.cs 프로젝트: xyuan/BoSSS
        internal static double GetMaxLocalMassMatrixDeterminant(ImmersedSpeciesMap speciesMap, CoordinateMapping mapping, CellMask cellMask, out int maxCondCell)
        {
            BlockMsrMatrix massMatrix = speciesMap.GetMassMatrixFactory(mapping).MassMatrix;
            Basis          maxBasis   = mapping.BasisS.ElementAtMax(b => b.Degree);

            MultidimensionalArray subMatrix = MultidimensionalArray.Create(
                maxBasis.Length, maxBasis.Length);

            double maxCond = 0.0;

            maxCondCell = -1;
            foreach (Chunk chunk in cellMask)
            {
                for (int i = 0; i < chunk.Len; i++)
                {
                    //IMatrix block = massMatrix.GetBlock(i + chunk.i0);
                    MultidimensionalArray block = GetBlock(massMatrix, i + chunk.i0);
                    for (int j = 0; j < maxBasis.Length; j++)
                    {
                        for (int k = 0; k < maxBasis.Length; k++)
                        {
                            subMatrix[j, k] = block[j, k];
                        }
                    }

                    double cond = subMatrix.cond();
                    if (cond > maxCond)
                    {
                        maxCond     = cond;
                        maxCondCell = i + chunk.i0;
                    }
                }
            }

            return(maxCond);
        }
예제 #22
0
    // Handle player movement
    private void movement(float delta)
    {
        // Apply gravity
        if (this.IsOnFloor())
        {
            direction = new Vector3();
        }
        else
        {
            direction   = direction.LinearInterpolate(new Vector3(), friction * delta);
            velocity.y += -gravity * delta;
        }

        // Apply player direction
        Basis transformbasis = headRay.GlobalTransform.basis;

        direction += (-input["left"] + input["right"]) * transformbasis.x;
        direction += (-input["forward"] + input["back"]) * transformbasis.z;

        direction.y = 0;
        direction   = direction.Normalized();

        // Interpolate between current and future positions
        Vector3 target = direction * normalSpeed;

        direction.y = 0;

        Vector3 tempVelocity = velocity.LinearInterpolate(target, normalSpeed * delta);

        // Apply interpolation
        velocity.x = tempVelocity.x;
        velocity.z = tempVelocity.z;

        // Move character
        velocity = MoveAndSlide(velocity, new Vector3(0, 1, 0), false, 6, (float)(Math.PI / 4.0), false);
    }
        public double CompareTexts()
        {
            _charsInTextA = Basis.Count();
            _charsInTextB = Target.Count();

            //Swap the texts if text A is larger than text B.
            if (_charsInTextA > _charsInTextB)
            {
                Swap();
            }

            //The lines 'i' in text A are compared to the linjes 'j' in text B.
            //for (int i = 0; i < _linesInTextA; i++)
            //{
            //    for (int j = 0; j < _linesInTextB; j++)
            //    {
            if (!(string.IsNullOrEmpty(Basis) || string.IsNullOrEmpty(Target)))
            {
                //Calculates the Levenshtein Distance. The return value is added to the list ListLevDis.
                ListLevDis.Add(CalcLevenshteinDistance(Basis, Target));
            }
            //}
            //For every line in text A the smallest Levenshtein Distance
            //is compoundassigned to levenshteinDistanceDouble.
            levenshteinDistanceDouble += ListLevDis.Min();
            //The list is cleared for the next iteration of the for loop.
            ListLevDis.Clear();
            //}

            //Calculates the Levenshtein Distance in percent.
            double LevDisPct = ((1 - (levenshteinDistanceDouble / _charsInTextA)) * 100);

            //Rounds off the Levenshtein Distance to 2 decimals.
            LevenshteinDistanceValue = Math.Round(LevDisPct, 2);
            return(LevenshteinDistanceValue);
        }
예제 #24
0
        /// <summary>
        /// Backup data for some DG field before update of grid.
        /// </summary>
        /// <param name="f"></param>
        /// <param name="Reference">
        /// Unique string reference under which the re-distributed data can be accessed later, within <see cref="RestoreDGField(DGField, string)"/>.
        /// </param>
        override public void BackupField(DGField f, string Reference)
        {
            if (!object.ReferenceEquals(f.GridDat, m_OldGrid))
            {
                throw new ArgumentException("DG field seems to be assigned to some other grid.");
            }

            Basis oldBasis = f.Basis;

            double[][] oldFieldsData = new double[m_oldJ][];
            m_oldDGFieldData.Add(Reference, oldFieldsData);

            for (int j = 0; j < m_oldJ; j++)
            {
                int      Nj     = oldBasis.GetLength(j);
                double[] data_j = new double[Nj];
                for (int n = 0; n < Nj; n++)
                {
                    data_j[n] = f.Coordinates[j, n];
                }

                oldFieldsData[j] = data_j;
            }
        }
예제 #25
0
 /// <summary>Initializes a new instance of the
 /// <see cref="TestableCloud"/>
 /// class.</summary>
 /// <param name="cloud">The cloud to test.</param>
 /// <param name="coordinates">The expected coordinates.</param>
 /// <param name="weights">The expected weights.</param>
 /// <param name="basis">The expected basis.</param>
 /// <param name="mean">The expected mean.</param>
 /// <param name="variance">The expected variance.</param>
 /// <param name="covariance">The expected covariances.</param>
 /// <param name="centred">The expected centered coordinates.</param>
 /// <param name="standardized">The expected standardized coordinates.</param>
 /// <param name="rebased">The expected re-based coordinates.</param>
 public TestableCloud(
     Cloud cloud,
     DoubleMatrix coordinates,
     DoubleMatrix weights,
     Basis basis,
     DoubleMatrix mean,
     double variance,
     DoubleMatrix covariance,
     DoubleMatrix centred,
     DoubleMatrix standardized,
     Dictionary <Basis, DoubleMatrix> rebased
     )
 {
     this.Cloud        = cloud;
     this.Coordinates  = coordinates;
     this.Weights      = weights;
     this.Basis        = basis;
     this.Mean         = mean;
     this.Variance     = variance;
     this.Covariance   = covariance;
     this.Centred      = centred;
     this.Standardized = standardized;
     this.Rebased      = rebased;
 }
예제 #26
0
    void InputMovement()
    {
        _moveDirection = Vector3.Zero;
        Basis cameraBasis = CameraLock.Transform.basis;

        if (Input.IsActionPressed("move_right"))
        {
            _moveDirection += cameraBasis.x;
        }
        if (Input.IsActionPressed("move_left"))
        {
            _moveDirection -= cameraBasis.x;
        }
        if (Input.IsActionPressed("move_up"))
        {
            _moveDirection -= cameraBasis.z;
        }
        if (Input.IsActionPressed("move_down"))
        {
            _moveDirection += cameraBasis.z;
        }
        _moveDirection.y = 0f;
        _moveDirection   = _moveDirection.Normalized();
    }
예제 #27
0
        public static void RestrictionOfSystemOpTest()
        {
            Basis B1 = new Basis(grid, 0), B2 = new Basis(grid, 2);
            var   Map = new UnsetteledCoordinateMapping(B1, B2);

            AggregationGridBasis[][] aB = AggregationGridBasis.CreateSequence(TestProgram.MgSeq.Take(2), new Basis[] { B1, B2 });

            var Lev0 = new MultigridMapping(Map, aB[0], new int[] { B1.Degree, B2.Degree });
            var Lev1 = new MultigridMapping(Map, aB[1], new int[] { B1.Degree, B2.Degree });


            int[] I0col = Lev0.GetSubvectorIndices(new int[] { 0 });
            int[] I1col = Lev0.GetSubvectorIndices(new int[] { 1 });
            int[] I0row = Lev1.GetSubvectorIndices(new int[] { 0 });
            int[] I1row = Lev1.GetSubvectorIndices(new int[] { 1 });

            var RestMtx = Lev1.FromOtherLevelMatrix(Lev0);

            MsrMatrix Rest00 = new MsrMatrix(I0row.Length, I0col.Length, 1, 1);

            RestMtx.WriteSubMatrixTo(Rest00, I0row, default(int[]), I0col, default(int[]));
            MsrMatrix Rest01 = new MsrMatrix(I0row.Length, I1col.Length, 1, 1);

            RestMtx.WriteSubMatrixTo(Rest01, I0row, default(int[]), I1col, default(int[]));
            MsrMatrix Rest10 = new MsrMatrix(I1row.Length, I0col.Length, 1, 1);

            RestMtx.WriteSubMatrixTo(Rest10, I1row, default(int[]), I0col, default(int[]));
            MsrMatrix Rest11 = new MsrMatrix(I1row.Length, I1col.Length, 1, 1);

            RestMtx.WriteSubMatrixTo(Rest11, I1row, default(int[]), I1col, default(int[]));

            Assert.IsTrue(Rest10.InfNorm() == 0.0);
            Assert.IsTrue(Rest01.InfNorm() == 0.0);
            Assert.IsTrue(Rest00.InfNorm() != 0.0);
            Assert.IsTrue(Rest11.InfNorm() != 0.0);
        }
예제 #28
0
    void move(float delta)
    {
        // Reset the direction of the player
        Vector3 direction = Vector3.Zero;

        Basis aim = (GetNode("Head/Camera") as Spatial).GlobalTransform.basis;

        if (Input.IsActionPressed("move_forward"))
        {
            direction -= aim.z;
        }
        if (Input.IsActionPressed("move_back"))
        {
            direction += aim.z;
        }
        if (Input.IsActionPressed("move_left"))
        {
            direction -= aim.x;
        }
        if (Input.IsActionPressed("move_right"))
        {
            direction += aim.x;
        }

        direction = direction.Normalized();

        if (IsOnFloor())
        {
            has_contact = true;
        }
        else if ((GetNode("RayCast") as RayCast).IsColliding())
        {
            has_contact = false;
        }

        if (has_contact && IsOnFloor())
        {
            MoveAndCollide(Vector3.Down);
        }

        velocity.y += gravity * delta;

        Vector3 temp_velocity = velocity;

        temp_velocity.y = 0;

        float speed;

        if (Input.IsActionPressed("move_sprint"))
        {
            speed = MAX_RUNNING_SPEED;
        }
        else
        {
            speed = MAX_SPEED;
        }

        Vector3 target = direction * speed;

        float acceleration;

        if (direction.Dot(temp_velocity) > 0)
        {
            acceleration = ACCEL;
        }
        else
        {
            acceleration = DEACCEL;
        }

        temp_velocity = temp_velocity.LinearInterpolate(target, acceleration * delta);

        velocity.x = temp_velocity.x;
        velocity.z = temp_velocity.z;

        if (has_contact && Input.IsActionJustPressed("jump"))
        {
            velocity.y  = jump_height;
            has_contact = false;
        }
    }
예제 #29
0
 /// <summary>
 /// Задает полям переданные значения, но:<br/>
 /// velocity = new Vector(0.0, 0.0, 0.0)<br/>
 /// referenceSystem = carrier<br/>
 /// isAnalizing = false<br/>
 /// </summary>
 ///
 /// <param name="ID"> Идентификатор</param>
 /// <param name="vector"> Вектор относительно базовой системы координат.</param>
 /// <param name="basis"> Базис относительно базовой системы координат.</param>
 /// <param name="view"> Область видимости.</param>
 /// <param name="carrier"> Аппарат, на котором закреплено средство связи.</param>
 ///
 /// <exception cref="ArgumentNullException">
 /// Вызывается при передаче null.
 /// </exception>
 public MainSpacecraftConnector(string ID, Vector vector, Basis basis, View view, MainSpacecraft carrier) :
     base(ID, vector, basis, view)
 {
     Carrier         = carrier;
     referenceSystem = Carrier;
 }
예제 #30
0
        /// <summary>
        /// modifies a matrix <paramref name="Mtx"/> and a right-hand-side <paramref name="rhs"/>
        /// in order to fix the pressure at some reference point
        /// </summary>
        /// <param name="map">row mapping for <paramref name="Mtx"/> as well as <paramref name="rhs"/></param>
        /// <param name="iVar">the index of the pressure variable in the mapping <paramref name="map"/>.</param>
        /// <param name="LsTrk"></param>
        /// <param name="Mtx"></param>
        /// <param name="rhs"></param>
        static public void SetPressureReferencePoint <T>(UnsetteledCoordinateMapping map, int iVar, LevelSetTracker LsTrk, BlockMsrMatrix Mtx, T rhs)
            where T : IList <double>
        {
            using (new FuncTrace()) {
                var GridDat = map.GridDat;

                if (rhs.Count != map.LocalLength)
                {
                    throw new ArgumentException();
                }
                if (!Mtx.RowPartitioning.EqualsPartition(map) || !Mtx.ColPartition.EqualsPartition(map))
                {
                    throw new ArgumentException();
                }

                Basis PressureBasis = (Basis)map.BasisS[iVar];
                int   D             = GridDat.SpatialDimension;

                long GlobalID, GlobalCellIndex;
                bool IsInside, onthisProc;
                GridDat.LocatePoint(new double[D], out GlobalID, out GlobalCellIndex, out IsInside, out onthisProc, LsTrk.Regions.GetCutCellSubGrid().VolumeMask.Complement());

                int iRowGl = -111;
                if (onthisProc)
                {
                    int jCell = (int)GlobalCellIndex - GridDat.CellPartitioning.i0;


                    NodeSet CenterNode = new NodeSet(GridDat.iGeomCells.GetRefElement(jCell), new double[D]);
                    MultidimensionalArray LevSetValues = LsTrk.DataHistories[0].Current.GetLevSetValues(CenterNode, jCell, 1);;


                    MultidimensionalArray CenterNodeGlobal = MultidimensionalArray.Create(1, D);
                    GridDat.TransformLocal2Global(CenterNode, CenterNodeGlobal, jCell);
                    //Console.WriteLine("Pressure Ref Point @( {0:0.###E-00} | {1:0.###E-00} )", CenterNodeGlobal[0,0], CenterNodeGlobal[0,1]);


                    LevelSetSignCode  scode = LevelSetSignCode.ComputeLevelSetBytecode(LevSetValues[0, 0]);
                    ReducedRegionCode rrc;
                    int No   = LsTrk.Regions.GetNoOfSpecies(jCell, out rrc);
                    int iSpc = LsTrk.GetSpeciesIndex(rrc, scode);

                    iRowGl = (int)map.GlobalUniqueCoordinateIndex_FromGlobal(iVar, GlobalCellIndex, 0);
                }
                iRowGl = iRowGl.MPIMax();


                // clear row
                // ---------
                if (onthisProc)
                {
                    // ref. cell is on local MPI process
                    int jCell = (int)GlobalCellIndex - GridDat.CellPartitioning.i0;

                    ReducedRegionCode rrc;
                    int NoOfSpc = LsTrk.Regions.GetNoOfSpecies(jCell, out rrc);

                    // set matrix row to identity
                    Mtx.ClearRow(iRowGl);
                    Mtx.SetDiagonalElement(iRowGl, 1.0);


                    // clear RHS
                    int iRow = iRowGl - Mtx.RowPartitioning.i0;
                    rhs[iRow] = 0;
                }

                // clear column
                // ------------
                {
                    for (int i = Mtx.RowPartitioning.i0; i < Mtx.RowPartitioning.iE; i++)
                    {
                        if (i != iRowGl)
                        {
                            Mtx[i, iRowGl] = 0;
                        }
                    }
                }
            }
        }
예제 #31
0
        /***************************************************/
        /**** Constructors                              ****/
        /***************************************************/

        public NodeVelocity(IComparable objectId, IComparable resultCase, int modeNumber, double timeStep, Basis orientation, double ux, double uy, double uz, double rx, double ry, double rz) :
            base(objectId, resultCase, modeNumber, timeStep, orientation)
        {
            UX = ux;
            UY = uy;
            UZ = uz;
            RX = rx;
            RY = ry;
            RZ = rz;
        }
예제 #32
0
    private void Walk(float delta)
    {
        //Since IsOnFloor() doesn't properly update on concave collision shapes, count the number of bodies that _JumpArea is colliding with


        //Get the rotation of the head
        Basis aim = Head.GlobalTransform.basis;

        //Get slope of floor and if ground hit, set head velocity
        Vector3 normal;
        bool    playerFeetOverlapsFloor = PlayerFeet.Singleton.Bodies > 0;

        if (playerFeetOverlapsFloor)
        {
            normal = GroundRay.GetCollisionNormal();
        }
        else
        {
            normal = Vector3.Up;
        }

        //Calculate ground angle
        float groundAngle = Mathf.Acos(normal.Dot(Vector3.Up));

        //Determine if slipping and set initial direction
        bool slipping       = false;
        bool noWalkSlipping = false;

        if (groundAngle > MaxSlopeSlip)
        {
            slipping = true;
            if (groundAngle > MaxSlopeNoWalk)
            {
                noWalkSlipping = true;
            }
            Direction = Vector3.Up.Slide(normal);
        }
        else
        {
            Direction = Vector3.Zero;
        }

        //Get crouch
        bool crouchPressed = CrouchToggle && !CrouchJumped?Input.IsActionJustPressed("crouch") : (Input.IsActionPressed("crouch") != Crouched);

        //Determine if landing
        PlayerArms.Singleton.Land = false;
        if (IsOnFloor())
        {
            if (WasInAir)
            {
                //GD.Print("Landed");
                //Reset number of jumps
                JumpsLeft = JumpCount;

                //Play land animations
                PlayerArms.Singleton.Fall = false;
                PlayerArms.Singleton.Land = true;
                if (!slipping && ImpactVelocity >= HeadDipThreshold)
                {
                    PlayerAnimationTree.Singleton.LandBlend = Mathf.Min(1f, Mathf.Abs((ImpactVelocity - HeadDipThreshold) / (-Gravity - HeadDipThreshold)));
                    PlayerAnimationTree.Singleton.Land();
                }

                //Play Land Sounds if Velocity is significant
                PlayerFeet.Singleton.LandPlayer.Play();

                //GD.Print(ImpactVelocity);
                //Deal fall damage
                if (ImpactVelocity >= FatalFallVelocity)
                {
                    PlayerHealthManager.Singleton.Kill("A Fatal Fall");
                }
                else if (ImpactVelocity >= MajorInjuryFallVelocity)
                {
                    PlayerHealthManager.Singleton.TakeDamage("A Major Spill", 50);
                }
                else if (ImpactVelocity >= MinorInjuryFallVelocity)
                {
                    PlayerHealthManager.Singleton.TakeDamage("A Minor Spill", 10);
                }

                //Determine if player had crouch jumped
                if (CrouchJumped)
                {
                    CrouchJumped    = false;
                    WantsToUncrouch = crouchPressed;
                }

                WasInAir = false;
            }
        }
        else if (Mathf.Abs(Velocity.y) > 4f)
        {
            //GD.Print(Velocity.y);
            WasInAir = true;
            PlayerArms.Singleton.Fall = true;
            ImpactVelocity            = -Velocity.y;
        }

        //Get input and set direction
        bool userMoving = (Vinput != 0 || Hinput != 0);

        Direction += aim.z * (slipping ? -1f : 1f) * Vinput;
        Direction += aim.x * (slipping ? -1f : 1f) * Hinput;
        if (Direction.Length() > 1f)
        {
            Direction = Direction.Normalized();
        }

        Vector3 velocityNoGravity = new Vector3(Velocity.x, 0, Velocity.z);

        //Get sprint
        if (SprintToggle)
        {
            if (Input.IsActionJustPressed("sprint"))
            {
                Sprint = !Sprint;
            }
        }
        else
        {
            Sprint = (Input.IsActionPressed("sprint") != SprintToWalk);
        }

        //Get speed and acceleration dependant variables
        bool accelerate = Direction.Dot(velocityNoGravity) > 0;

        //Set target speed
        Vector3 targetVelocity;

        if (slipping)
        {
            targetVelocity = Direction * Gravity * (1f - Vector3.Up.Dot(normal));
        }
        else
        {
            targetVelocity = Direction * (Sprint ? (IsOnFloor() ? FullSpeedSprint : Mathf.Max(Velocity.Length(), FullSpeedWalk)) : FullSpeedWalk);
        }

        //Apply gravity
        Velocity.y += Gravity * delta;


        //Calculate velocity
        float acceleration   = IsOnFloor() || (IsOnWall() && noWalkSlipping) ? AccelerationWalk: AccelerationAir;
        float deacceleration = IsOnFloor() ? DeaccelerationWalk : DeaccelerationAir;

        velocityNoGravity = velocityNoGravity.LinearInterpolate(targetVelocity, (accelerate ? acceleration : deacceleration) * delta);
        Velocity.x        = velocityNoGravity.x;
        Velocity.z        = velocityNoGravity.z;

        //Set walking animation blend
        float bob1D = PlayerArms.Singleton.Walk;

        if (userMoving && IsOnFloor())
        {
            bob1D = Mathf.Min(1f, bob1D + ((Sprint ? BobIncrementSprint : BobIncrementWalk) * delta));
        }
        else
        {
            bob1D = Mathf.Max(0.01f, bob1D - ((IsOnFloor() ? BobDecrementFloor : BobDecrementAir) * delta));
        }
        if (HeadBobbing)
        {
            PlayerAnimationTree.Singleton.HeadBobBlend = bob1D;
        }
        PlayerArms.Singleton.Walk = bob1D;
        PlayerAnimationTree.Singleton.HeadBobScale = Sprint ? 1.5f : 1f;

        //Set arm swing blend
        SwingTarget = SwingTarget.LinearInterpolate(Vector2.Zero, 0.05f);
        PlayerArms.Singleton.Swing = SwingTarget;

        //Set step timer
        if (bob1D > 0.1f)
        {
            if (PlayerFeet.Singleton.StepTimer.Paused == true)
            {
                //GD.Print("Not Paused");
                PlayerFeet.Singleton.StepTimer.Paused = false;
            }
        }
        else
        {
            if (PlayerFeet.Singleton.StepTimer.Paused == false)
            {
                //GD.Print("Paused");
                PlayerFeet.Singleton.StepTimer.Paused = true;
            }
        }
        PlayerFeet.Singleton.StepTimer.WaitTime = Sprint ? 0.25f : 0.5f;

        //Get jump
        PlayerArms.Singleton.Jump = false;
        if ((BunnyHopping ? Input.IsActionPressed("jump") : Input.IsActionJustPressed("jump")) && (playerFeetOverlapsFloor) || Input.IsActionJustPressed("jump") && JumpsLeft > 0)
        {
            PlayerArms.Singleton.Jump = true;
            if (!PlayerFeet.Singleton.JumpPlayer.Playing)
            {
                PlayerFeet.Singleton.JumpPlayer.Play();
            }
            Velocity.y = 0f;
            //Velocity += normal * JumpHeight;
            //Velocity.y *= (noWalkSlipping ? 0.1f : 1f);
            if (!slipping && Direction.Dot(velocityNoGravity) < 0f)
            {
                //GD.Print("Reset Velocity");
                Velocity.x = 0f;
                Velocity.z = 0f;
            }
            Velocity += (noWalkSlipping ? normal : Vector3.Up) * JumpHeight;
            PlayerFeet.Singleton.CanBunnyHop = false;
            _SnapArea.Snap = false;

            if (!playerFeetOverlapsFloor)
            {
                //Update number of jumps
                JumpsLeft -= 1;
            }
        }

        if (crouchPressed || (Crouched && WantsToUncrouch))
        {
            if (IsOnFloor())
            {
                //Check if uncrouch is possible
                if ((Crouched && StandArea.GetOverlappingBodies().Count == 0) || (!Crouched))
                {
                    //Invert crouch (animation, collision, etc. handled in get set)
                    Crouched        = !Crouched;
                    WantsToUncrouch = false;
                }
                else if (crouchPressed)
                {
                    //Invert WantToUncrouch. Player will uncrouch at latest opportunity.
                    WantsToUncrouch = !WantsToUncrouch;
                }
            }
            else if (CanCrouchJump && !Crouched && !CrouchJumped)
            {
                CrouchJumped = true;
                Crouched     = true;
                PlayerAnimationTree.Singleton.StateMachineCrouch.Start("CrouchJump");
                Translate(Vector3.Up * 1.1f);
                //GD.Print("Crouch jump.");
            }
        }

        //Get Climb
        if (Input.IsActionPressed("climb"))
        {
            WantsToClimb = true;
            ClimbTimer.Start(ClimbTimeout);
        }

        //Calculate ledge point
        Vector3 closestLedgePoint = Vector3.Inf;
        bool    canClimb          = false;
        bool    withCrouch        = false;

        ClimbLabel.Visible = false;
        if (!Crouched)
        {
            foreach (RayCast LedgeRay in LedgeRays)
            {
                if (LedgeRay.IsColliding())
                {
                    if (LedgeRay.GetCollisionPoint().DistanceTo(Translation) < closestLedgePoint.DistanceTo(Translation))
                    {
                        closestLedgePoint = LedgeRay.GetCollisionPoint();
                        canClimb          = true;
                    }
                }
            }
            closestLedgePoint = closestLedgePoint + (Vector3.Up * (StandHeight + 0.075f));

            if (canClimb)
            {
                //Disable all other colliders
                bool[] shapeDisabledState = new bool[OtherCollision.Count];
                for (int i = 0; i < OtherCollision.Count; ++i)
                {
                    //GD.Print("Disabling collision ", OtherCollision[i].Name);
                    shapeDisabledState[i]      = OtherCollision[i].Disabled;
                    OtherCollision[i].Disabled = true;
                }

                //Test to see if player has space to climb
                canClimb = !TestMove(new Transform(Quat.Identity, closestLedgePoint), Vector3.Zero);
                if (!canClimb)
                {
                    _CollisionStand.Disabled  = true;
                    _CollisionCrouch.Disabled = false;
                    canClimb   = !TestMove(new Transform(Quat.Identity, closestLedgePoint), Vector3.Zero);
                    withCrouch = canClimb;
                    _CollisionStand.Disabled  = false;
                    _CollisionCrouch.Disabled = true;
                }

                //Reset colliders
                for (int i = 0; i < OtherCollision.Count; ++i)
                {
                    //GD.Print("Reseting other collision", OtherCollision[i], " ", shapeDisabledState[i]);
                    OtherCollision[i].Disabled = shapeDisabledState[i];
                }
            }

            ClimbLabel.Visible = canClimb;
            if (canClimb && WantsToClimb)
            {
                if (withCrouch)
                {
                    Crouched = true;
                }

                //Set climb point and enter climb state
                ClimbPoint    = closestLedgePoint;
                ClimbStep     = (ClimbPoint - Translation).Normalized() * ClimbSpeed;
                ClimbDistance = (ClimbPoint - Translation).Length();
                PlayerAnimationTree.Singleton.Climb();
                PlayerAnimationTree.Singleton.HeadBobScale = 0f;
                Climbing = true;

                //Reset ImpactVelocity and zero y Velocity to avoid confusing animations
                ImpactVelocity = Velocity.y = 0f;
            }
        }

        //Move Player and calculate distance
        Vector3 o  = Translation;
        Vector3 vo = velocityNoGravity;

        if (userMoving || slipping)
        {
            Velocity = MoveAndSlideWithSnap(Velocity, _SnapArea.Snap ? Vector3.Down : Vector3.Zero, Vector3.Up, true, 4, MaxSlopeNoWalk);
        }
        else
        {
            //Velocity = MoveAndSlideWithSnap(Velocity, _SnapArea.Snap ? Vector3.Down : Vector3.Zero, Vector3.Up, true, 4, MaxSlopeNoWalk);
            Velocity = MoveAndSlide(Velocity, Vector3.Up, true, 4, MaxSlopeNoWalk);
            if (GetSlideCount() > 0)
            {
                KinematicCollision slide = GetSlideCollision(0);
                if (Vector3.Up.AngleTo(slide.Normal) < MaxSlopeSlip)
                {
                    //Player is sliding on a slope they shouldn't be sliding on.
                    Velocity = vo;
                }
            }
        }
        Vector3 d        = Translation;
        Vector3 distance = (d - o);

        //Calculate Acceleration and force
        MovementVelocity     = distance / delta;
        MovementAcceleration = 2f * distance / Mathf.Pow(delta, 2f);
        MovementForce        = Mass * MovementAcceleration;
    }
예제 #33
0
        public AggregationGridBasis(Basis b, AggregationGrid ag)
        {
            using (new FuncTrace()) {
                if (!object.ReferenceEquals(b.GridDat, GetGridData(ag)))
                {
                    throw new ArgumentException("mismatch in grid data object.");
                }
                this.DGBasis = b;
                this.AggGrid = ag;
                int N = b.Length;

                int JAGG = ag.iLogicalCells.NoOfLocalUpdatedCells;
                CompositeBasis = new MultidimensionalArray[JAGG];

                for (int jAgg = 0; jAgg < JAGG; jAgg++)   // loop over agglomerated cells...
                {
                    var compCell = ag.iLogicalCells.AggregateCellToParts[jAgg];


                    if (compCell.Length == 1)
                    {
                        CompositeBasis[jAgg] = MultidimensionalArray.Create(1, N, N);
                        for (int n = 0; n < N; n++)
                        {
                            CompositeBasis[jAgg][0, n, n] = 1.0;
                        }
                    }
                    else
                    {
                        // compute extrapolation basis
                        // ===========================

                        int I = compCell.Length - 1;
                        int[,] CellPairs = new int[I, 2];

                        for (int i = 0; i < I; i++)
                        {
                            CellPairs[i, 0] = compCell[0];
                            CellPairs[i, 1] = compCell[i + 1];
                        }
                        var ExpolMtx = MultidimensionalArray.Create(I + 1, N, N);
                        b.GetExtrapolationMatrices(CellPairs, ExpolMtx.ExtractSubArrayShallow(new int[] { 1, 0, 0 }, new int[] { I, N - 1, N - 1 }));
                        for (int n = 0; n < N; n++)
                        {
                            ExpolMtx[0, n, n] = 1.0;
                        }

                        // compute mass matrix
                        // ===================

                        var MassMatrix = MultidimensionalArray.Create(N, N);
                        MassMatrix.Multiply(1.0, ExpolMtx, ExpolMtx, 0.0, "lm", "kim", "kil");


                        // change to orthonormal basis
                        // ===========================
                        MultidimensionalArray B = MultidimensionalArray.Create(N, N);
                        MassMatrix.SymmetricLDLInversion(B, default(double[]));


                        CompositeBasis[jAgg] = MultidimensionalArray.Create(ExpolMtx.Lengths);
                        CompositeBasis[jAgg].Multiply(1.0, ExpolMtx, B, 0.0, "imn", "imk", "kn");

                        // check
                        // =====
#if DEBUG
                        MassMatrix.Clear();
                        for (int k = 0; k <= I; k++)
                        {
                            for (int l = 0; l < N; l++)     // over rows of mass matrix ...
                            {
                                for (int m = 0; m < N; m++) // over columns of mass matrix ...

                                {
                                    double mass_lm = 0.0;

                                    for (int i = 0; i < N; i++)
                                    {
                                        mass_lm += CompositeBasis[jAgg][k, i, m] * CompositeBasis[jAgg][k, i, l];
                                    }

                                    MassMatrix[l, m] += mass_lm;
                                }
                            }
                        }

                        MassMatrix.AccEye(-1.0);
                        Debug.Assert(MassMatrix.InfNorm() < 1.0e-9);
#endif
                    }
                }
            }
        }