public void Point(WorldPosition ourPosition, WorldPosition opponentWorldPosition) { arrowMesh.Position.Move(ourPosition.Location.X, ourPosition.Location.Y, ourPosition.Location.Z); Vector3 pointVector = opponentWorldPosition.Location - ourPosition.Location; float XRot, YRot; XRot = (float) Math.Atan2(-pointVector.Y, Math.Sqrt(pointVector.X * pointVector.X + pointVector.Z * pointVector.Z)); YRot = (float) Math.Atan2(pointVector.X, pointVector.Z); arrowMesh.Position.Rotate(XRot, YRot, 0.0f); }
/// <summary> /// Decompose and add a SuperElevation on top of MSTS track section /// </summary> /// <param name="viewer">Viewer reference.</param> /// <param name="dTrackList">DynamicTrackViewer list.</param> /// <param name="dTrackObj">Dynamic track section to decompose.</param> /// <param name="worldMatrixInput">Position matrix.</param> public static void DecomposeDynamicSuperElevation(Viewer viewer, List <DynamicTrackViewer> dTrackList, DyntrackObj dTrackObj, WorldPosition worldMatrixInput) { // DYNAMIC TRACK // ============= // Objectives: // 1-Decompose multi-subsection DT into individual sections. // 2-Create updated transformation objects (instances of WorldPosition) to reflect // root of next subsection. // 3-Distribute elevation change for total section through subsections. (ABANDONED) // 4-For each meaningful subsection of dtrack, build a separate SuperElevationPrimitive. // // Method: Iterate through each subsection, updating WorldPosition for the root of // each subsection. The rotation component changes only in heading. The translation // component steps along the path to reflect the root of each subsection. // The following vectors represent local positioning relative to root of original (5-part) section: Vector3 localV = Vector3.Zero; // Local position (in x-z plane) Vector3 localProjectedV; // Local next position (in x-z plane) Vector3 displacement; // Local displacement (from y=0 plane) Vector3 heading = Vector3.Forward; // Local heading (unit vector) WorldPosition worldMatrix = new WorldPosition(worldMatrixInput); // Make a copy so it will not be messed WorldPosition nextRoot = new WorldPosition(worldMatrix); // Will become initial root Vector3 sectionOrigin = worldMatrix.XNAMatrix.Translation; // Save root position worldMatrix.XNAMatrix.Translation = Vector3.Zero; // worldMatrix now rotation-only // Iterate through all subsections int count = -1; for (int iTkSection = 0; iTkSection < dTrackObj.trackSections.Count; iTkSection++) { count++; float length = 0, radius = -1; length = dTrackObj.trackSections[iTkSection].param1; // meters if straight; radians if curved if (length == 0.0) { continue; // Consider zero-length subsections vacuous } // Create new DT object copy; has only one meaningful subsection DyntrackObj subsection = new DyntrackObj(dTrackObj, iTkSection); // Create a new WorldPosition for this subsection, initialized to nextRoot, // which is the WorldPosition for the end of the last subsection. // In other words, beginning of present subsection is end of previous subsection. WorldPosition root = new WorldPosition(nextRoot); // Now we need to compute the position of the end (nextRoot) of this subsection, // which will become root for the next subsection. // Clear nextRoot's translation vector so that nextRoot matrix contains rotation only nextRoot.XNAMatrix.Translation = Vector3.Zero; // Straight or curved subsection? if (subsection.trackSections[0].isCurved == 0) // Straight section { // Heading stays the same; translation changes in the direction oriented // Rotate Vector3.Forward to orient the displacement vector localProjectedV = localV + length * heading; displacement = Traveller.MSTSInterpolateAlongStraight(localV, heading, length, worldMatrix.XNAMatrix, out localProjectedV); } else // Curved section { // Both heading and translation change // nextRoot is found by moving from Point-of-Curve (PC) to // center (O)to Point-of-Tangent (PT). radius = subsection.trackSections[0].param2; // meters Vector3 left = radius * Vector3.Cross(Vector3.Up, heading); // Vector from PC to O Matrix rot = Matrix.CreateRotationY(-length); // Heading change (rotation about O) // Shared method returns displacement from present world position and, by reference, // local position in x-z plane of end of this section displacement = Traveller.MSTSInterpolateAlongCurve(localV, left, rot, worldMatrix.XNAMatrix, out localProjectedV); heading = Vector3.Transform(heading, rot); // Heading change nextRoot.XNAMatrix = rot * nextRoot.XNAMatrix; // Store heading change } // Update nextRoot with new translation component nextRoot.XNAMatrix.Translation = sectionOrigin + displacement; sv = ev = mv = 0f; // if (section.SectionCurve != null) FindSectionValue(shape, root, nextRoot, viewer.Simulator, section, TileX, TileZ, dTrackObj.UID); //nextRoot.XNAMatrix.Translation += Vector3.Transform(trackLoc, worldMatrix.XNAMatrix); dTrackList.Add(new SuperElevationViewer(viewer, root, nextRoot, radius, length, sv, ev, mv, dir)); localV = localProjectedV; // Next subsection } }
/// <summary> /// Decompose and add a SuperElevation on top of MSTS track section converted from dynamic tracks /// </summary> /// <param name="viewer">Viewer reference.</param> /// <param name="dTrackList">DynamicTrackViewer list.</param> /// <param name="dTrackObj">Dynamic track section to decompose.</param> /// <param name="worldMatrixInput">Position matrix.</param> public static void DecomposeConvertedDynamicSuperElevation(Viewer viewer, List <DynamicTrackViewer> dTrackList, TrackObj dTrackObj, WorldPosition worldMatrixInput) { // The following vectors represent local positioning relative to root of original (5-part) section: Vector3 localV = Vector3.Zero; // Local position (in x-z plane) Vector3 localProjectedV; // Local next position (in x-z plane) Vector3 displacement; // Local displacement (from y=0 plane) Vector3 heading = Vector3.Forward; // Local heading (unit vector) WorldPosition worldMatrix = new WorldPosition(worldMatrixInput); // Make a copy so it will not be messed WorldPosition nextRoot = new WorldPosition(worldMatrix); // Will become initial root WorldPosition wcopy = new WorldPosition(nextRoot); Vector3 sectionOrigin = worldMatrix.XNAMatrix.Translation; // Save root position worldMatrix.XNAMatrix.Translation = Vector3.Zero; // worldMatrix now rotation-only TrackPath path; try { path = viewer.Simulator.TSectionDat.TSectionIdx.TrackPaths[dTrackObj.SectionIdx]; } catch (Exception) { return; //cannot find the path for the dynamic track } nextRoot = new WorldPosition(wcopy); // Will become initial root sectionOrigin = nextRoot.XNAMatrix.Translation; heading = Vector3.Forward; // Local heading (unit vector) localV = Vector3.Zero; // Local position (in x-z plane) Vector3 trackLoc = new Vector3(0, 0, 0);// +new Vector3(3, 0, 0); Matrix trackRot = Matrix.CreateRotationY(0); //heading = Vector3.Transform(heading, trackRot); // Heading change nextRoot.XNAMatrix = trackRot * nextRoot.XNAMatrix; uint[] sections = path.TrackSections; int count = -1; for (int i = 0; i < sections.Length; i++) { count++; float length, radius; uint sid = path.TrackSections[i]; TrackSection section = viewer.Simulator.TSectionDat.TrackSections[sid]; WorldPosition root = new WorldPosition(nextRoot); nextRoot.XNAMatrix.Translation = Vector3.Zero; if (section.SectionCurve == null) { length = section.SectionSize.Length; radius = -1; localProjectedV = localV + length * heading; displacement = Traveller.MSTSInterpolateAlongStraight(localV, heading, length, worldMatrix.XNAMatrix, out localProjectedV); } else { length = section.SectionCurve.Angle * 3.14f / 180; radius = section.SectionCurve.Radius; // meters Vector3 left; if (section.SectionCurve.Angle > 0) { left = radius * Vector3.Cross(Vector3.Down, heading); // Vector from PC to O } else { left = radius * Vector3.Cross(Vector3.Up, heading); // Vector from PC to O } Matrix rot = Matrix.CreateRotationY(-section.SectionCurve.Angle * 3.14f / 180); // Heading change (rotation about O) displacement = Traveller.MSTSInterpolateAlongCurve(localV, left, rot, worldMatrix.XNAMatrix, out localProjectedV); heading = Vector3.Transform(heading, rot); // Heading change nextRoot.XNAMatrix = trackRot * rot * nextRoot.XNAMatrix; // Store heading change } nextRoot.XNAMatrix.Translation = sectionOrigin + displacement; root.XNAMatrix.Translation += Vector3.Transform(trackLoc, worldMatrix.XNAMatrix); nextRoot.XNAMatrix.Translation += Vector3.Transform(trackLoc, worldMatrix.XNAMatrix); sv = ev = mv = 0f; dir = 1f; //if (section.SectionCurve != null) FindSectionValue(shape, root, nextRoot, viewer.Simulator, section, TileX, TileZ, dTrackObj.UID); //nextRoot.XNAMatrix.Translation += Vector3.Transform(trackLoc, worldMatrix.XNAMatrix); dTrackList.Add(new SuperElevationViewer(viewer, root, nextRoot, radius, length, sv, ev, mv, dir)); localV = localProjectedV; // Next subsection } }
public static AmbientHitableObject createTree(WorldPosition position) { return(AmbientHitableObjectType.Create(new WorldPosition(position.X, position.Y + WorldGrid.BlockSize.Y - 1, position.InteriorID), AmbientHitableObjectType.lookup[0])); }
public WorldPositionScore GetWorldPositionExpansionScore(global::Empire empire, City city, WorldPosition position) { city.SimulationObject.AddChild(this.districtProxyByEmpires[empire.Index]); WorldPositionScore result = null; if (this.WorldPositionningService.IsExtensionConstructible(position, false)) { result = this.ComputeExpansionScoreAtPosition(empire, city, city.WorldPosition, position); } this.cityProxyByEmpires[empire.Index].AddChild(this.districtProxyByEmpires[empire.Index]); return(result); }
public void ComputeFarestPositionInList(WorldPosition[] listOfPosition, WorldPosition origin, out WorldPosition final) { this.ComputeFarestPositionInList(listOfPosition, origin, PathfindingMovementCapacity.Ground, out final); }
private WorldPositionScore ComputeExpansionScoreAtPosition(global::Empire empire, City city, WorldPosition centerPosition, WorldPosition element) { if (!element.IsValid) { return(null); } WorldPositionScore worldPositionScore = new WorldPositionScore(element, this.fimse); int regionIndex = (int)this.WorldPositionningService.GetRegionIndex(element); int num = 0; bool flag = false; for (int i = 0; i < 6; i++) { WorldPosition neighbourTile = this.WorldPositionningService.GetNeighbourTile(element, (WorldOrientation)i, 1); if (neighbourTile.IsValid) { if ((int)this.WorldPositionningService.GetRegionIndex(neighbourTile) != regionIndex) { worldPositionScore.SumOfLostTiles++; } else if (!this.WorldPositionningService.IsExploitable(neighbourTile, 0)) { worldPositionScore.SumOfLostTiles++; } else { if (city != null) { District district = this.WorldPositionningService.GetDistrict(neighbourTile); if (district != null) { if (district.Type == DistrictType.Exploitation) { goto IL_12B; } float propertyValue = district.GetPropertyValue(SimulationProperties.NumberOfExtensionAround); if (propertyValue < (float)DepartmentOfTheInterior.MinimumNumberOfExtensionNeighbourForLevelUp) { num += (int)propertyValue; goto IL_12B; } goto IL_12B; } } flag |= this.WorldPositionningService.IsOceanTile(neighbourTile); worldPositionScore.Add(this.GetWorldPositionScore(empire.Index, neighbourTile), 1f); worldPositionScore.NewDistrictNeighbourgNumber++; if (!this.WorldPositionningService.IsWaterTile(neighbourTile)) { worldPositionScore.NewDistrictNotWaterNeighbourNumber++; } } } IL_12B :; } worldPositionScore.SumOfNumberOfExtensionAround = num; worldPositionScore.HasCostalTile = flag; return(worldPositionScore); }
public bool IsExploitable(WorldPosition position, int bits = 0) { byte terrainType = this.GetTerrainType(position); StaticString terrainTypeMappingName = this.GetTerrainTypeMappingName(terrainType); if (!StaticString.IsNullOrEmpty(terrainTypeMappingName)) { TerrainTypeMapping terrainTypeMapping = null; if (this.terrainTypeMappingDatabase != null && this.terrainTypeMappingDatabase.TryGetValue(terrainTypeMappingName, out terrainTypeMapping) && terrainTypeMapping.Layers != null && terrainTypeMapping.Layers.Length > 0) { for (int i = 0; i < terrainTypeMapping.Layers.Length; i++) { if (terrainTypeMapping.Layers[i].Type == WorldPositionning.LayerTypeConstruction && terrainTypeMapping.Layers[i].Name == WorldPositionning.LayerNameNotExploitable) { return(false); } } } } GridMap <bool> gridMap = this.World.Atlas.GetMap(WorldAtlas.Maps.Ridges) as GridMap <bool>; if (gridMap != null && gridMap.GetValue(position)) { return(false); } Region region = this.GetRegion(position); if (region != null && region.PointOfInterests != null) { int j = 0; while (j < region.PointOfInterests.Length) { PointOfInterest pointOfInterest = region.PointOfInterests[j]; if (pointOfInterest.WorldPosition != position) { j++; } else { Diagnostics.Assert(pointOfInterest != null); Diagnostics.Assert(pointOfInterest.PointOfInterestDefinition != null); Diagnostics.Assert(pointOfInterest.PointOfInterestDefinition.PointOfInterestTemplate != null); if (WorldPositionning.NonConvertedVillagesArentExploitable && pointOfInterest.Type == "Village") { if (!pointOfInterest.SimulationObject.Tags.Contains(BarbarianCouncil.VillageStatusConverted) && pointOfInterest.CreepingNodeGUID == GameEntityGUID.Zero) { return(false); } IGameEntity gameEntity; if (pointOfInterest.CreepingNodeGUID != GameEntityGUID.Zero && this.GameEntityRepositoryService.TryGetValue(pointOfInterest.CreepingNodeGUID, out gameEntity)) { CreepingNode creepingNode = gameEntity as CreepingNode; if (creepingNode.IsUnderConstruction) { return(false); } } } string text; if (pointOfInterest.PointOfInterestDefinition.PointOfInterestTemplate.Properties != null && pointOfInterest.PointOfInterestDefinition.PointOfInterestTemplate.Properties.TryGetValue(WorldPositionning.PreventsDistrictTypeExploitationConstruction, out text)) { return(false); } break; } } } return(true); }
public void SpawnProjectile(string projectileId, UnitModel sender, ITarget receiver, WorldPosition position) { // TODO: add command _worldModel.Projectiles.Add(_projectileRepository.CreateProjectileFromId(projectileId, sender, receiver, position)); }
public void ApplyAoeMoraleEffect(Agent affectedAgent, WorldPosition affectedAgentPosition, WorldPosition affectorAgentPosition, Team affectedAgentTeam, float moraleChangeAffected, float moraleChangeAffector, float radius, Predicate <Agent> affectedCondition = null, Predicate <Agent> affectorCondition = null) { if (AgentCharacterIsExpendable(affectedAgent)) { return; } IEnumerable <Agent> nearbyAgents = Mission.GetNearbyAgents(affectedAgentPosition.AsVec2, radius); int num = 10; int num2 = 10; foreach (Agent agent in nearbyAgents) { BasicCharacterObject character = agent.Character; BasicCultureObject culture = character != null ? character.Culture : null; string cultureStringId = culture != null ? culture.StringId : null; if (agent.Team != null) { float num3 = agent.GetWorldPosition().GetNavMeshVec3().Distance(affectedAgentPosition.GetNavMeshVec3()); if (num3 < radius && agent.IsAIControlled) { if (agent.Team.IsEnemyOf(affectedAgentTeam)) { if (num > 0 && (affectorCondition == null || affectorCondition(agent))) { float delta = MissionGameModels.Current.BattleMoraleModel.CalculateMoraleChangeToCharacter(agent, moraleChangeAffector, num3); agent.GetCustomMoraleComponents().ForEach(component => { if (component != null) { component.Morale += delta; } }); num--; } } else if (num2 > 0 && (affectedCondition == null || affectedCondition(agent))) { float delta2 = MissionGameModels.Current.BattleMoraleModel.CalculateMoraleChangeToCharacter(agent, moraleChangeAffected, num3); agent.GetCustomMoraleComponents().ForEach(component => { if (component != null) { component.Morale += delta2; } }); num2--; } } } } }
public static bool GetCharacterSpawn(byte cityState, out WorldPosition spawnPosition) { return(characterSpawnStore.TryGetValue(cityState, out spawnPosition)); }
public void MoveTo(WorldPosition position, int distance = 0) { position.CopyTo(TargetPosition); TargetDistance = distance; Move(); }
/// <summary> /// Creates a new mesh /// </summary> /// <param name="device">The device used to create the mesh</param> /// <param name="filename">the file to load</param> public void Create(Device device, string filename) { worldPosition = new WorldPosition(); GraphicsStream adjacencyBuffer; ExtendedMaterial[] Mat; this.device = device; if (device != null) { device.DeviceLost += new System.EventHandler(this.InvalidateDeviceObjects); device.Disposing += new System.EventHandler(this.InvalidateDeviceObjects); device.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects); } filename = MediaUtilities.FindFile(filename); // Load the mesh systemMemoryMesh = Mesh.FromFile(filename, MeshFlags.SystemMemory, device, out adjacencyBuffer, out Mat); Mesh tempMesh = null; string errorString; tempMesh = Mesh.Clean(systemMemoryMesh, adjacencyBuffer, adjacencyBuffer, out errorString); systemMemoryMesh.Dispose(); systemMemoryMesh = tempMesh; // Optimize the mesh for performance systemMemoryMesh.OptimizeInPlace(MeshFlags.OptimizeCompact | MeshFlags.OptimizeAttrSort | MeshFlags.OptimizeVertexCache, adjacencyBuffer); // Setup bounding volumes VertexBuffer vb = systemMemoryMesh.VertexBuffer; GraphicsStream vertexData = vb.Lock(0, 0, LockFlags.NoSystemLock); boundingSphere.Radius = Geometry.ComputeBoundingSphere(vertexData, systemMemoryMesh.NumberVertices, systemMemoryMesh.VertexFormat, out boundingSphere.CenterPoint); vb.Unlock(); vb.Dispose(); textures = new Texture[Mat.Length]; materials = new Direct3D.Material[Mat.Length]; for (int i = 0; i < Mat.Length; i++) { materials[i] = Mat[i].Material3D; // Set the ambient color for the material (D3DX does not do this) materials[i].Ambient = materials[i].Diffuse; if (Mat[i].TextureFilename != null) { // Create the texture textures[i] = TextureLoader.FromFile(device, MediaUtilities.FindFile(Mat[i].TextureFilename)); } } adjacencyBuffer.Close(); adjacencyBuffer = null; RestoreDeviceObjects(device, null); }
protected override bool TryComputeArmyMissionParameter() { if (this.ticket != null) { if (this.ticket.Raised) { this.ticket = null; } return(false); } if (base.AIDataArmyGUID.IsValid && this.TargetCity != null && this.TargetCity.Empire == base.Commander.Empire && this.aiDataRepository.GetAIData <AIData_City>(this.TargetCity.GUID) != null) { AIData_Army aidata = this.aiDataRepository.GetAIData <AIData_Army>(base.AIDataArmyGUID); if (aidata != null) { List <object> list = new List <object>(); list.Add(this.TargetCity); if (this.TargetCity.MaximumUnitSlot > this.TargetCity.CurrentUnitSlot + aidata.Army.CurrentUnitSlot) { return(base.TryCreateArmyMission("DefendCity_Bail", list)); } if (aidata.Army.CurrentUnitSlot > 1) { GameEntityGUID[] array = new GameEntityGUID[1]; for (int i = 0; i < aidata.Army.StandardUnits.Count; i++) { if (aidata.Army.StandardUnits[i].IsSettler && aidata.Army.StandardUnits[i].GetPropertyValue(SimulationProperties.Movement) > 0f) { array[0] = aidata.Army.StandardUnits[i].GUID; break; } } WorldPosition neighbourFirstAvailablePositionForArmyCreation = DepartmentOfDefense.GetNeighbourFirstAvailablePositionForArmyCreation(aidata.Army); if (neighbourFirstAvailablePositionForArmyCreation.IsValid && array[0].IsValid) { OrderTransferGarrisonToNewArmy order = new OrderTransferGarrisonToNewArmy(base.Commander.Empire.Index, base.AIDataArmyGUID, array, neighbourFirstAvailablePositionForArmyCreation, null, false, true, true); base.Commander.Empire.PlayerControllers.AI.PostOrder(order, out this.ticket, null); } return(false); } return(base.TryCreateArmyMission("ReachTarget", list)); } } Diagnostics.Assert(AIScheduler.Services != null); IIntelligenceAIHelper service = AIScheduler.Services.GetService <IIntelligenceAIHelper>(); Diagnostics.Assert(service != null); List <Region> list2 = new List <Region>(); if (service.TryGetListOfRegionToExplore(base.Commander.Empire, 0.95f, ref list2)) { foreach (Region region in list2) { if (AILayer_Exploration.IsRegionValidForExploration(base.Commander.Empire, region)) { return(base.TryCreateArmyMission("ExploreAt", new List <object> { region.Index })); } } return(false); } return(false); }
public SignalShape(Viewer viewer, SignalObj mstsSignal, string path, WorldPosition position, ShapeFlags flags) : base(viewer, path, position, flags) { #if DEBUG_SIGNAL_SHAPES Console.WriteLine("{0} signal {1}:", Location.ToString(), mstsSignal.UID); UID = mstsSignal.UID; #endif var signalShape = Path.GetFileName(path).ToUpper(); if (!viewer.SIGCFG.SignalShapes.ContainsKey(signalShape)) { Trace.TraceWarning("{0} signal {1} has invalid shape {2}.", Location.ToString(), mstsSignal.UID, signalShape); return; } var mstsSignalShape = viewer.SIGCFG.SignalShapes[signalShape]; #if DEBUG_SIGNAL_SHAPES Console.WriteLine(" Shape={0} SubObjs={1,-2} {2}", Path.GetFileNameWithoutExtension(path).ToUpper(), mstsSignalShape.SignalSubObjs.Count, mstsSignalShape.Description); #endif // The matrix names are used as the sub-object names. The sub-object visibility comes from // mstsSignal.SignalSubObj, which is mapped to names through mstsSignalShape.SignalSubObjs. var visibleMatrixNames = new bool[SharedShape.MatrixNames.Count]; for (var i = 0; i < mstsSignalShape.SignalSubObjs.Count; i++) if ((((mstsSignal.SignalSubObj >> i) & 0x1) == 1) && (SharedShape.MatrixNames.Contains(mstsSignalShape.SignalSubObjs[i].MatrixName))) visibleMatrixNames[SharedShape.MatrixNames.IndexOf(mstsSignalShape.SignalSubObjs[i].MatrixName)] = true; // All sub-objects except the one pointing to the first matrix (99.00% times it is the first one, but not always, see Protrain) are hidden by default. //For each other sub-object, look up its name in the hierarchy and use the visibility of that matrix. SubObjVisible = new bool[SharedShape.LodControls[0].DistanceLevels[0].SubObjects.Length]; SubObjVisible[0] = true; for (var i = 1; i < SharedShape.LodControls[0].DistanceLevels[0].SubObjects.Length; i++) { if (i == SharedShape.RootSubObjectIndex) SubObjVisible[i] = true; else { var subObj =SharedShape.LodControls[0].DistanceLevels[0].SubObjects[i]; int minHiLevIndex = 0; if (subObj.ShapePrimitives[0].Hierarchy[subObj.ShapePrimitives[0].HierarchyIndex] > 0) // Search for ShapePrimitive with lowest Hierarchy Value and check visibility with it { var minHiLev = 999; for (var j = 0; j < subObj.ShapePrimitives.Length; j++) { if (subObj.ShapePrimitives[0].Hierarchy[subObj.ShapePrimitives[j].HierarchyIndex] < minHiLev) { minHiLevIndex = j; minHiLev = subObj.ShapePrimitives[0].Hierarchy[subObj.ShapePrimitives[j].HierarchyIndex]; } } } SubObjVisible[i] = visibleMatrixNames[SharedShape.LodControls[0].DistanceLevels[0].SubObjects[i].ShapePrimitives[minHiLevIndex].HierarchyIndex]; } } #if DEBUG_SIGNAL_SHAPES for (var i = 0; i < mstsSignalShape.SignalSubObjs.Count; i++) Console.WriteLine(" SUBOBJ {1,-12} {0,-7} {2,3} {3,3} {4,2} {5,2} {6,-14} {8} ({7})", ((mstsSignal.SignalSubObj >> i) & 0x1) != 0 ? "VISIBLE" : "hidden", mstsSignalShape.SignalSubObjs[i].MatrixName, mstsSignalShape.SignalSubObjs[i].Optional ? "Opt" : "", mstsSignalShape.SignalSubObjs[i].Default ? "Def" : "", mstsSignalShape.SignalSubObjs[i].JunctionLink ? "JL" : "", mstsSignalShape.SignalSubObjs[i].BackFacing ? "BF" : "", mstsSignalShape.SignalSubObjs[i].SignalSubType == -1 ? "<none>" : MSTS.SignalShape.SignalSubObj.SignalSubTypes[mstsSignalShape.SignalSubObjs[i].SignalSubType], mstsSignalShape.SignalSubObjs[i].SignalSubSignalType, mstsSignalShape.SignalSubObjs[i].Description); for (var i = 0; i < SubObjVisible.Length; i++) Console.WriteLine(" SUBOBJ {0,-2} {1,-7}", i, SubObjVisible[i] ? "VISIBLE" : "hidden"); #endif if (mstsSignal.SignalUnits == null) { Trace.TraceWarning("{0} signal {1} has no SignalUnits.", Location.ToString(), mstsSignal.UID); return; } for (var i = 0; i < mstsSignal.SignalUnits.Units.Length; i++) { #if DEBUG_SIGNAL_SHAPES Console.Write(" UNIT {0}: TrItem={1,-5} SubObj={2,-2}", i, mstsSignal.SignalUnits.Units[i].TrItem, mstsSignal.SignalUnits.Units[i].SubObj); #endif // Find the simulation SignalObject for this shape. var signalAndHead = viewer.Simulator.Signals.FindByTrItem(mstsSignal.SignalUnits.Units[i].TrItem); if (!signalAndHead.HasValue) { Trace.TraceWarning("Skipped {0} signal {1} unit {2} with invalid TrItem {3}", Location.ToString(), mstsSignal.UID, i, mstsSignal.SignalUnits.Units[i].TrItem); continue; } // Get the signal sub-object for this unit (head). var mstsSignalSubObj = mstsSignalShape.SignalSubObjs[mstsSignal.SignalUnits.Units[i].SubObj]; if (mstsSignalSubObj.SignalSubType != 1) // SIGNAL_HEAD { Trace.TraceWarning("Skipped {0} signal {1} unit {2} with invalid SubObj {3}", Location.ToString(), mstsSignal.UID, i, mstsSignal.SignalUnits.Units[i].SubObj); continue; } var mstsSignalItem = (SignalItem)(viewer.Simulator.TDB.TrackDB.TrItemTable[mstsSignal.SignalUnits.Units[i].TrItem]); try { // Go create the shape head. Heads.Add(new SignalShapeHead(viewer, this, i, signalAndHead.Value.Value, mstsSignalItem, mstsSignalSubObj)); } catch (InvalidDataException error) { Trace.TraceWarning(error.Message); } #if DEBUG_SIGNAL_SHAPES Console.WriteLine(); #endif } }
protected override void CalculateCurrentOrder() { WorldPosition medianPosition = this.formation.QuerySystem.MedianPosition; bool flag = false; Vec2 vec2_1; WorldPosition worldPosition; Vec2 vec2_2; if (this.formation.QuerySystem.ClosestSignificantlyLargeEnemyFormation == null || this._archerFormation == null) { vec2_1 = this.formation.Direction; medianPosition.SetVec2(this.formation.QuerySystem.AveragePosition); } else { worldPosition = this.formation.QuerySystem.ClosestSignificantlyLargeEnemyFormation.MedianPosition; vec2_1 = worldPosition.AsVec2 - this.formation.QuerySystem.AveragePosition; float val2 = vec2_1.Normalize(); float num = this._archerFormation.QuerySystem.RangedUnitRatio * 0.5f / (float)this._archerFormation.arrangement.RankCount; switch (this._behaviorState) { case BehaviorCautiousAdvance.BehaviorState.Approaching: if ((double)val2 < (double)this._cantShootDistance * 0.800000011920929) { this._behaviorState = BehaviorCautiousAdvance.BehaviorState.Shooting; this._cantShoot = false; flag = true; } else if ((double)this._archerFormation.QuerySystem.MakingRangedAttackRatio >= (double)num * 1.20000004768372) { this._behaviorState = BehaviorCautiousAdvance.BehaviorState.Shooting; this._cantShoot = false; flag = true; } if (this._behaviorState == BehaviorCautiousAdvance.BehaviorState.Shooting) { this._shootPosition = this.formation.QuerySystem.AveragePosition + vec2_1 * 5f; break; } break; case BehaviorCautiousAdvance.BehaviorState.Shooting: if ((double)this._archerFormation.QuerySystem.MakingRangedAttackRatio <= (double)num) { if ((double)val2 > (double)this._archerFormation.QuerySystem.MissileRange) { this._behaviorState = BehaviorCautiousAdvance.BehaviorState.Approaching; this._cantShootDistance = Math.Min(this._cantShootDistance, this._archerFormation.QuerySystem.MissileRange * 0.9f); this._shootPosition = Vec2.Invalid; break; } if (!this._cantShoot) { this._cantShoot = true; this._cantShootTimer.Reset(Mission.Current.Time, this._archerFormation == null ? 10f : MBMath.Lerp(10f, 15f, (float)(((double)MBMath.ClampFloat((float)this._archerFormation.CountOfUnits, 10f, 60f) - 10.0) * 0.0199999995529652))); break; } if (this._cantShootTimer.Check(Mission.Current.Time)) { this._behaviorState = BehaviorCautiousAdvance.BehaviorState.Approaching; this._cantShootDistance = Math.Min(this._cantShootDistance, val2); this._shootPosition = Vec2.Invalid; break; } break; } this._cantShootDistance = Math.Max(this._cantShootDistance, val2); this._cantShoot = false; if ((!this.formation.QuerySystem.ClosestSignificantlyLargeEnemyFormation.IsRangedFormation && !this.formation.QuerySystem.ClosestSignificantlyLargeEnemyFormation.IsRangedCavalryFormation || (double)val2 < (double)this.formation.QuerySystem.ClosestSignificantlyLargeEnemyFormation.MissileRange && (double)this.formation.QuerySystem.ClosestSignificantlyLargeEnemyFormation.MakingRangedAttackRatio < 0.100000001490116) && (double)val2 < (double)Math.Min(this._archerFormation.QuerySystem.MissileRange * 0.4f, this._cantShootDistance * 0.667f)) { this._behaviorState = BehaviorCautiousAdvance.BehaviorState.PullingBack; this._shootPosition = Vec2.Invalid; break; } break; case BehaviorCautiousAdvance.BehaviorState.PullingBack: if ((double)val2 > (double)Math.Min(this._cantShootDistance, this._archerFormation.QuerySystem.MissileRange) * 0.800000011920929) { this._behaviorState = BehaviorCautiousAdvance.BehaviorState.Shooting; this._cantShoot = false; this._shootPosition = this.formation.QuerySystem.AveragePosition + vec2_1 * 5f; flag = true; break; } break; } switch (this._behaviorState) { case BehaviorCautiousAdvance.BehaviorState.Approaching: medianPosition = this.formation.QuerySystem.ClosestEnemyFormation.MedianPosition; if (this._switchedToShieldWallRecently && !this._switchedToShieldWallTimer.Check(Mission.Current.Time) && (double)this.formation.QuerySystem.FormationDispersedness > 2.0) { if (this._reformPosition.IsValid) { medianPosition.SetVec2(this._reformPosition); break; } worldPosition = this.formation.QuerySystem.Team.MedianTargetFormationPosition; vec2_2 = worldPosition.AsVec2 - this.formation.QuerySystem.AveragePosition; vec2_1 = vec2_2.Normalized(); this._reformPosition = this.formation.QuerySystem.AveragePosition + vec2_1 * 5f; medianPosition.SetVec2(this._reformPosition); break; } this._switchedToShieldWallRecently = false; this._reformPosition = Vec2.Invalid; medianPosition.SetVec2(this.formation.QuerySystem.ClosestEnemyFormation.AveragePosition); break; case BehaviorCautiousAdvance.BehaviorState.Shooting: if (this._shootPosition.IsValid) { medianPosition.SetVec2(this._shootPosition); break; } medianPosition.SetVec2(this.formation.QuerySystem.AveragePosition); break; case BehaviorCautiousAdvance.BehaviorState.PullingBack: medianPosition = this.formation.QuerySystem.MedianPosition; medianPosition.SetVec2(this.formation.QuerySystem.AveragePosition); break; } } worldPosition = this.CurrentOrder.GetPosition(this.formation); if (((!worldPosition.IsValid ? 1 : (this._behaviorState != BehaviorCautiousAdvance.BehaviorState.Shooting ? 1 : 0)) | (flag ? 1 : 0)) == 0) { worldPosition = this.CurrentOrder.GetPosition(this.formation); if ((double)worldPosition.GetNavMeshVec3().DistanceSquared(medianPosition.GetNavMeshVec3()) < (double)this.formation.Depth * (double)this.formation.Depth) { goto label_34; } } this.CurrentOrder = MovementOrder.MovementOrderMove(medianPosition); label_34: vec2_2 = this.CurrentFacingOrder.GetDirection(this.formation); if (vec2_2.IsValid && !(this._behaviorState != BehaviorCautiousAdvance.BehaviorState.Shooting | flag)) { vec2_2 = this.CurrentFacingOrder.GetDirection(this.formation); if ((double)vec2_2.DotProduct(vec2_1) > (double)MBMath.Lerp(0.5f, 1f, (float)(1.0 - (double)MBMath.ClampFloat(this.formation.Width, 1f, 20f) * 0.0500000007450581))) { return; } } this.CurrentFacingOrder = FacingOrder.FacingOrderLookAtDirection(vec2_1); }
public bool HasRidge(WorldPosition position) { GridMap <bool> gridMap = this.World.Atlas.GetMap(WorldAtlas.Maps.Ridges) as GridMap <bool>; return(gridMap != null && gridMap.GetValue(position)); }
public Vector2 GetDirection(WorldPosition worldPosition, WorldPosition lookAtWorldPosition) { return(WorldPosition.GetDirection(worldPosition, lookAtWorldPosition, this.world.WorldParameters.IsCyclicWorld, this.world.WorldParameters.Columns)); }
private WorldPositionScore ComputeColonizationScoreAtPosition(global::Empire empire, WorldPosition element) { if (!element.IsValid) { return(null); } bool flag = false; WorldPositionScore worldPositionScore = new WorldPositionScore(this.GetWorldPositionScore(empire.Index, element)); int regionIndex = (int)this.WorldPositionningService.GetRegionIndex(element); foreach (WorldPosition worldPosition in WorldPosition.ParseTilesAtRange(element, 1, this.WorldPositionningService.World.WorldParameters)) { if (worldPosition.IsValid) { if (this.WorldPositionningService.IsExploitable(worldPosition, 0)) { if ((int)this.WorldPositionningService.GetRegionIndex(worldPosition) == regionIndex) { flag |= this.WorldPositionningService.IsOceanTile(worldPosition); worldPositionScore.Add(this.GetWorldPositionScore(empire.Index, worldPosition), 1f); } } } } foreach (WorldPosition worldPosition2 in WorldPosition.ParseTilesAtRange(element, 1, this.WorldPositionningService.World.WorldParameters)) { if (worldPosition2.IsValid) { if (this.WorldPositionningService.IsExploitable(worldPosition2, 0)) { if ((int)this.WorldPositionningService.GetRegionIndex(worldPosition2) == regionIndex) { worldPositionScore.Add(this.ComputeExpansionScoreAtPosition(empire, null, element, worldPosition2), this.secondRangePercent); worldPositionScore.NewDistrictNeighbourgNumber++; if (!this.WorldPositionningService.IsWaterTile(worldPosition2)) { worldPositionScore.NewDistrictNotWaterNeighbourNumber++; } } } } } this.ComputeCountByOrientation(element, ref worldPositionScore.CountByOrientation); worldPositionScore.HasCostalTile = flag; return(worldPositionScore); }
public int GetDistance(WorldPosition left, WorldPosition right) { return(WorldPosition.GetDistance(left, right, this.world.WorldParameters.IsCyclicWorld, this.world.WorldParameters.Columns)); }
private WorldPositionScore ComputeCreepingNodeImprovementScoreAtPosition(global::Empire empire, City city, PointOfInterest creepingNodePOI, CreepingNodeImprovementDefinition creepingNodeImprovementDefinition) { if (creepingNodePOI == null) { return(null); } if (creepingNodeImprovementDefinition == null) { return(null); } WorldPosition worldPosition = creepingNodePOI.WorldPosition; if (!worldPosition.IsValid) { return(null); } WorldPositionScore worldPositionScore = new WorldPositionScore(worldPosition, this.fimse); int regionIndex = (int)this.WorldPositionningService.GetRegionIndex(worldPosition); int fidsiextractionRange = creepingNodeImprovementDefinition.FIDSIExtractionRange; int num = fidsiextractionRange; if (ELCPUtilities.UseELCPSymbiosisBuffs && num > 0) { num = ((fidsiextractionRange < 7) ? 1 : 2); } WorldPosition[] worldPositions = new WorldCircle(worldPosition, num).GetWorldPositions(this.WorldPositionningService.World.WorldParameters); int num2 = 0; bool flag = false; foreach (WorldPosition worldPosition2 in worldPositions) { if (worldPosition2.IsValid) { if ((int)this.WorldPositionningService.GetRegionIndex(worldPosition2) != regionIndex) { worldPositionScore.SumOfLostTiles++; } else if (!this.WorldPositionningService.IsExploitable(worldPosition2, 0)) { worldPositionScore.SumOfLostTiles++; } else { if (city != null) { District district = this.WorldPositionningService.GetDistrict(worldPosition2); if (district != null) { if (district.Type == DistrictType.Exploitation) { goto IL_17A; } float propertyValue = district.GetPropertyValue(SimulationProperties.NumberOfExtensionAround); if (propertyValue < (float)DepartmentOfTheInterior.MinimumNumberOfExtensionNeighbourForLevelUp) { num2 += (int)propertyValue; goto IL_17A; } goto IL_17A; } } flag |= this.WorldPositionningService.IsWaterTile(worldPosition2); worldPositionScore.Add(this.GetWorldPositionScore(empire.Index, worldPosition2), 1f); worldPositionScore.NewDistrictNeighbourgNumber++; if (!this.WorldPositionningService.IsWaterTile(worldPosition2)) { worldPositionScore.NewDistrictNotWaterNeighbourNumber++; } } } IL_17A :; } worldPositionScore.SumOfNumberOfExtensionAround = num2; worldPositionScore.HasCostalTile = flag; return(worldPositionScore); }
public District GetDistrict(WorldPosition worldPosition) { return(this.worldAtlasDistricts.GetValue(worldPosition)); }
public void ComputeFarestPositionInList(WorldPosition[] listOfPosition, WorldPosition origin, PathfindingMovementCapacity pathfindingCapacity, out WorldPosition final) { WorldPosition worldPosition = WorldPosition.Invalid; if (listOfPosition.Length > 0) { IGameService service = Services.GetService <IGameService>(); Diagnostics.Assert(service != null); IWorldPositionningService service2 = service.Game.Services.GetService <IWorldPositionningService>(); Diagnostics.Assert(service2 != null); IPathfindingService service3 = service.Game.Services.GetService <IPathfindingService>(); float num = 0f; for (int i = 0; i < listOfPosition.Length; i++) { if (service3.IsTilePassable(listOfPosition[i], pathfindingCapacity, (PathfindingFlags)0) && service3.IsTileStopable(listOfPosition[i], pathfindingCapacity, (PathfindingFlags)0)) { float num2 = (float)service2.GetDistance(listOfPosition[i], origin); if (num2 > num) { worldPosition = listOfPosition[i]; num = num2; } } } } final = worldPosition; }
public int GetExplorationBits(WorldPosition position) { return((int)this.worldAtlasExploration.GetValue((int)position.Row, (int)position.Column)); }
public void DestroyBlock(WorldPosition pos) { _world.DestroyBlock(pos); }
public WorldPosition GetNeighbourTile(WorldPosition positionInWorldReference, WorldOrientation direction, int distance = 1) { WorldPosition neighbourTile = WorldPosition.GetNeighbourTile(positionInWorldReference, direction, distance); return(WorldPosition.GetValidPosition(neighbourTile, this.world.WorldParameters)); }
public static AmbientObject createSmallRocks(WorldPosition position) { return(AmbientObjectType.Create(new WorldPosition(position.X - 12.5f + WorldGrid.BlockSize.X / 2, position.Y + 10 + WorldGrid.BlockSize.Y / 2, position.InteriorID), AmbientObjectType.lookup[random.Next(0, 2)])); }
public WorldOrientation GetOrientation(WorldPosition worldPosition, WorldPosition lookAtWorldPosition) { return(WorldPosition.GetOrientation(worldPosition, lookAtWorldPosition, this.world.WorldParameters.IsCyclicWorld, this.world.WorldParameters.Columns)); }
/// <summary> /// Decompose and add a SuperElevation on top of MSTS track section /// </summary> /// <param name="viewer">Viewer reference.</param> /// <param name="trackList">DynamicTrackViewer list.</param> /// <param name="trackObj">Dynamic track section to decompose.</param> /// <param name="worldMatrixInput">Position matrix.</param> /// <param name="TileX">TileX coordinates.</param> /// <param name="TileZ">TileZ coordinates.</param> /// <param name="shapeFilePath">Path to the shape file.</param> public static bool DecomposeStaticSuperElevation(Viewer viewer, List <DynamicTrackViewer> trackList, TrackObj trackObj, WorldPosition worldMatrixInput, int TileX, int TileZ, string shapeFilePath) { TrackShape shape = null; try { shape = viewer.Simulator.TSectionDat.TrackShapes.Get(trackObj.SectionIdx); if (shape.RoadShape == true) { return(false); } } catch (Exception) { return(false); } SectionIdx[] SectionIdxs = shape.SectionIdxs; int count = -1; int drawn = 0; bool isTunnel = shape.TunnelShape; List <TrVectorSection> sectionsinShape = new List <TrVectorSection>(); //List<DynamicTrackViewer> tmpTrackList = new List<DynamicTrackViewer>(); foreach (SectionIdx id in SectionIdxs) { uint[] sections = id.TrackSections; for (int i = 0; i < sections.Length; i++) { count++; uint sid = id.TrackSections[i]; TrackSection section = viewer.Simulator.TSectionDat.TrackSections.Get(sid); if (Math.Abs(section.SectionSize.Width - viewer.Simulator.SuperElevationGauge) > 0.2) { continue; //the main route has a gauge different than mine } if (section.SectionCurve == null) { continue; //with strait track, will remove all related sections later } TrVectorSection tmp = null; if (section.SectionCurve != null) { tmp = FindSectionValue(shape, viewer.Simulator, section, TileX, TileZ, trackObj.UID); } if (tmp == null) //cannot find the track for super elevation, will return 0; { continue; } sectionsinShape.Add(tmp); drawn++; } } if (drawn <= count || isTunnel)//tunnel or not every section is in SE, will remove all sections in the shape out { if (sectionsinShape.Count > 0) { RemoveTracks(viewer.Simulator, sectionsinShape); } return(false); } return(true); }
public byte GetTerrainType(WorldPosition position) { return(this.worldAtlasTerrain.GetValue(position)); }
/// <summary> /// Creates a new mesh /// </summary> /// <param name="device">The device used to create the mesh</param> /// <param name="filename">the file to load</param> public void Create(Device device, string filename) { worldPosition = new WorldPosition(); GraphicsStream adjacencyBuffer; ExtendedMaterial[] Mat; this.device = device; if (device != null) { device.DeviceLost += new System.EventHandler(this.InvalidateDeviceObjects); device.Disposing += new System.EventHandler(this.InvalidateDeviceObjects); device.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects); } filename = MediaUtilities.FindFile(filename); // Load the mesh systemMemoryMesh = Mesh.FromFile(filename, MeshFlags.SystemMemory, device, out adjacencyBuffer, out Mat); Mesh tempMesh = null; string errorString; tempMesh = Mesh.Clean(CleanType.Optimization, systemMemoryMesh, adjacencyBuffer, adjacencyBuffer, out errorString); if (tempMesh != systemMemoryMesh) { systemMemoryMesh.Dispose(); systemMemoryMesh = tempMesh; } // Optimize the mesh for performance MeshFlags flags = MeshFlags.OptimizeCompact | MeshFlags.OptimizeAttributeSort | MeshFlags.OptimizeVertexCache; systemMemoryMesh.OptimizeInPlace(flags, adjacencyBuffer); adjacencyBuffer.Close(); adjacencyBuffer = null; // Setup bounding volumes VertexBuffer vb = systemMemoryMesh.VertexBuffer; GraphicsStream vertexData = vb.Lock(0, 0, LockFlags.ReadOnly); boundingSphere.Radius = Geometry.ComputeBoundingSphere(vertexData,systemMemoryMesh.NumberVertices,systemMemoryMesh.VertexFormat, out boundingSphere.CenterPoint); vb.Unlock(); vb.Dispose(); textures = new Texture[Mat.Length]; materials = new Direct3D.Material[Mat.Length]; for (int i=0; i<Mat.Length; i++) { materials[i] = Mat[i].Material3D; // Set the ambient color for the material (D3DX does not do this) materials[i].Ambient = materials[i].Diffuse; if (Mat[i].TextureFilename != null) { // Create the texture textures[i] = TextureLoader.FromFile(device, MediaUtilities.FindFile(Mat[i].TextureFilename)); } } RestoreDeviceObjects(device, null); }
public sbyte GetTerrainHeight(WorldPosition position) { return(this.worldAtlasTerrainHeight.GetValue(position)); }