public Creature() { genome = new GenomeTree(); startPosition = new Vector3(); creatureStructure = genome.Generate(startPosition); }
// Use this for initialization void Awake() { dependencyLines = new Dictionary<GameObject, VectorLine>(); planet = null; structure = null; neighbors = new List<Structure>(); }
public Structure(Structure TargetCopy) { Type = TargetCopy.Type; Name = TargetCopy.Name; Description = TargetCopy.Description; CostTime = TargetCopy.CostTime; CostFuel = TargetCopy.CostFuel; CostMetal = TargetCopy.CostMetal; CostOrganic = TargetCopy.CostOrganic; CostTime = TargetCopy.CostTime; StructureLimit = TargetCopy.StructureLimit; BonusStructures = TargetCopy.BonusStructures; BonusFuel = TargetCopy.BonusFuel; BonusMetal = TargetCopy.BonusMetal; BonusCrystal = TargetCopy.BonusCrystal; BonusOrganic = TargetCopy.BonusOrganic; ModifierBuildTime = TargetCopy.ModifierBuildTime; ModifierFuel = TargetCopy.ModifierFuel; ModifierMetal = TargetCopy.ModifierMetal; ModifierOrganic = TargetCopy.ModifierOrganic; RequiredStructures = new List<string> (TargetCopy.RequiredStructures); RestrictedEnvironments = new List<Planet.PlanetType> (TargetCopy.RestrictedEnvironments); }
public LinkStructureToParentCommand(Viking.UI.Controls.SectionViewerControl parent, Structure structure, Location_CanvasViewModel location) : base(parent) { this.putativeStruct = structure; this.putativeLoc = location; StructureType LocType = this.putativeStruct.Type; if (LocType != null) { linecolor = new Microsoft.Xna.Framework.Color(LocType.Color.R, LocType.Color.G, LocType.Color.B, 128); } else { linecolor = Microsoft.Xna.Framework.Color.Green; } //Transform the location position to the correct coordinates transformedPos = parent.SectionToVolume(new GridVector2(putativeLoc.X, putativeLoc.Y)); parent.Cursor = Cursors.Cross; }
/** * Default constsructor for custom fields. * @param field An array of field parameters (package, type, name, array/size, value) * @param filename The name of the file in which the field is defined */ public Field(Structure structure, string filename, string[] field) : base(filename, field[0]) { this.typename = field[1]; this.type = TypeID(field[1]); this.element = null; this.structure = structure; if (field[3] == null) { this.array = -1; } else if (field[3].Length == 0) { this.array = 0; } else { this.array = Int32.Parse(field[3]); } this.field_value = field[4]; Name = field[2]; // TODO: Default value functionality not yet implemented! // DefaultValue = fi.value; }
public ConfigBuilder(string pattern, Structure structure, ConfigBuilt builtEvent) { _pattern = pattern; _builtEvent = builtEvent; _structure = structure; SimpleBuild = false; }
public static bool TryQueryStructure( Structure term, PrologContext context, out ELNode foundNode, out ELNodeEnumerator enumerator) { // // Dispatch based on the functor and arity. // // Handle root queries, i.e. /Key if (term.IsFunctor(Symbol.Slash, 1)) return TryRootQuery(term, context, out foundNode, out enumerator); if (!IsELTerm(term)) throw new Exception("Malformed EL query: " + ISOPrologWriter.WriteToString(term)); if (term.IsFunctor(SBindNodeOperator, 2)) { var variableToBind = term.Argument(1) as LogicVariable; if (variableToBind == null) throw new ArgumentException("RHS of >> must be an uninstantiated variable: "+ ISOPrologWriter.WriteToString(term.Argument(1))); foundNode = null; return TryNodeBindingQuery(out enumerator, term.Argument(0), variableToBind, context); } return TryChildQuery( out foundNode, out enumerator, term.Argument(0), term.Argument(1), term.Functor == Symbol.Colon, context); }
public void AddType(Structure type) { // Find the previous group. ScopeMember oldMember = FindMember(type.GetName()); if(oldMember != null) { if(!oldMember.IsTypeGroup()) throw new ModuleException("expected type group."); // Find the previous definition. TypeGroup oldGroup = (TypeGroup)oldMember; if(oldGroup.Find(type.GetGenericPrototype()) != null) throw new ModuleException("matching type already exists."); // Add the type into the group. oldGroup.Insert(type); } else { // Create a new type group. TypeGroup newGroup = new TypeGroup(type.GetName(), this); newGroup.Insert(type); AddMember(newGroup); } }
private void FUNCTIONAL(Structure tp, string termname, int options) { if ((options & NUMBERVARS) != 0 && USDVAR(termname) && __ARITY(tp) == 1) { int varno; Object tp2; tp2 = __LASTARG(tp, 1); tp2 = Term.Deref(tp2); if (tp2 is int) { varno = (int) tp2; if (lastitem == IDENTIFIER_ITEM) PUTCHAR(' '); PUTCHAR((char)(varno%26 + 'A')); if ((varno = varno/26) != 0) { LowLevelWrite(varno); } lastitem = IDENTIFIER_ITEM; return; } } showname(termname, options); PUTSOLO('('); for (int i = 1; i < __ARITY(tp); i++) { recwriteterm(__ARG(tp, i), options, 1000, 1201); PUTSOLO(','); } if (__ARITY(tp)>0) recwriteterm(__LASTARG(tp, __ARITY(tp)), options, 1000, 1201); PUTSOLO(')'); }
public StructureInstance(Structure template, GenericInstance instance, ScopeMember factory, ChelaModule module) : base(module) { this.factory = factory; Initialize(template, instance); }
/// <summary> /// Draw lines and colors related to dependency. /// </summary> public void DrawDependencyInfo(Planet planet, Structure structure) { this.planet = planet; this.structure = structure; List<Structure> neighbors = planet.GetNeigboringStructures(transform.position); this.neighbors = neighbors; bool isValid = false; ClearDependencyLines(); foreach(Structure neighbor in neighbors) { if(structure.CheckRequirements(neighbor.GetOutput())) { UpdateDependencyLine(neighbor.gameObject); isValid = true; } else ClearDependencyLine(neighbor.gameObject); } if(isValid) renderer.material.color = Color.green; else { renderer.material.color = Color.red; } }
/// <summary> /// Calculates the slice area inside of a contour definition for a given slice Z /// </summary> private static double GetSliceArea(Image image, int sliceZ, Structure psoas) { var area = double.NaN; var contour = psoas.GetContoursOnImagePlane(sliceZ); if (contour.Count() > 0) { var inside = 0; for (int x = 0; x < image.XSize; x++) { for (int y = 0; y < image.XSize; y++) { var dx = (x * image.XRes * image.XDirection + image.Origin).x; var dy = (y * image.YRes * image.YDirection + image.Origin).y; var dz = (sliceZ * image.ZRes * image.ZDirection + image.Origin).z; if (psoas.IsPointInsideSegment(new VVector(dx, dy, dz))) { inside++; } } } var vxArea = image.XRes / 10 * image.YRes / 10; var contourArea = inside * vxArea; area = contourArea; } return area; }
private void btnGo_Click(object sender, EventArgs e) { int StructureNumber; try { StructureNumber = this.numStructure.IntValue; } catch(FormatException ) { return; } StructureObj structure = Store.Structures.GetObjectByID((long)StructureNumber); if (structure == null) { MessageBox.Show(this, "No structure found with that ID", "Error", MessageBoxButtons.OK); return; } Structure structView = new Structure(structure); structView.ShowProperties(); this.Close(); }
public void GenerateFromGenome(WheelGene gene,Structure parent) { //var wg:WheelGenome; //if( genome.WheelGenomes.Length > genome.wheelPositions.Length) { // var newWheelPositions = new Vector3[genome.WheelGenomes.Length]; // for (var k = 0; k<genome.wheelPositions.Length; k++) { // newWheelPositions[k] = genome.wheelPositions[k]; // } // for (var j = k; j<newWheelPositions.Length; j++) { // newWheelPositions[j] = genome.randomVector3(); // } // genome.wheelPositions = newWheelPositions; // //} // // for(var i=0; i<genome.WheelGenomes.Length; i++) { // wg = genome.WheelGenomes[i]; // GameObject wheel = Utilities.loadObject(wg.wheelType,position + genome.wheelPositions[i]*structuralDistance,false); // wheel.transform.Rotate(wg.initialAngle); // ConfigurableJoint joint = gaController.j.createJoint(wheel,cartbase,Vector3(0,0,0),Vector3(1,0,0)); // joint.angularYMotion=ConfigurableJointMotion.Free; // joint.targetAngularVelocity=Vector3(0,5,0); // joint.angularYZDrive.mode=JointDriveMode.Velocity; // thiscart.components[i] = wheel; // } }
public bool CanBuyStructure(Structure struc) { bool tmpCanBuy = true; foreach(Cost cst in struc.costs) if(GM.resourceManager.GetResource (cst.resource).amount < (cst.amount * struc.costMultiplier) + (struc.amount * cst.scaling)) tmpCanBuy = false; return tmpCanBuy; }
protected override void OnShowObject(object Object) { this.Obj = Object as Structure; Debug.Assert(this.Obj != null); this.checkVerified.Checked = this.Obj.Verified; this.numConfidence.Value = System.Convert.ToDecimal(this.Obj.Confidence); }
public void KillStructure() { Structure structure = new Structure(500, new Vector3(0, 0, 0)); structure.Kill(); // Structure isn't alive anymore Assert.AreEqual<bool>(false, structure.Alive); }
protected override void OnShowObject(object Object) { this.Obj = Object as Structure; Debug.Assert(this.Obj != null); if(null != this.Obj.Notes) this.textNotes.Text = this.Obj.Notes; }
public CreateNewStructureCommand(Viking.UI.Controls.SectionViewerControl parent, Structure structure, Location_CanvasViewModel location) : base(parent) { this.newStruct = structure; this.newLoc = location; }
public override void InitStructure() { structure = new Structure(prefab); structure.gameObject.transform.parent = this.gameObject.transform; structure.Color(RandomColor()); structure.Scale(options.size); Position(options.position); }
public override void LinkHue(Structure hue) { base.LinkHue(hue); Networking.RpcUpdateShieldHue(Hue); if (Hues.Count == 1) CurrentHue = Hue; }
/// <summary> /// Creates a map of slice position z to area of the structure on that slice. Used for finding the correct slice to sample /// </summary> private static Dictionary<int, double> GetSliceAreas(Image image, Structure s) { Dictionary<int, double> slices = new Dictionary<int, double>(); for (int z = 0; z < image.ZSize; z++) { var contourArea = GetSliceArea(image, z, s); slices.Add(z, contourArea); } return slices; }
//DragDropItem Events void OnDragStart() { currentPlanet = Game.gui.planetMenu.planet.GetComponent<Planet>(); isBeingDragged = true; GameObject marker = GameObject.Instantiate(dragBehavior.prefab) as GameObject; currentPlacingStructure = marker.GetComponent<Structure>(); //We need to turn off the collider during dragging, otherwise it can intercept NGUI drop events if(marker.collider != null) marker.collider.enabled = false; }
public CsStructure(Structure structure, PropertyDictionary options) { _structure = structure; _options = options; if (_options.HasStringFor("surrogate-for") && !_options.HasValueFor("surrogate-for-is-reference-type")) { throw new LanguageException("Any use of \"surrogate-for\" must be accompanied with \"surrogate-for-is-reference-type\"."); } }
public static void WriteRss(Structure.RssFeed value, Stream destination) { var xsn = new XmlSerializerNamespaces(); xsn.Add("atom", "http://www.w3.org/2005/Atom"); xsn.Add("dc", "http://purl.org/dc/elements/1.1/"); xsn.Add("content", "http://purl.org/rss/1.0/modules/content/"); var ser = new XmlSerializer(value.GetType()); ser.Serialize(destination, value, xsn); }
public static Structure GetRecordingWindow(String name) { Process[] processes = Process.GetProcessesByName("Mobizen"); Structure ws = new Structure(); foreach (Process p in processes) { Point position = new Point(400, 300); ws.mainWindow = p.MainWindowHandle; EnumWindows(delegate(IntPtr wnd, IntPtr param) { if (GetWindow(wnd, 4) == ws.mainWindow) { EnumWindowsProc wcp = delegate(IntPtr w, IntPtr x) { return true; }; if (EnumChildWindows(wnd, wcp, IntPtr.Zero)) { ws.messageWindow = wnd; return false; } } return true; }, IntPtr.Zero); EnumChildWindows(ws.messageWindow, delegate(IntPtr wnd, IntPtr param) { if (ws.contentWindow == null) { ws.contentWindow = wnd; ws.position = new RECT(); GetWindowRect(wnd, ref ws.position); return true; } RECT current = new RECT(); GetWindowRect(wnd, ref current); int bestTotal = (ws.position.Right - ws.position.Left) * (ws.position.Bottom - ws.position.Top); int currentTotal = (current.Right - current.Left) * (current.Bottom - current.Top); int windowWidth = current.Right - current.Left; int windowHeight = current.Bottom - current.Top; if (currentTotal > bestTotal && windowWidth > windowHeight && (GetWindowLong(wnd, GWL_STYLE) & WS_VISIBLE) > 0) { ws.contentWindow = wnd; ws.position = current; } return true; }, IntPtr.Zero); } return ws; }
public void StructureCreation() { Structure structure = new Structure(500, new Vector3(1, 0, 2)); // Structure has correct health Assert.AreEqual<int>(500, structure.Health.Amount); // Structure is alive Assert.AreEqual<bool>(true, structure.Alive); // Structure has the correct position Assert.AreEqual<Vector3>(new Vector3(1, 0, 2), structure.Position); }
public void AddStructure(Structure OP, bool updateImmediately) { if (!OpExists(OP.Location)) { _structures.Add(OP.Location, OP); if (!_changedThisTick.ContainsKey(OP.Location)) _changedThisTick.Add(OP.Location, OP); else { _changedThisTick[OP.Location] = OP; } } }
protected override BooleanValue SendMessage(Structure content) { if (!Connected) { return false; } processor.Send(content); return true; }
public static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, ref Structure.SECURITY_ATTRIBUTES lpProcessAttributes, ref Structure.SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref Structure.STARTUPINFO lpStartupInfo, out Structure.PROCESS_INFORMATION lpProcessInformation);
// Generate test structure // - Loads all scenes and gets data from test lists // - Reorganises for menu layout IEnumerator GenerateStructure() { yield return(null); // TODO - Remove testStructure = new Structure(); // Create new test structure instance List <TestType> typeList = GenerateTypeListAndInstances(); // Generate type list and create instances ProjectSettings projectSettings = SuiteManager.GetProjectSettings(); // Get the suite list if (projectSettings == null) // If no suite list found { StopAllCoroutines(); // Abort } for (int su = 0; su < projectSettings.suiteList.Count; su++) // Iterate suites on suite list { Suite newSuite = new Suite(); // Create new suite instance newSuite.suiteName = projectSettings.suiteList[su].suiteName; // Set suite name from suite list newSuite.types = CloneTestTypeList(typeList); // Clone the type list RenderPipelineAsset pipeline = projectSettings.suiteList[su].defaultRenderPipeline; newSuite.suitePipeline = Common.GetRenderPipelineName(pipeline); for (int gr = 0; gr < projectSettings.suiteList[su].groups.Count; gr++) // Iterate groups { RenderPipelineAsset grpPipeline = projectSettings.suiteList[su].groups[gr].renderPipelineOverride; for (int te = 0; te < projectSettings.suiteList[su].groups[gr].tests.Count; te++) // Iterate tests { GraphicsTestFramework.Test test = projectSettings.suiteList[su].groups[gr].tests[te]; // Get test if (Common.IsTestApplicable(test)) { int[] types = TestTypeManager.Instance.GetTypeSelectionFromBitMask(test.testTypes); // Get type array from test's bitmask for (int ty = 0; ty < types.Length; ty++) // Iterate types of the test { Group newGroup = FindDuplicateGroupInType(newSuite, types[ty], projectSettings.suiteList[su].groups[gr].groupName); // Find duplicate groups in the type if (newGroup == null) // If not found { newGroup = new Group(); // Create a new group instance newGroup.groupName = projectSettings.suiteList[su].groups[gr].groupName; // Set group name if (grpPipeline != null) { newGroup.groupPipeline = Common.GetRenderPipelineName(grpPipeline); // Set the group pipeline name } FindDuplicateTypeInSuite(newSuite, types[ty]).groups.Add(newGroup); // Add the group to the type } Test newTest = new Test(); // Create new test instance string[] pathSplit = projectSettings.suiteList[su].groups[gr].tests[te].scenePath.Split('/'); // Split path for scene name newTest.testName = pathSplit[pathSplit.Length - 1].Replace(".unity", "");; // Set test name newTest.scenePath = projectSettings.suiteList[su].groups[gr].tests[te].scenePath; // Set scene path newGroup.tests.Add(newTest); // Add test to scene } } } } for (int ty = 0; ty < newSuite.types.Count; ty++) // Iterate types { if (newSuite.types[ty].groups.Count == 0) // If empty { newSuite.types.RemoveAt(ty); // Remove it } } newSuite.types.TrimExcess(); // Trim the types list testStructure.suites.Add(newSuite); // Add to suites list } m_IsGenerated = true; // Set generated Console.Instance.Write(DebugLevel.Logic, MessageLevel.Log, "TestStructure finished generating"); // Write to console ProgressScreen.Instance.SetState(false, ProgressType.LocalLoad, ""); // Disable ProgressScreen }
public IEnumerator GenerateAnalyticStructure(ResultsIOData[] resultsA, ResultsIOData[] resultsB) { yield return(null); testStructure = new Structure(); // Create new test structure instance List <TestType> typeList = GenerateTypeListAndInstances(); // Generate type list and create instances int groupColumn = Common.FindResultsDataIOFieldIdByName(resultsA[0], "GroupName"); // Get group column ID if (groupColumn == -1) // If error return { Console.Instance.Write(DebugLevel.Critical, MessageLevel.LogError, "GroupName ID not found"); // Debug } int testColumn = Common.FindResultsDataIOFieldIdByName(resultsA[0], "TestName"); // Get test column ID if (testColumn == -1) // If error return { Console.Instance.Write(DebugLevel.Critical, MessageLevel.LogError, "TestName ID not found"); // Debug } for (int i = 0; i < resultsA.Length; i++) { Debug.LogWarning(resultsA[i].testType); string suiteName = resultsA[i].suite; Suite suite = FindDuplicateSuiteInStructure(suiteName); if (suite == null) { suite = new Suite(); // Create new suite instance suite.suiteName = suiteName; // Set suite name suite.types = CloneTestTypeList(typeList); // Clone the type list testStructure.suites.Add(suite); // Add to suites list } //iterate through all the tests in ResultsIOData.Rows for (int row = 0; row < resultsA[i].resultsRow.Count; row++) { string groupName = resultsA[i].resultsRow[row].resultsColumn[groupColumn]; // Get group name int typeIndex = TestTypeManager.Instance.GetTestTypeIndexFromName(resultsA[i].testType); // Get type index if (typeIndex == -1) // If error return { Console.Instance.Write(DebugLevel.Critical, MessageLevel.LogError, "TestType ID not found"); // Debug } Group group = FindDuplicateGroupInType(suite, typeIndex, groupName); if (group == null) { group = new Group(); // Create new group instance group.groupName = groupName; // Set group name suite.types[typeIndex].groups.Add(group); // Add to groups list } string testName = resultsA[i].resultsRow[row].resultsColumn[testColumn]; // Get test name TestResults test = new TestResults(); // Create new TestResults test.testName = testName; // Set test name //create resultsIOdata for this single row ResultsIOData riodA = new ResultsIOData(); riodA.suite = resultsA[i].suite; riodA.testType = resultsA[i].testType; riodA.baseline = resultsA[i].baseline; riodA.fieldNames = resultsA[i].fieldNames; riodA.resultsRow.Add(resultsA[i].resultsRow[row]); test.dataA = riodA; // Set results data A if (resultsB != null) // If analytic comparison { ResultsIOData riodB = new ResultsIOData(); riodB.suite = resultsB[i].suite; riodB.testType = resultsB[i].testType; riodB.baseline = resultsB[i].baseline; riodB.fieldNames = resultsB[i].fieldNames; riodB.resultsRow.Add(resultsB[i].resultsRow[row]); test.dataB = riodB; // Set results data B } else { ResultsIOData riodB = new ResultsIOData(); riodB.suite = resultsA[i].suite; riodB.testType = resultsA[i].testType; riodB.baseline = true; //resultsA[i].baseline; // TODO - Should be true riodB.fieldNames = resultsA[i].fieldNames; riodB.resultsRow.Add(resultsA[i].resultsRow[row]); test.dataB = riodB; // Set results data A } group.tests.Add(test); // Add to group } } // Reiterate suites to remove empty type entries for (int i = 0; i < testStructure.suites.Count; i++) { for (int ty = 0; ty < testStructure.suites[i].types.Count; ty++) // Iterate types { if (testStructure.suites[i].types[ty].groups.Count == 0) // If empty { testStructure.suites[i].types.RemoveAt(ty); // Remove it } } testStructure.suites[i].types.TrimExcess(); // Trim the types list } Console.Instance.Write(DebugLevel.Logic, MessageLevel.Log, "AnalyticTestStructure finished generating"); // Write to console if (resultsB == null) // If analytic { Menu.Instance.GenerateTestRunner(RunnerType.Analytic); // Generate anyaltic test runner } else // If analytic comparison { Menu.Instance.GenerateTestRunner(RunnerType.AnalyticComparison); } }
public LockTunnel(Structure parentStructure) : base(parentStructure) { CreateStandardTerminals(Direction.Input, 1u, 1u, PFTypes.Void); }
/// <summary> /// Informs character of the specified event. Does not copy the eventDescription. /// </summary> /// <param name="eventDescription">A Prolog term describing the event. /// WARNING: does not copy the term, so it must either be ground or not used elsewhere.</param> public void QueueEvent(Structure eventDescription) { eventQueue.Enqueue((Structure)Term.CopyInstantiation(eventDescription)); }
public static void BuildStructure(World world, Vector3Int startPos, Structure structure) { structures[(int)structure].Build(world, startPos); }
public void AddStructure(Structure s) { if (s.surfaceRect != SurfaceRect.full) { FORCED_GetExtension().AddStructure(s); if (s.placeInCenter) { mainStructure = s; mainStructureIsABlocker = false; } return; } else { if (extension != null) { extension.Annihilate(PlaneAnnihilationOrder.ExtensionRemovedByFullScaledStructure); extension = null; } if (mainStructure != null) { if (!mainStructureIsABlocker) { mainStructure.Annihilate(StructureAnnihilationOrder.GetReplacingOrder(mainStructure.isArtificial)); } else { mainStructure.SectionDeleted(pos); } } mainStructure = s; mainStructureIsABlocker = false; var t = s.transform; t.parent = host.GetBlock().myChunk.transform; if (!(s.IsIPlanable())) { t.rotation = Quaternion.Euler(GetEulerRotationForQuad()); } if (!(s is Hotel)) { t.position = GetCenterPosition(); } else //костыль { switch (faceIndex) { case Block.FWD_FACE_INDEX: case Block.RIGHT_FACE_INDEX: case Block.LEFT_FACE_INDEX: case Block.BACK_FACE_INDEX: t.position = GetCenterPosition() + GetLookVector() * 0.5f * Block.QUAD_SIZE + Vector3.down * 0.5f * Block.QUAD_SIZE; break; case Block.DOWN_FACE_INDEX: t.position = GetCenterPosition() + GetLookVector() * Block.QUAD_SIZE; break; default: t.position = GetCenterPosition(); break; } } mainStructure.SetVisibility(visibilityMode, true); } }
public Tuple <List <CollisionCheckViewModel>, Model3DGroup> GetCollisionSummary(PlanningItemViewModel planningItem) { var waitWindowCollision = new WaitWindowCollision(); waitWindowCollision.Show(); var calculator = new CollisionSummariesCalculator(); var collimatorModelGroup = new Model3DGroup(); var isoModelGroup = new Model3DGroup(); var modelGroup = new Model3DGroup(); upDir = new Vector3D(0, -1, 0); lookDir = new Vector3D(0, 0, 1); isoctr = new Point3D(0, 0, 0); //just to initalize cameraPosition = new Point3D(0, 0, -3500); var CollisionSummaries = new List <CollisionCheckViewModel>(); // Create some materials var redMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Red)); var darkblueMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.DarkBlue)); var collimatorMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Green)); Structure bodyStruct; var iso3DMesh = calculator.CalculateIsoMesh(isoctr); MeshGeometry3D bodyMesh = null; MeshGeometry3D couchMesh = null; if (planningItem.PlanningItemObject is PlanSetup) { PlanSetup planSetup = (PlanSetup)planningItem.PlanningItemObject; bodyStruct = planSetup.StructureSet.Structures.Where(x => x.Id.Contains("BODY")).First(); bodyMesh = bodyStruct.MeshGeometry; foreach (Structure structure in planSetup.StructureSet.Structures) { if (structure.StructureCodeInfos.FirstOrDefault().Code != null) { if (structure.StructureCodeInfos.FirstOrDefault().Code == "Support") { Structure couchStruct = structure; couchMesh = couchStruct.MeshGeometry; } } } foreach (Beam beam in planSetup.Beams) { isoctr = calculator.GetIsocenter(beam); iso3DMesh = calculator.CalculateIsoMesh(calculator.GetIsocenter(beam)); bool view = true; if (planSetup.TreatmentOrientation.ToString() == "HeadFirstProne") { upDir = new Vector3D(0, 1, 0); } bool isArc = false; bool isElectron = false; bool isSRSCone = false; collimatorMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Green)); if (beam.IsSetupField == true) { continue; } if (beam.Name.Contains("Subfield 2") || beam.Name.Contains("Subfield 3")) { continue; } if (beam.EnergyModeDisplayName.Contains("E")) { isElectron = true; } if (beam.EnergyModeDisplayName.Contains("SRS")) { isSRSCone = true; } if (beam.Technique.Id.Contains("ARC")) { isArc = true; collimatorMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.GreenYellow)); } foreach (Structure structure in planSetup.StructureSet.Structures) { if (structure.Id.Contains("CouchSurface") == true) { Structure couchStruct = planSetup.StructureSet.Structures.Where(x => x.Id.Contains("CouchSurface")).First(); couchMesh = couchStruct.MeshGeometry; } } MeshGeometry3D collimatorMesh = calculator.CalculateCollimatorMesh(planSetup, beam, isoctr, isArc, isElectron, isSRSCone); string shortestDistanceBody = "2000000"; string shortestDistanceTable = "2000000"; string status = "Clear"; shortestDistanceBody = calculator.ShortestDistance(collimatorMesh, bodyMesh); if (couchMesh != null) { shortestDistanceTable = calculator.ShortestDistance(collimatorMesh, couchMesh); } else { shortestDistanceTable = " - "; status = " - "; } Console.WriteLine(beam.Id + " - gantry to body is " + shortestDistanceBody + " cm"); Console.WriteLine(beam.Id + " - gantry to table is " + shortestDistanceTable + " cm"); if (shortestDistanceTable != " - ") { if ((Convert.ToDouble(shortestDistanceBody) < 3.0) || (Convert.ToDouble(shortestDistanceTable) < 3.0)) { collimatorMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Red)); status = "Collision"; } } collimatorModelGroup.Children.Add(new GeometryModel3D { Geometry = collimatorMesh, Material = collimatorMaterial, BackMaterial = darkblueMaterial }); isoModelGroup.Children.Add(new GeometryModel3D { Geometry = iso3DMesh, Material = redMaterial, BackMaterial = redMaterial }); var collisionSummary = calculator.GetFieldCollisionSummary(beam, view, shortestDistanceBody, shortestDistanceTable, status); CollisionSummaries.Add(collisionSummary); } } modelGroup = CreateModel(bodyMesh, couchMesh, isoModelGroup, collimatorModelGroup, collimatorMaterial); waitWindowCollision.Close(); return(Tuple.Create(CollisionSummaries, modelGroup)); }
public StructureDlg(Structure s) { this.InitializeComponent(); this.fStructure = s; this.NameBox.Text = this.fStructure.Name; }
/// <summary> /// Return true if the value given is allowed for the field given. This uses the hints from the GUI /// system to decide what is and isn't allowed. (For example if a GUI slider goes from 10 to 20 at /// increments of 2, then a value of 17 is not something you could achieve in the GUI, being only able /// to go from 16 to 18 skipping over 17, and therefore this routine would return false for trying to /// set it to 17). /// <br/><br/> /// Note that the value passed in may be altered (which is why it's ref) when it's not /// exactly legal, but it's CLOSE ENOUGH to be coerced into a legal value. For example, /// you set a slider to 10.45 and the slider only allows values on the 0.5 marks like 10, 10.5, 11. etc. /// Rather than deny the attempt, the value will be nudged to the nearest legal value. /// </summary> /// <param name="field">Which KSPField is being checked?</param> /// <param name="newVal">What is the value it's being set to? It is possible to /// alter the value to an acceptable replacement which is why it passes by ref</param> /// <param name="except">An exception you can choose to throw if you want, or null if the value is legal.</param> /// <returns>Is it legal?</returns> private bool IsLegalValue(BaseField field, ref Structure newVal, out KOSException except) { except = null; bool isLegal = true; Type fType = field.FieldInfo.FieldType; object convertedVal = newVal; // Using TryGetFieldUIControl() to obtain the control that goes with this // field is from advice from TriggerAU, who gave that advice in // a forum post when I described the problems we were having with the servo // parts in Breaking Ground DLC. (There is some kind of work being done here // that seems to allow one field's ranges to override another's as the servo // parts need to do. This is work which doesn't seem to happen if you look at // the KSPField's control ranges directly): UI_Control control; if (!partModule.Fields.TryGetFieldUIControl(field.name, out control)) { throw new KOSInvalidFieldValueException("Field appears to have no UI control attached so kOS refuses to let a script change it."); } if (!control.controlEnabled) { except = new KOSInvalidFieldValueException("Field is read-only"); return false; } if (!newVal.GetType().IsSubclassOf(fType)) { try { convertedVal = Convert.ChangeType(newVal, fType); } catch (InvalidCastException) { except = new KOSCastException(newVal.GetType(), fType); return false; } catch (FormatException) { except = new KOSCastException(newVal.GetType(), fType); return false; } } // Some of these are subclasses of each other, so don't change this to an if/else. // It's a series of if's on purpose so it checks all classes the control is derived from. if (control is UI_Toggle) { // Seems there's nothing to check here, but maybe later there will be? } if (control is UI_Label) { except = new KOSInvalidFieldValueException("Labels are read-only objects that can't be changed"); isLegal = false; } var vector2 = control as UI_Vector2; if (vector2 != null) { // I have no clue what this actually looks like in the UI? What is a // user editable 2-D vector widget? I've never seen this before. if (convertedVal != null) { var vec2 = (Vector2)convertedVal; if (vec2.x < vector2.minValueX || vec2.x > vector2.maxValueX || vec2.y < vector2.minValueY || vec2.y > vector2.maxValueY) { except = new KOSInvalidFieldValueException("Vector2 is outside of allowed range of values"); isLegal = false; } } } var range = control as UI_FloatRange; if (range != null) { float val = Convert.ToSingle(convertedVal); val = KOSMath.ClampToIndent(val, range.minValue, range.maxValue, range.stepIncrement); convertedVal = Convert.ToDouble(val); } newVal = FromPrimitiveWithAssert(convertedVal); return isLegal; }
private Guid GetTargetGuid(Structure target) { var api = RemoteTechHook.Instance; if (target is StringValue) { string targetString = target.ToString(); if (targetString.Equals(NoTargetString, StringComparison.InvariantCultureIgnoreCase)) { return(api.GetNoTargetGuid()); } else if (targetString.Equals(ActiveVesselString, StringComparison.InvariantCultureIgnoreCase)) { return(api.GetActiveVesselGuid()); } else { IEnumerable <string> groundStations = api.GetGroundStations(); foreach (var groundStation in groundStations) { if (targetString.Equals(groundStation)) { return(api.GetGroundStationGuid(groundStation)); } } var body = FlightGlobals.Bodies.Where(b => b.bodyName.Equals(targetString, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (body != null) { return(api.GetCelestialBodyGuid(body)); } else { var vessel = FlightGlobals.Vessels.FirstOrDefault(v => v.vesselName.Equals(targetString, StringComparison.InvariantCultureIgnoreCase)); if (vessel != null) { if (partModule.vessel.id.Equals(vessel.id)) { throw new KOSInvalidFieldValueException("Current vessel can't be the target"); } return(vessel.id); } } } } else if (target is BodyTarget) { BodyTarget targetBody = (BodyTarget)target; return(api.GetCelestialBodyGuid(targetBody.Body)); } else if (target is VesselTarget) { VesselTarget targetVessel = (VesselTarget)target; if (partModule.vessel.id.Equals(targetVessel.Vessel.id)) { throw new KOSInvalidFieldValueException("Current vessel can't be the target"); } return(targetVessel.Vessel.id); } throw new KOSInvalidFieldValueException("Acceptable values are: \"" + NoTargetString + "\", \"" + ActiveVesselString + "\", name of a ground station, name of a body, name of a vessel, Body, Vessel"); }
private bool OnBusMessage(Bus bus, Message msg) { switch (msg.Type) { case MessageType.Eos: StopIterating(); Close(false); OnEventChanged(PlayerEvent.EndOfStream); OnEos(); break; case MessageType.StateChanged: if (msg.Src == playbin) { State old_state, new_state, pending_state; msg.ParseStateChanged(out old_state, out new_state, out pending_state); HandleStateChange(old_state, new_state, pending_state); } break; case MessageType.Buffering: int buffer_percent = msg.ParseBuffering(); HandleBuffering(buffer_percent); break; case MessageType.Tag: TagList tag_list = msg.ParseTag(); tag_list.Foreach(HandleTag); break; case MessageType.Error: GLib.GException err; string debug; msg.ParseError(out err, out debug); HandleError(err); break; case MessageType.Element: if (Gst.PbUtils.Global.IsMissingPluginMessage(msg)) { string detail = Gst.PbUtils.Global.MissingPluginMessageGetInstallerDetail(msg); if (detail == null) { return(false); } if (missing_details.Contains(detail)) { Log.DebugFormat("Ignoring missing element details, already prompted ('{0}')", detail); return(false); } Log.DebugFormat("Saving missing element details ('{0}')", detail); missing_details.Add(detail); Log.Error("Missing GStreamer Plugin", Gst.PbUtils.Global.MissingPluginMessageGetDescription(msg), true); InstallPluginsContext install_context = new InstallPluginsContext(); Gst.PbUtils.Global.InstallPluginsAsync(missing_details.ToArray(), install_context, OnInstallPluginsReturn); } else if (NavigationAdapter.MessageGetType(msg) == NavigationMessageType.CommandsChanged) { dvd_manager.HandleCommandsChanged(playbin); } break; case MessageType.StreamStart: HandleStreamStart(); break; case MessageType.Application: string name; Structure s = msg.Structure; name = s.Name; if (String.IsNullOrEmpty(name) && name == "stream-changed") { video_manager.ParseStreamInfo(); } break; } return(true); }
public override void Update(float deltaTime, Camera cam) { if (nodes.Count == 0) { return; } Character user = item.ParentInventory?.Owner as Character; removeNodeDelay = (user?.SelectedConstruction == null) ? removeNodeDelay - deltaTime : 0.5f; Submarine sub = item.Submarine; if (connections[0] != null && connections[0].Item.Submarine != null) { sub = connections[0].Item.Submarine; } if (connections[1] != null && connections[1].Item.Submarine != null) { sub = connections[1].Item.Submarine; } if (Screen.Selected != GameMain.SubEditorScreen) { //cannot run wires from sub to another if (item.Submarine != sub && sub != null && item.Submarine != null) { ClearConnections(); return; } if (item.CurrentHull == null) { Structure attachTarget = Structure.GetAttachTarget(item.WorldPosition); canPlaceNode = attachTarget != null; sub = sub ?? attachTarget?.Submarine; Vector2 attachPos = GetAttachPosition(user); newNodePos = sub == null ? attachPos : attachPos - sub.Position - sub.HiddenSubPosition; } else { newNodePos = GetAttachPosition(user); if (sub != null) { newNodePos -= sub.HiddenSubPosition; } canPlaceNode = true; } //prevent the wire from extending too far when rewiring if (nodes.Count > 0) { if (user == null) { return; } Vector2 prevNodePos = nodes[nodes.Count - 1]; if (sub != null) { prevNodePos += sub.HiddenSubPosition; } float currLength = 0.0f; for (int i = 0; i < nodes.Count - 1; i++) { currLength += Vector2.Distance(nodes[i], nodes[i + 1]); } currLength += Vector2.Distance(nodes[nodes.Count - 1], newNodePos); if (currLength > MaxLength) { Vector2 diff = nodes[nodes.Count - 1] - newNodePos; Vector2 pullBackDir = diff == Vector2.Zero ? Vector2.Zero : Vector2.Normalize(diff); user.AnimController.Collider.ApplyForce(pullBackDir * user.Mass * 50.0f, maxVelocity: NetConfig.MaxPhysicsBodyVelocity); user.AnimController.UpdateUseItem(true, user.WorldPosition + pullBackDir * 200.0f); if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer) { if (currLength > MaxLength * 1.5f) { ClearConnections(); #if SERVER CreateNetworkEvent(); #endif return; } } } } } else { #if CLIENT bool disableGrid = SubEditorScreen.IsSubEditor() && PlayerInput.IsShiftDown(); newNodePos = disableGrid ? item.Position : RoundNode(item.Position); #else newNodePos = RoundNode(item.Position); #endif if (sub != null) { newNodePos -= sub.HiddenSubPosition; } canPlaceNode = true; } if (item != null) { Vector2 relativeNodePos = newNodePos - item.Position; if (sub != null) { relativeNodePos += sub.HiddenSubPosition; } sectionExtents = new Vector2( Math.Max(Math.Abs(relativeNodePos.X), sectionExtents.X), Math.Max(Math.Abs(relativeNodePos.Y), sectionExtents.Y)); } }
public bool Connect(Connection newConnection, bool addNode = true, bool sendNetworkEvent = false) { for (int i = 0; i < 2; i++) { if (connections[i] == newConnection) { return(false); } } if (!connections.Any(c => c == null)) { return(false); } for (int i = 0; i < 2; i++) { if (connections[i] != null && connections[i].Item == newConnection.Item) { addNode = false; break; } } if (item.body != null) { item.Submarine = newConnection.Item.Submarine; } newConnection.ConnectionPanel.DisconnectedWires.Remove(this); for (int i = 0; i < 2; i++) { if (connections[i] != null) { continue; } connections[i] = newConnection; FixNodeEnds(); if (!addNode) { break; } Submarine refSub = newConnection.Item.Submarine; if (refSub == null) { Structure attachTarget = Structure.GetAttachTarget(newConnection.Item.WorldPosition); if (attachTarget == null) { continue; } refSub = attachTarget.Submarine; } Vector2 nodePos = refSub == null ? newConnection.Item.Position : newConnection.Item.Position - refSub.HiddenSubPosition; if (nodes.Count > 0 && nodes[0] == nodePos) { break; } if (nodes.Count > 1 && nodes[nodes.Count - 1] == nodePos) { break; } //make sure we place the node at the correct end of the wire (the end that's closest to the new node pos) int newNodeIndex = 0; if (nodes.Count > 1) { if (Vector2.DistanceSquared(nodes[nodes.Count - 1], nodePos) < Vector2.DistanceSquared(nodes[0], nodePos)) { newNodeIndex = nodes.Count; } } if (newNodeIndex == 0 && nodes.Count > 1) { nodes.Insert(0, nodePos); } else { nodes.Add(nodePos); } break; } SetConnectedDirty(); if (connections[0] != null && connections[1] != null) { foreach (ItemComponent ic in item.Components) { if (ic == this) { continue; } ic.Drop(null); } if (item.Container != null) { item.Container.RemoveContained(this.item); } if (item.body != null) { item.body.Enabled = false; } IsActive = false; CleanNodes(); } if (item.body != null) { item.Submarine = newConnection.Item.Submarine; } if (sendNetworkEvent) { #if SERVER if (GameMain.Server != null) { CreateNetworkEvent(); } #endif //the wire is active if only one end has been connected IsActive = connections[0] == null ^ connections[1] == null; } Drawable = IsActive || nodes.Any(); UpdateSections(); return(true); }
public override void Execute(MeterDataSet meterDataSet) { FaultDataResource faultDataResource = meterDataSet.GetResource <FaultDataResource>(); string stationKey = meterDataSet.Meter.Location.LocationKey; foreach (var kvp in faultDataResource.FaultLookup) { DataGroup dataGroup = kvp.Key; DataAnalysis.FaultGroup faultGroup = kvp.Value; string lineKey = dataGroup.Asset.AssetKey; for (int i = 0; i < faultGroup.Faults.Count; i++) { int faultNumber = i + 1; DataAnalysis.Fault fault = faultGroup.Faults[i]; if (fault.IsSuppressed) { continue; } string distance = fault.Summaries .Where(summary => summary.IsValid) .Where(summary => summary.IsSelectedAlgorithm) .Select(summary => summary.Distance.ToString("0.###")) .FirstOrDefault(); if (distance == null) { return; } string url = string.Format(Settings.URLFormat, stationKey, lineKey, distance); string structureInfo = GetStructureInfo(url); DataTable structureData = ToDataTable(structureInfo); if (structureData.Rows.Count == 0) { return; } Func <string, string> fieldMappingLookup = FieldMappingLookup; string assetKeyField = fieldMappingLookup("AssetKey"); string latitudeKeyField = fieldMappingLookup("Latitude"); string longitudeKeyField = fieldMappingLookup("Longitude"); if (!structureData.Columns.Contains(assetKeyField)) { return; } using (AdoDataConnection connection = meterDataSet.CreateDbConnection()) { TableOperations <Event> eventTable = new TableOperations <Event>(connection); Event evt = eventTable.GetEvent(meterDataSet.FileGroup, dataGroup); int faultSummaryID = connection.ExecuteScalar <int>(FaultSummaryQuery, evt.ID, faultNumber); TableOperations <Structure> structureTable = new TableOperations <Structure>(connection); foreach (DataRow row in structureData.Rows) { string assetKey = row.Field <string>(assetKeyField); string latitude = null; string longitude = null; if (structureData.Columns.Contains(latitudeKeyField)) { latitude = row.Field <string>(latitudeKeyField); } if (structureData.Columns.Contains(longitudeKeyField)) { longitude = row.Field <string>(longitudeKeyField); } Structure structure = structureTable.QueryRecordWhere("AssetKey = {0}", assetKey) ?? new Structure() { AssetKey = assetKey }; structure.AssetID = dataGroup.Asset.ID; if (double.TryParse(latitude, out double lat)) { structure.Latitude = lat; } if (double.TryParse(longitude, out double lon)) { structure.Longitude = lon; } structureTable.AddNewOrUpdateRecord(structure); if (structure.ID == 0) { structure.ID = connection.ExecuteScalar <int>("SELECT @@IDENTITY"); } if (faultSummaryID != 0) { connection.ExecuteNonQuery("INSERT INTO NearestStructure(FaultSummaryID, StructureID, Deviation) VALUES({0}, {1}, 0)", faultSummaryID, structure.ID); } } } } } }
public BorrowTunnel(Structure parentStructure, Common.BorrowMode borrowMode) : base(parentStructure) { CreateStandardTerminals(NationalInstruments.CommonModel.Direction.Input, 1u, 1u, NITypes.Void); BorrowMode = borrowMode; }
public void AddSpecial(Structure structure, RectTransform widget) { widget.SetParent(_groups[structure]); }
/// <summary>Creates a new instance of MessageIterator </summary> public NuGenMessageIterator(Structure start, System.String direction, bool handleUnexpectedSegments) { this.currentStructure = start; this.direction = direction; this.handleUnexpectedSegments = handleUnexpectedSegments; }
void ExportDVHs(PlanSetup plan, StructureSet ss, string[] structureIds, XmlWriter writer) { writer.WriteStartElement("html"); writer.WriteStartElement("head"); writer.WriteElementString("title", "web dvh"); XElement script = new XElement("script", new XAttribute("type", "text/javascript"), new XAttribute("src", "https://www.google.com/jsapi"), "// need this due to bug in google LineChart javascript" ); script.WriteTo(writer); script = new XElement("script", new XAttribute("type", "text/javascript"), @" google.load('visualization', '1', { packages: ['corechart'] }); "); script.WriteTo(writer); Tuple <string, DVHData>[] listDVHs = new Tuple <string, DVHData> [structureIds.Length]; int index = 0, maxPtsIndex = 0; int maxDVHPts = int.MinValue; // search through the list of structure ids until we find one Structure structure = null; foreach (string volumeId in structureIds) { structure = (from s in ss.Structures where s.Id.ToUpper().CompareTo(volumeId.ToUpper()) == 0 select s).FirstOrDefault(); if (structure == null) { continue; // structure not found } DVHData dvh = plan.GetDVHCumulativeData(structure, DoseValuePresentation.Absolute, VolumePresentation.Relative, 0.1); listDVHs[index] = new Tuple <string, DVHData>(volumeId, dvh); if (maxDVHPts < dvh.CurveData.Count()) { maxPtsIndex = index; } maxDVHPts = Math.Max(maxDVHPts, dvh.CurveData.Count()); index++; } // collect the dose / volume data into a single matrix double [,] dvhData = new double[maxDVHPts, listDVHs.Count()]; for (int j = 0; j < listDVHs.Count(); j++) { for (int i = 0; i < maxDVHPts; i++) { dvhData[i, j] = 0.0; DVHData dvh = listDVHs[j].Item2; if (dvh.CurveData.Count() > i) { dvhData[i, j] = dvh.CurveData[i].Volume; } } } string javascript = @" function drawVisualization() { var data = google.visualization.arrayToDataTable([ ['Dose'"; foreach (Tuple <string, DVHData> dvhItemData1 in listDVHs) { javascript += ", '" + dvhItemData1.Item1 + "'"; } javascript += @"], "; int x = 0; foreach (DVHPoint pt in listDVHs[maxPtsIndex].Item2.CurveData) { string doseVolumes = string.Format("[{0:0.0}", pt.DoseValue.Dose); for (int j = 0; j < listDVHs.Count(); j++) { doseVolumes += string.Format(",{0:0.00000}", dvhData[x, j]); } doseVolumes += @"],"; javascript += doseVolumes; x++; } javascript += @" ]); // Create and draw the visualization. new google.visualization.LineChart(document.getElementById('xxxxx')). draw(data, { width: 1000, height: 800, vAxis: { maxValue: 100 } } ); } google.setOnLoadCallback(drawVisualization); "; XElement script2 = new XElement("script", new XAttribute("type", "text/javascript"), javascript ); script2.WriteTo(writer); writer.WriteEndElement();// head XElement body = new XElement("body", new XElement("div", new XAttribute("id", "xxxxx"), new XAttribute("style", "width: 900px; height: 500px;") )); body.WriteTo(writer); writer.WriteEndElement();// html }
public byte GetVoxel(Vector3 pos) { int yPos = Mathf.FloorToInt(pos.y); /* IMMUTABLE PASS */ // If outside world, return air. if (!IsVoxelInWorld(pos)) { return(0); } // If bottom block of chunk, return bedrock. if (yPos == 0) { return(1); } /* BIOME SELECTION PASS*/ int solidGroundHeight = 42; float sumOfHeights = 0f; int count = 0; float strongestWeight = 0f; int strongestBiomeIndex = 0; for (int i = 0; i < biomes.Length; i++) { float weight = Noise.Get2DPerlin(new Vector2(pos.x, pos.z), biomes[i].offset, biomes[i].scale); // Keep track of which weight is strongest. if (weight > strongestWeight) { strongestWeight = weight; strongestBiomeIndex = i; } // Get the height of the terrain (for the current biome) and multiply it by its weight. float height = biomes[i].terrainHeight * Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 0, biomes[i].terrainScale) * weight; // If the height value is greater 0 add it to the sum of heights. if (height > 0) { sumOfHeights += height; count++; } } // Set biome to the one with the strongest weight. BiomeAttributes biome = biomes[strongestBiomeIndex]; // Get the average of the heights. sumOfHeights /= count; int terrainHeight = Mathf.FloorToInt(sumOfHeights + solidGroundHeight); //BiomeAttributes biome = biomes[index]; /* BASIC TERRAIN PASS */ byte voxelValue = 0; if (yPos == terrainHeight) { voxelValue = biome.surfaceBlock; } else if (yPos < terrainHeight && yPos > terrainHeight - 4) { voxelValue = biome.subSurfaceBlock; } else if (yPos > terrainHeight) { return(0); } else { voxelValue = 2; } /* SECOND PASS */ if (voxelValue == 2) { foreach (Lode lode in biome.lodes) { if (yPos > lode.minHeight && yPos < lode.maxHeight) { if (Noise.Get3DPerlin(pos, lode.noiseOffset, lode.scale, lode.threshold)) { voxelValue = lode.blockID; } } } } /* TREE PASS */ if (yPos == terrainHeight && biome.placeMajorFlora) { if (Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 0, biome.majorFloraZoneScale) > biome.majorFloraZoneThreshold) { if (Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 0, biome.majorFloraPlacementScale) > biome.majorFloraPlacementThreshold) { modifications.Enqueue(Structure.GenerateMajorFlora(biome.majorFloraIndex, pos, biome.minHeight, biome.maxHeight)); } } } return(voxelValue); }
private static Table CreateSetField(Field p) { Structure struktura = p.DataDict.Structures.First(s => s.Name == p.Name); return((struktura != null) ? new Table(struktura.ComponentsList.Select(s => s.Name).ToList()) : null); }
public override void SetValue(Structure value, string index = "") { this.value.Set(value, index); }
/// <summary> /// Creates the function for delete the entity. /// </summary> /// <param name="myStructure">Structure to extract the data.</param> /// <param name="streamText">A stringBuilder to write the data.</param> protected override void CreateDeleteFunction(Structure myStructure, StringBuilder streamText) { streamText.Append($"void {myStructure.AliasName}_delete({myStructure.FinalStructureName}* this);\n"); }
partial void FixStructureProjSpecific(Character user, float deltaTime, Structure targetStructure, int sectionIndex);
private List <RuinShape> GenerateStructures(List <VoronoiCell> caveCells, Rectangle ruinArea, bool mirror) { List <RuinShape> shapes = new List <RuinShape>(rooms); shapes.AddRange(corridors); if (mirror) { foreach (RuinShape shape in shapes) { shape.MirrorX(ruinArea.Center.ToVector2()); } } foreach (RuinShape leaf in shapes) { RuinStructureType wallType = RuinStructureType.Wall; if (!(leaf is BTRoom)) { wallType = RuinStructureType.CorridorWall; } //rooms further from the entrance are more likely to have hard-to-break walls else if (Rand.Range(0.0f, leaf.DistanceFromEntrance, Rand.RandSync.Server) > 1.5f) { wallType = RuinStructureType.HeavyWall; } //generate walls -------------------------------------------------------------- foreach (Line wall in leaf.Walls) { var structurePrefab = RuinStructure.GetRandom(wallType, leaf.GetLineAlignment(wall)); if (structurePrefab == null) { continue; } float radius = (wall.A.X == wall.B.X) ? (structurePrefab.Prefab as StructurePrefab).Size.X * 0.5f : (structurePrefab.Prefab as StructurePrefab).Size.Y * 0.5f; Rectangle rect = new Rectangle( (int)(wall.A.X - radius), (int)(wall.B.Y + radius), (int)((wall.B.X - wall.A.X) + radius * 2.0f), (int)((wall.B.Y - wall.A.Y) + radius * 2.0f)); //cut a section off from both ends of a horizontal wall to get nicer looking corners if (wall.A.Y == wall.B.Y) { rect.Inflate(-32, 0); if (rect.Width < Submarine.GridSize.X) { continue; } } var structure = new Structure(rect, structurePrefab.Prefab as StructurePrefab, null); structure.MoveWithLevel = true; structure.SetCollisionCategory(Physics.CollisionLevel); } //generate backgrounds -------------------------------------------------------------- var background = RuinStructure.GetRandom(RuinStructureType.Back, Alignment.Center); if (background == null) { continue; } Rectangle backgroundRect = new Rectangle(leaf.Rect.X, leaf.Rect.Y + leaf.Rect.Height, leaf.Rect.Width, leaf.Rect.Height); new Structure(backgroundRect, (background.Prefab as StructurePrefab), null).MoveWithLevel = true; var submarineBlocker = BodyFactory.CreateRectangle(GameMain.World, ConvertUnits.ToSimUnits(leaf.Rect.Width), ConvertUnits.ToSimUnits(leaf.Rect.Height), 1, ConvertUnits.ToSimUnits(leaf.Center)); submarineBlocker.IsStatic = true; submarineBlocker.CollisionCategories = Physics.CollisionWall; submarineBlocker.CollidesWith = Physics.CollisionWall; } List <RuinShape> doorlessRooms = new List <RuinShape>(shapes); //generate doors & sensors that close them ------------------------------------------------------------- var sensorPrefab = MapEntityPrefab.Find("Alien Motion Sensor") as ItemPrefab; var wirePrefab = MapEntityPrefab.Find("Wire") as ItemPrefab; foreach (Corridor corridor in corridors) { var doorPrefab = RuinStructure.GetRandom(corridor.IsHorizontal ? RuinStructureType.Door : RuinStructureType.Hatch, Alignment.Center); if (doorPrefab == null) { continue; } //find all walls that are parallel to the corridor var suitableWalls = corridor.IsHorizontal ? corridor.Walls.FindAll(c => c.A.Y == c.B.Y) : corridor.Walls.FindAll(c => c.A.X == c.B.X); if (!suitableWalls.Any()) { continue; } doorlessRooms.Remove(corridor); Vector2 doorPos = corridor.Center; //choose a random wall to place the door next to var wall = suitableWalls[Rand.Int(suitableWalls.Count, Rand.RandSync.Server)]; if (corridor.IsHorizontal) { doorPos.X = (wall.A.X + wall.B.X) / 2.0f; } else { doorPos.Y = (wall.A.Y + wall.B.Y) / 2.0f; } var door = new Item(doorPrefab.Prefab as ItemPrefab, doorPos, null); door.MoveWithLevel = true; door.GetComponent <Items.Components.Door>().IsOpen = Rand.Range(0.0f, 1.0f, Rand.RandSync.Server) < 0.8f; if (sensorPrefab == null || wirePrefab == null) { continue; } var sensorRoom = corridor.ConnectedRooms.FirstOrDefault(r => r != null && rooms.Contains(r)); if (sensorRoom == null) { continue; } var sensor = new Item(sensorPrefab, new Vector2( Rand.Range(sensorRoom.Rect.X, sensorRoom.Rect.Right, Rand.RandSync.Server), Rand.Range(sensorRoom.Rect.Y, sensorRoom.Rect.Bottom, Rand.RandSync.Server)), null); sensor.MoveWithLevel = true; var wire = new Item(wirePrefab, sensorRoom.Center, null).GetComponent <Items.Components.Wire>(); wire.Item.MoveWithLevel = false; var conn1 = door.Connections.Find(c => c.Name == "set_state"); conn1.AddLink(0, wire); wire.Connect(conn1, false); var conn2 = sensor.Connections.Find(c => c.Name == "state_out"); conn2.AddLink(0, wire); wire.Connect(conn2, false); } //generate props -------------------------------------------------------------- for (int i = 0; i < shapes.Count * 2; i++) { Alignment[] alignments = new Alignment[] { Alignment.Top, Alignment.Bottom, Alignment.Right, Alignment.Left, Alignment.Center }; var prop = RuinStructure.GetRandom(RuinStructureType.Prop, alignments[Rand.Int(alignments.Length, Rand.RandSync.Server)]); if (prop == null) { continue; } Vector2 size = (prop.Prefab is StructurePrefab) ? ((StructurePrefab)prop.Prefab).Size : Vector2.Zero; //if the prop is placed at the center of the room, we have to use a room without a door (because they're also placed at the center) var shape = prop.Alignment.HasFlag(Alignment.Center) ? doorlessRooms[Rand.Int(doorlessRooms.Count, Rand.RandSync.Server)] : shapes[Rand.Int(shapes.Count, Rand.RandSync.Server)]; Vector2 position = shape.Rect.Center.ToVector2(); if (prop.Alignment.HasFlag(Alignment.Top)) { position = new Vector2(Rand.Range(shape.Rect.X + size.X, shape.Rect.Right - size.X, Rand.RandSync.Server), shape.Rect.Bottom - 64); } else if (prop.Alignment.HasFlag(Alignment.Bottom)) { position = new Vector2(Rand.Range(shape.Rect.X + size.X, shape.Rect.Right - size.X, Rand.RandSync.Server), shape.Rect.Top + 64); } else if (prop.Alignment.HasFlag(Alignment.Right)) { position = new Vector2(shape.Rect.Right - 64, Rand.Range(shape.Rect.Y + size.X, shape.Rect.Bottom - size.Y, Rand.RandSync.Server)); } else if (prop.Alignment.HasFlag(Alignment.Left)) { position = new Vector2(shape.Rect.X + 64, Rand.Range(shape.Rect.Y + size.X, shape.Rect.Bottom - size.Y, Rand.RandSync.Server)); } if (prop.Prefab is ItemPrefab) { var item = new Item((ItemPrefab)prop.Prefab, position, null); item.MoveWithLevel = true; } else { new Structure(new Rectangle( (int)(position.X - size.X / 2.0f), (int)(position.Y + size.Y / 2.0f), (int)size.X, (int)size.Y), prop.Prefab as StructurePrefab, null).MoveWithLevel = true; } } return(shapes); }
private void RefreshSpreadDelta(Structure structure) { SpreadDelta = Random.Range(25f, 50f) / (structure.BaseFlammability / 10); }
public virtual void processTicketRequests(Structure layout, List <Requests> requests) { for (int i = 0; i < requests.Count; i++) { Requests request = requests[i]; if (request.VerifyComplete) { continue; } /* * -2 is an indicator when we can't handle the party. */ if (request.NoOfTickets > layout.AvailableSeats) { request.RowNumber = -2; request.SectionNumber = -2; continue; } List <TheaterSection> sections = layout.SectionList; for (int j = 0; j < sections.Count; j++) { TheaterSection section = sections[j]; if (request.NoOfTickets == section.AvailableSeats) { request.SectionNumber = section.SectionNumber; request.RowNumber = section.RowNumber; layout.AvailableSeats = layout.AvailableSeats - request.NoOfTickets; section.AvailableSeats = section.AvailableSeats - request.NoOfTickets; request.VerifyComplete = true; break; } else if (request.NoOfTickets < section.AvailableSeats) { int requestNo = findCompleteRequest(requests, section.AvailableSeats - request.NoOfTickets, i); if (requestNo != -1) { request.SectionNumber = section.SectionNumber; request.RowNumber = section.RowNumber; layout.AvailableSeats = layout.AvailableSeats - request.NoOfTickets; section.AvailableSeats = section.AvailableSeats - request.NoOfTickets; request.VerifyComplete = true; Requests completeRequest = requests[requestNo]; completeRequest.SectionNumber = section.SectionNumber; completeRequest.RowNumber = section.RowNumber; layout.AvailableSeats = layout.AvailableSeats - completeRequest.NoOfTickets; section.AvailableSeats = section.AvailableSeats - completeRequest.NoOfTickets; completeRequest.VerifyComplete = true; break; } else { int sectionNo = findSectionByAvailableSeats(sections, request.NoOfTickets); if (sectionNo >= 0) { TheaterSection perferctSection = sections[sectionNo]; request.RowNumber = perferctSection.RowNumber; request.SectionNumber = perferctSection.SectionNumber; perferctSection.AvailableSeats = perferctSection.AvailableSeats - request.NoOfTickets; layout.AvailableSeats = layout.AvailableSeats - request.NoOfTickets; request.VerifyComplete = true; break; } else { request.RowNumber = section.RowNumber; request.SectionNumber = section.SectionNumber; section.AvailableSeats = section.AvailableSeats - request.NoOfTickets; layout.AvailableSeats = layout.AvailableSeats - request.NoOfTickets; request.VerifyComplete = true; break; } } } } /* * -1 is an indicator when we need to split the party. */ if (!request.VerifyComplete) { request.RowNumber = -1; request.SectionNumber = -1; } } Console.WriteLine("Final Distribution of Seats by Name , Seat .\n"); foreach (Requests request in requests) { Console.WriteLine(request.Status); } }
protected override void RunCommand(IEnumerable <string> args) { List <string> argsList = args.ToList(); if (showCommandHelp(argsList)) { return; } bool itemsLong = withItems == "long"; bool inventoryLong = withInventory == "long"; bool tamedLong = tamed == "long"; bool structuresLong = withStructures == "long"; Stopwatch stopwatch = new Stopwatch(GlobalOptions.UseStopWatch); bool mapNeeded = withItems != null || tamed != null || withStructures != null || withInventory != null; if (!GlobalOptions.Quiet && mapNeeded) { Console.WriteLine("Need to load map, this may take some time..."); } string saveGame = argsList.Count > 0 ? argsList[0] : Path.Combine(GlobalOptions.ArkToolsConfiguration.BasePath, GlobalOptions.ArkToolsConfiguration.ArkSavegameFilename); string outputDirectory = argsList.Count > 1 ? argsList[1] : Path.Combine(GlobalOptions.ArkToolsConfiguration.BasePath, GlobalOptions.ArkToolsConfiguration.TribesPath); string saveDir = Path.GetDirectoryName(saveGame); Dictionary <int, HashSet <TribeBase> > baseMap; CustomDataContext context = new CustomDataContext(); if (mapNeeded) { ArkDataManager.LoadData(GlobalOptions.Language); ArkSavegame mapSave = new ArkSavegame().ReadBinary <ArkSavegame>(saveGame, ReadingOptions.Create().WithBuildComponentTree(true)); context.Savegame = mapSave; context.MapData = LatLonCalculator.ForSave(context.Savegame); stopwatch.Stop("Loading map data"); if (withBases) { baseMap = new Dictionary <int, HashSet <TribeBase> >(); foreach (GameObject gameObject in mapSave) { // Skip items and stuff without a location if (gameObject.IsItem || gameObject.Location == null) { continue; } string signText = gameObject.GetPropertyValue <string>("SignText"); long? targetingTeam = gameObject.GetPropertyValue <long?>("TargetingTeam"); if (signText != null && targetingTeam != null) { // Might be a 'Base' sign MatchCollection matcher = basePattern.Matches(signText); if (matcher.Any()) { // Found a base sign, add it to the set, automatically replacing duplicates int tribeId = (int)targetingTeam; LocationData location = gameObject.Location; string baseName = matcher[1].Value; float size = float.Parse(matcher[2].Value); TribeBase tribeBase = new TribeBase(baseName, location.X, location.Y, location.Z, size); if (!baseMap.ContainsKey(tribeId)) { baseMap[tribeId] = new HashSet <TribeBase>(); } baseMap[tribeId].Add(tribeBase); } } } stopwatch.Stop("Collecting bases"); } else { baseMap = null; } if (mapSave.HibernationEntries.Any() && tamed != null) { List <GameObject> combinedObjects = context.Savegame.Objects.ToList(); foreach (HibernationEntry entry in context.Savegame.HibernationEntries) { ObjectCollector collector = new ObjectCollector(entry, 1); combinedObjects.AddRange(collector.Remap(combinedObjects.Count)); } context.ObjectContainer = new GameObjectContainer(combinedObjects); } else { context.ObjectContainer = mapSave; } } else { baseMap = null; } List <Action> tasks = GlobalOptions.Parallel ? new List <Action>() : null; void mapWriter(JsonTextWriter generator, int tribeId) { if (!mapNeeded) { return; } List <GameObject> structures = new List <GameObject>(); List <GameObject> creatures = new List <GameObject>(); List <Item> items = new List <Item>(); List <Item> blueprints = new List <Item>(); List <DroppedItem> droppedItems = new List <DroppedItem>(); // Apparently there is a behavior in ARK causing certain structures to exist twice within a save HashSet <ArkName> processedList = new HashSet <ArkName>(); // Bases HashSet <TribeBase> bases = withBases ? baseMap[tribeId] : null; foreach (GameObject gameObject in context.ObjectContainer) { if (gameObject.IsItem) { continue; } int targetingTeam = gameObject.GetPropertyValue <int>("TargetingTeam", defaultValue: -1); if (targetingTeam == -1) { continue; } TeamType teamType = TeamTypes.ForTeam(targetingTeam); if (tribeId == -1 && teamType != TeamType.Player) { continue; } if (tribeId == 0 && teamType != TeamType.NonPlayer) { continue; } if (tribeId > 0 && tribeId != targetingTeam) { continue; } // Determine base if we have bases TribeBase tribeBase; if (bases != null && gameObject.Location != null) { TribeBase matchedBase = null; foreach (TribeBase potentialBase in bases) { if (potentialBase.InsideBounds(gameObject.Location)) { matchedBase = potentialBase; break; } } tribeBase = matchedBase; } else { tribeBase = null; } if (gameObject.IsCreature()) { if (!processedList.Contains(gameObject.Names[0])) { if (tribeBase != null) { tribeBase.Creatures.Add(gameObject); } else { creatures.Add(gameObject); } processedList.Add(gameObject.Names[0]); } else { // Duped Creature continue; } } else if (!gameObject.IsPlayer() && !gameObject.IsWeapon() && !gameObject.IsDroppedItem()) { // LinkedPlayerDataID: Players ain't structures // AssociatedPrimalItem: Items equipped by sleeping players // MyItem: dropped item if (!processedList.Contains(gameObject.Names[0])) { if (tribeBase != null) { tribeBase.Structures.Add(gameObject); } else { structures.Add(gameObject); } processedList.Add(gameObject.Names[0]); } else { // Duped Structure continue; } } else { if (!processedList.Contains(gameObject.Names[0])) { processedList.Add(gameObject.Names[0]); } else { // Duped Player or dropped Item or weapon continue; } } void itemHandler(ObjectReference itemReference) { GameObject item = itemReference.GetObject(context.Savegame); if (item != null && !Item.isDefaultItem(item)) { if (processedList.Contains(item.Names[0])) { // happens for players having items in their quick bar return; } processedList.Add(item.Names[0]); if (item.HasAnyProperty("bIsBlueprint")) { if (tribeBase != null) { tribeBase.Blueprints.Add(new Item(item)); } else { blueprints.Add(new Item(item)); } } else { if (tribeBase != null) { tribeBase.Items.Add(new Item(item)); } else { items.Add(new Item(item)); } } } } void droppedItemHandler(GameObject droppedItemObject) { DroppedItem droppedItem = new DroppedItem(droppedItemObject, context.Savegame); if (tribeBase != null) { tribeBase.DroppedItems.Add(droppedItem); } else { droppedItems.Add(droppedItem); } } if (withItems != null && withInventory == null) { foreach (GameObject inventory in gameObject.Components.Values) { if (!inventory.IsInventory()) { continue; } List <ObjectReference> inventoryItems = inventory.GetPropertyValue <IArkArray, ArkArrayObjectReference>("InventoryItems"); foreach (ObjectReference itemReference in inventoryItems ?? Enumerable.Empty <ObjectReference>()) { itemHandler(itemReference); } List <ObjectReference> equippedItems = inventory.GetPropertyValue <IArkArray, ArkArrayObjectReference>("EquippedItems"); foreach (ObjectReference itemReference in equippedItems ?? Enumerable.Empty <ObjectReference>()) { itemHandler(itemReference); } } } ObjectReference myItem = gameObject.GetPropertyValue <ObjectReference>("MyItem"); if (myItem != null) { if (withItems != null && withInventory == null) { itemHandler(myItem); } else if (withInventory != null) { droppedItemHandler(gameObject); } } } void writeStructures(IEnumerable <GameObject> structList) { if (withStructures == null) { return; } generator.WriteArrayFieldStart("structures"); if (structuresLong) { foreach (GameObject structureObject in structList) { Structure structure = new Structure(structureObject, context.Savegame); generator.WriteStartObject(); structure.writeAllProperties(generator, context, writeAllFields); if (withInventory != null) { structure.writeInventory(generator, context, writeAllFields, !inventoryLong); } generator.WriteEndObject(); } } else { Dictionary <ArkName, long> structMap = structList.GroupBy(o => o.ClassName).ToDictionary(objects => objects.Key, objects => objects.LongCount()); foreach (KeyValuePair <ArkName, long> entry in structMap.OrderByDescending(pair => pair.Value)) { generator.WriteStartObject(); string name = entry.Key.ToString(); if (ArkDataManager.HasStructure(name)) { name = ArkDataManager.GetStructure(name).Name; } generator.WriteField("name", name); generator.WriteField("count", entry.Value); generator.WriteEndObject(); } } generator.WriteEndArray(); } void writeCreatures(List <GameObject> creaList) { if (tamed == null) { return; } generator.WriteArrayFieldStart("tamed"); if (tamedLong) { foreach (GameObject creatureObject in creaList) { Creature creature = new Creature(creatureObject, context.Savegame); generator.WriteStartObject(); creature.writeAllProperties(generator, context, writeAllFields); if (withInventory != null) { creature.writeInventory(generator, context, writeAllFields, !inventoryLong); } generator.WriteEndObject(); } } else { Dictionary <ArkName, long> creaMap = creaList.GroupBy(o => o.ClassName).ToDictionary(objects => objects.Key, objects => objects.LongCount()); foreach (KeyValuePair <ArkName, long> entry in creaMap.OrderByDescending(pair => pair.Value)) { generator.WriteStartObject(); string name = entry.Key.ToString(); if (ArkDataManager.HasCreature(name)) { name = ArkDataManager.GetCreature(name).Name; } generator.WriteField("name", name); generator.WriteField("count", entry.Value); generator.WriteEndObject(); } } generator.WriteEndArray(); } void writeDroppedItems(List <DroppedItem> droppedList) { if (withInventory == null) { return; } generator.WriteArrayFieldStart("droppedItems"); foreach (DroppedItem droppedItem in droppedList) { generator.WriteStartObject(); droppedItem.writeAllProperties(generator, context, writeAllFields); droppedItem.writeInventory(generator, context, writeAllFields, !inventoryLong); generator.WriteEndObject(); } generator.WriteEndArray(); } if (withBases && bases != null) { generator.WriteArrayFieldStart("bases"); foreach (TribeBase tribeBase in bases) { generator.WriteStartObject(); generator.WriteField("name", tribeBase.Name); generator.WriteField("x", tribeBase.X); generator.WriteField("y", tribeBase.Y); generator.WriteField("z", tribeBase.Z); generator.WriteField("lat", context.MapData.CalculateLat(tribeBase.Y)); generator.WriteField("lon", context.MapData.CalculateLon(tribeBase.X)); generator.WriteField("radius", tribeBase.Size); writeCreatures(tribeBase.Creatures); writeStructures(tribeBase.Structures); writeDroppedItems(tribeBase.DroppedItems); if (itemsLong) { generator.WritePropertyName("items"); Inventory.writeInventoryLong(generator, context, tribeBase.Items, writeAllFields); generator.WritePropertyName("blueprints"); Inventory.writeInventoryLong(generator, context, tribeBase.Blueprints, writeAllFields); } else { generator.WritePropertyName("items"); Inventory.writeInventorySummary(generator, tribeBase.Items); generator.WritePropertyName("blueprints"); Inventory.writeInventorySummary(generator, tribeBase.Blueprints); } generator.WriteEndObject(); } generator.WriteStartObject(); } writeCreatures(creatures); writeStructures(structures); writeDroppedItems(droppedItems); if (itemsLong) { generator.WritePropertyName("items"); Inventory.writeInventoryLong(generator, context, items, writeAllFields); generator.WritePropertyName("blueprints"); Inventory.writeInventoryLong(generator, context, blueprints, writeAllFields); } else { generator.WritePropertyName("items"); Inventory.writeInventorySummary(generator, items); generator.WritePropertyName("blueprints"); Inventory.writeInventorySummary(generator, blueprints); } if (withBases && bases != null) { generator.WriteEndObject(); generator.WriteEndArray(); } } foreach (string path in Directory.EnumerateFiles(saveDir).Where(path => tribePattern.IsMatch(path))) { Action task = () => { try { Tribe tribe = new Tribe(path, ReadingOptions.Create()); string tribeFileName = tribe.tribeId + ".json"; string tribePath = Path.Combine(outputDirectory, tribeFileName); CommonFunctions.WriteJson(tribePath, (generator, writingOptions) => { generator.WriteStartObject(); tribe.writeAllProperties(generator, context, writeAllFields); mapWriter(generator, tribe.tribeId); generator.WriteEndObject(); }, writingOptions); } catch (Exception ex) { Console.Error.WriteLine("Found potentially corrupt ArkTribe: " + path); if (GlobalOptions.Verbose) { Console.Error.WriteLine(ex.Message); Console.Error.WriteLine(ex.StackTrace); } } }; if (tasks != null) { tasks.Add(task); } else { task(); } } if (tasks != null) { Parallel.ForEach(tasks, task => task()); } if (tribeless) { string tribePath = Path.Combine(outputDirectory, "tribeless.json"); CommonFunctions.WriteJson(tribePath, (generator, writingOptions) => { generator.WriteStartObject(); mapWriter(generator, -1); generator.WriteEndObject(); }, writingOptions); } if (nonPlayers) { string tribePath = Path.Combine(outputDirectory, "non-players.json"); CommonFunctions.WriteJson(tribePath, (generator, writingOptions) => { generator.WriteStartObject(); mapWriter(generator, 0); generator.WriteEndObject(); }, writingOptions); } stopwatch.Stop("Loading tribes and writing info"); stopwatch.Print(); }
public void ClearStructure()//clears the structure, needed as analytic creates one that differs from the testing { testStructure = null; m_IsGenerated = false; }
/// <summary> /// Creates The Constructor of the structure with its parameters. /// </summary> /// <param name="myStructure">Structure to extract the data.</param> /// <param name="streamText">A stringBuilder to write the data.</param> /// <param name="packsDone">Amount of steps done.</param> /// <param name="fullPackSize">Amount of total steps to do.</param> protected override void CreateBuilderWithParams(Structure myStructure, StringBuilder streamText, short packsDone, short fullPackSize) { streamText.Append($"{myStructure.FinalStructureName}* {myStructure.AliasName}_new("); // auxStrName* strShort_new(parametersLine); AddParametersToConstructor(myStructure, streamText); }
public void Execute(ScriptContext context /*, System.Windows.Window window, ScriptEnvironment environment*/) { // TODO : Add here the code that is called when the script is launched from Eclipse. string name = context.Patient.Name; MessageBox.Show(name); //pull informatino from the plansetup. string msg = ""; PlanSetup ps = context.PlanSetup; //prescription information from the plan. msg += String.Format("Number of Fractions: {0}\n", ps.NumberOfFractions); msg += String.Format("Dose per Fraction: {0}\n", ps.DosePerFraction); msg += String.Format("Total Dose: {0}\n", ps.TotalDose); //get approval history of the plan. msg += "Approval History\n"; foreach (var approve in ps.ApprovalHistory) { msg += String.Format("\tStatus: {0} by {1} {2}\n" , approve.ApprovalStatus, approve.UserId, approve.ApprovalDateTime); } //calculation model used msg += String.Format("Dose calculation Model: {0}\n", ps.PhotonCalculationModel); //iterate through the beams and get some information about these fields. msg += String.Format("Plan has {0} fields\n", ps.Beams.Count()); foreach (Beam b in ps.Beams.OrderBy(o => o.BeamNumber)) { msg += String.Format("\t{0}: {1:F1}MU\n", b.Id, b.Meterset.Value); msg += String.Format("\t\tGantry: {0}; Collimator: {1}\n", b.ControlPoints.First().GantryAngle, b.ControlPoints.First().CollimatorAngle); } //iterate information through the structures. msg += String.Format("Structure set {0} has {1} structures\n", ps.StructureSet.Id, ps.StructureSet.Structures.Count()); foreach (Structure s in ps.StructureSet.Structures) { msg += String.Format("\t{0}: {1:F1}cc Type: {2}\n", s.Id, s.Volume, s.DicomType); } //find the target volume of the plan. Structure target = ps.StructureSet.Structures.Single(o => o.Id == ps.TargetVolumeID); //D95 of the target volume msg += "Custom Dose Metrics\n"; DoseValue d95 = ps.GetDoseAtVolume(target, 95, VolumePresentation.Relative, DoseValuePresentation.Absolute); msg += String.Format("\t{0}: D95 = {1}\n", target.Id, d95); //D2 of the target volume DoseValue d2 = ps.GetDoseAtVolume(target, 2, VolumePresentation.Relative, DoseValuePresentation.Absolute); msg += String.Format("\t{0}: D2 = {1}\n", target.Id, d2); //maximum dose to the cord. Structure Cord = ps.StructureSet.Structures.Single(o => o.Id == "Cord"); DoseValue cmax = ps.GetDoseAtVolume( Cord, 0, VolumePresentation.Relative, DoseValuePresentation.Absolute); msg += String.Format("\t{0}: Max = {1}\n", Cord.Id, cmax); Structure parotid = ps.StructureSet.Structures.First(o => o.Id.Contains("Parotid")); double v30Gy = ps.GetVolumeAtDose(parotid, new DoseValue(3000, DoseValue.DoseUnit.cGy), VolumePresentation.Relative); msg += String.Format("\t{0}: D95 = {1:F2}%\n", parotid.Id, v30Gy); MessageBox.Show(msg); //export the target DVH to a CSV File. //declare file save path string filename = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\dvh.csv"; //get hte dvh of the target. DVHData dvh = ps.GetDVHCumulativeData( target, DoseValuePresentation.Absolute, VolumePresentation.Relative, 1); //write the file. using (StreamWriter sw = new StreamWriter(filename)) { sw.WriteLine("Dose, Volume"); foreach (DVHPoint dvhd in dvh.CurveData) { sw.WriteLine(String.Format("{0:F2},{1:F2}" , dvhd.DoseValue.Dose, dvhd.Volume)); } } }