public GUIAnimator(GFXContainer gfx, LevelSet lvl, TimingSource.Sources timingSrc, MetroProgressBar pgJumpRes) { this.Gfx = gfx; this.Lvl = lvl; this.pgJumpRes = pgJumpRes; IsActive = true; SetTimingSource(timingSrc); }
public Texture2D[] GetIconsFrom(LevelSet levelSet) { // This loops through each icon in the level and add the icon for that // item to an array of Texture2Ds. Texture2D[] icons = new Texture2D[levelSet.items.Length]; for (int i = 0; i < icons.Length; i++) { icons[i] = GetIconOf(levelSet.items[i].prefab.transform); } return icons; }
void ParameterUpdate(IEnumerable <DGField> CurrentState, IEnumerable <DGField> ParameterVar, int CutCellQuadOrder, Dictionary <SpeciesId, MultidimensionalArray> AgglomeratedCellLengthScales) { LevelSet Phi = (LevelSet)(this.LsTrk.LevelSets[0]); SpeciesId[] SpcToCompute = AgglomeratedCellLengthScales.Keys.ToArray(); DGField[] U0; if (CurrentState != null) { U0 = CurrentState.Take(D).ToArray(); } else { U0 = null; } DGField[] Stress0; Stress0 = CurrentState.Skip(D + 1).Take(3).ToArray(); if (U0.Count() != D) { throw new ArgumentException("Spatial dimesion and number of velocity parameter components does not match!"); } if (Stress0.Count() != D + 1) { throw new ArgumentException("Spatial dimesion and number of stress parameter components does not match!"); } // linearization velocity: DGField[] U0_U0mean; if (this.U0meanrequired) { XDGBasis U0meanBasis = new XDGBasis(this.LsTrk, 0); VectorField <XDGField> U0mean = new VectorField <XDGField>(D, U0meanBasis, "U0mean_", XDGField.Factory); U0_U0mean = ArrayTools.Cat <DGField>(U0, U0mean); U0mean.Clear(); ComputeAverageU(U0, U0mean, CutCellQuadOrder, LsTrk.GetXDGSpaceMetrics(SpcToCompute, CutCellQuadOrder, 1).XQuadSchemeHelper); } else { U0_U0mean = new DGField[2 * D]; } //if (this.Control.SetParamsAnalyticalSol == false) { //SinglePhaseField[] __VelocityXGradient = ParameterVar.Skip(2 * D).Take(D).Select(f => f as SinglePhaseField).ToArray(); //SinglePhaseField[] __VelocityYGradient = ParameterVar.Skip(3 * D).Take(D).Select(f => f as SinglePhaseField).ToArray(); //Debug.Assert(ArrayTools.AreEqual(__VelocityXGradient, VelocityXGradient.ToArray(), (fa, fb) => object.ReferenceEquals(fa, fb))); //Debug.Assert(ArrayTools.AreEqual(__VelocityYGradient, VelocityYGradient.ToArray(), (fa, fb) => object.ReferenceEquals(fa, fb))); //if (VelocityXGradient == null) { // VelocityXGradient = new VectorField<XDGField>(D, CurrentState.ElementAt(0).Basis, "VelocityX_Gradient", XDGField.Factory); //} VelocityXGradient.Clear(); VelocityXGradient.GradientByFlux(1.0, U0[0]); //if (VelocityYGradient == null) { // VelocityYGradient = new VectorField<XDGField>(D, CurrentState.ElementAt(1).Basis, "VelocityY_Gradient", XDGField.Factory); //} VelocityYGradient.Clear(); VelocityYGradient.GradientByFlux(1.0, U0[1]); //} if (this.useArtificialDiffusion == true) { throw new NotImplementedException("artificial diffusion not jet fully implemented..."); //SinglePhaseField __ArtificialViscosity = ParameterVar.Skip(5 * D + 1).Take(1).Select(f => f as SinglePhaseField).ToArray()[0]; //if (!object.ReferenceEquals(this.artificalViscosity, __ArtificialViscosity)) // throw new ApplicationException(); //ArtificialViscosity.ProjectArtificalViscosityToDGField(__ArtificialViscosity, perssonsensor, this.Control.SensorLimit, artificialMaxViscosity); } }
public static void ParseGameData(string str, bool isLevelEditor = false) { JsonData jsonData = null; jsonData = JsonMapper.ToObject(Resources.Load <TextAsset>("gamedata" + PlayerPrefsManager.GetLang().ToLower() + FugoUtils.getGameIndex()).text); JsonData data = jsonData["Sections"]; sections = new List <Section>(); ParseData(data, sections); string empty = string.Empty; if (empty != string.Empty) { List <Section> list = new List <Section>(); try { JsonData jsonData2 = JsonMapper.ToObject(Resources.Load <TextAsset>("gamedata" + PlayerPrefsManager.GetLang().ToLower() + "ab" + empty).text); ParseData(jsonData2["Sections"], list); for (int i = 0; i < list.Count; i++) { for (int j = 0; j < list[i].sets.Count; j++) { for (int k = 0; k < list[i].sets[j].levels.Count; k++) { sections[i].sets[j].levels[k] = list[i].sets[j].levels[k]; } } } } catch { UnityEngine.Debug.Log("there is no ab levels"); } } JsonData jsonData3 = jsonData["DailyLevels"]; dailyPuzzles = new Section(); for (int l = 0; l < jsonData3.Count; l++) { LevelSet levelSet = new LevelSet(jsonData3[l]["SetID"].ToString(), jsonData3[l]["SectionID"].ToString(), jsonData3[l]["SetName"].ToString(), jsonData3[l]["SetFullName"].ToString(), jsonData3[l]["SetColor"].ToString(), jsonData3[l]["TitleColor"].ToString(), jsonData3[l]["RibbonColor"].ToString(), jsonData3[l]["CompletedLevelBGColor"].ToString(), jsonData3[l]["CompletedLevelLetterColor"].ToString(), jsonData3[l]["CompletedLevelNumberColor"].ToString(), jsonData3[l]["NotCompletedLevelBGColor"].ToString(), jsonData3[l]["NotCompletedLevelLetterColor"].ToString(), jsonData3[l]["NotCompletedLevelNumberColor"].ToString(), jsonData3[l]["SelectedLevelBGColor"].ToString(), jsonData3[l]["SelectedLevelLetterColor"].ToString(), jsonData3[l]["SelectedLevelNumberColor"].ToString(), jsonData3[l]["InGameLetterColor"].ToString(), jsonData3[l]["InGameCircleColor"].ToString(), jsonData3[l]["InGameSelectedLetterColor"].ToString(), jsonData3[l]["InGameSelectedLetterBGColor"].ToString(), jsonData3[l]["InGameHeaderColor"].ToString(), jsonData3[l]["InGameHintColor"].ToString(), jsonData3[l]["InGameRibbonColor"].ToString(), jsonData3[l]["InGameTileColor"].ToString(), jsonData3[l]["BackgroundImage"].ToString(), int.Parse(jsonData3[l]["XCoordinate"].ToString()), int.Parse(jsonData3[l]["YCoordinate"].ToString()), jsonData3[l]["TopText"].ToString(), jsonData3[l]["BottomText"].ToString()); JsonData jsonData4 = jsonData3[l]["Levels"]; for (int m = 0; m < jsonData4.Count; m++) { Level level = new Level(); level.letters = jsonData4[m]["Letters"].ToString(); level.id = jsonData4[m]["LevelID"].ToString(); level.height = int.Parse(jsonData4[m]["Row"].ToString()); level.width = int.Parse(jsonData4[m]["Column"].ToString()); try { level.otherWords = jsonData4[m]["OtherWords"].ToString().Split(','); } catch (Exception) { } string[] array = jsonData4[m]["Words"].ToString().Split('|'); string[] array2 = array; foreach (string text in array2) { string[] array3 = text.Split(','); Word word = new Word(); word.Y = int.Parse(array3[0]); word.X = int.Parse(array3[1]); word.word = array3[2]; word.length = word.word.Length; word.positions = new Vector3[word.length]; word.letters = new GameObject[word.length]; if (array3[3] == "H" || array3[3] == "BH") { word.orientation = Orientation.HORIZONTAL; if (array3[3] == "BH") { word.bonus = true; } } else if (array3[3] == "V" || array3[3] == "BV") { word.orientation = Orientation.VERTICAL; if (array3[3] == "BV") { word.bonus = true; } } level.words.Add(word); } levelSet.levels.Add(level); } dailyPuzzles.sets.Add(levelSet); } Resources.UnloadUnusedAssets(); }
/// <summary> /// /// </summary> public void AssembleMatrix_Timestepper <T>( int CutCellQuadOrder, BlockMsrMatrix OpMatrix, double[] OpAffine, Dictionary <SpeciesId, MultidimensionalArray> AgglomeratedCellLengthScales, IEnumerable <T> U0, VectorField <SinglePhaseField> SurfaceForce, VectorField <SinglePhaseField> LevelSetGradient, SinglePhaseField ExternalyProvidedCurvature, UnsetteledCoordinateMapping RowMapping, UnsetteledCoordinateMapping ColMapping, double time) where T : DGField { if (ColMapping.BasisS.Count != this.Op.DomainVar.Count) { throw new ArgumentException(); } if (RowMapping.BasisS.Count != this.Op.CodomainVar.Count) { throw new ArgumentException(); } // check: var Tracker = this.LsTrk; int D = Tracker.GridDat.SpatialDimension; if (U0 != null && U0.Count() != D) { throw new ArgumentException(); } LevelSet Phi = (LevelSet)(Tracker.LevelSets[0]); SpeciesId[] SpcToCompute = AgglomeratedCellLengthScales.Keys.ToArray(); // parameter assembly // ================== // normals: SinglePhaseField[] Normals; // Normal vectors: length not normalized - will be normalized at each quad node within the flux functions. if (this.NormalsRequired) { if (LevelSetGradient == null) { LevelSetGradient = new VectorField <SinglePhaseField>(D, Phi.Basis, SinglePhaseField.Factory); LevelSetGradient.Gradient(1.0, Phi); } Normals = LevelSetGradient.ToArray(); } else { Normals = new SinglePhaseField[D]; } // curvature: SinglePhaseField Curvature; if (this.CurvatureRequired) { Curvature = ExternalyProvidedCurvature; } else { Curvature = null; } // linearization velocity: DGField[] U0_U0mean; if (this.U0meanrequired) { XDGBasis U0meanBasis = new XDGBasis(Tracker, 0); VectorField <XDGField> U0mean = new VectorField <XDGField>(D, U0meanBasis, "U0mean_", XDGField.Factory); U0_U0mean = ArrayTools.Cat <DGField>(U0, U0mean); } else { U0_U0mean = new DGField[2 * D]; } // concatenate everything var Params = ArrayTools.Cat <DGField>( U0_U0mean, Curvature, ((SurfaceForce != null) ? SurfaceForce.ToArray() : new SinglePhaseField[D]), Normals); // linearization velocity: if (this.U0meanrequired) { VectorField <XDGField> U0mean = new VectorField <XDGField>(U0_U0mean.Skip(D).Take(D).Select(f => ((XDGField)f)).ToArray()); U0mean.Clear(); if (this.physParams.IncludeConvection) { ComputeAverageU(U0, U0mean, CutCellQuadOrder, LsTrk.GetXDGSpaceMetrics(SpcToCompute, CutCellQuadOrder, 1).XQuadSchemeHelper); } } // assemble the matrix & affine vector // =================================== // compute matrix Op.ComputeMatrixEx(Tracker, ColMapping, Params, RowMapping, OpMatrix, OpAffine, false, time, true, AgglomeratedCellLengthScales, SpcToCompute); }
static void Main(string[] args) { Log.LogToConsole = true; DateTime start = DateTime.Now; Sorter sorter = new Sorter(); // Parse options. int i = 0; while (i < args.Length) { string arg = args[i]; i++; string stringValue = i < args.Length ? args[i] : ""; int intValue = AsInteger(stringValue); bool boolValue = intValue != 0; if (arg == "--output-file") { sorter.OutputFile = stringValue; i++; continue; } if (arg == "--design-string") { try { sorter.Design = new Level(stringValue); } catch (Exception ex) { Console.WriteLine("Exception parsing design: {0}", ex.Message); Environment.Exit(1); } i++; continue; } if (arg == "--design-file") { try { LevelSet levelSet = new LevelSet(stringValue); sorter.Design = levelSet[0]; } catch (Exception ex) { Console.WriteLine("Exception loading design file: {0}", ex.Message); Environment.Exit(1); } i++; continue; } if (arg == "--nodes") { sorter.Nodes = intValue; i++; continue; } if (arg == "--verbose") { sorter.Verbose = intValue; i++; continue; } if (arg == "--reject-sokoban-on-target") { sorter.RejectSokobanOnTarget = boolValue; i++; continue; } if (arg == "--reject-dead-ends") { sorter.RejectDeadEnds = boolValue; i++; continue; } if (arg == "--reject-captured-targets") { sorter.RejectCapturedTargets = boolValue; i++; continue; } if (arg == "--move-limit") { sorter.MoveLimit = intValue; i++; continue; } if (arg == "--push-limit") { sorter.PushLimit = intValue; i++; continue; } if (arg == "--change-limit") { sorter.ChangeLimit = intValue; i++; continue; } if (arg == "--box-move-limit") { sorter.BoxMoveLimit = intValue; i++; continue; } if (arg == "--check-first-level-only") { sorter.CheckFirstLevelOnly = boolValue; i++; continue; } if (arg == "--parse-statistics") { sorter.ParseStatistics = boolValue; i++; continue; } if (arg == "--normalize-levels") { sorter.NormalizeLevels = boolValue; i++; continue; } if (arg == "--validate-normalization") { sorter.ValidateNormalization = boolValue; i++; continue; } if (arg[0] == '-') { Console.WriteLine("unsupported argument: {0}", arg); Environment.Exit(1); } i--; break; } while (i < args.Length) { string arg = args[i++]; List<string> fileList = new List<string>(); try { string dir = Path.GetDirectoryName(arg); if (String.IsNullOrEmpty(dir)) { dir = Directory.GetCurrentDirectory(); } fileList.AddRange(Directory.GetFiles(Path.GetFullPath(dir), Path.GetFileName(arg))); } catch (Exception ex) { Console.WriteLine("Exception globbing {0}: {1}", arg, ex.Message); Environment.Exit(1); } foreach (string file in fileList) { sorter.AddLevelSet(file); } } sorter.Sort(); DateTime finish = DateTime.Now; Console.WriteLine(String.Format("Sort took {0} seconds.", finish - start)); }
/// <summary> /// Determines the line segments bounding the selected reference /// element (cf. <see cref="RefElement"/>) in reference coordinates /// </summary> /// <returns></returns> private LineSegment[] GetReferenceLineSegments() { Stack <RefElement> simplexHierarchy = new Stack <RefElement>(); RefElement currentSimplex = RefElement; int spatialDimension = RefElement.SpatialDimension; int n = 0; while (currentSimplex.GetType() != lineSimplex.GetType()) { // If n > 2, the edge of the edge of a simplex is not a line. // This is hardly likely in 2d/3d. if (n > 2) { throw new ApplicationException("Something went terribly wrong."); } simplexHierarchy.Push(currentSimplex); currentSimplex = currentSimplex.FaceRefElement; n++; } MultidimensionalArray vertexCoordinates = MultidimensionalArray.Create(2, 1); vertexCoordinates[0, 0] = -1.0; vertexCoordinates[1, 0] = 1.0; while (simplexHierarchy.Count > 0) { currentSimplex = simplexHierarchy.Pop(); int noOfVertices = vertexCoordinates.GetLength(0); int D = currentSimplex.SpatialDimension; MultidimensionalArray volumeCoordinates = MultidimensionalArray.Create( noOfVertices * currentSimplex.NoOfFaces, currentSimplex.SpatialDimension); for (int e = 0; e < currentSimplex.NoOfFaces; e++) { MultidimensionalArray coordinates = MultidimensionalArray.Create(noOfVertices, D); currentSimplex.TransformFaceCoordinates(e, vertexCoordinates, coordinates); for (int i = 0; i < noOfVertices; i++) { for (int d = 0; d < D; d++) { volumeCoordinates[e * noOfVertices + i, d] = coordinates[i, d]; } } } vertexCoordinates = volumeCoordinates; } Debug.Assert( vertexCoordinates.GetLength(0) % 2 == 0, "Even number of vertices expected"); int initialNumberOfLineSegments = vertexCoordinates.GetLength(0) / 2; List <LineSegment> lineSegments = new List <LineSegment>(initialNumberOfLineSegments); for (int i = 0; i < initialNumberOfLineSegments; i++) { var p0 = vertexCoordinates.GetRow(2 * i + 0); int iP0 = this.RefElement.Vertices.FindRow(p0, 1.0e-8); var p1 = vertexCoordinates.GetRow(2 * i + 1); int iP1 = this.RefElement.Vertices.FindRow(p1, 1.0e-8); LineSegment newSegment = new LineSegment(spatialDimension, this.RefElement, p0, p1, iP0, iP1, RootFindingAlgorithm); if (!lineSegments.Contains(newSegment)) { lineSegments.Add(newSegment); //tracker.Subscribe(newSegment); } } foreach (LineSegment segment in lineSegments) { LevelSet levelSetField = levelSetData.LevelSet as LevelSet; if (levelSetField != null) { segment.ProjectBasisPolynomials(levelSetField.Basis); } } return(lineSegments.ToArray()); }
/// <summary> /// /// </summary> public void AssembleMatrix <T>(BlockMsrMatrix OpMatrix, double[] OpAffine, UnsetteledCoordinateMapping RowMapping, UnsetteledCoordinateMapping ColMapping, IEnumerable <T> CurrentState, Dictionary <SpeciesId, MultidimensionalArray> AgglomeratedCellLengthScales, double time, int CutCellQuadOrder, VectorField <SinglePhaseField> SurfaceForce, VectorField <SinglePhaseField> LevelSetGradient, SinglePhaseField ExternalyProvidedCurvature, bool[] updateSolutionParams = null, DGField[] ExtParams = null) where T : DGField { //IEnumerable<T> CoupledCurrentState = null, IEnumerable<T> CoupledParams = null) where T : DGField { // checks: if (ColMapping.BasisS.Count != this.m_XOp.DomainVar.Count) { throw new ArgumentException(); } if (RowMapping.BasisS.Count != this.m_XOp.CodomainVar.Count) { throw new ArgumentException(); } int D = this.LsTrk.GridDat.SpatialDimension; if (CurrentState != null && !config.solveEnergy && !config.solveHeat && CurrentState.Count() != (D + 1)) { throw new ArgumentException(); } if (OpMatrix == null && CurrentState == null) { throw new ArgumentException(); } DGField[] U0; if (CurrentState != null) { U0 = CurrentState.Take(D).ToArray(); } else { U0 = null; } // parameter assembly // ================== #region param assembly LevelSet Phi = (LevelSet)(this.LsTrk.LevelSets[0]); SpeciesId[] SpcToCompute = AgglomeratedCellLengthScales.Keys.ToArray(); // linearization velocity: DGField[] U0_U0mean; if (this.U0meanrequired) { XDGBasis U0meanBasis = new XDGBasis(this.LsTrk, 0); VectorField <XDGField> U0mean = new VectorField <XDGField>(D, U0meanBasis, "U0mean_", XDGField.Factory); U0mean.Clear(); if (this.physParams.IncludeConvection) { ComputeAverageU(U0, U0mean, CutCellQuadOrder, LsTrk.GetXDGSpaceMetrics(SpcToCompute, CutCellQuadOrder, 1).XQuadSchemeHelper); } U0_U0mean = ArrayTools.Cat <DGField>(U0, U0mean); } else { U0_U0mean = new DGField[2 * D]; } // linearization velocity: //if (this.U0meanrequired) { // VectorField<XDGField> U0mean = new VectorField<XDGField>(U0_U0mean.Skip(D).Take(D).Select(f => ((XDGField)f)).ToArray()); // U0mean.Clear(); // if (this.physParams.IncludeConvection) // ComputeAverageU(U0, U0mean, CutCellQuadOrder, LsTrk.GetXDGSpaceMetrics(SpcToCompute, CutCellQuadOrder, 1).XQuadSchemeHelper); //} // normals: SinglePhaseField[] Normals; // Normal vectors: length not normalized - will be normalized at each quad node within the flux functions. if (this.NormalsRequired) { if (LevelSetGradient == null) { LevelSetGradient = new VectorField <SinglePhaseField>(D, Phi.Basis, SinglePhaseField.Factory); LevelSetGradient.Gradient(1.0, Phi); } Normals = LevelSetGradient.ToArray(); } else { Normals = new SinglePhaseField[D]; } // curvature: SinglePhaseField Curvature; if (this.CurvatureRequired) { Curvature = ExternalyProvidedCurvature; } else { Curvature = null; } // velocity gradient vectors var VelMap = new CoordinateMapping(U0); DGField[] VelParam = VelMap.Fields.ToArray(); VectorField <DGField> GradVelX = new VectorField <DGField>(D, VelParam[0].Basis, "VelocityXGradient", XDGField.Factory); for (int d = 0; d < D; d++) { foreach (var Spc in this.LsTrk.SpeciesIdS) { DGField f_Spc = ((VelParam[0] as XDGField).GetSpeciesShadowField(Spc)); SubGrid sf = this.LsTrk.Regions.GetSpeciesSubGrid(Spc); (GradVelX[d] as XDGField).GetSpeciesShadowField(Spc).DerivativeByFlux(1.0, f_Spc, d, optionalSubGrid: sf); } } GradVelX.ForEach(F => F.CheckForNanOrInf(true, true, true)); VectorField <DGField> GradVelY = new VectorField <DGField>(D, VelParam[0].Basis, "VelocityYGradient", XDGField.Factory); for (int d = 0; d < D; d++) { foreach (var Spc in this.LsTrk.SpeciesIdS) { DGField f_Spc = ((VelParam[1] as XDGField).GetSpeciesShadowField(Spc)); SubGrid sf = this.LsTrk.Regions.GetSpeciesSubGrid(Spc); (GradVelY[d] as XDGField).GetSpeciesShadowField(Spc).DerivativeByFlux(1.0, f_Spc, d, optionalSubGrid: sf); } } GradVelY.ForEach(F => F.CheckForNanOrInf(true, true, true)); VectorField <DGField> GradVelXGradX = new VectorField <DGField>(D, VelParam[0].Basis, "VelocityXGradX_Gradient", XDGField.Factory); for (int d = 0; d < D; d++) { foreach (var Spc in this.LsTrk.SpeciesIdS) { DGField f_Spc = ((GradVelX[0] as XDGField).GetSpeciesShadowField(Spc)); SubGrid sf = this.LsTrk.Regions.GetSpeciesSubGrid(Spc); (GradVelXGradX[d] as XDGField).GetSpeciesShadowField(Spc).DerivativeByFlux(1.0, f_Spc, d, optionalSubGrid: sf); } } GradVelXGradX.ForEach(F => F.CheckForNanOrInf(true, true, true)); VectorField <DGField> GradVelXGradY = new VectorField <DGField>(D, VelParam[0].Basis, "VelocityXGradY_Gradient", XDGField.Factory); for (int d = 0; d < D; d++) { foreach (var Spc in this.LsTrk.SpeciesIdS) { DGField f_Spc = ((GradVelX[1] as XDGField).GetSpeciesShadowField(Spc)); SubGrid sf = this.LsTrk.Regions.GetSpeciesSubGrid(Spc); (GradVelXGradY[d] as XDGField).GetSpeciesShadowField(Spc).DerivativeByFlux(1.0, f_Spc, d, optionalSubGrid: sf); } } GradVelXGradY.ForEach(F => F.CheckForNanOrInf(true, true, true)); VectorField <DGField> GradVelYGradX = new VectorField <DGField>(D, VelParam[0].Basis, "VelocityYGradX_Gradient", XDGField.Factory); for (int d = 0; d < D; d++) { foreach (var Spc in this.LsTrk.SpeciesIdS) { DGField f_Spc = ((GradVelY[0] as XDGField).GetSpeciesShadowField(Spc)); SubGrid sf = this.LsTrk.Regions.GetSpeciesSubGrid(Spc); (GradVelYGradX[d] as XDGField).GetSpeciesShadowField(Spc).DerivativeByFlux(1.0, f_Spc, d, optionalSubGrid: sf); } } GradVelYGradX.ForEach(F => F.CheckForNanOrInf(true, true, true)); VectorField <DGField> GradVelYGradY = new VectorField <DGField>(D, VelParam[0].Basis, "VelocityYGradY_Gradient", XDGField.Factory); for (int d = 0; d < D; d++) { foreach (var Spc in this.LsTrk.SpeciesIdS) { DGField f_Spc = ((GradVelY[1] as XDGField).GetSpeciesShadowField(Spc)); SubGrid sf = this.LsTrk.Regions.GetSpeciesSubGrid(Spc); (GradVelYGradY[d] as XDGField).GetSpeciesShadowField(Spc).DerivativeByFlux(1.0, f_Spc, d, optionalSubGrid: sf); } } GradVelYGradY.ForEach(F => F.CheckForNanOrInf(true, true, true)); // pressure and gradient var PressMap = new CoordinateMapping(CurrentState.ToArray()[D]); DGField[] PressParam = PressMap.Fields.ToArray(); VectorField <DGField> PressGrad = new VectorField <DGField>(D, PressParam[0].Basis, "PressureGrad", XDGField.Factory); for (int d = 0; d < D; d++) { foreach (var Spc in this.LsTrk.SpeciesIdS) { DGField f_Spc = ((PressParam[0] as XDGField).GetSpeciesShadowField(Spc)); SubGrid sf = this.LsTrk.Regions.GetSpeciesSubGrid(Spc); (PressGrad[d] as XDGField).GetSpeciesShadowField(Spc).DerivativeByFlux(1.0, f_Spc, d, optionalSubGrid: sf); } } PressGrad.ForEach(F => F.CheckForNanOrInf(true, true, true)); // gravity var GravMap = new CoordinateMapping(ExtParams); DGField[] GravParam = GravMap.Fields.ToArray(); // heat flux for evaporation DGField[] HeatFluxParam = new DGField[D]; if (config.solveHeat) { if (config.conductMode == ConductivityInSpeciesBulk.ConductivityMode.SIP && updateSolutionParams[D + 1]) { HeatFluxParam = new VectorField <XDGField>(D, CurrentState.ToArray()[D + 1].Basis, "HeatFlux0_", XDGField.Factory).ToArray(); Dictionary <string, double> kSpc = new Dictionary <string, double>(); kSpc.Add("A", -thermParams.k_A); kSpc.Add("B", -thermParams.k_B); XNSEUtils.ComputeGradientForParam(CurrentState.ToArray()[D + 1], HeatFluxParam, this.LsTrk, kSpc, this.LsTrk.Regions.GetCutCellSubGrid()); } else if (config.conductMode != ConductivityInSpeciesBulk.ConductivityMode.SIP && updateSolutionParams[D + 2]) { var HeatFluxMap = new CoordinateMapping(CurrentState.ToArray().GetSubVector(D + 2, D)); HeatFluxParam = HeatFluxMap.Fields.ToArray(); } else { HeatFluxParam = storedParams.GetSubVector(2 * D + 4, D); } } if (ExtParams != null) { HeatFluxParam = ExtParams; } #endregion // concatenate everything var Params = ArrayTools.Cat <DGField>( U0_U0mean, Normals, Curvature, ((SurfaceForce != null) ? SurfaceForce.ToArray() : new SinglePhaseField[D])); if (config.solveEnergy) { Params = ArrayTools.Cat <DGField>(Params.ToArray <DGField>(), GradVelX, GradVelY, GradVelXGradX, GradVelXGradY, GradVelYGradX, GradVelYGradY, PressParam, PressGrad, GravMap); } if (config.solveHeat) { Params = ArrayTools.Cat <DGField>(Params.ToArray <DGField>(), CurrentState.ToArray <DGField>().GetSubVector(D + 1, 1), HeatFluxParam, new SinglePhaseField[1]); } // store old params for (int p = 0; p < Params.Length; p++) { if (Params[p] != null) { storedParams[p] = Params[p].CloneAs(); } } // advanced settings for the navier slip boundary condition // ======================================================== CellMask SlipArea; switch (this.dntParams.GNBC_Localization) { case NavierSlip_Localization.Bulk: { SlipArea = this.LsTrk.GridDat.BoundaryCells.VolumeMask; break; } case NavierSlip_Localization.ContactLine: { SlipArea = null; break; } case NavierSlip_Localization.Nearband: { SlipArea = this.LsTrk.GridDat.BoundaryCells.VolumeMask.Intersect(this.LsTrk.Regions.GetNearFieldMask(this.LsTrk.NearRegionWidth)); break; } case NavierSlip_Localization.Prescribed: { throw new NotImplementedException(); } default: throw new ArgumentException(); } MultidimensionalArray SlipLengths; SlipLengths = this.LsTrk.GridDat.Cells.h_min.CloneAs(); SlipLengths.Clear(); //SlipLengths.AccConstant(-1.0); if (SlipArea != null) { foreach (Chunk cnk in SlipArea) { for (int i = cnk.i0; i < cnk.JE; i++) { switch (this.dntParams.GNBC_SlipLength) { case NavierSlip_SlipLength.hmin_DG: { int degU = ColMapping.BasisS.ToArray()[0].Degree; SlipLengths[i] = this.LsTrk.GridDat.Cells.h_min[i] / (degU + 1); break; } case NavierSlip_SlipLength.hmin_Grid: { SlipLengths[i] = SlipLengths[i] = this.LsTrk.GridDat.Cells.h_min[i]; break; } case NavierSlip_SlipLength.Prescribed_SlipLength: { SlipLengths[i] = this.physParams.sliplength; break; } case NavierSlip_SlipLength.Prescribed_Beta: { SlipLengths[i] = -1.0; break; } } } } } // interface coefficients // ====================== MultidimensionalArray lambdaI, muI; lambdaI = SlipLengths.CloneAs(); lambdaI.Clear(); muI = SlipLengths.CloneAs(); muI.Clear(); foreach (Chunk cnk in this.LsTrk.Regions.GetCutCellMask()) { for (int i = cnk.i0; i < cnk.JE; i++) { double lI = 0.0; double mI = 0.0; // do the magic!!! if (this.LsTrk.GridDat.Cells.CellCenter[i, 0] > 0 && this.LsTrk.GridDat.Cells.CellCenter[i, 1] > 0) { } if (this.LsTrk.GridDat.Cells.CellCenter[i, 0] > 0 && this.LsTrk.GridDat.Cells.CellCenter[i, 1] < 0) { //lI = config.physParams.Sigma; mI = config.physParams.Sigma; } if (this.LsTrk.GridDat.Cells.CellCenter[i, 0] < 0 && this.LsTrk.GridDat.Cells.CellCenter[i, 1] < 0) { //lI = -config.physParams.Sigma; mI = -config.physParams.Sigma; } if (this.LsTrk.GridDat.Cells.CellCenter[i, 0] < 0 && this.LsTrk.GridDat.Cells.CellCenter[i, 1] > 0) { //lI = 10 * config.physParams.Sigma; mI = 10 * config.physParams.Sigma; } lambdaI[i] = lI; muI[i] = mI; } } // assemble the matrix & affine vector // =================================== IDictionary <SpeciesId, MultidimensionalArray> InterfaceLengths = this.LsTrk.GetXDGSpaceMetrics(this.LsTrk.SpeciesIdS.ToArray(), CutCellQuadOrder).CutCellMetrics.InterfaceArea; BitArray EvapMicroRegion = this.LsTrk.GridDat.GetBoundaryCells().GetBitMask(); EvapMicroRegion.SetAll(false); // compute matrix if (OpMatrix != null) { XSpatialOperatorMk2.XEvaluatorLinear mtxBuilder = this.m_XOp.GetMatrixBuilder(LsTrk, ColMapping, Params, RowMapping); foreach (var kv in AgglomeratedCellLengthScales) { mtxBuilder.CellLengthScales[kv.Key] = kv.Value; this.m_XOp.UserDefinedValues[this.LsTrk.GetSpeciesName(kv.Key)]["SlipLengths"] = SlipLengths; this.m_XOp.UserDefinedValues[this.LsTrk.GetSpeciesName(kv.Key)]["EvapMicroRegion"] = EvapMicroRegion; if (config.prescribedMassflux != null) { double[] dummyX = new double[] { 0.0, 0.0 }; this.m_XOp.UserDefinedValues[this.LsTrk.GetSpeciesName(kv.Key)]["prescribedMassflux"] = config.prescribedMassflux(dummyX, time); } } if (this.m_XOp.SurfaceElementOperator.TotalNoOfComponents > 0) { foreach (var kv in InterfaceLengths) { this.m_XOp.UserDefinedValues[this.LsTrk.GetSpeciesName(kv.Key)]["InterfaceLengths"] = kv.Value; this.m_XOp.UserDefinedValues[this.LsTrk.GetSpeciesName(kv.Key)]["lambda_interface"] = lambdaI; this.m_XOp.UserDefinedValues[this.LsTrk.GetSpeciesName(kv.Key)]["mu_interface"] = muI; } } mtxBuilder.time = time; mtxBuilder.ComputeMatrix(OpMatrix, OpAffine); } else { XSpatialOperatorMk2.XEvaluatorNonlin eval = this.m_XOp.GetEvaluatorEx(this.LsTrk, CurrentState.ToArray(), Params, RowMapping); foreach (var kv in AgglomeratedCellLengthScales) { eval.CellLengthScales[kv.Key] = kv.Value; this.m_XOp.UserDefinedValues[this.LsTrk.GetSpeciesName(kv.Key)]["SlipLengths"] = SlipLengths; this.m_XOp.UserDefinedValues[this.LsTrk.GetSpeciesName(kv.Key)]["EvapMicroRegion"] = EvapMicroRegion; if (config.prescribedMassflux != null) { double[] dummyX = new double[] { 0.0, 0.0 }; this.m_XOp.UserDefinedValues[this.LsTrk.GetSpeciesName(kv.Key)]["prescribedMassflux"] = config.prescribedMassflux(dummyX, time); } } if (this.m_XOp.SurfaceElementOperator.TotalNoOfComponents > 0) { foreach (var kv in InterfaceLengths) { this.m_XOp.UserDefinedValues[this.LsTrk.GetSpeciesName(kv.Key)]["InterfaceLengths"] = kv.Value; this.m_XOp.UserDefinedValues[this.LsTrk.GetSpeciesName(kv.Key)]["lambda_interface"] = lambdaI; this.m_XOp.UserDefinedValues[this.LsTrk.GetSpeciesName(kv.Key)]["mu_interface"] = muI; } } eval.time = time; eval.Evaluate(1.0, 1.0, OpAffine); } }
protected override void CreateFields() { Phi = new LevelSet(new Basis(this.GridData, 2), "LevelSet"); base.LsTrk = new LevelSetTracker((GridData)this.GridData, this.momentFittingVariant, 1, new string[] { "A", "B" }, Phi); }
public void StageChange() { obsRef = InfiniteScroll.Instance.currentStage; }
protected override bool HeightDirectionIsSuitable( LinearSayeSpace <Cube> arg, LinearPSI <Cube> psi, NodeSet x_center, int heightDirection, MultidimensionalArray agradient, int cell) { //throw new NotImplementedException(); //Determine bounds //----------------------------------------------------------------------------------------------------------------- NodeSet nodeOnPsi = psi.ProjectOnto(x_center); MultidimensionalArray jacobian = grid.Jacobian.GetValue_Cell(nodeOnPsi, cell, 1); jacobian = jacobian.ExtractSubArrayShallow(new int[] { 0, 0, -1, -1 }); LevelSet levelSet = lsData.LevelSet as LevelSet; MultidimensionalArray hessian = MultidimensionalArray.Create(1, 1, 3, 3); levelSet.EvaluateHessian(cell, 1, nodeOnPsi, hessian); hessian = hessian.ExtractSubArrayShallow(new int[] { 0, 0, -1, -1 }).CloneAs(); //hessian = jacobian * hessian; hessian.ApplyAll(x => Math.Abs(x)); MultidimensionalArray gradient = lsData.GetLevelSetGradients(nodeOnPsi, cell, 1); gradient = gradient.ExtractSubArrayShallow(0, 0, -1).CloneAs(); //abs(Hessian) * 0,5 * diameters.^2 = delta ,( square each entry of diameters) , //this bounds the second error term from taylor series //+ + + + double[] arr = arg.Diameters.CloneAs(); psi.SetInactiveDimsToZero(arr); MultidimensionalArray diameters = MultidimensionalArray.CreateWrapper(arr, 3, 1); diameters = jacobian * diameters; diameters.ApplyAll(x => 0.5 * x * x); MultidimensionalArray delta = hessian * diameters; delta = delta.ExtractSubArrayShallow(-1, 0); //Check if suitable //----------------------------------------------------------------------------------------------------------------- //|gk| > δk //Gradient should be able to turn arround psi.SetInactiveDimsToZero(gradient.Storage); if (Math.Abs(gradient[heightDirection]) > delta[heightDirection]) { bool suitable = true; // ||Grad + maxChange|| should be smaller than 20 * // Sum_j( g_j + delta_j)^2 / (g_k - delta_k)^2 < 20 double sum = 0; for (int j = 0; j < delta.Length; ++j) { sum += Math.Pow(Math.Abs(gradient[j]) + delta[j], 2); } sum /= Math.Pow(Math.Abs(gradient[heightDirection]) - delta[heightDirection], 2); suitable &= sum < 20; return(suitable); } return(false); }
void Start() { SelectedLevelIndex = -1; LevelSet set = menuFunctions.levelSet; int newLevelCount = 0; int firstIndex = -1; List <LevelSelectObject> tmpList = new List <LevelSelectObject>(); for (int i = 0; i < set.levels.Length; i++) { if (set.getSceneNumber(i) >= SceneManager.sceneCountInBuildSettings || set.getSceneNumber(i) < 4) { continue; } bool complete = true; LevelSet.Difficulty difficulty = set.levels[i].difficulty; if (!PlayerPrefs.HasKey("level complete " + set.ID + " " + set.getSceneNumber(i)) || PlayerPrefs.GetInt("level complete " + set.ID + " " + set.getSceneNumber(i)) != 1) { complete = false; if (firstIndex == -1) { firstIndex = i; } } if (difficulty == LevelSet.Difficulty.TUTORIAL) { newLevelCount = MaxAvailableLevelsInSection; if (!complete) { newLevelCount = 1; } } bool levelAvailable = newLevelCount >= 1; if (difficulty >= LevelSet.Difficulty.SANDBOX) { levelAvailable = true; } if (newLevelCount >= 0 || levelAvailable) { GameObject newObject = Instantiate(LevelSelectObjectPrefab, transform); LevelSelectObject selectObject = newObject.GetComponent <LevelSelectObject>(); tmpList.Add(selectObject); selectObject.SetLevel(set.levels[i], i, this, levelAvailable, complete); } if (!complete) { newLevelCount--; newLevelCount = Mathf.Min(newLevelCount, MaxAvailableLevelsInSection); } } if (firstIndex == -1) { firstIndex = set.levels.Length - 1; } SelectedLevelIndex = firstIndex; list = tmpList.ToArray(); PlayButton.interactable = SelectedLevelIndex >= 0; list[SelectedLevelIndex].Refresh(); scrollRect.verticalNormalizedPosition = Mathf.Clamp(1 - (firstIndex * 1f / (set.levels.Length - 2)), 0, 1); }
private void cmdLoadLevel_Click(object sender, RoutedEventArgs e) { string filepath = Helper.OpenFile(); if (filepath == null) return; ThisLevel.ClearLevel(MainGFX); try { ThisLevel = LevelSet.LoadLevel(filepath); ThisLevel.BuildLevel(MainGFX); lstSprites.ItemsSource = ThisLevel.Sprites; lstSprites.Items.Refresh(); GUIAni = new GUIAnimator(gfx: MainGFX, lvl: ThisLevel, timingSrc: TimingSource.Sources.CompositionTargetRendering, pgJumpRes: pgJumpResource); } catch (Exception ex) { MessageBox_Dispatched("Failed loading level description", ex.Message); } }
/// <summary> /// Instantiates those fields that are marked by an <see cref="InstantiateFromControlFileAttribute"/> - attribute; /// </summary> public static void CreateFieldsAuto(object _this, IGridData context, IDictionary <string, FieldOpts> FieldOptions, XQuadFactoryHelper.MomentFittingVariants cutCellQuadType, ICollection <DGField> IOFields, ICollection <DGField> RegisteredFields) { FieldInfo[] fields = _this.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Static); FieldInfo LevelSetTracker = null; List <FieldInfo> LevelSets = new List <FieldInfo>(); List <FieldInfo> OtherFields = new List <FieldInfo>(); #region DetermineTypeOfFields // Determine the Type of the Fields foreach (FieldInfo f in fields) { object[] atts = f.GetCustomAttributes(typeof(InstantiateFromControlFileAttribute), true); if (atts.Length != 0) { if (atts.Length != 1) { throw new ApplicationException("should not happen"); } Type HistoryType, VectorType, ComponentType; GetTypes(f, out HistoryType, out VectorType, out ComponentType); if (typeof(LevelSet).IsAssignableFrom(ComponentType)) { LevelSets.Add(f); } else { OtherFields.Add(f); } } atts = f.GetCustomAttributes(typeof(LevelSetTrackerAttribute), true); if (atts.Length != 0) { if (atts.Length != 1) { throw new ApplicationException("should not happen"); } if (f.FieldType != typeof(LevelSetTracker)) { throw new ApplicationException("stupid."); } if (LevelSetTracker != null) { throw new ApplicationException("only one level set tracker is allowed"); } LevelSetTracker = f; } } #endregion #region CreateLevelSets // create Level Sets .. // ===================== // must be initialized before the XDG fields ... FieldInfo[] LevelSetsSorted = new FieldInfo[LevelSets.Count]; if (LevelSets.Count > 4) { throw new ApplicationException("at maximum, 4 different level sets are supported."); } if (LevelSets.Count > 1) { // more than 1 level set -> level set index is required. for (int i = 0; i < LevelSets.Count; i++) { FieldInfo fi = LevelSets[i]; object[] atts2 = fi.GetCustomAttributes(typeof(LevelSetIndexAttribute), true); if (atts2.Length > 1) { throw new ApplicationException("should not happen (AttributeUsage.AllowMultiple = false for 'LevelSetIndexAttribute')"); } if (atts2.Length < 1) { throw new ApplicationException("missing 'LevelSetIndexAttribute' for level set '" + fi.Name + "' in class '" + fi.ReflectedType.Name + "'; this contains " + LevelSets.Count + " level sets, so level set indices in the range 0 (including) to " + LevelSets.Count + " (excluding) are required."); } LevelSetIndexAttribute lsia = (LevelSetIndexAttribute)atts2[0]; if (lsia.m_idx < 0 || lsia.m_idx >= LevelSets.Count) { throw new ApplicationException("error with level set index for level set '" + fi.Name + "': index is specified as " + lsia.m_idx + ", but allowed range is " + "0 (including) to " + LevelSets.Count + " (excluding)."); } if (LevelSetsSorted[lsia.m_idx] != null) { throw new ApplicationException("error with level set index " + lsia.m_idx + ": " + " assigned for at least two level sets, i.e. for '" + fi.Name + "' and for '" + LevelSetsSorted[lsia.m_idx].Name + "' -- each index is allowed only once."); } } } else if (LevelSets.Count == 1) { LevelSetsSorted[0] = LevelSets[0]; } LevelSet[] LevelSetsInstances = new LevelSet[LevelSets.Count]; for (int i = 0; i < LevelSetsSorted.Length; i++) { InstantiateField(LevelSetsSorted[i], _this, IOFields, RegisteredFields, FieldOptions, context, null); object o = LevelSetsSorted[i].GetValue(_this); if (o is ScalarFieldHistory <LevelSet> ) { LevelSetsInstances[i] = ((ScalarFieldHistory <LevelSet>)LevelSetsSorted[i].GetValue(_this)).Current; } else { LevelSetsInstances[i] = (LevelSet)LevelSetsSorted[i].GetValue(_this); } } #endregion #region CreareLevelSetTracker // create level set tracker // ======================== LevelSetTracker lsTrk = null; foreach (DGField f in RegisteredFields) { if (f is XDGField) { LevelSetTracker _lsTrk = ((XDGField)f).Basis.Tracker; if (lsTrk == null) { lsTrk = _lsTrk; } else { if (!object.ReferenceEquals(lsTrk, _lsTrk)) { throw new NotSupportedException(); } } } } if (lsTrk == null) { if (LevelSets.Count > 0) { if (LevelSetTracker == null) { throw new ApplicationException("missing Level Set Tracker"); } LevelSetTrackerAttribute att = (LevelSetTrackerAttribute)(LevelSetTracker.GetCustomAttributes(typeof(LevelSetTrackerAttribute), true)[0]); switch (LevelSetsSorted.Length) { case 1: lsTrk = new LevelSetTracker((GridData)context, cutCellQuadType, att.m_NearCellWidth, (string[])(att.GetSpeciesTable(1)), LevelSetsInstances[0]); break; case 2: lsTrk = new LevelSetTracker((GridData)context, cutCellQuadType, att.m_NearCellWidth, (string[, ])(att.GetSpeciesTable(2)), LevelSetsInstances[0], LevelSetsInstances[1]); break; case 3: lsTrk = new LevelSetTracker((GridData)context, cutCellQuadType, att.m_NearCellWidth, (string[, , ])(att.GetSpeciesTable(3)), LevelSetsInstances[0], LevelSetsInstances[1], LevelSetsInstances[2]); break; case 4: lsTrk = new LevelSetTracker((GridData)context, cutCellQuadType, att.m_NearCellWidth, (string[, , , ])(att.GetSpeciesTable(4)), LevelSetsInstances[0], LevelSetsInstances[1], LevelSetsInstances[2], LevelSetsInstances[3]); break; } LevelSetTracker.SetValue(_this, lsTrk); } } #endregion // create other Fields, e.g. single phase, XDG, ... // ================================================ foreach (FieldInfo f in OtherFields) { InstantiateField(f, _this, IOFields, RegisteredFields, FieldOptions, context, lsTrk); } }
public void createBoard() { logLevelStart(); bonus = null; scale = base.transform.Find("Scale"); Vector2 sizeDelta = cellTemp.GetComponent <RectTransform>().sizeDelta; cellSize = sizeDelta.x; float num = 1336f / (float)Screen.height; width = (float)Screen.width * num / cellSize; Vector2 sizeDelta2 = scale.parent.GetComponent <RectTransform>().sizeDelta; height = sizeDelta2.y / cellSize; if (levelToOpen == PlayerPrefsManager.GetLevel()) { levelToOpen = -1; } if (levelToOpen == -1) { info = FugoUtils.getLevelInfo(); } else { info = FugoUtils.getLevelInfo(levelToOpen); } DateTime now = DateTime.Now; if (daily) { sec = Games.dailyPuzzles; set = sec.sets[now.Month - 1]; level = set.levels[now.Day - 1]; } else { sec = Games.sections[info[0]]; set = sec.sets[info[1]]; level = set.levels[info[2]]; } ParticleAnimationManager.instance.PlayAnimation(set); Cell.cellColor = set.InGameTileColor; Cell.strokeColor = set.InGameSelectedLetterBGColor; nextSet = (set.levels.Count - 1 == info[2] && (levelToOpen == -1 || levelToOpen == PlayerPrefsManager.GetLevel())); nextSec = (sec.sets.Count - 1 == info[1] && (levelToOpen == -1 || levelToOpen == PlayerPrefsManager.GetLevel()) && nextSet); if (nextSet) { GameMenuController.instance.setGoldAmount(25); } if (nextSec) { GameMenuController.instance.setGoldAmount(100); } cellBGColor = FugoUtils.HexToColor(set.InGameSelectedLetterBGColor); board = new GameObject[level.width, level.height]; background.SetActive(value: true); string path = "BGImages/" + set.bgImage; Sprite sprite = Resources.Load <Sprite>(path); background.GetComponent <Image>().sprite = sprite; background.transform.Find("Blur").gameObject.SetActive(value: false); if (PlayerPrefsManager.IsBlueMode()) { background.SetActive(value: false); } if (levelToOpen != -1) { int[] levelInfo = FugoUtils.getLevelInfo(); int[] levelInfo2 = FugoUtils.getLevelInfo(levelToOpen); UnityEngine.Debug.Log(levelInfo[1]); UnityEngine.Debug.Log(levelInfo2[1]); blur = (levelInfo[1] == levelInfo2[1]); } else { blur = true; } if (blur) { background.transform.Find("Blur").gameObject.SetActive(value: true); } else { background.transform.Find("Blur").gameObject.SetActive(value: true); FugoUtils.ChangeAlpha(background.transform.Find("Blur").GetComponent <Image>(), 0f); BlurControl.instance.enableBlur(); } if (daily) { background.transform.Find("Blur").gameObject.SetActive(value: false); } name.GetComponent <Text>().text = set.SetFullName + " ● " + (info[2] + 1); name.GetComponent <Text>().color = FugoUtils.HexToColor(set.InGameHeaderColor); float a = width / (float)level.width; float b = height / (float)level.height; scaleAmount = Mathf.Min(a, b); scaleAmount *= 0.9f; cellSize *= scaleAmount; offsetX = Vector2.up * ((float)level.height - height) * cellSize * 0.5f * scaleAmount; offsetY = Vector2.left * ((float)level.width - width) * cellSize * 0.5f * scaleAmount; offsetX = Vector2.left * cellSize * level.width * 0.5f + Vector2.right * cellSize * 0.5f; offsetY = Vector2.up * cellSize * level.height * 0.5f + Vector2.down * cellSize * 0.5f; for (int i = 0; i < level.width; i++) { for (int j = 0; j < level.height; j++) { GameObject gameObject = UnityEngine.Object.Instantiate(cellTemp); gameObject.transform.SetParent(scale); gameObject.transform.localPosition = Vector3.zero; gameObject.transform.SetAsFirstSibling(); gameObject.SetActive(value: false); RectTransform component = gameObject.GetComponent <RectTransform>(); component.anchoredPosition = (Vector3.right * i + Vector3.down * j) * cellSize; component.anchoredPosition += offsetX + offsetY; board[i, j] = gameObject; gameObject.transform.localScale = Vector3.one; gameObject.transform.Find("BG").localScale = Vector3.zero; gameObject.transform.Find("BG/Text").GetComponent <Text>().color = FugoUtils.HexToColor(set.InGameHintColor); component.sizeDelta = Vector2.one * cellSize; Cell component2 = gameObject.GetComponent <Cell>(); component2.x = i; component2.y = j; } } GameObject[,] array = board; int length = array.GetLength(0); int length2 = array.GetLength(1); for (int k = 0; k < length; k++) { for (int l = 0; l < length2; l++) { GameObject gameObject2 = array[k, l]; if (gameObject2.activeSelf) { } } } bool flag = false; foreach (Word word in level.words) { if (word.bonus) { flag = true; bonus = word; } try { placeWord(word); } catch (Exception) { } } if (flag) { Movements.instance.executeWithDelay((Movements.Execute)TutorialController.instance.openBonus, 0.5f); } byte[] bytes = Encoding.Default.GetBytes(SystemInfo.deviceUniqueIdentifier); int seed = PlayerPrefsManager.GetLevel() + BitConverter.ToInt32(bytes, 0); UnityEngine.Random.InitState(seed); UnityEngine.Random.InitState(DateTime.Now.Millisecond); Movements.instance.executeWithDelay((Movements.Execute)WheelController.instance.newGame, 0.55f); MapController.instance.setColors(); if (daily && PlayerPrefsManager.IsItFirstDaily()) { Movements.instance.executeWithDelay((Movements.Execute)TutorialController.instance.openDaily, 1.5f); } if (levelToOpen == -1) { if (PlayerPrefsManager.GetLevel() == 1) { WheelController.running = false; UnityEngine.Debug.Log("tutorial1"); Movements.instance.executeWithDelay((Movements.Execute)TutorialController.instance.openFirst, 1.5f); } if (PlayerPrefsManager.GetLevel() == 3) { WheelController.running = false; UnityEngine.Debug.Log("tutorial2"); Movements.instance.executeWithDelay((Movements.Execute)TutorialController.instance.openSecond, 1.5f); } if (PlayerPrefsManager.GetLevel() == 5) { WheelController.running = false; UnityEngine.Debug.Log("tutorial3"); Movements.instance.executeWithDelay((Movements.Execute)TutorialController.instance.openThird, 1.5f); } } }
public XDGTestSetup( int p, double AggregationThreshold, int TrackerWidth, MultigridOperator.Mode mumo, XQuadFactoryHelper.MomentFittingVariants momentFittingVariant, ScalarFunction LevSetFunc = null) { // Level set, tracker and XDG basis // ================================ if (LevSetFunc == null) { LevSetFunc = ((_2D)((x, y) => 0.8 * 0.8 - x * x - y * y)).Vectorize(); } LevSet = new LevelSet(new Basis(grid, 2), "LevelSet"); LevSet.Clear(); LevSet.ProjectField(LevSetFunc); LsTrk = new LevelSetTracker(grid, XQuadFactoryHelper.MomentFittingVariants.Classic, TrackerWidth, new string[] { "A", "B" }, LevSet); LsTrk.UpdateTracker(); XB = new XDGBasis(LsTrk, p); XSpatialOperator Dummy = new XSpatialOperator(1, 0, 1, QuadOrderFunc.SumOfMaxDegrees(RoundUp: true), "C1", "u"); //Dummy.EquationComponents["c1"].Add(new Dummy.Commit(); //Tecplot.PlotFields(new DGField[] { LevSet }, "agglo", 0.0, 3); // operator // ======== Debug.Assert(p <= 4); XDGBasis opXB = new XDGBasis(LsTrk, 4); // we want to have a very precise quad rule var map = new UnsetteledCoordinateMapping(opXB); int quadOrder = Dummy.QuadOrderFunction(map.BasisS.Select(bs => bs.Degree).ToArray(), new int[0], map.BasisS.Select(bs => bs.Degree).ToArray()); //agg = new MultiphaseCellAgglomerator(new CutCellMetrics(momentFittingVariant, quadOrder, LsTrk, LsTrk.SpeciesIdS.ToArray()), AggregationThreshold, false); agg = LsTrk.GetAgglomerator(LsTrk.SpeciesIdS.ToArray(), quadOrder, __AgglomerationTreshold: AggregationThreshold); foreach (var S in LsTrk.SpeciesIdS) { Console.WriteLine("Species {0}, no. of agglomerated cells {1} ", LsTrk.GetSpeciesName(S), agg.GetAgglomerator(S).AggInfo.SourceCells.Count()); } // mass matrix factory // =================== // Basis maxB = map.BasisS.ElementAtMax(b => b.Degree); //MassFact = new MassMatrixFactory(maxB, agg); MassFact = LsTrk.GetXDGSpaceMetrics(LsTrk.SpeciesIdS.ToArray(), quadOrder, 1).MassMatrixFactory; // Test field // ========== // set the test field: this is a polynomial function, // but different for each species; On this field, restriction followed by prolongation should be the identity this.Xdg_uTest = new XDGField(this.XB, "uTest"); Dictionary <SpeciesId, double> dumia = new Dictionary <SpeciesId, double>(); int i = 2; foreach (var Spc in LsTrk.SpeciesIdS) { dumia.Add(Spc, i); i -= 1; } SetTestValue(Xdg_uTest, dumia); // dummy operator matrix which fits polynomial degree p // ==================================================== Xdg_opMtx = new BlockMsrMatrix(Xdg_uTest.Mapping, Xdg_uTest.Mapping); Xdg_opMtx.AccEyeSp(120.0); // XDG Aggregation BasiseS // ======================= //XAggB = MgSeq.Select(agGrd => new XdgAggregationBasis[] { new XdgAggregationBasis(uTest.Basis, agGrd) }).ToArray(); XAggB = new XdgAggregationBasis[MgSeq.Length][]; var _XAggB = AggregationGridBasis.CreateSequence(MgSeq, Xdg_uTest.Mapping.BasisS); for (int iLevel = 0; iLevel < XAggB.Length; iLevel++) { XAggB[iLevel] = new[] { (XdgAggregationBasis)(_XAggB[iLevel][0]) }; XAggB[iLevel][0].Update(agg); } // Multigrid Operator // ================== Xdg_opMtx = new BlockMsrMatrix(Xdg_uTest.Mapping, Xdg_uTest.Mapping); Xdg_opMtx.AccEyeSp(120.0); XdgMultigridOp = new MultigridOperator(XAggB, Xdg_uTest.Mapping, Xdg_opMtx, MassFact.GetMassMatrix(Xdg_uTest.Mapping, false), new MultigridOperator.ChangeOfBasisConfig[][] { new MultigridOperator.ChangeOfBasisConfig[] { new MultigridOperator.ChangeOfBasisConfig() { VarIndex = new int[] { 0 }, mode = mumo, Degree = p } } }); }
public static GameObject getLevel(int level) { GameObject original = Resources.Load <GameObject>("Prefabs/BoardTemplate"); GameObject original2 = Resources.Load <GameObject>("Prefabs/DebugCell"); int[] levelInfo = FugoUtils.getLevelInfo(level); Section section = Games.sections[levelInfo[0]]; LevelSet levelSet = section.sets[levelInfo[1]]; Level level2 = levelSet.levels[levelInfo[2]]; float num = FugoUtils.boardHeight; float num2 = num * FugoUtils.getBoardRatio(); GameObject gameObject = UnityEngine.Object.Instantiate(original); Transform transform = gameObject.transform.Find("Board"); float val = 7.5f / (float)level2.width; float val2 = num / 100f / (float)level2.height; float num3 = Math.Min(val, val2); float num4 = 100f * num3; float val3 = num2 / (float)level2.width; float val4 = num / (float)level2.height; num4 = Math.Min(val3, val4); float num5 = num2 - (float)level2.width * num4; float num6 = num - (float)level2.height * num4; UnityEngine.Debug.Log(num + " " + level2.height + " " + cellSize); num5 *= 0.5f; num6 *= 0.5f; RectTransform component = transform.GetComponent <RectTransform>(); UnityEngine.Debug.Log("board size " + component.sizeDelta); Vector2 sizeDelta = component.sizeDelta; sizeDelta.y = FugoUtils.adBoardHeight; component.sizeDelta = sizeDelta; Vector2 anchoredPosition = component.anchoredPosition; anchoredPosition.y = -100f; component.anchoredPosition = anchoredPosition; List <Word> words = level2.words; foreach (Word item in words) { int length = item.length; int x = item.X; int y = item.Y; for (int i = 0; i < length; i++) { GameObject gameObject2 = UnityEngine.Object.Instantiate(original2); gameObject2.GetComponent <Image>().color = FugoUtils.HexToColor(levelSet.InGameSelectedLetterBGColor); gameObject2.transform.Find("Text").GetComponent <Text>().color = FugoUtils.HexToColor(levelSet.InGameSelectedLetterColor); gameObject2.transform.Find("Text").GetComponent <Text>().text = item.word[i].ToString(); RectTransform component2 = gameObject2.GetComponent <RectTransform>(); gameObject2.transform.SetParent(transform.transform); component2.anchorMin = Vector2.up; component2.anchorMax = Vector2.up; component2.pivot = Vector2.up; component2.sizeDelta = Vector2.one * num4; component2.anchoredPosition = Vector2.right * x * num4 + Vector2.down * y * num4; component2.anchoredPosition += Vector2.down * num6 + Vector2.right * num5; if (item.orientation == Orientation.HORIZONTAL) { component2.anchoredPosition += Vector2.right * i * num4; } else { component2.anchoredPosition += Vector2.down * i * num4; } gameObject2.transform.localScale = Vector3.one; } } return(gameObject); }
/// <summary> /// /// </summary> public void AssembleMatrix_Timestepper <T>( int CutCellQuadOrder, BlockMsrMatrix OpMatrix, double[] OpAffine, Dictionary <SpeciesId, MultidimensionalArray> AgglomeratedCellLengthScales, IEnumerable <T> CurrentState, VectorField <SinglePhaseField> SurfaceForce, VectorField <SinglePhaseField> LevelSetGradient, SinglePhaseField ExternalyProvidedCurvature, UnsetteledCoordinateMapping RowMapping, UnsetteledCoordinateMapping ColMapping, double time, IEnumerable <T> CoupledCurrentState = null, IEnumerable <T> CoupledParams = null) where T : DGField { if (ColMapping.BasisS.Count != this.Op.DomainVar.Count) { throw new ArgumentException(); } if (RowMapping.BasisS.Count != this.Op.CodomainVar.Count) { throw new ArgumentException(); } // check: var Tracker = this.LsTrk; int D = Tracker.GridDat.SpatialDimension; if (CurrentState != null && CurrentState.Count() != (D + 1)) { throw new ArgumentException(); } if (OpMatrix == null && CurrentState == null) { throw new ArgumentException(); } DGField[] U0; if (CurrentState != null) { U0 = CurrentState.Take(D).ToArray(); } else { U0 = null; } LevelSet Phi = (LevelSet)(Tracker.LevelSets[0]); SpeciesId[] SpcToCompute = AgglomeratedCellLengthScales.Keys.ToArray(); IDictionary <SpeciesId, MultidimensionalArray> InterfaceLengths = this.LsTrk.GetXDGSpaceMetrics(this.LsTrk.SpeciesIdS.ToArray(), CutCellQuadOrder).CutCellMetrics.InterfaceArea; // advanced settings for the navier slip boundary condition // ======================================================== CellMask SlipArea; switch (this.dntParams.GNBC_Localization) { case NavierSlip_Localization.Bulk: { SlipArea = this.LsTrk.GridDat.BoundaryCells.VolumeMask; break; } case NavierSlip_Localization.ContactLine: { SlipArea = null; break; } case NavierSlip_Localization.Nearband: { SlipArea = this.LsTrk.GridDat.BoundaryCells.VolumeMask.Intersect(this.LsTrk.Regions.GetNearFieldMask(this.LsTrk.NearRegionWidth)); break; } case NavierSlip_Localization.Prescribed: { throw new NotImplementedException(); } default: throw new ArgumentException(); } MultidimensionalArray SlipLengths; SlipLengths = this.LsTrk.GridDat.Cells.h_min.CloneAs(); SlipLengths.Clear(); //SlipLengths.AccConstant(-1.0); if (SlipArea != null) { foreach (Chunk cnk in SlipArea) { for (int i = cnk.i0; i < cnk.JE; i++) { switch (this.dntParams.GNBC_SlipLength) { case NavierSlip_SlipLength.hmin_DG: { int degU = ColMapping.BasisS.ToArray()[0].Degree; SlipLengths[i] = this.LsTrk.GridDat.Cells.h_min[i] / (degU + 1); break; } case NavierSlip_SlipLength.hmin_Grid: { SlipLengths[i] = SlipLengths[i] = this.LsTrk.GridDat.Cells.h_min[i]; break; } case NavierSlip_SlipLength.Prescribed_SlipLength: { SlipLengths[i] = this.physParams.sliplength; break; } case NavierSlip_SlipLength.Prescribed_Beta: { SlipLengths[i] = -1.0; break; } } } } } // parameter assembly // ================== // normals: SinglePhaseField[] Normals; // Normal vectors: length not normalized - will be normalized at each quad node within the flux functions. if (this.NormalsRequired) { if (LevelSetGradient == null) { LevelSetGradient = new VectorField <SinglePhaseField>(D, Phi.Basis, SinglePhaseField.Factory); LevelSetGradient.Gradient(1.0, Phi); } Normals = LevelSetGradient.ToArray(); } else { Normals = new SinglePhaseField[D]; } // curvature: SinglePhaseField Curvature; if (this.CurvatureRequired) { Curvature = ExternalyProvidedCurvature; } else { Curvature = null; } // linearization velocity: DGField[] U0_U0mean; if (this.U0meanrequired) { XDGBasis U0meanBasis = new XDGBasis(Tracker, 0); VectorField <XDGField> U0mean = new VectorField <XDGField>(D, U0meanBasis, "U0mean_", XDGField.Factory); U0_U0mean = ArrayTools.Cat <DGField>(U0, U0mean); } else { U0_U0mean = new DGField[2 * D]; } // Temperature gradient for evaporation VectorField <DGField> GradTemp = new VectorField <DGField>(D, new XDGBasis(LsTrk, 0), XDGField.Factory); if (CoupledCurrentState != null) { DGField Temp = CoupledCurrentState.ToArray()[0]; GradTemp = new VectorField <DGField>(D, Temp.Basis, "GradTemp", XDGField.Factory); XNSEUtils.ComputeGradientForParam(Temp, GradTemp, this.LsTrk); } // concatenate everything var Params = ArrayTools.Cat <DGField>( U0_U0mean, Curvature, ((SurfaceForce != null) ? SurfaceForce.ToArray() : new SinglePhaseField[D]), Normals, ((evaporation) ? GradTemp.ToArray() : new SinglePhaseField[D]), ((evaporation) ? CoupledCurrentState.ToArray <DGField>() : new SinglePhaseField[1]), ((evaporation) ? CoupledParams.ToArray <DGField>() : new SinglePhaseField[1])); //((evaporation) ? GradTemp.ToArray() : new SinglePhaseField[D])); // linearization velocity: if (this.U0meanrequired) { VectorField <XDGField> U0mean = new VectorField <XDGField>(U0_U0mean.Skip(D).Take(D).Select(f => ((XDGField)f)).ToArray()); U0mean.Clear(); if (this.physParams.IncludeConvection) { ComputeAverageU(U0, U0mean, CutCellQuadOrder, LsTrk.GetXDGSpaceMetrics(SpcToCompute, CutCellQuadOrder, 1).XQuadSchemeHelper); } } // assemble the matrix & affine vector // =================================== // compute matrix if (OpMatrix != null) { //Op.ComputeMatrixEx(Tracker, // ColMapping, Params, RowMapping, // OpMatrix, OpAffine, false, time, true, // AgglomeratedCellLengthScales, // InterfaceLengths, SlipLengths, // SpcToCompute); XSpatialOperator.XEvaluatorLinear mtxBuilder = Op.GetMatrixBuilder(LsTrk, ColMapping, Params, RowMapping, SpcToCompute); foreach (var kv in AgglomeratedCellLengthScales) { mtxBuilder.SpeciesOperatorCoefficients[kv.Key].CellLengthScales = kv.Value; mtxBuilder.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("SlipLengths", SlipLengths); if (evaporation) { BitArray EvapMicroRegion = new BitArray(this.LsTrk.GridDat.Cells.Count);; // this.LsTrk.GridDat.GetBoundaryCells().GetBitMask(); mtxBuilder.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("EvapMicroRegion", EvapMicroRegion); } } if (Op.SurfaceElementOperator.TotalNoOfComponents > 0) { foreach (var kv in InterfaceLengths) { mtxBuilder.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("InterfaceLengths", kv.Value); } } mtxBuilder.time = time; mtxBuilder.ComputeMatrix(OpMatrix, OpAffine); #if DEBUG // remark: remove this piece in a few months from now on (09may18) if no problems occur { BlockMsrMatrix checkOpMatrix = new BlockMsrMatrix(RowMapping, ColMapping); double[] checkAffine = new double[OpAffine.Length]; Op.ComputeMatrixEx(Tracker, ColMapping, Params, RowMapping, OpMatrix, OpAffine, false, time, true, AgglomeratedCellLengthScales, InterfaceLengths, SlipLengths, SpcToCompute); double[] checkResult = checkAffine.CloneAs(); var currentVec = new CoordinateVector(CurrentState.ToArray()); checkOpMatrix.SpMV(1.0, new CoordinateVector(CurrentState.ToArray()), 1.0, checkResult); double L2_dist = GenericBlas.L2DistPow2(checkResult, OpAffine).MPISum().Sqrt(); double RefNorm = (new double[] { checkResult.L2NormPow2(), OpAffine.L2NormPow2(), currentVec.L2NormPow2() }).MPISum().Max().Sqrt(); Assert.LessOrEqual(L2_dist, RefNorm * 1.0e-6); Debug.Assert(L2_dist < RefNorm * 1.0e-6); } #endif } else { XSpatialOperator.XEvaluatorNonlin eval = Op.GetEvaluatorEx(Tracker, CurrentState.ToArray(), Params, RowMapping, SpcToCompute); foreach (var kv in AgglomeratedCellLengthScales) { eval.SpeciesOperatorCoefficients[kv.Key].CellLengthScales = kv.Value; eval.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("SlipLengths", SlipLengths); if (evaporation) { BitArray EvapMicroRegion = new BitArray(this.LsTrk.GridDat.Cells.Count); eval.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("EvapMicroRegion", EvapMicroRegion); } } if (Op.SurfaceElementOperator.TotalNoOfComponents > 0) { foreach (var kv in InterfaceLengths) { eval.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("InterfaceLengths", kv.Value); } } eval.time = time; eval.Evaluate(1.0, 1.0, OpAffine); } // check // ===== /* * { * DGField[] testDomainFieldS = ColMapping.BasisS.Select(bb => new XDGField(bb as XDGBasis)).ToArray(); * CoordinateVector test = new CoordinateVector(testDomainFieldS); * * DGField[] errFieldS = ColMapping.BasisS.Select(bb => new XDGField(bb as XDGBasis)).ToArray(); * CoordinateVector Err = new CoordinateVector(errFieldS); * * var eval = Op.GetEvaluatorEx(LsTrk, * testDomainFieldS, Params, RowMapping); * * foreach (var s in this.LsTrk.SpeciesIdS) * eval.SpeciesOperatorCoefficients[s].CellLengthScales = AgglomeratedCellLengthScales[s]; * * eval.time = time; * int L = test.Count; * Random r = new Random(); * for(int i = 0; i < L; i++) { * test[i] = r.NextDouble(); * } * * * * double[] R1 = new double[L]; * double[] R2 = new double[L]; * eval.Evaluate(1.0, 1.0, R1); * * R2.AccV(1.0, OpAffine); * OpMatrix.SpMV(1.0, test, 1.0, R2); * * Err.AccV(+1.0, R1); * Err.AccV(-1.0, R2); * * double ErrDist = GenericBlas.L2DistPow2(R1, R2).MPISum().Sqrt(); * * double Ref = test.L2NormPow2().MPISum().Sqrt(); * * Debug.Assert(ErrDist <= Ref*1.0e-5, "Mismatch between explicit evaluation of XDG operator and matrix."); * } */ }
protected override void CreateFields() { this.LevSet = new LevelSet(new Basis(this.GridData, 2), "Phi"); this.LsTrk = new LevelSetTracker(this.GridData, XQuadFactoryHelper.MomentFittingVariants.Classic, 1, new string[] { "A", "B" }, LevSet); Pressure = new XDGField(new XDGBasis(this.LsTrk, 2), "Pressure"); }
public void ProcessLevelSet(string filename) { Log.DebugPrint("Processing level set {0}", filename); LevelSet levelSet = new LevelSet(filename); int i = 0; foreach (Level level in levelSet) { ProcessLevel(level, i); i++; } }
/// <summary> /// Obtaining the time integrated spatial discretization of the reinitialization equation in a narrow band around the zero level set, based on a Godunov's numerical Hamiltonian calculation /// </summary> /// <param name="LS"> The level set function </param> /// <param name="Restriction"> The narrow band around the zero level set </param> /// <param name="NumberOfTimesteps"> /// maximum number of pseudo-timesteps /// </param> /// <param name="thickness"> /// The smoothing width of the signum function. /// This is the main stabilization parameter for re-initialization. /// It should be set to approximately 3 cells. /// </param> /// <param name="TimestepSize"> /// size of the pseudo-timestep /// </param> public void ReInitialize(LevelSet LS, SubGrid Restriction, double thickness, double TimestepSize, int NumberOfTimesteps) { using (var tr = new FuncTrace()) { // log parameters: tr.Info("thickness: " + thickness.ToString(NumberFormatInfo.InvariantInfo)); tr.Info("TimestepSize: " + TimestepSize.ToString(NumberFormatInfo.InvariantInfo)); tr.Info("NumberOfTimesteps: " + NumberOfTimesteps); ExplicitEuler TimeIntegrator; SpatialOperator SO; Func <int[], int[], int[], int> QuadratureOrder = QuadOrderFunc.NonLinear(3); if (m_ctx.SpatialDimension == 2) { SO = new SpatialOperator(1, 5, 1, QuadratureOrder, new string[] { "LS", "LSCGV", "LSDG[0]", "LSUG[0]", "LSDG[1]", "LSUG[1]", "Result" }); SO.EquationComponents["Result"].Add(new GodunovHamiltonian(m_ctx, thickness)); SO.Commit(); TimeIntegrator = new RungeKutta(m_Scheme, SO, new CoordinateMapping(LS), new CoordinateMapping(LSCGV, LSDG[0], LSUG[0], LSDG[1], LSUG[1]), sgrd: Restriction); } else { SO = new SpatialOperator(1, 7, 1, QuadratureOrder, new string[] { "LS", "LSCGV", "LSDG[0]", "LSUG[0]", "LSDG[1]", "LSUG[1]", "LSDG[2]", "LSUG[2]", "Result" }); SO.EquationComponents["Result"].Add(new GodunovHamiltonian(m_ctx, thickness)); SO.Commit(); TimeIntegrator = new RungeKutta(m_Scheme, SO, new CoordinateMapping(LS), new CoordinateMapping(LSCGV, LSDG[0], LSUG[0], LSDG[1], LSUG[1], LSDG[2], LSUG[2]), sgrd: Restriction); } // Calculating the gradients in each sub-stage of a Runge-Kutta integration procedure ExplicitEuler.ChangeRateCallback EvalGradients = delegate(double t1, double t2) { LSUG.Clear(); CalculateLevelSetGradient(LS, LSUG, "Upwind", Restriction); LSDG.Clear(); CalculateLevelSetGradient(LS, LSDG, "Downwind", Restriction); LSCG.Clear(); CalculateLevelSetGradient(LS, LSCG, "Central", Restriction); LSCGV.Clear(); var VolMask = (Restriction != null) ? Restriction.VolumeMask : null; LSCGV.ProjectAbs(1.0, VolMask, LSCG.ToArray()); }; TimeIntegrator.OnBeforeComputeChangeRate += EvalGradients; { EvalGradients(0, 0); var GodunovResi = new SinglePhaseField(LS.Basis, "Residual"); SO.Evaluate(1.0, 0.0, LS.Mapping, TimeIntegrator.ParameterMapping.Fields, GodunovResi.Mapping, Restriction); //Tecplot.Tecplot.PlotFields(ArrayTools.Cat<DGField>( LSUG, LSDG, LS, GodunovResi), "Residual", 0, 3); } // pseudo-timestepping // =================== double factor = 1.0; double time = 0; LevelSet prevLevSet = new LevelSet(LS.Basis, "prevLevSet"); CellMask RestrictionMask = (Restriction == null) ? null : Restriction.VolumeMask; for (int i = 0; (i < NumberOfTimesteps); i++) { tr.Info("Level set reinitialization pseudo-timestepping, timestep " + i); // backup old Levelset // ------------------- prevLevSet.Clear(); prevLevSet.Acc(1.0, LS, RestrictionMask); // time integration // ---------------- double dt = TimestepSize * factor; tr.Info("dt = " + dt.ToString(NumberFormatInfo.InvariantInfo) + " (factor = " + factor.ToString(NumberFormatInfo.InvariantInfo) + ")"); TimeIntegrator.Perform(dt); time += dt; // change norm // ------ prevLevSet.Acc(-1.0, LS, RestrictionMask); double ChangeNorm = prevLevSet.L2Norm(RestrictionMask); Console.WriteLine("Reinit: PseudoTime: {0} - Changenorm: {1}", i, ChangeNorm); //Tecplot.Tecplot.PlotFields(new SinglePhaseField[] { LS }, m_ctx, "Reinit-" + i, "Reinit-" + i, i, 3); } //*/ } }
public void AddLevelSet(string filename) { if (verbose >= 1) { Log.DebugPrint("Adding level set: {0}", filename); } // Load level set. LevelSet levelSet = null; try { levelSet = new LevelSet(filename); } catch (Exception ex) { Log.DebugPrint("Exception loading level set: {0}", ex.Message); return; } bool reportedFile = false; int solved = 0; int added = 0; // Process each level. int levelNumber = 0; foreach (Level level in levelSet) { // In case we need to know which level caused a problem. levelNumber++; if (verbose >= 2) { Log.DebugPrint("Adding level: {0}", levelNumber); } // Ignore pathological levels. if (!level.IsTraditional) { continue; } // Filter based on design. if (design != null && !LevelUtils.MatchesDesign(level, design)) { if (checkFirstLevelOnly) { if (reportedFile) { Console.WriteLine(); Console.WriteLine("Design differed after the first level"); } return; } continue; } // Filter based on level criteria. if (rejectDeadEnds && LevelUtils.HasDeadEnds(level)) { continue; } if (rejectCapturedTargets && LevelUtils.HasCapturedTargets(level)) { continue; } // Report file for first level we use the solver on. if (!reportedFile) { Log.DebugPrint("Loading {0}...", filename); reportedFile = true; } int moves = 0; int pushes = 0; int changes = 0; int minBoxMoves = 0; Level finalLevel = level; bool parsedStatistics = false; if (parseStatistics && !String.IsNullOrEmpty(level.Name)) { // Get stats from the level name string. string stats = level.Name; string[] fields = stats.Split(','); if (fields.Length >= 3) { moves = ParseTrailingInteger("moves", fields[0]); pushes = ParseTrailingInteger("pushes", fields[1]); changes = ParseTrailingInteger("changes", fields[2]); if (fields.Length >= 4) { minBoxMoves = ParseTrailingInteger("min", fields[3]); } if (moves != -1 && pushes != -1 && changes != -1) { parsedStatistics = true; } } } if (!parsedStatistics) { // Solve normally. Console.Write("."); solved++; if (solved % 70 == 0) { Console.WriteLine(); } if (normalizeLevels) { finalLevel = LevelUtils.NormalizeLevel(finalLevel); } MoveList finalMoveList = FinalSolve(finalLevel); Validate(level, finalLevel, finalMoveList); if (finalMoveList == null) { continue; } moves = finalMoveList.Count; pushes = LevelUtils.SolutionPushes(finalMoveList); changes = LevelUtils.SolutionChanges(finalLevel, finalMoveList); minBoxMoves = LevelUtils.MinimumBoxMoves(finalLevel, finalMoveList); } // Filter based on solution criteria. if (moves < moveLimit) { continue; } if (changes < changeLimit) { continue; } if (pushes < pushLimit) { continue; } if (minBoxMoves < boxMoveLimit) { continue; } // Check for duplicates including possible chiral pair. Level chiralLevel = LevelUtils.NormalizeLevel(LevelUtils.GetMirroredLevel(finalLevel)); if (set.Contains(finalLevel) || set.Contains(chiralLevel)) { continue; } set.Add(finalLevel, levelNumber); set.Add(chiralLevel, levelNumber); // Add it the results. LevelInfo info = new LevelInfo(); info.Level = finalLevel; info.Moves = moves; info.Pushes = pushes; info.Changes = changes; info.InsideSquares = finalLevel.InsideSquares; info.MinimumBoxMoves = minBoxMoves; results.Add(info); added++; } if (solved > 0) { Console.WriteLine(); } if (added > 0) { Console.WriteLine("Levels added: {0}", added); } }
static void Main(string[] args) { Log.LogToConsole = true; Log.LogFile = "LevelGenerator.log"; DateTime start = DateTime.Now; string[] loma = { "####|#$.#|#$.#|#$.#|####", "####|#$.#|#.$#|#$.#|####", "###|#.#|#*#|#*#|#$#|###", "###|#.#|#$#|#*#|#$#|#.#|###", "####|#$$#|#$.#|#..#|####", "#####|#?$?#|#.*.#|#?$?#|#####", "#####|#?$?#|#$*.#|#?.?#|#####", "#####|#?*?#|#.?$#|#?*?#|#####", "####|#$*#|#*.#|####", "#####|#$$?#|#$-.#|#?..#|#####", }; Generator generator = new Generator(); Generator.AlgorithmType algorithm = Generator.AlgorithmType.Unspecified; List<Level> designs = new List<Level>(); int i = 0; while (i < args.Length) { string arg = args[i]; i++; string stringValue = i < args.Length ? args[i] : ""; int intValue = AsInteger(stringValue); bool boolValue = intValue != 0; if (arg == "--output-file") { generator.OutputFile = stringValue; i++; continue; } if (arg == "--reject-sokoban-on-target") { generator.RejectSokobanOnTarget = boolValue; i++; continue; } if (arg == "--reject-dead-ends") { generator.RejectDeadEnds = boolValue; i++; continue; } if (arg == "--reject-captured-targets") { generator.RejectCapturedTargets = boolValue; i++; continue; } if (arg == "--reuse-solver") { generator.ReuseSolver = boolValue; i++; continue; } if (arg == "--move-sokoban") { generator.MoveSokoban = boolValue; i++; continue; } if (arg == "--threads") { generator.Threads = intValue; i++; continue; } if (arg == "--min-size") { generator.MinimumSize = intValue; i++; continue; } if (arg == "--box-move-limit") { generator.BoxMoveLimit = intValue; i++; continue; } if (arg == "--boxes") { generator.Boxes = intValue; i++; continue; } if (arg == "--displaced") { generator.Displaced = intValue; i++; continue; } if (arg == "--distance") { generator.Distance = intValue; i++; continue; } if (arg == "--islands") { generator.Islands = intValue; i++; continue; } if (arg == "--max-size") { generator.MaximumSize = intValue; i++; continue; } if (arg == "--seed") { generator.Seed = intValue; i++; continue; } if (arg == "--growth") { generator.Growth = intValue; i++; continue; } if (arg == "--density") { generator.Density = intValue; i++; continue; } if (arg == "--move-limit") { generator.MoveLimit = intValue; i++; continue; } if (arg == "--push-limit") { generator.PushLimit = intValue; i++; continue; } if (arg == "--change-limit") { generator.ChangeLimit = intValue; i++; continue; } if (arg == "--count") { generator.Count = intValue; i++; continue; } if (arg == "--design-string") { try { foreach (string field in stringValue.Split(',')) { Level design = new Level(field); designs.Add(design); } } catch (Exception ex) { Console.WriteLine("Exception parsing design: {0}", ex.Message); Environment.Exit(1); } i++; continue; } if (arg == "--design-file") { LevelSet levelSet = null; try { levelSet = new LevelSet(stringValue); } catch (Exception ex) { Console.WriteLine("Exception loading design file: {0}", ex.Message); Environment.Exit(1); } foreach (Level design in levelSet) { designs.Add(design); } i++; continue; } if (arg == "--loma-design") { int index = intValue; Level design = new Level(loma[index - 1]); designs.Add(design); i++; continue; } if (arg == "--algorithm") { if (stringValue == "none") { algorithm = Generator.AlgorithmType.Unspecified; } else { algorithm |= (Generator.AlgorithmType)Enum.Parse(typeof(Generator.AlgorithmType), stringValue, true); } i++; continue; } if (arg == "--nodes") { generator.Nodes = intValue; i++; continue; } if (arg == "--calculate-deadlocks") { generator.CalculateDeadlocks = boolValue; i++; continue; } if (arg == "--verbose") { generator.Verbose = intValue; i++; continue; } if (arg == "--clear-design") { generator.ClearDesign = boolValue; i++; continue; } if (arg == "--use-entire-level") { generator.UseEntireLevel = boolValue; i++; continue; } Console.WriteLine("unsupported argument: {0}", arg); Environment.Exit(1); } if (algorithm == Generator.AlgorithmType.Unspecified) { algorithm = generator.Algorithm; } if (designs.Count == 0) { designs.Add(new Level("###|# #|###")); } generator.Algorithm = algorithm; generator.Designs = designs; generator.Generate(); DateTime finish = DateTime.Now; Console.WriteLine(String.Format("Generate took {0} seconds.", finish - start)); }
private static void ParseData(JsonData data, List <Section> sectionList) { for (int i = 0; i < data.Count; i++) { Section section = new Section(data[i]["SectionID"].ToString(), data[i]["Title"].ToString(), data[i]["TitleColor"].ToString(), data[i]["FirstSetColor"].ToString(), data[i]["LastSetColor"].ToString(), data[i]["KeyColor"].ToString(), data[i]["BGCoverColor"].ToString(), data[i]["BGCoverColorCurrent"].ToString(), data[i]["TextColor"].ToString(), data[i]["SetTitleColor"].ToString(), data[i]["BGName"].ToString(), data[i]["MapName"].ToString(), data[i]["MapColor"].ToString(), data[i]["MapLockedColor"].ToString(), data[i]["TitleBGColor"].ToString()); JsonData jsonData = data[i]["Sets"]; for (int j = 0; j < jsonData.Count; j++) { LevelSet levelSet = new LevelSet(jsonData[j]["SetID"].ToString(), jsonData[j]["SectionID"].ToString(), jsonData[j]["SetName"].ToString(), jsonData[j]["SetFullName"].ToString(), jsonData[j]["SetColor"].ToString(), jsonData[j]["TitleColor"].ToString(), jsonData[j]["RibbonColor"].ToString(), jsonData[j]["CompletedLevelBGColor"].ToString(), jsonData[j]["CompletedLevelLetterColor"].ToString(), jsonData[j]["CompletedLevelNumberColor"].ToString(), jsonData[j]["NotCompletedLevelBGColor"].ToString(), jsonData[j]["NotCompletedLevelLetterColor"].ToString(), jsonData[j]["NotCompletedLevelNumberColor"].ToString(), jsonData[j]["SelectedLevelBGColor"].ToString(), jsonData[j]["SelectedLevelLetterColor"].ToString(), jsonData[j]["SelectedLevelNumberColor"].ToString(), jsonData[j]["InGameLetterColor"].ToString(), jsonData[j]["InGameCircleColor"].ToString(), jsonData[j]["InGameSelectedLetterColor"].ToString(), jsonData[j]["InGameSelectedLetterBGColor"].ToString(), jsonData[j]["InGameHeaderColor"].ToString(), jsonData[j]["InGameHintColor"].ToString(), jsonData[j]["InGameRibbonColor"].ToString(), jsonData[j]["InGameTileColor"].ToString(), jsonData[j]["BackgroundImage"].ToString(), int.Parse(jsonData[j]["XCoordinate"].ToString()), int.Parse(jsonData[j]["YCoordinate"].ToString()), jsonData[j]["TopText"].ToString(), jsonData[j]["BottomText"].ToString()); JsonData jsonData2 = jsonData[j]["Levels"]; for (int k = 0; k < jsonData2.Count; k++) { Level level = new Level(); level.letters = jsonData2[k]["Letters"].ToString(); level.id = jsonData2[k]["LevelID"].ToString(); level.height = int.Parse(jsonData2[k]["Row"].ToString()); level.width = int.Parse(jsonData2[k]["Column"].ToString()); try { level.otherWords = jsonData2[k]["OtherWords"].ToString().Split(','); } catch (Exception) { } string[] array = jsonData2[k]["Words"].ToString().Split('|'); string[] array2 = array; foreach (string text in array2) { string[] array3 = text.Split(','); Word word = new Word(); word.Y = int.Parse(array3[0]); word.X = int.Parse(array3[1]); word.word = array3[2]; word.length = word.word.Length; word.positions = new Vector3[word.length]; word.letters = new GameObject[word.length]; if (array3[3] == "H" || array3[3] == "BH") { word.orientation = Orientation.HORIZONTAL; if (array3[3] == "BH") { word.bonus = true; } } else if (array3[3] == "V" || array3[3] == "BV") { word.orientation = Orientation.VERTICAL; if (array3[3] == "BV") { word.bonus = true; } } level.words.Add(word); } levelSet.levels.Add(level); } section.sets.Add(levelSet); } if (data[i].Keys.Contains("HiddenSets")) { jsonData = data[i]["HiddenSets"]; for (int m = 0; m < jsonData.Count; m++) { LevelSet levelSet2 = new LevelSet(jsonData[m]["SetID"].ToString(), jsonData[m]["SectionID"].ToString(), jsonData[m]["SetName"].ToString(), jsonData[m]["SetFullName"].ToString(), jsonData[m]["SetColor"].ToString(), jsonData[m]["TitleColor"].ToString(), jsonData[m]["RibbonColor"].ToString(), jsonData[m]["CompletedLevelBGColor"].ToString(), jsonData[m]["CompletedLevelLetterColor"].ToString(), jsonData[m]["CompletedLevelNumberColor"].ToString(), jsonData[m]["NotCompletedLevelBGColor"].ToString(), jsonData[m]["NotCompletedLevelLetterColor"].ToString(), jsonData[m]["NotCompletedLevelNumberColor"].ToString(), jsonData[m]["SelectedLevelBGColor"].ToString(), jsonData[m]["SelectedLevelLetterColor"].ToString(), jsonData[m]["SelectedLevelNumberColor"].ToString(), jsonData[m]["InGameLetterColor"].ToString(), jsonData[m]["InGameCircleColor"].ToString(), jsonData[m]["InGameSelectedLetterColor"].ToString(), jsonData[m]["InGameSelectedLetterBGColor"].ToString(), jsonData[m]["InGameHeaderColor"].ToString(), jsonData[m]["InGameHintColor"].ToString(), jsonData[m]["InGameRibbonColor"].ToString(), jsonData[m]["InGameTileColor"].ToString(), jsonData[m]["BackgroundImage"].ToString(), int.Parse(jsonData[m]["XCoordinate"].ToString()), int.Parse(jsonData[m]["YCoordinate"].ToString()), jsonData[m]["TopText"].ToString(), jsonData[m]["BottomText"].ToString(), jsonData[m]["Price"].ToString()); JsonData jsonData3 = jsonData[m]["Levels"]; for (int n = 0; n < jsonData3.Count; n++) { Level level2 = new Level(); level2.letters = jsonData3[n]["Letters"].ToString(); level2.id = jsonData3[n]["LevelID"].ToString(); level2.height = int.Parse(jsonData3[n]["Row"].ToString()); level2.width = int.Parse(jsonData3[n]["Column"].ToString()); level2.offsetX = int.Parse(jsonData3[n]["ColumnDifference"].ToString()); level2.offsetY = int.Parse(jsonData3[n]["RowDifference"].ToString()); level2.gameID = string.Empty; if (jsonData3[n].Keys.Contains("GameID")) { level2.gameID = jsonData3[n]["GameID"].ToString(); } try { level2.otherWords = jsonData3[n]["OtherWords"].ToString().Split(','); } catch (Exception) { } string[] array4 = jsonData3[n]["Words"].ToString().Split('|'); string[] array5 = array4; foreach (string text2 in array5) { string[] array6 = text2.Split(','); Word word2 = new Word(); word2.Y = int.Parse(array6[0]); word2.X = int.Parse(array6[1]); word2.word = array6[2]; word2.length = word2.word.Length; word2.positions = new Vector3[word2.length]; word2.letters = new GameObject[word2.length]; if (array6[3] == "H" || array6[3] == "BH") { word2.orientation = Orientation.HORIZONTAL; if (array6[3] == "BH") { word2.bonus = true; } } else if (array6[3] == "V" || array6[3] == "BV") { word2.orientation = Orientation.VERTICAL; if (array6[3] == "BV") { word2.bonus = true; } } level2.words.Add(word2); } levelSet2.levels.Add(level2); } section.hiddensets.Add(levelSet2); } } if (section.sets[0].levels.Count > 0) { sectionList.Add(section); } } }
NodeSet ProjectOntoLevset(int jCell, NodeSet Nodes) { int D = Nodes.GetLength(1); int NoOfNodes = Nodes.GetLength(0); var m_Context = this.tracker.GridDat; LevelSet LevSet = (LevelSet)(this.tracker.LevelSets[this.LevelSetIndex]); MultidimensionalArray LevSetValues = MultidimensionalArray.Create(1, NoOfNodes); MultidimensionalArray LevSetGrad = MultidimensionalArray.Create(1, NoOfNodes, D); MultidimensionalArray x0_i_Local = MultidimensionalArray.Create(1, NoOfNodes, D); MultidimensionalArray x0_i_Global = MultidimensionalArray.Create(1, NoOfNodes, D); // quadrature nodes in global coordinates MultidimensionalArray x0_ip1_Local = MultidimensionalArray.Create(1, NoOfNodes, D); MultidimensionalArray x0_ip1_Global = MultidimensionalArray.Create(NoOfNodes, D); // set initial value; x0_i_Local.SetSubArray(Nodes, 0, -1, -1); int NN = NoOfNodes; for (int i = 0; i < 10; i++) { double radiusError = 0; int j = jCell; LevSet.Evaluate(j, 1, Nodes, LevSetValues, 0, 0.0); LevSet.EvaluateGradient(j, 1, Nodes, LevSetGrad); m_Context.TransformLocal2Global(new NodeSet(this.Kref, x0_i_Local.ExtractSubArrayShallow(0, -1, -1)), j, 1, x0_i_Global, 0); for (int nn = 0; nn < NN; nn++) { double sc = 0; for (int d = 0; d < D; d++) { sc += LevSetGrad[0, nn, d].Pow2(); } for (int d = 0; d < D; d++) { double xd = x0_i_Global[0, nn, d] - LevSetGrad[0, nn, d] * LevSetValues[0, nn] / sc; x0_ip1_Global[nn, d] = xd; } radiusError += Math.Abs(LevSetValues[0, nn]); } m_Context.TransformGlobal2Local(x0_ip1_Global, x0_ip1_Local, j, 1, 0); // next iter: x0_i <- x0_{i+1} x0_i_Local.Set(x0_ip1_Local); Nodes = (new NodeSet(this.Kref, x0_i_Local.ExtractSubArrayShallow(0, -1, -1))); } return(Nodes); }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="OpMatrix"></param> /// <param name="OpAffine"></param> /// <param name="RowMapping"></param> /// <param name="ColMapping"></param> /// <param name="CurrentState"></param> /// <param name="AgglomeratedCellLengthScales"></param> /// <param name="time"></param> /// <param name="CutCellQuadOrder"></param> /// <param name="SurfaceForce"></param> /// <param name="LevelSetGradient"></param> /// <param name="ExternalyProvidedCurvature"></param> public void AssembleMatrix <T>(BlockMsrMatrix OpMatrix, double[] OpAffine, UnsetteledCoordinateMapping RowMapping, UnsetteledCoordinateMapping ColMapping, IEnumerable <T> CurrentState, Dictionary <SpeciesId, MultidimensionalArray> AgglomeratedCellLengthScales, double time, int CutCellQuadOrder, VectorField <SinglePhaseField> SurfaceForce, VectorField <SinglePhaseField> LevelSetGradient, SinglePhaseField ExternalyProvidedCurvature, double currentWeissenberg, IEnumerable <T> CoupledCurrentState = null, IEnumerable <T> CoupledParams = null) where T : DGField { // checks: if (ColMapping.BasisS.Count != this.m_XOp.DomainVar.Count) { throw new ArgumentException(); } if (RowMapping.BasisS.Count != this.m_XOp.CodomainVar.Count) { throw new ArgumentException(); } int D = this.LsTrk.GridDat.SpatialDimension; if (CurrentState != null && CurrentState.Count() != (D + 4)) { throw new ArgumentException(); } if (OpMatrix == null && CurrentState == null) { throw new ArgumentException(); } DGField[] U0; if (CurrentState != null) { U0 = CurrentState.Take(D).ToArray(); } else { U0 = null; } DGField[] Stress0; Stress0 = CurrentState.Skip(D + 1).Take(3).ToArray(); if (U0.Count() != D) { throw new ArgumentException("Spatial dimesion and number of velocity parameter components does not match!"); } if (Stress0.Count() != D + 1) { throw new ArgumentException("Spatial dimesion and number of stress parameter components does not match!"); } // advanced settings for the navier slip boundary condition // ======================================================== CellMask SlipArea; switch (this.dntParams.GNBC_Localization) { case NavierSlip_Localization.Bulk: { SlipArea = this.LsTrk.GridDat.BoundaryCells.VolumeMask; break; } case NavierSlip_Localization.ContactLine: { SlipArea = null; break; } case NavierSlip_Localization.Nearband: { SlipArea = this.LsTrk.GridDat.BoundaryCells.VolumeMask.Intersect(this.LsTrk.Regions.GetNearFieldMask(this.LsTrk.NearRegionWidth)); break; } case NavierSlip_Localization.Prescribed: { throw new NotImplementedException(); } default: throw new ArgumentException(); } MultidimensionalArray SlipLengths; SlipLengths = this.LsTrk.GridDat.Cells.h_min.CloneAs(); SlipLengths.Clear(); //SlipLengths.AccConstant(-1.0); if (SlipArea != null) { foreach (Chunk cnk in SlipArea) { for (int i = cnk.i0; i < cnk.JE; i++) { switch (this.dntParams.GNBC_SlipLength) { case NavierSlip_SlipLength.hmin_DG: { int degU = ColMapping.BasisS.ToArray()[0].Degree; SlipLengths[i] = this.LsTrk.GridDat.Cells.h_min[i] / (degU + 1); break; } case NavierSlip_SlipLength.hmin_Grid: { SlipLengths[i] = SlipLengths[i] = this.LsTrk.GridDat.Cells.h_min[i]; break; } case NavierSlip_SlipLength.Prescribed_SlipLength: { SlipLengths[i] = this.physParams.sliplength; break; } case NavierSlip_SlipLength.Prescribed_Beta: { SlipLengths[i] = -1.0; break; } } } } } // parameter assembly // ================== LevelSet Phi = (LevelSet)(this.LsTrk.LevelSets[0]); SpeciesId[] SpcToCompute = AgglomeratedCellLengthScales.Keys.ToArray(); // normals: SinglePhaseField[] Normals; // Normal vectors: length not normalized - will be normalized at each quad node within the flux functions. if (this.NormalsRequired) { if (LevelSetGradient == null) { LevelSetGradient = new VectorField <SinglePhaseField>(D, Phi.Basis, SinglePhaseField.Factory); LevelSetGradient.Gradient(1.0, Phi); } Normals = LevelSetGradient.ToArray(); } else { Normals = new SinglePhaseField[D]; } // curvature: SinglePhaseField Curvature; if (this.CurvatureRequired) { Curvature = ExternalyProvidedCurvature; } else { Curvature = null; } // Velocity and stresses for linearization // linearization velocity: DGField[] U0_U0mean; if (this.U0meanrequired) { XDGBasis U0meanBasis = new XDGBasis(this.LsTrk, 0); VectorField <XDGField> U0mean = new VectorField <XDGField>(D, U0meanBasis, "U0mean_", XDGField.Factory); U0_U0mean = ArrayTools.Cat <DGField>(U0, U0mean); } else { U0_U0mean = new DGField[2 * D]; } if (VelocityXGradient == null) { VelocityXGradient = new VectorField <XDGField>(D, CurrentState.ElementAt(0).Basis, "VelocityX_Gradient", XDGField.Factory); } if (VelocityYGradient == null) { VelocityYGradient = new VectorField <XDGField>(D, CurrentState.ElementAt(1).Basis, "VelocityY_Gradient", XDGField.Factory); } // concatenate everything var Params = ArrayTools.Cat <DGField>( U0_U0mean, VelocityXGradient, VelocityYGradient, Stress0, //artificalViscosity, Normals, Curvature, ((SurfaceForce != null) ? SurfaceForce.ToArray() : new SinglePhaseField[D])); // linearization velocity: if (this.U0meanrequired) { VectorField <XDGField> U0mean = new VectorField <XDGField>(U0_U0mean.Skip(D).Take(D).Select(f => ((XDGField)f)).ToArray()); U0mean.Clear(); if (this.physParams.IncludeConvection) { ComputeAverageU(U0, U0mean, CutCellQuadOrder, LsTrk.GetXDGSpaceMetrics(SpcToCompute, CutCellQuadOrder, 1).XQuadSchemeHelper); } } // assemble the matrix & affine vector // =================================== IDictionary <SpeciesId, MultidimensionalArray> InterfaceLengths = this.LsTrk.GetXDGSpaceMetrics(this.LsTrk.SpeciesIdS.ToArray(), CutCellQuadOrder).CutCellMetrics.InterfaceArea; BitArray EvapMicroRegion = this.LsTrk.GridDat.GetBoundaryCells().GetBitMask(); EvapMicroRegion.SetAll(false); // compute matrix if (OpMatrix != null) { if (!useJacobianForOperatorMatrix) { XSpatialOperatorMk2.XEvaluatorLinear mtxBuilder = this.m_XOp.GetMatrixBuilder(LsTrk, ColMapping, Params, RowMapping, SpcToCompute); this.ParameterUpdate(CurrentState, Params, CutCellQuadOrder, AgglomeratedCellLengthScales); foreach (var kv in AgglomeratedCellLengthScales) { mtxBuilder.SpeciesOperatorCoefficients[kv.Key].CellLengthScales = kv.Value; mtxBuilder.SpeciesOperatorCoefficients[kv.Key].EdgeLengthScales = this.LsTrk.GridDat.Edges.h_max_Edge; mtxBuilder.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("SlipLengths", SlipLengths); mtxBuilder.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("EvapMicroRegion", EvapMicroRegion); } if (this.m_XOp.SurfaceElementOperator.TotalNoOfComponents > 0) { foreach (var kv in InterfaceLengths) { mtxBuilder.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("InterfaceLengths", kv.Value); } } mtxBuilder.time = time; mtxBuilder.ComputeMatrix(OpMatrix, OpAffine); foreach (var kv in AgglomeratedCellLengthScales) { mtxBuilder.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("Weissenbergnumber", currentWeissenberg); } } else { throw new NotImplementedException("The FDbuilder for the Jacobian is missing for the XSpatial Opearator!"); // Finite Difference Linearization //XSpatialOperatorMk2.XEvaluatorLinear FDBuilder = this.m_XOp.GetFDJacobianBuilder(domMap, Params, codMap, this.ParameterUpdate); //foreach (var kv in AgglomeratedCellLengthScales) { // FDbuilder.SpeciesOperatorCoefficients[kv.Key].CellLengthScales = kv.Value; // FDbuilder.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("SlipLengths", SlipLengths); // FDbuilder.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("EvapMicroRegion", EvapMicroRegion); //} //if (this.m_XOp.SurfaceElementOperator.TotalNoOfComponents > 0) { // foreach (var kv in InterfaceLengths) { // FDbuilder.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("InterfaceLengths", kv.Value); // } //} //FDbuilder.time = time; //FDbuilder.ComputeMatrix(OpMatrix, OpAffine); //// FDJacobian has (Mx +b) as RHS, for unsteady calc. we must subtract Mx for real affine Vector! //OpMatrix.SpMV(-1.0, new CoordinateVector(CurrentState), 1.0, OpAffine); //foreach (var kv in AgglomeratedCellLengthScales) { // FDbuilder.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("Weissenbergnumber", currentWeissenberg); //} } } else { XSpatialOperatorMk2.XEvaluatorNonlin eval = this.m_XOp.GetEvaluatorEx(this.LsTrk, CurrentState.ToArray(), Params, RowMapping, SpcToCompute); foreach (var kv in AgglomeratedCellLengthScales) { eval.SpeciesOperatorCoefficients[kv.Key].CellLengthScales = kv.Value; eval.SpeciesOperatorCoefficients[kv.Key].EdgeLengthScales = this.LsTrk.GridDat.Edges.h_max_Edge; eval.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("SlipLengths", SlipLengths); eval.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("EvapMicroRegion", EvapMicroRegion); eval.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("Weissenbergnumber", currentWeissenberg); } if (this.m_XOp.SurfaceElementOperator.TotalNoOfComponents > 0) { foreach (var kv in InterfaceLengths) { eval.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("InterfaceLengths", kv.Value); } } eval.time = time; eval.Evaluate(1.0, 1.0, OpAffine); } }
/// <summary> /// Finds the roots using <see cref="GSL.gsl_poly_complex_solve"/> /// </summary> /// <param name="segment"></param> /// <param name="levelSet"></param> /// <param name="cell"></param> /// <param name="iKref"></param> /// <returns></returns> public double[] GetRoots(LineSegment segment, ILevelSet levelSet, int cell, int iKref) { LevelSet levelSetField = levelSet as LevelSet; if (levelSetField == null) { throw new NotImplementedException("Method currently only works for polynomial level sets"); } int maxNoOfCoefficientsPerDimension = levelSetField.Basis.Degree + 1; int noOfPolynomials = segment.ProjectedPolynomialCoefficients.GetLength(1); double[] coefficients = new double[maxNoOfCoefficientsPerDimension]; for (int i = 0; i < noOfPolynomials; i++) { double dgCoefficient = levelSetField.Coordinates[cell, i]; for (int j = 0; j < maxNoOfCoefficientsPerDimension; j++) { coefficients[j] += dgCoefficient * segment.ProjectedPolynomialCoefficients[iKref, i, j]; } } // Make sure "leading" coefficient (i.e., the last element of the // list of coefficients) is not too small since this will make gsl // crash (or lead to bogus results) int newLength = coefficients.Length; while (newLength > 0 && Math.Abs(coefficients[newLength - 1]) < EPSILON) { newLength--; } if (newLength != coefficients.Length) { coefficients = coefficients.Take(newLength).ToArray(); } // Make sure polynomial is not constant since this will make gsl crash if (newLength < 2) { return(new double[0]); } int maxNoOfRoots = coefficients.Length - 1; double[] roots = new double[2 * maxNoOfRoots]; GCHandle coefficientHandle = GCHandle.Alloc(coefficients, GCHandleType.Pinned); GCHandle rootsHandle = GCHandle.Alloc(roots, GCHandleType.Pinned); IntPtr workSpace = GSL.gsl_poly_complex_workspace_alloc(coefficients.Length); GSL.gsl_poly_complex_solve( coefficientHandle.AddrOfPinnedObject(), coefficients.Length, workSpace, rootsHandle.AddrOfPinnedObject()); GSL.gsl_poly_complex_workspace_free(workSpace); coefficientHandle.Free(); rootsHandle.Free(); List <double> realRoots = new List <double>(levelSetField.Basis.Degree); for (int i = 0; i < maxNoOfRoots; i++) { double realPart = roots[2 * i]; double imaginaryPart = roots[2 * i + 1]; // Exclude |$realPart| == 1.0 since it doesn't matter if (imaginaryPart == 0.0 && Math.Abs(realPart) <= 1.0 - EPSILON) { realRoots.Add(realPart); } } return(realRoots.OrderBy(d => d).ToArray()); }
public void AfterGameFadeIn(LevelSet currentSet) { StartCoroutine(AfterGameFadeInThread(currentSet)); }
/// <summary> /// Uses a safe-guarded Newton method to find all roots on /// <paramref name="segment"/> /// </summary> /// <param name="segment"></param> /// <param name="levelSet"></param> /// <param name="cell"></param> /// <param name="iKref"></param> /// <returns></returns> public double[] GetRoots(LineSegment segment, ILevelSet levelSet, int cell, int iKref) { LevelSet levelSetField = levelSet as LevelSet; if (levelSetField == null) { throw new NotImplementedException("Method currently only works for polynomial level sets"); } int maxNoOfCoefficientsPerDimension = levelSetField.Basis.Degree + 1; int noOfPolynomials = segment.ProjectedPolynomialCoefficients.GetLength(1); double[] coefficients = new double[maxNoOfCoefficientsPerDimension]; for (int i = 0; i < noOfPolynomials; i++) { double dgCoefficient = levelSetField.Coordinates[cell, i]; for (int j = 0; j < maxNoOfCoefficientsPerDimension; j++) { coefficients[j] += dgCoefficient * segment.ProjectedPolynomialCoefficients[iKref, i, j]; } } //if(coefficients.L2NormPow2() < this.Tolerance) { // // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // special case : // // the zero-level-set is probably parallel to this line segment // // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // return new double[] { -1.0, 1.0 }; //} double[] roots; unsafe { fixed(double *pCoeff = &coefficients[coefficients.Length - 1]) { double xLow = -1.0; double xHigh = 1.0; int NO_OF_BRACKETS = 8; List <double> lowerBounds = new List <double>(); List <double> upperBounds = new List <double>(); double dx2 = 2.0 / NO_OF_BRACKETS; double x = xLow; double fOld = Eval(x, pCoeff, coefficients.Length); for (int i = 0; i < NO_OF_BRACKETS; i++) { x += dx2; double fNew = Eval(x, pCoeff, coefficients.Length); if (i == 0 && fOld.Abs() < Tolerance) { lowerBounds.Add(x - dx2); upperBounds.Add(x); fOld = fNew; continue; } else { if (fNew.Abs() < Tolerance) { lowerBounds.Add(x - dx2); upperBounds.Add(x); x += dx2; fOld = Eval(x, pCoeff, coefficients.Length); continue; } } if (fNew * fOld <= 0.0) { lowerBounds.Add(x - dx2); upperBounds.Add(x); } fOld = fNew; } // Actual Newton-Raphson int MAX_ITERATIONS = 50; roots = new double[lowerBounds.Count]; for (int j = 0; j < lowerBounds.Count; j++) { xLow = lowerBounds[j]; xHigh = upperBounds[j]; double fLeft = Eval(xLow, pCoeff, coefficients.Length); double fRight = Eval(xHigh, pCoeff, coefficients.Length); if (fLeft.Abs() < Tolerance) { roots[j] = xLow; break; } if (fRight.Abs() < Tolerance) { roots[j] = xHigh; break; } if (fLeft.Sign() == fRight.Sign()) { throw new Exception(); } if (fLeft > 0.0) { xLow = upperBounds[j]; xHigh = lowerBounds[j]; } double root = 0.5 * (xLow + xHigh); double f; double df; Eval(root, pCoeff, coefficients.Length, out f, out df); double dxOld = (xHigh - xLow).Abs(); double dx = dxOld; int i = 0; while (true) { if (i > MAX_ITERATIONS) { throw new Exception("Max iterations exceeded"); } double a = ((root - xHigh) * df - f) * ((root - xLow) * df - f); if (a > 0.0 || 2.0 * Math.Abs(f) > Math.Abs(dxOld * df)) { // Newton out of range or too slow -> Bisect dxOld = dx; dx = 0.5 * (xHigh - xLow); root = xLow + dx; } else { // Take Newton step dxOld = dx; dx = -f / df; //// Convergence acceleration according to Yao2014 //double fDelta = Eval(root + dx, pCoeff, coefficients.Length); //dx = -(f + fDelta) / df; root += dx; } Eval(root, pCoeff, coefficients.Length, out f, out df); if (Math.Abs(f) <= Tolerance) { roots[j] = root; break; } if (f < 0.0) { xLow = root; } else { xHigh = root; } i++; } } } } return(roots); }
/// <summary> /// still a hack... /// </summary> static object InstantiateFromAttribute(FieldInfo f, InstantiateFromControlFileAttribute at, Type type, ICollection <DGField> IOFields, ICollection <DGField> RegisteredFields, //AppControl ctrl, IDictionary <string, FieldOpts> FieldOptions, IGridData ctx, LevelSetTracker lstrk) { // create instance // =============== object member_value = null; Type HistoryType = null; Type VectorType = null; Type ComponentType = null; GetTypes(f, out HistoryType, out VectorType, out ComponentType); if (VectorType != null) { // vector field branch // +++++++++++++++++++ if (at.m_IsScalarField) { throw new ApplicationException("illegal use of 'InstantiateFromControlFileAttribute' (with Scalar Declaration) on a Vector class"); } int D = ctx.SpatialDimension; string[] cName = at.GetControlFileNames(f, D); string[] iName = at.GetInCodeIdentifications(f, D); // determine DG polynomial degree of basis int[] Deg = new int[D]; for (int d = 0; d < D; d++) { Deg[d] = GetDegree(cName[d], iName[d], FieldOptions); } if (at.m_DegreesMustBeEqual) { int deg0 = Deg[0]; for (int d = 1; d < D; d++) { if (Deg[d] != deg0) { StringWriter errMsg = new StringWriter(); errMsg.Write("DG Polynomial degree of fields {"); for (int dd = 0; dd < D; dd++) { errMsg.Write(cName[dd]); if (dd < D - 1) { errMsg.Write(", "); } } errMsg.Write("} must be equal, but found {"); for (int dd = 0; dd < D; dd++) { errMsg.Write(Deg[dd]); if (dd < D - 1) { errMsg.Write(", "); } } errMsg.Write("} in control file."); throw new ApplicationException(errMsg.ToString()); } } } // create instance: components SinglePhaseField[] fld = new SinglePhaseField[D]; XDGField[] xfld = new XDGField[D]; DGField[] _fld = new DGField[D]; for (int d = 0; d < D; d++) { if (ComponentType == typeof(SinglePhaseField)) { fld[d] = new SinglePhaseField(new Basis(ctx, Deg[d]), iName[d]); _fld[d] = fld[d]; } else if (ComponentType == typeof(XDGField)) { xfld[d] = new XDGField(new XDGBasis(lstrk, Deg[d]), iName[d]); _fld[d] = xfld[d]; fld = null; } else { throw new NotSupportedException("unknown type."); } RegisteredFields.Add(_fld[d]); } // create instance: Vector-Field container var ci = VectorType.GetConstructor(new Type[] { ComponentType.MakeArrayType() }); member_value = ci.Invoke(new object[] { (fld != null) ? ((object)fld) : ((object)xfld) }); //member_value = ci.Invoke( new object[] { ((object)fld) }); // io for (int d = 0; d < D; d++) { AddToIO(iName[d], _fld[d], FieldOptions, IOFields, at); } } else { // scalar field branch // +++++++++++++++++++ if (at.m_IsVectorField) { throw new ApplicationException("illegal use of 'InstantiateFromControlFileAttribute' (with Vector Declaration) on a Non-Vector class"); } // identification string cName = at.GetControlFileName(f); string iName = at.GetInCodeIdentification(f); // create basis int Deg = GetDegree(cName, iName, FieldOptions); Basis b = new Basis(ctx, Deg); // create instance DGField fld = null; if (ComponentType == typeof(SinglePhaseField)) { fld = new SinglePhaseField(b, iName); } else if (ComponentType == typeof(LevelSet)) { fld = new LevelSet(b, iName); } else if (ComponentType == typeof(XDGField)) { fld = new XDGField(new XDGBasis(lstrk, Deg), iName); } else { throw new NotImplementedException(); } RegisteredFields.Add(fld); AddToIO(iName, fld, FieldOptions, IOFields, at); member_value = fld; } // History, if desired if (HistoryType != null) { member_value = (HistoryType.GetConstructors()[0]).Invoke(new object[] { member_value }); } return(member_value); }
public MainWindow(MainWindow other) { InitializeComponent(); Initialize(); this.customLevel = other.customLevel; this.levelSet = other.levelSet; if (this.customLevel) { SetCustomLevel(other.originalLevel, other.level); } else { this.currentLevelNumber = other.currentLevelNumber; SetLevel(levelSet[currentLevelNumber], new PlayingLevel(other.Level)); } RefreshLevel(); }
public void CreateLevels(LevelSet set) { curSet = set; title.text = set.SetFullName; title.color = FugoUtils.HexToColor(set.TitleColor); ribbon.color = FugoUtils.HexToColor(set.RibbonColor); bg.sprite = Resources.Load <Sprite>("BGImages/" + set.bgImage); FugoUtils.ChangeAlpha(ribbon, 0f); FugoUtils.ChangeAlpha(title, 0f); FugoUtils.ChangeAlpha(levelsBG.GetComponent <Image>(), 0f); FugoUtils.ChangeAlpha(bg, 0f); bigLevel.localScale = Vector3.zero; List <int> hiddenLevelsInSet = FugoUtils.GetHiddenLevelsInSet(set); CreateEmptyLevels(hiddenLevelsInSet); IEnumerator enumerator = levelHolder.GetEnumerator(); try { while (enumerator.MoveNext()) { Transform level = (Transform)enumerator.Current; SetHiddenSetProperties(level, "locked", set); } } finally { IDisposable disposable; if ((disposable = (enumerator as IDisposable)) != null) { disposable.Dispose(); } } int hiddenLevel = PlayerPrefsManager.GetHiddenLevel(int.Parse(set.SetID)); int num = 0; for (int i = 0; i < hiddenLevelsInSet.Count; i++) { num += hiddenLevelsInSet[i]; if (num >= hiddenLevel) { currentSet = levelHolder.GetChild(i); break; } } int num2 = 0; int num3 = 1; IEnumerator enumerator2 = levelHolder.GetEnumerator(); try { while (enumerator2.MoveNext()) { Transform transform = (Transform)enumerator2.Current; if (transform == currentSet) { SetHiddenSetProperties(transform, "current", set); CreateEmptyBigStars(bigLevel, currentSet.Find("StarHolder").childCount); bigLevel.Find("LevelText").GetComponent <Text>().text = currentSet.Find("LevelText").GetComponent <Text>().text; StartCoroutine(AnimateCurrentLevel(transform, 0.5f)); break; } num3 += hiddenLevelsInSet[num2]; SetHiddenSetProperties(transform, "completed", set); num2++; } } finally { IDisposable disposable2; if ((disposable2 = (enumerator2 as IDisposable)) != null) { disposable2.Dispose(); } } PaintAllChilds(bigLevel.Find("StarHolder"), FugoUtils.HexToColor(set.NotCompletedLevelBGColor)); bigLevel.Find("LevelText").GetComponent <Text>().color = FugoUtils.HexToColor(set.SelectedLevelNumberColor); bigLevel.GetComponent <Image>().color = FugoUtils.HexToColor(set.SelectedLevelBGColor); curLevelInGame = hiddenLevel - num3 + 1; for (int j = 0; j < hiddenLevel - num3; j++) { if (bigLevel.Find("StarHolder").childCount > j) { bigLevel.Find("StarHolder").GetChild(j).GetComponent <Image>() .color = FugoUtils.HexToColor(set.CompletedLevelBGColor); } } panel.gameObject.SetActive(value: true); StartCoroutine(AnimateSetScreen()); if (currentSet == null) { CreateEmptyBigStars(bigLevel, hiddenLevelsInSet[hiddenLevelsInSet.Count - 1]); bigLevel.Find("LevelText").GetComponent <Text>().text = hiddenLevelsInSet.Count.ToString(); PaintAllChilds(bigLevel.Find("StarHolder"), FugoUtils.HexToColor(set.CompletedLevelBGColor)); } }
private void LoadLevelSet(string filename) { try { using (TextReader reader = File.OpenText(filename)) { levelSet = new LevelSet(reader); } SelectLevel(0); } catch (Exception ex) { MessageBox.Show(String.Format("Exception loading level set: {0}", ex.Message)); } }
public LineSegment[] GetReferenceLineSegments() { Stack <Simplex> simplexHierarchy = new Stack <Simplex>(); Simplex currentSimplex = Simplex; int spatialDimension = Simplex.SpatialDimension; int n = 0; while (currentSimplex.GetType() != lineSimplex.GetType()) { if (n > MAX_SIMPLEX_LEVELS) { throw new ApplicationException("Something went terribly wrong. Please contact Björn"); } simplexHierarchy.Push(currentSimplex); currentSimplex = currentSimplex.EdgeSimplex; n++; } MultidimensionalArray vertexCoordinates = MultidimensionalArray.Create(2, 1); vertexCoordinates[0, 0] = -1.0; vertexCoordinates[1, 0] = 1.0; while (simplexHierarchy.Count > 0) { currentSimplex = simplexHierarchy.Pop(); int noOfVertices = vertexCoordinates.GetLength(0); int D = currentSimplex.SpatialDimension; MultidimensionalArray volumeCoordinates = MultidimensionalArray.Create( noOfVertices * currentSimplex.NoOfEdges, currentSimplex.SpatialDimension); for (int e = 0; e < currentSimplex.NoOfEdges; e++) { MultidimensionalArray coordinates = MultidimensionalArray.Create(noOfVertices, D); currentSimplex.EdgeToVolumeCoordinates(e, vertexCoordinates, coordinates); for (int i = 0; i < noOfVertices; i++) { for (int d = 0; d < D; d++) { volumeCoordinates[e * noOfVertices + i, d] = coordinates[i, d]; } } } vertexCoordinates = volumeCoordinates; } Debug.Assert( vertexCoordinates.GetLength(0) % 2 == 0, "Even number of vertices expected"); int initialNumberOfLineSegments = vertexCoordinates.GetLength(0) / 2; List <LineSegment> lineSegments = new List <LineSegment>(initialNumberOfLineSegments); for (int i = 0; i < initialNumberOfLineSegments; i++) { LineSegment newSegment = new LineSegment(spatialDimension, RootFindingAlgorithm); for (int d = 0; d < spatialDimension; d++) { newSegment.Start[d] = vertexCoordinates[2 * i + 0, d]; newSegment.End[d] = vertexCoordinates[2 * i + 1, d]; } if (!lineSegments.Contains(newSegment)) { lineSegments.Add(newSegment); tracker.Subscribe(newSegment); } } foreach (LineSegment segment in lineSegments) { LevelSet levelSetField = tracker.LevelSets[levSetIndex] as LevelSet; if (levelSetField != null) { segment.ProjectBasisPolynomials(levelSetField.Basis); } } return(lineSegments.ToArray()); }
private void LoadLevelSet(byte[] buffer) { using (MemoryStream stream = new MemoryStream(buffer)) { using (TextReader reader = new StreamReader(stream)) { levelSet = new LevelSet(reader); } } SelectLevel(0); }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="OpMatrix"></param> /// <param name="OpAffine"></param> /// <param name="RowMapping"></param> /// <param name="ColMapping"></param> /// <param name="CurrentState"></param> /// <param name="AgglomeratedCellLengthScales"></param> /// <param name="time"></param> /// <param name="CutCellQuadOrder"></param> /// <param name="SurfaceForce"></param> /// <param name="LevelSetGradient"></param> /// <param name="ExternalyProvidedCurvature"></param> public void AssembleMatrix <T>(BlockMsrMatrix OpMatrix, double[] OpAffine, UnsetteledCoordinateMapping RowMapping, UnsetteledCoordinateMapping ColMapping, IEnumerable <T> CurrentState, Dictionary <SpeciesId, MultidimensionalArray> AgglomeratedCellLengthScales, double time, int CutCellQuadOrder, VectorField <SinglePhaseField> SurfaceForce, VectorField <SinglePhaseField> LevelSetGradient, SinglePhaseField ExternalyProvidedCurvature, IEnumerable <T> CoupledCurrentState = null, IEnumerable <T> CoupledParams = null) where T : DGField { // checks: if (ColMapping.BasisS.Count != this.m_XOp.DomainVar.Count) { throw new ArgumentException(); } if (RowMapping.BasisS.Count != this.m_XOp.CodomainVar.Count) { throw new ArgumentException(); } int D = this.LsTrk.GridDat.SpatialDimension; if (CurrentState != null && CurrentState.Count() != (D + 1)) { throw new ArgumentException(); } if (OpMatrix == null && CurrentState == null) { throw new ArgumentException(); } DGField[] U0; if (CurrentState != null) { U0 = CurrentState.Take(D).ToArray(); } else { U0 = null; } // advanced settings for the navier slip boundary condition // ======================================================== CellMask SlipArea; switch (this.dntParams.GNBC_Localization) { case NavierSlip_Localization.Bulk: { SlipArea = this.LsTrk.GridDat.BoundaryCells.VolumeMask; break; } case NavierSlip_Localization.ContactLine: { SlipArea = null; break; } case NavierSlip_Localization.Nearband: { SlipArea = this.LsTrk.GridDat.BoundaryCells.VolumeMask.Intersect(this.LsTrk.Regions.GetNearFieldMask(this.LsTrk.NearRegionWidth)); break; } case NavierSlip_Localization.Prescribed: { throw new NotImplementedException(); } default: throw new ArgumentException(); } MultidimensionalArray SlipLengths; SlipLengths = this.LsTrk.GridDat.Cells.h_min.CloneAs(); SlipLengths.Clear(); //SlipLengths.AccConstant(-1.0); if (SlipArea != null) { foreach (Chunk cnk in SlipArea) { for (int i = cnk.i0; i < cnk.JE; i++) { switch (this.dntParams.GNBC_SlipLength) { case NavierSlip_SlipLength.hmin_DG: { int degU = ColMapping.BasisS.ToArray()[0].Degree; SlipLengths[i] = this.LsTrk.GridDat.Cells.h_min[i] / (degU + 1); break; } case NavierSlip_SlipLength.hmin_Grid: { SlipLengths[i] = SlipLengths[i] = this.LsTrk.GridDat.Cells.h_min[i]; break; } case NavierSlip_SlipLength.Prescribed_SlipLength: { SlipLengths[i] = this.physParams.sliplength; break; } case NavierSlip_SlipLength.Prescribed_Beta: { SlipLengths[i] = -1.0; break; } } } } } // parameter assembly // ================== LevelSet Phi = (LevelSet)(this.LsTrk.LevelSets[0]); SpeciesId[] SpcToCompute = AgglomeratedCellLengthScales.Keys.ToArray(); // normals: SinglePhaseField[] Normals; // Normal vectors: length not normalized - will be normalized at each quad node within the flux functions. if (this.NormalsRequired) { if (LevelSetGradient == null) { LevelSetGradient = new VectorField <SinglePhaseField>(D, Phi.Basis, SinglePhaseField.Factory); LevelSetGradient.Gradient(1.0, Phi); } Normals = LevelSetGradient.ToArray(); } else { Normals = new SinglePhaseField[D]; } // curvature: SinglePhaseField Curvature; if (this.CurvatureRequired) { Curvature = ExternalyProvidedCurvature; } else { Curvature = null; } // linearization velocity: DGField[] U0_U0mean; if (this.U0meanrequired) { XDGBasis U0meanBasis = new XDGBasis(this.LsTrk, 0); VectorField <XDGField> U0mean = new VectorField <XDGField>(D, U0meanBasis, "U0mean_", XDGField.Factory); U0_U0mean = ArrayTools.Cat <DGField>(U0, U0mean); } else { U0_U0mean = new DGField[2 * D]; } // Temperature gradient for evaporation VectorField <DGField> GradTemp = new VectorField <DGField>(D, new XDGBasis(LsTrk, 0), XDGField.Factory); if (CoupledCurrentState != null) { DGField Temp = CoupledCurrentState.ToArray()[0]; GradTemp = new VectorField <DGField>(D, Temp.Basis, "GradTemp", XDGField.Factory); XNSEUtils.ComputeGradientForParam(Temp, GradTemp, this.LsTrk); } // concatenate everything var Params = ArrayTools.Cat <DGField>( U0_U0mean, Curvature, ((SurfaceForce != null) ? SurfaceForce.ToArray() : new SinglePhaseField[D]), Normals, ((CoupledCurrentState != null) ? GradTemp.ToArray() : new SinglePhaseField[D]), ((CoupledCurrentState != null) ? CoupledCurrentState.ToArray <DGField>() : new SinglePhaseField[1]), ((CoupledCurrentState != null) ? CoupledParams.ToArray <DGField>() : new SinglePhaseField[1])); //((evaporation) ? GradTemp.ToArray() : new SinglePhaseField[D])); // linearization velocity: if (this.U0meanrequired) { VectorField <XDGField> U0mean = new VectorField <XDGField>(U0_U0mean.Skip(D).Take(D).Select(f => ((XDGField)f)).ToArray()); U0mean.Clear(); if (this.physParams.IncludeConvection) { ComputeAverageU(U0, U0mean, CutCellQuadOrder, LsTrk.GetXDGSpaceMetrics(SpcToCompute, CutCellQuadOrder, 1).XQuadSchemeHelper); } } // assemble the matrix & affine vector // =================================== IDictionary <SpeciesId, MultidimensionalArray> InterfaceLengths = this.LsTrk.GetXDGSpaceMetrics(this.LsTrk.SpeciesIdS.ToArray(), CutCellQuadOrder).CutCellMetrics.InterfaceArea; // compute matrix if (OpMatrix != null) { XSpatialOperatorMk2.XEvaluatorLinear mtxBuilder = this.m_XOp.GetMatrixBuilder(LsTrk, ColMapping, Params, RowMapping, SpcToCompute); foreach (var kv in AgglomeratedCellLengthScales) { mtxBuilder.SpeciesOperatorCoefficients[kv.Key].CellLengthScales = kv.Value; mtxBuilder.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("SlipLengths", SlipLengths); } if (this.m_XOp.SurfaceElementOperator.TotalNoOfComponents > 0) { foreach (var kv in InterfaceLengths) { mtxBuilder.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("InterfaceLengths", kv.Value); } } mtxBuilder.time = time; mtxBuilder.ComputeMatrix(OpMatrix, OpAffine); } else { XSpatialOperatorMk2.XEvaluatorNonlin eval = this.m_XOp.GetEvaluatorEx(this.LsTrk, CurrentState.ToArray(), Params, RowMapping, SpcToCompute); foreach (var kv in AgglomeratedCellLengthScales) { eval.SpeciesOperatorCoefficients[kv.Key].CellLengthScales = kv.Value; eval.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("SlipLengths", SlipLengths); } if (this.m_XOp.SurfaceElementOperator.TotalNoOfComponents > 0) { foreach (var kv in InterfaceLengths) { eval.SpeciesOperatorCoefficients[kv.Key].UserDefinedValues.Add("InterfaceLengths", kv.Value); } } eval.time = time; eval.Evaluate(1.0, 1.0, OpAffine); } }
private void tempStart() { int num = 0; if (daily) { DateTime now = DateTime.Now; section = Games.dailyPuzzles; set = section.sets[now.Month - 1]; game = set.levels[now.Day - 1]; game.mode = GameMode.DAILY; } else { num = ((levelToOpen != -1) ? levelToOpen : PlayerPrefsManager.GetLevel()); int[] levelInfo = FugoUtils.getLevelInfo(num); if (mode == GameMode.ADVENTURE) { section = Games.GetSection(adventureSectionId); set = section.getHiddenSet(adventureSetId); UnityEngine.Debug.Log(adventureGameId + " " + adventureSetId + " " + adventureSectionId); Adventure adventure = Games.adventure = new Adventure(section, set, set.getLevelsWithID(adventureGameId)); if (slidePos == 0) { Games.adventure.curPos = 0; } else { Games.adventure.curPos = slidePos - 1; } game = Games.adventure.Levels[Games.adventure.curPos]; game.setId = int.Parse(adventureSetId); game.mode = GameMode.ADVENTURE; UnityEngine.Debug.Log(game.part); if (game.adventure.Width == -1) { calculateSize(); } } else { section = Games.sections[levelInfo[0]]; set = section.sets[levelInfo[1]]; game = set.levels[levelInfo[2]]; } UnityEngine.Debug.Log("game name " + UISwapper.flipGame); name.gameObject.SetActive(value: true); } string path = "BGImages/" + set.bgImage; game.set = set; background.sprite = Resources.Load <Sprite>(path); background.gameObject.SetActive(value: true); newGame(game); if (UISwapper.flipGame) { StartCoroutine(ArabicText.fixAllNextFrame()); } name.color = HeaderColor; Color headerColor = HeaderColor; headerColor.a = 0f; name.color = headerColor; }
private IBMFieldSet(IGridData gridData, CNSControl config, IBMFieldSet template) : base(gridData, config, template) { LevelSet = template.LevelSet.CloneAs(); }
public void ReInitialize(LevelSet LS = null, SubGrid Restriction = null) { ReInitializeWithOutput(LS, Restriction); }
public void ProcessLevel(string filename, int index) { Log.DebugPrint("Processing level {0} in file {1}", index + 1, filename); LevelSet levelSet = new LevelSet(filename); ProcessLevel(levelSet[index], index); }
/// <summary> /// Gathers the line segments bounding <see cref="RefElement"/> in /// reference coordinates. /// </summary> /// <returns> /// An array of line segments /// <list type="bullet"> /// <item>1st index: Edge index</item> /// <item>2nd index: Edge of edge index</item> /// </list> /// </returns> /// <remarks> /// Each line segment will appear twice in the result, since it is /// stored for each edge separately. However, this method ensures that /// corresponding segments are represented by the same object (reference /// equality) which ensures that this does not affect performance. /// </remarks> private LineSegment[,] GetReferenceLineSegments() { int D = lsData.GridDat.SpatialDimension; int noOfEdges = lsData.GridDat.Grid.RefElements[0].NoOfFaces; int noOfEdgesOfEdge = RefElement.FaceRefElement.NoOfFaces; MultidimensionalArray edgeOfEdgeVertices = MultidimensionalArray.Create(2, 1); edgeOfEdgeVertices[0, 0] = -1.0; edgeOfEdgeVertices[1, 0] = 1.0; MultidimensionalArray edgeVertices = MultidimensionalArray.Create( edgeOfEdgeVertices.GetLength(0), RefElement.FaceRefElement.SpatialDimension); MultidimensionalArray volumeVertices = MultidimensionalArray.Create( edgeVertices.GetLength(0), D); // Remember encountered segments so that $lineSegments contains no // duplicates and roots can be cached efficiently Dictionary <LineSegment, LineSegment> seenSegments = new Dictionary <LineSegment, LineSegment>( noOfEdges * noOfEdgesOfEdge / 2); LineSegment[,] lineSegments = new LineSegment[noOfEdges, noOfEdgesOfEdge]; LevelSet levelSetField = lsData.LevelSet as LevelSet; for (int ee = 0; ee < noOfEdgesOfEdge; ee++) { RefElement.FaceRefElement.TransformFaceCoordinates(ee, edgeOfEdgeVertices, edgeVertices); for (int e = 0; e < noOfEdges; e++) { lsData.GridDat.Grid.RefElements[0].TransformFaceCoordinates( e, edgeVertices, volumeVertices); double[] start = new double[D]; double[] end = new double[D]; for (int d = 0; d < D; d++) { start[d] = volumeVertices[0, d]; end[d] = volumeVertices[1, d]; } LineSegment newSegment = new LineSegment(D, this.RefElement, start, end, rootFindingAlgorithm: RootFindingAlgorithm); // Assert that the segment does not already exist LineSegment segment; if (!seenSegments.TryGetValue(newSegment, out segment)) { segment = newSegment; seenSegments.Add(segment, segment); if (levelSetField != null) { segment.ProjectBasisPolynomials(levelSetField.Basis); } //tracker.Subscribe(segment); } lineSegments[e, ee] = segment; } } return(lineSegments); }
/// <summary> /// Load Level and start animators /// </summary> /// <param name="gWin">Main game window object</param> /// <param name="levelFileName">Name of XML-File with level layout</param> /// <returns></returns> public static LevelSet StartLevel(GameWindow gWin, string levelFileName) { LevelSet Level = null; SpriteObject.AnimatedByDefault = false; string LevelPath = Helper.DataLocalPath + @"\" + levelFileName; //GC.Collect(); //GC.WaitForPendingFinalizers(); ThisLevel.ClearLevel(gWin.MainGFX); ThisLevel = LevelSet.LoadLevel(LevelPath); ThisLevel.BuildLevel(gWin.MainGFX); GWin = gWin; GUIAni = new GUIAnimator(gfx: gWin.MainGFX, lvl: ThisLevel, timingSrc: TimingSource.Sources.CompositionTargetRendering, pgJumpRes: gWin.pgJumpResource); Player = gWin.MainGFX.FindObject("Player") as CarObject; if (Player == null) { ErrorMsg("No 'Player' object defined!"); return Level; } // Particle Systems do not start by AnimatedByDefault = true // therefore call property setter ThisLevel.AnimatedAllSprites = true; Scroller = new SmoothGameScroller(Player, gWin.MainGFX, gWin.GameWrapper); return Level; }
private void Load(LevelSet level) { currentLevel = level; enemyGenerator.loadEnemies(level.GetEnemies()); backgroundGenerator.loadBackgrounds(level.GetBackgrounds()); }