public void AddDiscoveredAsteroid(IMyVoxelBase asteroid) { if (!_asteroids.ContainsKey(asteroid)) { _asteroids.Add(asteroid, 1); } }
private bool DeletePlanet(IMyVoxelBase planetEntity) { if (planetEntity == null) return false; var name = planetEntity.StorageName; planetEntity.SyncObject.SendCloseRequest(); MyAPIGateway.Utilities.ShowMessage("planet", "'{0}' deleted.", name); return true; }
//time out is 5 for performance reasons public ConquestMission(bool ong, Vector3D loc, int start,ActionTypes missiont, int timeout = 0, bool isasteroid = false, IMyVoxelBase ast = null) { MissionType = missiont; Ongoing = ong; Location = loc; StartTime = start; IsAsteroid = isasteroid; this.timeout = r.Next((int) (timeout*.7),(int) (timeout*1.3)); asteroid = ast; }
public static void RequestRevertShape(IMyVoxelBase voxelMap, IMyVoxelShape voxelShape) { MyVoxelBase voxel = voxelMap as MyVoxelBase; MyShape shape = voxelShape as MyShape; if ((voxel != null) && (shape != null)) { shape.SendRevertRequest(voxel); } }
public VoxelData(Ingame.IMyOreDetector oreDetector, IMyVoxelBase voxel, float maxRange) { this.m_logger = new Logger(GetType().Name, () => oreDetector.CubeGrid.DisplayName, () => oreDetector.DisplayNameText, () => voxel.ToString()); this.m_oreDetector = oreDetector; this.m_voxel = voxel; this.m_storage.Resize(new Vector3I(QUERY_STEP, QUERY_STEP, QUERY_STEP)); this.m_maxRange = maxRange; m_logger.debugLog("Created for voxel at " + voxel.PositionLeftBottomCorner, "VoxelData()"); }
public static void RequestCutOutShape(IMyVoxelBase voxelMap, IMyVoxelShape voxelShape) { MyVoxelBase voxelbool = voxelMap as MyVoxelBase; MyShape shape = voxelShape as MyShape; if ((voxelbool != null) && (shape != null)) { shape.SendCutOutRequest(voxelbool); } }
public static void RequestPaintInShape(IMyVoxelBase voxelMap, IMyVoxelShape voxelShape, byte materialIdx) { MyVoxelBase voxel = voxelMap as MyVoxelBase; MyShape shape = voxelShape as MyShape; if ((voxel != null) && (shape != null)) { shape.SendPaintRequest(voxel, materialIdx); } }
public static void RequestFillInShape(IMyVoxelBase voxelMap, IMyVoxelShape voxelShape, byte materialIdx) { var map = voxelMap as MyVoxelBase; var shape = voxelShape as MyShape; if (map != null && shape != null) { shape.SendFillRequest(map.GetSyncObject, materialIdx); } }
//time out is 5 for performance reasons public ConquestMission(bool ong, Vector3D loc, int start, ActionTypes missiont, int timeout = 0, bool isasteroid = false, IMyVoxelBase ast = null) { MissionType = missiont; Ongoing = ong; Location = loc; StartTime = start; IsAsteroid = isasteroid; this.timeout = r.Next((int)(timeout * .7), (int)(timeout * 1.3)); asteroid = ast; }
public static void RequestCutOutShape(IMyVoxelBase voxelMap, IMyVoxelShape voxelShape) { var map = voxelMap as MyVoxelBase; var shape = voxelShape as MyShape; if (map != null && shape != null) { shape.SendCutOutRequest(map); } }
public static void RequestPaintInShape(IMyVoxelBase voxelMap, IMyVoxelShape voxelShape, byte materialIdx) { var map = voxelMap as MyVoxelBase; var shape = voxelShape as MyShape; if (map != null && shape != null) { shape.SendPaintRequest(map, materialIdx); } }
public VoxelData(IMyOreDetector oreDetector, IMyVoxelBase voxel, float maxRange) { this.m_oreDetector = oreDetector; this.m_voxel = voxel; this.m_storage.Resize(new Vector3I(QUERY_STEP, QUERY_STEP, QUERY_STEP)); this.m_maxRange = maxRange; (this.m_voxel as MyVoxelBase).RangeChanged += m_voxel_RangeChanged; this.NeedsUpdate = true; Log.DebugLog("Created for voxel at " + voxel.PositionLeftBottomCorner); }
public void Scan(IMyVoxelBase asteroid) { try { FindMaterial(asteroid, asteroid.GetPosition(), 4, asteroid.LocalAABB.Max.Normalize()); } catch (Exception e) { Util.GetInstance().LogError(e.ToString()); } }
private bool DeletePlanet(ulong steamId, IMyVoxelBase planetEntity) { if (planetEntity == null) { return(false); } var name = planetEntity.StorageName; planetEntity.SyncObject.SendCloseRequest(); MyAPIGateway.Utilities.SendMessage(steamId, "planet", "'{0}' deleted.", name); return(true); }
private void DeletePlanet(ulong steamId, IMyVoxelBase planetEntity) { if (planetEntity == null || planetEntity.Closed) { MyAPIGateway.Utilities.SendMessage(steamId, "planet", "already deleted."); return; } var name = planetEntity.StorageName; planetEntity.Close(); MyAPIGateway.Utilities.SendMessage(steamId, "planet", "'{0}' deleted.", name); }
private bool IsInsideVoxel_ALt(IMyVoxelBase voxelmap, Vector3D world, float radius = 0.866f) { var sphere = new BoundingSphereD(world, radius); var entity = MyAPIGateway.Entities.GetIntersectionWithSphere(ref sphere); if (entity?.EntityId == voxelmap.EntityId) { return(true); } return(false); }
private static void ComputeShapeBounds(IMyVoxelBase voxelMap, ref BoundingBoxD shapeAabb, Vector3D voxelMapMinCorner, Vector3I storageSize, out Vector3I voxelMin, out Vector3I voxelMax) { MyVoxelCoordSystems.WorldPositionToVoxelCoord(voxelMapMinCorner, ref shapeAabb.Min, out voxelMin); MyVoxelCoordSystems.WorldPositionToVoxelCoord(voxelMapMinCorner, ref shapeAabb.Max, out voxelMax); MyVoxelBase voxelBase = voxelMap as MyVoxelBase; voxelMin += voxelBase.StorageMin; voxelMax += voxelBase.StorageMin + 1; storageSize -= 1; Vector3I.Clamp(ref voxelMin, ref Vector3I.Zero, ref storageSize, out voxelMin); Vector3I.Clamp(ref voxelMax, ref Vector3I.Zero, ref storageSize, out voxelMax); }
private bool IsInsideVoxel(IMyVoxelBase voxelmap, Vector3D world, float radius = 0.866f) { byte material, content; GetVoxelContent(voxelmap, world, out content, out material); var voxelMat = MyDefinitionManager.Static.GetVoxelMaterialDefinition(material); if (content == MyVoxelConstants.VOXEL_CONTENT_EMPTY || voxelMat == null) { return(false); } return(true); }
public static void Storage_ClampVoxelCoord(this IMyVoxelBase Voxel, ref Vector3I voxelCoord, int distance = 1) { if (Voxel == null) { throw new ArgumentNullException(nameof(Voxel)); } if (Voxel.Storage == null) { throw new ArgumentException("Voxel.Storage is null"); } Vector3I vector3I = Voxel.Storage.Size - distance; Vector3I.Clamp(ref voxelCoord, ref Vector3I.Zero, ref vector3I, out voxelCoord); }
public static void RemoveVoxelAt(this IMyVoxelBase Voxel, Vector3I LocalPoint) { if (Voxel == null) { throw new ArgumentNullException(nameof(Voxel)); } if (Voxel.Storage == null) { throw new ArgumentException("Voxel.Storage is null"); } MyVoxelBase _Voxel = Voxel as MyVoxelBase; VoxelRemove remover = new VoxelRemove(); _Voxel.Storage.ExecuteOperationFast(ref remover, MyStorageDataTypeFlags.Content, ref LocalPoint, ref LocalPoint, false); }
private bool ReplaceAsteroidMaterial(ulong steamId, IMyVoxelBase originalAsteroid, string searchMaterialName1, string searchMaterialName2) { MyVoxelMaterialDefinition material1; string suggestedMaterials = ""; if (!Support.FindMaterial(searchMaterialName1, out material1, ref suggestedMaterials)) { MyAPIGateway.Utilities.SendMessage(steamId, "Invalid Material1 specified.", "Cannot find the material '{0}'.\r\nTry the following: {1}", searchMaterialName1, suggestedMaterials); return(true); } MyVoxelMaterialDefinition material2; if (!Support.FindMaterial(searchMaterialName2, out material2, ref suggestedMaterials)) { MyAPIGateway.Utilities.SendMessage(steamId, "Invalid Material2 specified.", "Cannot find the material '{0}'.\r\nTry the following: {1}", searchMaterialName2, suggestedMaterials); return(true); } var oldStorage = originalAsteroid.Storage; var oldCache = new MyStorageData(); oldCache.Resize(oldStorage.Size); oldStorage.ReadRange(oldCache, MyStorageDataTypeFlags.ContentAndMaterial, 0, Vector3I.Zero, oldStorage.Size - 1); Vector3I p; for (p.Z = 0; p.Z < oldStorage.Size.Z; ++p.Z) { for (p.Y = 0; p.Y < oldStorage.Size.Y; ++p.Y) { for (p.X = 0; p.X < oldStorage.Size.X; ++p.X) { var material = oldCache.Material(ref p); if (material == material1.Index) { oldCache.Material(ref p, material2.Index); } } } } oldStorage.WriteRange(oldCache, MyStorageDataTypeFlags.ContentAndMaterial, Vector3I.Zero, oldStorage.Size - 1); MyAPIGateway.Utilities.SendMessage(steamId, "Asteroid", "'{0}' material '{1}' replaced with '{2}'.", originalAsteroid.StorageName, material1.Id.SubtypeName, material2.Id.SubtypeName); return(true); }
private void OnOreSearchComplete(bool success, IMyVoxelBase foundVoxel, string oreName, IEnumerable <Vector3D> positions) { Log.DebugLog("success: " + success + ", foundVoxel: " + foundVoxel + ", oreName: " + oreName, Logger.severity.DEBUG); if (!success) { Log.DebugLog("No ore target found", Logger.severity.INFO); m_navSet.OnTaskComplete_NavRot(); m_navSet.Settings_Commands.Complaint = InfoString.StringId.NoOreFound; return; } m_targetVoxel = foundVoxel; m_oreName = oreName; if (m_approachFinders != null) { m_approachFinders.Clear(); } else { ResourcePool.Get(out m_approachFinders); } Vector3D centre = TargetVoxel.GetCentre(); double minSpace = 4d * m_grid.LocalVolume.Radius; foreach (Vector3D pos in positions) { Vector3D deposit = pos; if (deposit == centre) { deposit += 1; } m_approachFinders.Add(new DepositFreeSpace(TargetVoxel, ref deposit, minSpace)); if (m_approachFinders.Count == MaxDeposits) { break; } } Log.DebugLog("Created " + m_approachFinders.Count + " finders for " + oreName); m_stage = Stage.GetApproach; }
public static bool HasVoxelAt(this IMyVoxelBase Voxel, Vector3I LocalPoint) { if (Voxel == null) { throw new ArgumentNullException(nameof(Voxel)); } if (Voxel.Storage == null) { throw new ArgumentException("Voxel.Storage is null"); } MyVoxelBase _Voxel = Voxel as MyVoxelBase; VoxelHit hit = new VoxelHit(); _Voxel.Storage.ExecuteOperationFast(ref hit, MyStorageDataTypeFlags.Content, ref LocalPoint, ref LocalPoint, false); return(hit.HasHit); }
public bool GetVoxelContent(IMyVoxelBase voxel, Vector3D position, out byte content, out byte material, MyStorageData cache = null, Vector3D?endpoint = null, MyVoxelRequestFlags flags = 0) { if (endpoint == null) { endpoint = position; } content = 0; material = 0; if (voxel == null || voxel.Storage == null) { return(false); } if (cache == null) { cache = new MyStorageData(); } var targetMin = position; Vector3D targetMax = endpoint.Value; Vector3I minVoxel, maxVoxel; MyVoxelCoordSystems.WorldPositionToVoxelCoord(voxel.PositionLeftBottomCorner, ref targetMin, out minVoxel); MyVoxelCoordSystems.WorldPositionToVoxelCoord(voxel.PositionLeftBottomCorner, ref targetMax, out maxVoxel); MyVoxelBase voxelBase = voxel as MyVoxelBase; minVoxel += voxelBase.StorageMin; maxVoxel += voxelBase.StorageMin; voxel.Storage.ClampVoxel(ref minVoxel); voxel.Storage.ClampVoxel(ref maxVoxel); cache.Resize(minVoxel, maxVoxel); voxel.Storage.ReadRange(cache, MyStorageDataTypeFlags.ContentAndMaterial, 0, minVoxel, maxVoxel, ref flags); // Grab content and material content = cache.Content(0); material = cache.Material(0); return(cache.ContainsVoxelsAboveIsoLevel()); }
public static void RemoveVoxelContent(long voxelId, Vector3D position, out byte materialRemoved, out float amountOfMaterial) { materialRemoved = 0; amountOfMaterial = 0f; MyStorageData cache = new MyStorageData(); IMyEntity entity; if (!MyAPIGateway.Entities.TryGetEntityById(voxelId, out entity)) { return; } IMyVoxelBase voxel = entity as IMyVoxelBase; byte original, material; var targetMin = position; var targetMax = position; Vector3I minVoxel, maxVoxel; MyVoxelCoordSystems.WorldPositionToVoxelCoord(voxel.PositionLeftBottomCorner, ref targetMin, out minVoxel); MyVoxelCoordSystems.WorldPositionToVoxelCoord(voxel.PositionLeftBottomCorner, ref targetMax, out maxVoxel); OreDetector.Instance.GetVoxelContent(voxel, position, out original, out material, cache); if (original == MyVoxelConstants.VOXEL_CONTENT_EMPTY) { Logger.Instance.LogMessage("Voxel Content empty"); //Logging.Instance.WriteLine(string.Format("Content is empty")); return; } // Calculate Material Mined var voxelMat = MyDefinitionManager.Static.GetVoxelMaterialDefinition(material); materialRemoved = material; amountOfMaterial = OreDetector.CalculateAmount(voxelMat, original * 3.9f); // Remove Content cache.Content(0, 0); voxel.Storage.WriteRange(cache, MyStorageDataTypeFlags.ContentAndMaterial, minVoxel, maxVoxel); }
public override bool Invoke(ulong steamId, long playerId, string messageText) { var match = Regex.Match(messageText, @"/roidreplace\s+(?<Asteroid>[^\s]+)\s+(?<Material1>[^\s]+)\s+(?<Material2>[^\s]+)", RegexOptions.IgnoreCase); if (match.Success) { var searchAsteroidName = match.Groups["Asteroid"].Value; IMyVoxelBase originalAsteroid = null; if (!Support.FindAsteroid(steamId, searchAsteroidName, out originalAsteroid)) { MyAPIGateway.Utilities.SendMessage(steamId, "Cannot find asteroid", string.Format("'{0}'", searchAsteroidName)); return(true); } var searchMaterialName1 = match.Groups["Material1"].Value; var searchMaterialName2 = match.Groups["Material2"].Value; return(ReplaceAsteroidMaterial(steamId, originalAsteroid, searchMaterialName1, searchMaterialName2)); } match = Regex.Match(messageText, @"/roidreplace\s+(?<Material1>[^\s]+)\s+(?<Material2>[^\s]+)", RegexOptions.IgnoreCase); if (match.Success) { IMyEntity entity = Support.FindLookAtEntity(MyAPIGateway.Session.ControlledObject, false, false, false, true, true, false); if (entity != null && entity is IMyVoxelMap) { var voxelMap = (IMyVoxelMap)entity; var searchMaterialName1 = match.Groups["Material1"].Value; var searchMaterialName2 = match.Groups["Material2"].Value; return(ReplaceAsteroidMaterial(steamId, voxelMap, searchMaterialName1, searchMaterialName2)); } else { MyAPIGateway.Utilities.SendMessage(steamId, "Asteroid", "Was not targeted."); } } return(false); }
private void OnOreSearchComplete(bool success, Vector3D orePosition, IMyVoxelBase foundMap, string oreName) { if (!success) { m_logger.debugLog("No ore target found", Logger.severity.INFO); m_navSet.OnTaskComplete_NavRot(); m_navSet.Settings_Commands.Complaint = InfoString.StringId.NoOreFound; return; } m_targetVoxel = foundMap; m_depositPos = orePosition; m_depositOre = oreName; Vector3 toCentre = Vector3.Normalize(m_targetVoxel.GetCentre() - m_depositPos); GetExteriorPoint(m_depositPos, toCentre, m_longestDimension, exterior => { m_approach = new LineSegmentD(exterior - toCentre * m_longestDimension * 5f, exterior); m_state = State.Approaching; m_logger.debugLog("approach: " + m_approach.From.ToGpsTag("From") + ", " + m_approach.To.ToGpsTag("To")); }); }
public static bool HasVoxelAt(this IMyVoxelBase Voxel, Vector3D Point) { if (Voxel == null) { throw new ArgumentNullException(nameof(Voxel)); } if (Voxel.Storage == null) { throw new ArgumentException("Voxel.Storage is null"); } MyVoxelBase _Voxel = Voxel as MyVoxelBase; VoxelHit hit = new VoxelHit(); //The following magic is taken from Sandbox.Game.Entities.VoxelBaseExtensions Vector3 value; MyVoxelCoordSystems.WorldPositionToLocalPosition(Point, _Voxel.PositionComp.WorldMatrix, _Voxel.PositionComp.WorldMatrixInvScaled, _Voxel.SizeInMetresHalf, out value); Vector3I voxelCoord = new Vector3I(value / 1f) + _Voxel.StorageMin; _Voxel.Storage.ExecuteOperationFast(ref hit, MyStorageDataTypeFlags.Content, ref voxelCoord, ref voxelCoord, false); return(hit.HasHit); }
public static MyPlanet GetClosestPlanet(Vector3D position, out double distSquared) { IMyVoxelBase closest = null; double bestDistance = double.MaxValue; MyAPIGateway.Session.VoxelMaps.GetInstances(null, voxel => { if (voxel is MyPlanet) { double distance = Vector3D.DistanceSquared( position, voxel.WorldMatrix.Translation ); if (distance < bestDistance) { bestDistance = distance; closest = voxel; } } return(false); }); distSquared = bestDistance; return((MyPlanet)closest); }
public static Vector3D GetCentre(this IMyEntity entity) { IMyCubeBlock block = entity as IMyCubeBlock; if (block != null) { return(block.GetPosition()); } MyPlanet planet = entity as MyPlanet; if (planet != null) { return(planet.WorldMatrix.Translation); } IMyVoxelBase asteroid = entity as IMyVoxelBase; if (asteroid != null) { return(asteroid.WorldAABB.Center); } return(Vector3D.Transform(entity.LocalAABB.Center, entity.WorldMatrix)); }
public static void MyVoxelGenerator_ComputeShapeBounds(this IMyVoxelBase VoxelMap, ref BoundingBoxD shapeAabb, out Vector3I voxelMin, out Vector3I voxelMax) { if (VoxelMap == null) { throw new ArgumentNullException(nameof(VoxelMap)); } if (VoxelMap.Storage == null) { throw new ArgumentException("Voxel.Storage is null"); } MyVoxelBase voxelMap = VoxelMap as MyVoxelBase; Vector3I storageSize = voxelMap.Storage.Size; MyVoxelCoordSystems.WorldPositionToVoxelCoord(voxelMap.PositionLeftBottomCorner, ref shapeAabb.Min, out voxelMin); MyVoxelCoordSystems.WorldPositionToVoxelCoord(voxelMap.PositionLeftBottomCorner, ref shapeAabb.Max, out voxelMax); voxelMin += voxelMap.StorageMin; voxelMax += voxelMap.StorageMin; voxelMax += 1; storageSize -= 1; Vector3I.Clamp(ref voxelMin, ref Vector3I.Zero, ref storageSize, out voxelMin); Vector3I.Clamp(ref voxelMax, ref Vector3I.Zero, ref storageSize, out voxelMax); }
public override bool Invoke(ulong steamId, long playerId, string messageText) { var match = Regex.Match(messageText, @"/roidfill\s+(?<Asteroid>[^\s]+)\s+(?<Material>[^\s]+)", RegexOptions.IgnoreCase); if (match.Success) { var searchAsteroidName = match.Groups["Asteroid"].Value; IMyVoxelBase originalAsteroid = null; if (!Support.FindAsteroid(steamId, searchAsteroidName, out originalAsteroid)) { MyAPIGateway.Utilities.SendMessage(steamId, "Cannot find asteroid", string.Format("'{0}'", searchAsteroidName)); return(true); } var searchMaterialName = match.Groups["Material"].Value; MyVoxelMaterialDefinition material; string suggestedMaterials = ""; if (!Support.FindMaterial(searchMaterialName, out material, ref suggestedMaterials)) { MyAPIGateway.Utilities.SendMessage(steamId, "Invalid Material specified.", "Cannot find the material '{0}'.\r\nTry the following: {1}", searchMaterialName, suggestedMaterials); return(true); } var boxShape = MyAPIGateway.Session.VoxelMaps.GetBoxVoxelHand(); // boundaries are in local space, you need to set translation into Transform property boxShape.Boundaries = (BoundingBoxD)originalAsteroid.PositionComp.LocalAABB; boxShape.Transform = MatrixD.CreateTranslation(originalAsteroid.PositionComp.GetPosition()); MyAPIGateway.Session.VoxelMaps.PaintInShape(originalAsteroid, boxShape, material.Index); MyAPIGateway.Utilities.SendMessage(steamId, "Asteroid", "'{0}' filled with material '{1}'.", originalAsteroid.StorageName, material.Id.SubtypeName); return(true); } return(false); }
public static void GetAsteroidData(IMyVoxelBase asteroid, out Vector3D center, out int radius, out float strength) { GetAsteroidData(asteroid, 2, out center, out radius, out strength); }
public static int CalculateAsteroidRadius(IMyVoxelBase asteroid) { double size = ((double)asteroid.Storage.Size.AbsMax() / (double)Settings.asteroid_maxsize); return Math.Min(Math.Max((int)Math.Round(size * Settings.radius_max), Settings.radius_min), Settings.radius_max); }
public static float CalculateAsteroidStrength(IMyVoxelBase asteroid) { double size = ((double)asteroid.Storage.Size.AbsMax() / (double)Settings.asteroid_maxsize); return Math.Min(Math.Max((float)(size * Settings.strength_max), Settings.strength_min), Settings.strength_max); }
public void AddNearbyAsteroid(IMyVoxelBase asteroid) { if (!_nearbyAsteroids.Contains(asteroid)) _nearbyAsteroids.Add(asteroid); }
IMyVoxelBase IMyVoxelMaps.GetVoxelMapWhoseBoundingBoxIntersectsBox(ref VRageMath.BoundingBoxD boundingBox, IMyVoxelBase ignoreVoxelMap) { return GetVoxelMapWhoseBoundingBoxIntersectsBox(ref boundingBox, ignoreVoxelMap as Game.Entities.MyVoxelBase); }
/// <summary> /// /// </summary> /// <param name="voxelMap"></param> /// <param name="resolution">0 to 8. 0 for fine/slow detail.</param> /// <param name="distance"></param> /// <returns></returns> private int FindMaterial(IMyVoxelBase voxelMap, Vector3D center, int resolution, double distance) { int hits = 0; var materials = MyDefinitionManager.Static.GetVoxelMaterialDefinitions().Where(v => v.IsRare).ToArray(); var findMaterial = materials.Select(f => f.Index).ToArray(); var storage = voxelMap.Storage; var scale = (int)Math.Pow(2, resolution); //MyAPIGateway.Utilities.ShowMessage("center", center.ToString()); var point = new Vector3I(center - voxelMap.PositionLeftBottomCorner); //MyAPIGateway.Utilities.ShowMessage("point", point.ToString()); var min = ((point - (int)distance) / 64) * 64; min = Vector3I.Max(min, Vector3I.Zero); //MyAPIGateway.Utilities.ShowMessage("min", min.ToString()); var max = ((point + (int)distance) / 64) * 64; max = Vector3I.Max(max, min + 64); //MyAPIGateway.Utilities.ShowMessage("max", max.ToString()); //MyAPIGateway.Utilities.ShowMessage("size", voxelMap.StorageName + " " + storage.Size.ToString()); if (min.X >= storage.Size.X || min.Y >= storage.Size.Y || min.Z >= storage.Size.Z) { //MyAPIGateway.Utilities.ShowMessage("size", "out of range"); return 0; } var oldCache = new MyStorageDataCache(); //var smin = new Vector3I(0, 0, 0); //var smax = new Vector3I(31, 31, 31); ////var size = storage.Size; //var size = smax - smin + 1; //size = new Vector3I(16, 16, 16); //oldCache.Resize(size); //storage.ReadRange(oldCache, MyStorageDataTypeFlags.ContentAndMaterial, resolution, Vector3I.Zero, size - 1); var smax = (max / scale) - 1; var smin = (min / scale); var size = smax - smin + 1; oldCache.Resize(size); storage.ReadRange(oldCache, MyStorageDataTypeFlags.ContentAndMaterial, resolution, smin, smax); //MyAPIGateway.Utilities.ShowMessage("smax", smax.ToString()); //MyAPIGateway.Utilities.ShowMessage("size", size .ToString()); //MyAPIGateway.Utilities.ShowMessage("size - 1", (size - 1).ToString()); Vector3I p; for (p.Z = 0; p.Z < size.Z; ++p.Z) for (p.Y = 0; p.Y < size.Y; ++p.Y) for (p.X = 0; p.X < size.X; ++p.X) { // place GPS in the center of the Voxel var position = voxelMap.PositionLeftBottomCorner + (p * scale) + (scale / 2) + min; if (Math.Sqrt((position - center).LengthSquared()) < distance) { var content = oldCache.Content(ref p); var material = oldCache.Material(ref p); if (content > 0 && findMaterial.Contains(material)) { var index = Array.IndexOf(findMaterial, material); var name = materials[index].MinedOre; var gps = MyAPIGateway.Session.GPS.Create("Ore " + name, "scanore", position, true, false); MyAPIGateway.Session.GPS.AddLocalGps(gps); hits++; } } } return hits; }
private void TransferFromTarget(NaniteMiningItem target) { // Must be invoked from game thread IMyEntity entity; if (!MyAPIGateway.Entities.TryGetEntityById(target.VoxelId, out entity)) { CancelTarget(target); return; } MyAPIGateway.Parallel.Start(() => { try { if (entity == null || !IsValidVoxelTarget(target, entity)) { MyAPIGateway.Utilities.InvokeOnGameThread(() => { CancelTarget(target); }); return; } MyAPIGateway.Utilities.InvokeOnGameThread(() => { // Invocation 0 try { var def = MyDefinitionManager.Static.GetVoxelMaterialDefinition(target.VoxelMaterial); var item = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>(def.MinedOre); var inventory = ((MyCubeBlock)m_constructionBlock.ConstructionBlock).GetInventory(); MyInventory targetInventory = ((MyCubeBlock)m_constructionBlock.ConstructionBlock).GetInventory(); if (targetInventory != null && targetInventory.CanItemsBeAdded((MyFixedPoint)(target.Amount), item.GetId())) { if (entity == null) { CancelTarget(target); return; } var ownerName = targetInventory.Owner as IMyTerminalBlock; if (ownerName != null) { Logging.Instance.WriteLine($"[Mining] Transfer - Adding {target.Amount} {item.GetId().SubtypeName} to {ownerName.CustomName}", 1); } if (!targetInventory.AddItems((MyFixedPoint)(target.Amount), item)) { Logging.Instance.WriteLine($"Error while transferring {target.Amount} {item.GetId().SubtypeName}! Aborting mining operation."); return; } IMyVoxelBase voxel = entity as IMyVoxelBase; MyVoxelBase voxelBase = voxel as MyVoxelBase; voxelBase.RequestVoxelOperationSphere(target.Position, 1f, target.VoxelMaterial, MyVoxelBase.OperationType.Cut); AddMinedPosition(target); CompleteTarget(target); return; } Logging.Instance.WriteLine("[Mining] Mined materials could not be moved. No free cargo space (probably)!", 1); CancelTarget(target); } catch (Exception e) { Logging.Instance.WriteLine($"Exception in NaniteMiningTargets.TransferFromTarget (Invocation 0):\n{e}"); } }); } catch (Exception e) { Logging.Instance.WriteLine($"Exception in NaniteMiningTargets.TransferFromTarget:\n{e}"); } }); }
public void HoldingTool(bool trigger) { var character = MyAPIGateway.Session.ControlledObject as IMyCharacter; if(character == null) return; var view = character.GetHeadMatrix(true, true); var target = view.Translation + (view.Forward * placeDistance); selectedVoxelMap = null; maps.Clear(); MyAPIGateway.Session.VoxelMaps.GetInstances(maps, delegate (IMyVoxelBase map) { if(map.StorageName == null) return false; var min = map.PositionLeftBottomCorner; var max = min + map.Storage.Size; return (min.X <= target.X && target.X <= max.X && min.Y <= target.Y && target.Y <= max.Y && min.Z <= target.Z && target.Z <= max.Z); }); // DEBUG testing //var sphere = new BoundingSphereD(pos, 1); //var entities = new List<MyEntity>(); // TODO global //MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref sphere, entities, MyEntityQueryType.Static); //foreach(var ent in entities) //{ // var map = ent as IMyVoxelBase; // if(map != null) // maps.Add(map); //} if(maps.Count == 1) { selectedVoxelMap = maps[0]; } else if(maps.Count > 1) { if(Input.IsNewGameControlPressed(MyControlsSpace.USE) && InputHandler.IsInputReadable()) selectedVoxelMapIndex++; if(selectedVoxelMapIndex >= maps.Count) selectedVoxelMapIndex = 0; selectedVoxelMap = maps[selectedVoxelMapIndex]; SetToolStatus("Selected Voxel Map: " + selectedVoxelMap.StorageName + " (" + (selectedVoxelMapIndex + 1) + " of " + maps.Count + ")", MyFontEnum.White, 100); } SetCrosshairColor(CROSSHAIR_INVALID); if(selectedVoxelMap == null) { if(trigger) { SetToolStatus("Concrete can only be placed on planets or asteroids!", MyFontEnum.Red, 1500); } } else { if(selectedVoxelMap.EntityId != previousSelectedVoxelMapId) { previousSelectedVoxelMapId = selectedVoxelMap.EntityId; selectedVoxelMapTicks = VOXEL_MAP_SELECTED_TICKS; } var placed = ToolProcess(selectedVoxelMap, target, view, trigger); if(trigger && placed && !MyAPIGateway.Session.CreativeMode) { SendToServer_Ammo(character.EntityId, false); // expend the ammo manually } } }
private bool ToolProcess(IMyVoxelBase voxels, Vector3D target, MatrixD view, bool trigger) { var planet = voxels as MyPlanet; IMyVoxelShape placeShape = null; var input = Input; bool inputReadable = true; // InputHandler.IsInputReadable(); // HACK undo this comment ^ once InputHandler.IsInputReadable() no longer throws exceptions when not in a menu; also remove all other InputHandler.IsInputReadable() instances from the code bool removeMode = false; if(inputReadable) { var scroll = input.DeltaMouseScrollWheelValue(); removeMode = input.IsAnyCtrlKeyPressed(); if(scroll != 0 && InputHandler.IsInputReadable()) { if(input.IsAnyCtrlKeyPressed()) { if(scroll > 0) placeDistance += 0.2f; else placeDistance -= 0.2f; placeDistance = MathHelper.Clamp(placeDistance, 2f, 6f); PlaySound("HudItem", 0.1f); SetToolStatus("Distance: " + Math.Round(placeDistance, 2), MyFontEnum.Green, 1500); } else if(input.IsAnyShiftKeyPressed()) { if(scroll > 0) placeScale += 0.25f; else placeScale -= 0.25f; placeScale = MathHelper.Clamp(placeScale, 0.5f, 3f); PlaySound("HudItem", 0.1f); SetToolStatus("Scale: " + Math.Round(placeScale, 2), MyFontEnum.Green, 1500); } /* TODO shape? else { switch(selectedShape) { case PlaceShape.BOX: selectedShape = (scroll > 0 ? PlaceShape.SPHERE : PlaceShape.RAMP); break; case PlaceShape.SPHERE: selectedShape = (scroll > 0 ? PlaceShape.CAPSULE : PlaceShape.BOX); break; case PlaceShape.CAPSULE: selectedShape = (scroll > 0 ? PlaceShape.RAMP : PlaceShape.SPHERE); break; case PlaceShape.RAMP: selectedShape = (scroll > 0 ? PlaceShape.BOX : PlaceShape.CAPSULE); break; } SetToolStatus("Shape: " + selectedShape, MyFontEnum.Green, 1500); } */ } if(input.IsNewGameControlPressed(MyControlsSpace.FREE_ROTATION) && InputHandler.IsInputReadable()) { if(++snap > 2) snap = 0; PlaySound("HudItem", 0.1f); switch(snap) { case 0: SetToolStatus("Snap mode disabled.", MyFontEnum.Green, 1500); break; case 1: SetToolStatus("Snap mode set to voxel-grid.", MyFontEnum.Green, 1500); break; case 2: SetToolStatus("Snap mode set to altitude.", MyFontEnum.Green, 1500); break; } } bool shift = input.IsAnyShiftKeyPressed(); var rotateInput = RotateInput(shift); if((rotateInput.X != 0 || rotateInput.Y != 0 || rotateInput.Z != 0) && InputHandler.IsInputReadable()) { if(shift || ++skipSoundTicks > 15) { skipSoundTicks = 0; PlaySound("HudRotateBlock", 0.1f); } rotated = true; float angle = (shift ? 15f : (input.IsAnyAltKeyPressed() ? 0.1f : 1)); if(rotateInput.X != 0) placeMatrix *= MatrixD.CreateFromAxisAngle(placeMatrix.Up, MathHelper.ToRadians(rotateInput.X * angle)); if(rotateInput.Y != 0) placeMatrix *= MatrixD.CreateFromAxisAngle(placeMatrix.Left, MathHelper.ToRadians(rotateInput.Y * angle)); if(rotateInput.Z != 0) placeMatrix *= MatrixD.CreateFromAxisAngle(placeMatrix.Forward, MathHelper.ToRadians(rotateInput.Z * angle)); } if(input.IsNewGameControlPressed(MyControlsSpace.CUBE_BUILDER_CUBESIZE_MODE) && InputHandler.IsInputReadable()) { PlaySound("HudItem", 0.1f); var grid = CubeBuilder.FindClosestGrid(); if(grid != null) { placeMatrix = grid.WorldMatrix; rotated = true; SetToolStatus("Aligned with selected grid.", MyFontEnum.Green, 1500); } else { if(rotated) { placeMatrix.Up = Vector3D.Up; placeMatrix.Right = Vector3D.Right; placeMatrix.Forward = Vector3D.Forward; rotated = false; SetToolStatus("Alignement reset.", MyFontEnum.Green, 1500); } else { var center = (planet != null ? planet.WorldMatrix.Translation : voxels.PositionLeftBottomCorner + (voxels.Storage.Size / 2)); var dir = (target - center); var altitude = Math.Round(dir.Normalize(), 0); target = center + (dir * altitude); placeMatrix = MatrixD.CreateFromDir(dir, view.Forward); rotated = true; SetToolStatus((planet != null ? "Aligned towards center of planet." : "Aligned towards center of asteroid."), MyFontEnum.Green, 1500); } } } } if(snap == 0) // no snapping { placeMatrix.Translation = target; } else if(snap == 1) // snap to voxel grid { target = voxels.PositionLeftBottomCorner + Vector3I.Round(target - voxels.PositionLeftBottomCorner); placeMatrix.Translation = target; var gridColor = Color.Wheat * 0.25f; const float gridLineWidth = 0.01f; const float gridLineLength = 3f; const float gridLineLengthHalf = gridLineLength / 2; const string gridLineMaterial = "ConcreteTool_FadeOutLine"; var upHalf = (Vector3.Up / 2); var rightHalf = (Vector3.Right / 2); var forwardHalf = (Vector3.Forward / 2); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + upHalf + -rightHalf + Vector3.Forward * gridLineLengthHalf, Vector3.Backward, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + upHalf + rightHalf + Vector3.Forward * gridLineLengthHalf, Vector3.Backward, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + -upHalf + -rightHalf + Vector3.Forward * gridLineLengthHalf, Vector3.Backward, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + -upHalf + rightHalf + Vector3.Forward * gridLineLengthHalf, Vector3.Backward, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + forwardHalf + -rightHalf + Vector3.Up * gridLineLengthHalf, Vector3.Down, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + forwardHalf + rightHalf + Vector3.Up * gridLineLengthHalf, Vector3.Down, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + -forwardHalf + -rightHalf + Vector3.Up * gridLineLengthHalf, Vector3.Down, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + -forwardHalf + rightHalf + Vector3.Up * gridLineLengthHalf, Vector3.Down, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + forwardHalf + -upHalf + Vector3.Right * gridLineLengthHalf, Vector3.Left, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + forwardHalf + upHalf + Vector3.Right * gridLineLengthHalf, Vector3.Left, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + -forwardHalf + -upHalf + Vector3.Right * gridLineLengthHalf, Vector3.Left, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + -forwardHalf + upHalf + Vector3.Right * gridLineLengthHalf, Vector3.Left, gridLineLength, gridLineWidth); } else if(snap == 2) // snap to distance increments from center { var center = (planet != null ? planet.WorldMatrix.Translation : voxels.PositionLeftBottomCorner + (voxels.Storage.Size / 2)); var dir = (target - center); int altitude = (int)Math.Round(dir.Normalize(), 0); target = center + (dir * altitude); if(inputReadable && input.IsAnyShiftKeyPressed() && InputHandler.IsInputReadable()) { if(input.IsNewKeyPressed(MyKeys.Shift)) altitudeLock = altitude; if(Math.Abs(altitude - altitudeLock) > 3) { if(!hudUnablePlayed) { PlaySound("HudUnable", 0.1f); hudUnablePlayed = true; } Utilities.ShowNotification("Too far away from locked altitude!", 16, MyFontEnum.Red); return false; } target = center + (dir * altitudeLock); Utilities.ShowNotification("Locked to altitude.", 16, MyFontEnum.Blue); hudUnablePlayed = false; } placeMatrix.Translation = target; var gridColor = Color.Wheat * 0.25f; const float gridLineWidth = 0.01f; const float gridLineLength = 3f; const float gridLineLengthHalf = gridLineLength / 2; const string gridLineMaterial = "ConcreteTool_FadeOutLine"; MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + (dir * 3.75), -dir, 7.5f, gridLineWidth); var vertical = Vector3D.Cross(dir, view.Forward); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target - (dir * 1.5) + vertical * gridLineLengthHalf, -vertical, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target - (dir * 0.5) + vertical * gridLineLengthHalf, -vertical, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + (dir * 0.5) + vertical * gridLineLengthHalf, -vertical, gridLineLength, gridLineWidth); MyTransparentGeometry.AddLineBillboard(gridLineMaterial, gridColor, target + (dir * 1.5) + vertical * gridLineLengthHalf, -vertical, gridLineLength, gridLineWidth); } var colorWire = Color.Green * 0.5f; var colorFace = Color.Gray * 0.1f; const byte cooldownTicks = 15; const byte cooldownTicksGlow = 10; const int removeTargetTicks = 15; //int removeTargetTicks = (int)(30 * placeScale); if(removeMode) colorWire = (holdPressRemove > 0 ? Color.Lerp(Color.Red, Color.OrangeRed, ((float)holdPressRemove / (float)removeTargetTicks)) : Color.Red) * 0.5f; else if(cooldown >= cooldownTicksGlow) colorWire = Color.Blue * 0.5f; else if(cooldown > 0) colorWire = Color.White * 0.1f; { var shape = MyAPIGateway.Session.VoxelMaps.GetBoxVoxelHand(); var vec = (Vector3D.One / 2) * placeScale; var box = new BoundingBoxD(-vec, vec); shape.Boundaries = box; placeShape = shape; MySimpleObjectDraw.DrawTransparentBox(ref placeMatrix, ref box, ref colorWire, MySimpleObjectRasterizer.Wireframe, 1, 0.01f, "Square", "Square", false); MySimpleObjectDraw.DrawTransparentBox(ref placeMatrix, ref box, ref colorFace, MySimpleObjectRasterizer.Solid, 1, 0.01f, "Square", "Square", false); } // TODO shapes? /* switch(selectedShape) { default: // BOX { // box code here break; } case PlaceShape.SPHERE: { var shape = MyAPIGateway.Session.VoxelMaps.GetSphereVoxelHand(); shape.Radius = placeScale; placeShape = shape; MySimpleObjectDraw.DrawTransparentSphere(ref placeMatrix, shape.Radius, ref colorWire, MySimpleObjectRasterizer.Wireframe, 12, "Square", "Square", 0.01f); MySimpleObjectDraw.DrawTransparentSphere(ref placeMatrix, shape.Radius, ref colorFace, MySimpleObjectRasterizer.Solid, 12, "Square", "Square", 0.01f); break; } case PlaceShape.CAPSULE: { var shape = MyAPIGateway.Session.VoxelMaps.GetCapsuleVoxelHand(); shape.Radius = placeScale; placeShape = shape; MySimpleObjectDraw.DrawTransparentCapsule(ref placeMatrix, shape.Radius, 2, ref colorWire, 12, "Square"); break; } case PlaceShape.RAMP: { var shape = MyAPIGateway.Session.VoxelMaps.GetRampVoxelHand(); shape.RampNormal = Vector3D.Forward; // TODO direction shape.RampNormalW = placeScale; placeShape = shape; var vec = (Vector3D.One / 2) * placeScale; var box = new BoundingBoxD(-vec, vec); MySimpleObjectDraw.DrawTransparentRamp(ref placeMatrix, ref box, ref colorWire, "Square"); break; } } */ if(cooldown > 0 && --cooldown > 0) return false; if(trigger) { placeShape.Transform = placeMatrix; if(removeMode) { holdPressRemove++; if(holdPressRemove % 3 == 0) SetToolStatus("Removing " + (int)(((float)holdPressRemove / (float)removeTargetTicks) * 100f) + "%...", MyFontEnum.Red, 500); if(holdPressRemove >= removeTargetTicks) { MyAPIGateway.Session.VoxelMaps.CutOutShape(voxels, placeShape); PlaySound("HudDeleteBlock", 0.1f); cooldown = cooldownTicks; holdPressRemove = 0; } return false; // don't use ammo for removal } else { var box = placeShape.GetWorldBoundary(); ents.Clear(); MyAPIGateway.Entities.GetEntities(ents, (ent => ent.Physics != null && !ent.Physics.IsStatic && (ent is IMyCubeGrid || ent is IMyFloatingObject || ent is IMyCharacter) && ent.WorldAABB.Intersects(ref box))); int found = ents.Count; if(found > 0) { var localPlayerFound = ents.RemoveWhere((e) => e.EntityId == MyAPIGateway.Session.ControlledObject.Entity.EntityId) > 0; SetCrosshairColor(CROSSHAIR_BLOCKED); SetToolStatus((found == 1 ? (localPlayerFound ? "You're in the way!" : "Something is in the way!") : (localPlayerFound ? "You and " + (ents.Count - 1) : "" + ents.Count) + " things are in the way!"), MyFontEnum.Red, 1500); if(!hudUnablePlayed) { PlaySound("HudUnable", 0.1f); hudUnablePlayed = true; } return false; } hudUnablePlayed = false; MyAPIGateway.Session.VoxelMaps.FillInShape(voxels, placeShape, material.Index); PlaySound("HudPlaceBlock", 0.1f); cooldown = cooldownTicks; holdPressRemove = 0; return true; } } else { hudUnablePlayed = false; } holdPressRemove = 0; return false; // don't use ammo }
public void HolsterTool() { holdingTool = null; selectedVoxelMap = null; SetCrosshairColor(null); toolStatus?.Hide(); }
public static void RequestFillInShape(IMyVoxelBase voxelMap, IMyVoxelShape voxelShape, byte materialIdx) { var map = voxelMap as MyVoxelBase; var shape = voxelShape as MyShape; if (map != null && shape != null) { shape.SendFillRequest(map.SyncObject, materialIdx); } }
/// <summary> /// Find the closest ore to position that matches one of the oreType /// </summary> /// <param name="position">The position to search near</param> /// <param name="oreType">The types of ore to search for</param> /// <param name="orePosition">The postion of the ore that was found</param> /// <param name="voxel">The voxel map that contains the ore that was found</param> /// <param name="oreName">The name of the ore that was found</param> /// <returns>True iff an ore was found</returns> public bool FindClosestOre(Vector3D position, byte[] oreType, out Vector3D orePosition, out IMyVoxelBase voxel, out string oreName) { IOrderedEnumerable<IMyVoxelBase> sortedByDistance; using (l_voxelDate.AcquireExclusiveUsing()) sortedByDistance = m_voxelData.Keys.OrderBy(map => Vector3.DistanceSquared(position, map.GetPosition())); foreach (IMyVoxelBase map in sortedByDistance) { VoxelData data; using (l_voxelDate.AcquireSharedUsing()) data = m_voxelData[map]; m_logger.debugLog("PositionLeftBottomCorner: " + map.PositionLeftBottomCorner + ", pos: " + position, "FindClosestOre()"); byte foundOreType; if (data.GetClosest(oreType, ref position, out orePosition, out foundOreType)) { oreName = MyDefinitionManager.Static.GetVoxelMaterialDefinition(foundOreType).MinedOre; m_logger.debugLog("PositionLeftBottomCorner: " + map.PositionLeftBottomCorner + ", worldPosition: " + orePosition + ", distance: " + Vector3D.Distance(position, orePosition), "FindClosestOre()"); voxel = map; return true; } } orePosition = Vector3D.Zero; voxel = null; oreName = null; return false; }
public void AddNearbyAsteroid(IMyVoxelBase asteroid) { navigation.AddNearbyAsteroid(asteroid); }
/* * Credits to midspace for the help on this method * http://forums.keenswh.com/post/show_single_post?pid=1286008590&postcount=12 */ public static void GetAsteroidData(IMyVoxelBase asteroid, int lod, out Vector3D center, out int radius, out float strength) { int scale = Math.Max((int)Math.Pow(lod, 2), 1); Vector3I maxSize = asteroid.Storage.Size / scale; int diff = maxSize.AbsMax() / 512; if (diff > 1) { GetAsteroidData(asteroid, lod + diff, out center, out radius, out strength); return; } cache.Resize(maxSize); asteroid.Storage.ReadRange(cache, MyStorageDataTypeFlags.ContentAndMaterial, lod, Vector3I.Zero, maxSize - 1); Vector3I min = Vector3I.MaxValue; Vector3I max = Vector3I.MinValue; Vector3I p; byte content; for (p.Z = 0; p.Z < maxSize.Z; p.Z++) { for (p.Y = 0; p.Y < maxSize.Y; p.Y++) { for (p.X = 0; p.X < maxSize.X; p.X++) { content = cache.Content(ref p); if (content > 0) { min = Vector3I.Min(min, p); max = Vector3I.Max(max, p + 1); } } } } min *= scale; max *= scale; center = new BoundingBoxD(asteroid.PositionLeftBottomCorner + min, asteroid.PositionLeftBottomCorner + max).Center; radius = CalculateAsteroidRadius(asteroid); strength = CalculateAsteroidStrength(asteroid); }
private bool ReplaceAsteroidMaterial(IMyVoxelBase originalAsteroid, string searchMaterialName1, string searchMaterialName2) { MyVoxelMaterialDefinition material1; string suggestedMaterials = ""; if (!Support.FindMaterial(searchMaterialName1, out material1, ref suggestedMaterials)) { MyAPIGateway.Utilities.ShowMessage("Invalid Material1 specified.", "Cannot find the material '{0}'.\r\nTry the following: {1}", searchMaterialName1, suggestedMaterials); return true; } MyVoxelMaterialDefinition material2; if (!Support.FindMaterial(searchMaterialName2, out material2, ref suggestedMaterials)) { MyAPIGateway.Utilities.ShowMessage("Invalid Material2 specified.", "Cannot find the material '{0}'.\r\nTry the following: {1}", searchMaterialName2, suggestedMaterials); return true; } var oldStorage = originalAsteroid.Storage; var oldCache = new MyStorageDataCache(); oldCache.Resize(oldStorage.Size); oldStorage.ReadRange(oldCache, MyStorageDataTypeFlags.ContentAndMaterial, 0, Vector3I.Zero, oldStorage.Size - 1); Vector3I p; for (p.Z = 0; p.Z < oldStorage.Size.Z; ++p.Z) for (p.Y = 0; p.Y < oldStorage.Size.Y; ++p.Y) for (p.X = 0; p.X < oldStorage.Size.X; ++p.X) { var material = oldCache.Material(ref p); if (material == material1.Index) oldCache.Material(ref p, material2.Index); } oldStorage.WriteRange(oldCache, MyStorageDataTypeFlags.ContentAndMaterial, Vector3I.Zero, oldStorage.Size - 1); MyAPIGateway.Utilities.ShowMessage("Asteroid", "'{0}' material '{1}' replaced with '{2}'.", originalAsteroid.StorageName, material1.Id.SubtypeName, material2.Id.SubtypeName); return true; }
private Gravity GetGravityInAsteroid(IMyVoxelBase asteroid) { Vector3D min = asteroid.PositionLeftBottomCorner; Vector3D max = min + asteroid.Storage.Size; foreach (Gravity gravity in gravityPoints) { if (gravity.center.IsInsideInclusive(ref min, ref max)) { return gravity; } } return null; }
/// <summary> /// Move player to Voxel. Either Asteroid or planet. /// </summary> /// <param name="sourcePlayer"></param> /// <param name="targetVoxel"></param> /// <param name="safely"></param> /// <param name="updatedPosition"></param> /// <param name="emptySourceMessage"></param> /// <param name="emptyTargetMessage"></param> /// <param name="noSafeLocationMessage"></param> /// <returns></returns> public static bool MovePlayerToVoxel(IMyPlayer sourcePlayer, IMyVoxelBase targetVoxel, bool safely, Action<Vector3D> updatedPosition, Action emptySourceMessage, Action emptyTargetMessage, Action noSafeLocationMessage) { if (sourcePlayer == null) { if (emptySourceMessage != null) emptySourceMessage.Invoke(); return false; } if (targetVoxel == null || targetVoxel.Closed) { if (emptyTargetMessage != null) emptyTargetMessage.Invoke(); return false; } Vector3D position; MatrixD matrix; if (targetVoxel is IMyVoxelMap) { var asteroid = (IMyVoxelMap)targetVoxel; position = asteroid.PositionLeftBottomCorner; // have the player facing the asteroid. var fwd = asteroid.WorldMatrix.Translation - asteroid.PositionLeftBottomCorner; fwd.Normalize(); // calculate matrix to orient player to asteroid center. var up = Vector3D.CalculatePerpendicularVector(fwd); matrix = MatrixD.CreateWorld(position, fwd, up); } else if (targetVoxel is Sandbox.Game.Entities.MyPlanet) { var planet = (Sandbox.Game.Entities.MyPlanet)targetVoxel; // User current player position as starting point to find surface point. Vector3D findFromPoint = sourcePlayer.GetPosition(); Vector3D closestSurfacePoint; MyVoxelCoordSystems.WorldPositionToLocalPosition(planet.PositionLeftBottomCorner, ref findFromPoint, out closestSurfacePoint); position = planet.GetClosestSurfacePointGlobal(ref closestSurfacePoint); var up = position - planet.WorldMatrix.Translation; up.Normalize(); position = position + (up * 0.5d); // add a small margin because the voxel LOD can sometimes push a player down when first loading a distant cluster. // calculate matrix to orient player to planet. var fwd = Vector3D.CalculatePerpendicularVector(up); matrix = MatrixD.CreateWorld(position, fwd, up); } else { return false; } if (safely && !FindPlayerFreePosition(ref position, sourcePlayer)) { if (noSafeLocationMessage != null) noSafeLocationMessage.Invoke(); return false; } var currentPosition = sourcePlayer.Controller.ControlledEntity.Entity.GetPosition(); MessageSyncEntity.Process(sourcePlayer.Controller.ControlledEntity.Entity, SyncEntityType.Position | SyncEntityType.Matrix, Vector3.Zero, position, matrix); if (updatedPosition != null) updatedPosition.Invoke(currentPosition); return true; }
/// <summary> /// Move player to Voxel. Either Asteroid or planet. /// </summary> /// <param name="sourcePlayer"></param> /// <param name="targetVoxel"></param> /// <param name="safely"></param> /// <param name="updatedPosition"></param> /// <param name="emptySourceMessage"></param> /// <param name="emptyTargetMessage"></param> /// <param name="noSafeLocationMessage"></param> /// <returns></returns> public static bool MovePlayerToVoxel(IMyPlayer sourcePlayer, IMyVoxelBase targetVoxel, bool safely, Action<Vector3D> updatedPosition, Action emptySourceMessage, Action emptyTargetMessage, Action noSafeLocationMessage) { if (sourcePlayer == null) { if (emptySourceMessage != null) emptySourceMessage.Invoke(); return false; } if (targetVoxel == null || targetVoxel.Closed) { if (emptyTargetMessage != null) emptyTargetMessage.Invoke(); return false; } Vector3D position; MatrixD matrix; if (targetVoxel is IMyVoxelMap) { var asteroid = (IMyVoxelMap)targetVoxel; position = asteroid.PositionLeftBottomCorner; // have the player facing the asteroid. var fwd = asteroid.WorldMatrix.Translation - asteroid.PositionLeftBottomCorner; fwd.Normalize(); // calculate matrix to orient player to asteroid center. var up = Vector3D.CalculatePerpendicularVector(fwd); matrix = MatrixD.CreateWorld(position, fwd, up); } else if (targetVoxel is Sandbox.Game.Entities.MyPlanet) { var planet = (Sandbox.Game.Entities.MyPlanet)targetVoxel; // User current player position as starting point to find surface point. Vector3D findFromPoint = sourcePlayer.GetPosition(); Vector3D closestSurfacePoint; MyVoxelCoordSystems.WorldPositionToLocalPosition(planet.PositionLeftBottomCorner, ref findFromPoint, out closestSurfacePoint); Vector3D vector3D = planet.GetWorldGravityNormalized(ref findFromPoint); //closestSurfacePoint = planet.GetClosestSurfacePoint(ref closestSurfacePoint, ref vector3D, 20, 0); //MyVoxelCoordSystems.LocalPositionToWorldPosition(planet.PositionLeftBottomCorner, ref closestSurfacePoint, out position); // TODO: Untested. position = planet.GetClosestSurfacePointGlobal(ref closestSurfacePoint); var up = position - planet.WorldMatrix.Translation; up.Normalize(); position = position + (up * 0.5d); // add a small margin because the voxel LOD can sometimes push a player down when first loading a distant cluster. // calculate matrix to orient player to planet. var fwd = Vector3D.CalculatePerpendicularVector(up); matrix = MatrixD.CreateWorld(position, fwd, up); } else { return false; } if (safely && !FindPlayerFreePosition(ref position, sourcePlayer)) { if (noSafeLocationMessage != null) noSafeLocationMessage.Invoke(); return false; } var currentPosition = sourcePlayer.Controller.ControlledEntity.Entity.GetPosition(); // The SetWorldMatrix doesn't rotate the player quickly enough before SetPosition is called, as // the player will bounce off objects before it's correct orentation is actually registered. sourcePlayer.Controller.ControlledEntity.Entity.SetWorldMatrix(matrix); sourcePlayer.Controller.ControlledEntity.Entity.SetPosition(position); if (updatedPosition != null) updatedPosition.Invoke(currentPosition); return true; }
bool IMyVoxelMaps.Exist(IMyVoxelBase voxelMap) { return Exist(voxelMap as MyVoxelBase); }
void IMyVoxelMaps.MakeCrater(IMyVoxelBase voxelMap, BoundingSphereD sphere, Vector3 normal, byte materialIdx) { var material = MyDefinitionManager.Static.GetVoxelMaterialDefinition(materialIdx); MyVoxelGenerator.MakeCrater((MyVoxelBase)voxelMap, sphere, normal, material); }
public static void RegisterMiner(IMyCubeGrid miner, IMyVoxelBase voxel) { if (Instance == null || !ServerSettings.GetSetting<bool>(ServerSettings.SettingName.bImmortalMiner)) return; Instance.miners.Add(miner, voxel); }
/// <summary> /// /// </summary> /// <param name="voxelMap"></param> /// <param name="center"></param> /// <param name="resolution">0 to 8. 0 for fine/slow detail.</param> /// <param name="distance"></param> /// <param name="scanHits"></param> /// <returns></returns> private void FindMaterial(IMyVoxelBase voxelMap, Vector3D center, int resolution, double distance, List <ScanHit> scanHits) { const double checkDistance = 50 * 50; // 50 meter seperation. var materials = MyDefinitionManager.Static.GetVoxelMaterialDefinitions().Where(v => v.IsRare).ToArray(); var findMaterial = materials.Select(f => f.Index).ToArray(); var storage = voxelMap.Storage; var scale = (int)Math.Pow(2, resolution); //MyAPIGateway.Utilities.ShowMessage("center", center.ToString()); var point = new Vector3I(center - voxelMap.PositionLeftBottomCorner); //MyAPIGateway.Utilities.ShowMessage("point", point.ToString()); var min = ((point - (int)distance) / 64) * 64; min = Vector3I.Max(min, Vector3I.Zero); //MyAPIGateway.Utilities.ShowMessage("min", min.ToString()); var max = ((point + (int)distance) / 64) * 64; max = Vector3I.Max(max, min + 64); //MyAPIGateway.Utilities.ShowMessage("max", max.ToString()); //MyAPIGateway.Utilities.ShowMessage("size", voxelMap.StorageName + " " + storage.Size.ToString()); if (min.X >= storage.Size.X || min.Y >= storage.Size.Y || min.Z >= storage.Size.Z) { //MyAPIGateway.Utilities.ShowMessage("size", "out of range"); return; } var oldCache = new MyStorageData(); //var smin = new Vector3I(0, 0, 0); //var smax = new Vector3I(31, 31, 31); ////var size = storage.Size; //var size = smax - smin + 1; //size = new Vector3I(16, 16, 16); //oldCache.Resize(size); //storage.ReadRange(oldCache, MyStorageDataTypeFlags.ContentAndMaterial, resolution, Vector3I.Zero, size - 1); var smax = (max / scale) - 1; var smin = (min / scale); var size = smax - smin + 1; oldCache.Resize(size); storage.ReadRange(oldCache, MyStorageDataTypeFlags.ContentAndMaterial, resolution, smin, smax); //MyAPIGateway.Utilities.ShowMessage("smax", smax.ToString()); //MyAPIGateway.Utilities.ShowMessage("size", size .ToString()); //MyAPIGateway.Utilities.ShowMessage("size - 1", (size - 1).ToString()); Vector3I p; for (p.Z = 0; p.Z < size.Z; ++p.Z) { for (p.Y = 0; p.Y < size.Y; ++p.Y) { for (p.X = 0; p.X < size.X; ++p.X) { // place GPS in the center of the Voxel Vector3D position = voxelMap.PositionLeftBottomCorner + (p * scale) + (scale / 2f) + min; if (Math.Sqrt((position - center).LengthSquared()) < distance) { byte content = oldCache.Content(ref p); byte material = oldCache.Material(ref p); if (content > 0 && findMaterial.Any(m => m == material)) { bool addHit = true; foreach (ScanHit scanHit in scanHits) { if (scanHit.Material == material && Vector3D.DistanceSquared(position, scanHit.Position) < checkDistance) { addHit = false; break; } } if (addHit) { scanHits.Add(new ScanHit(position, material)); } } } } } } }
void IMyVoxelMaps.CutOutShape(IMyVoxelBase voxelMap, IMyVoxelShape voxelShape) { MyVoxelGenerator.RequestCutOutShape(voxelMap, voxelShape); }
public static bool MoveShipToVoxel(IMyCubeGrid sourceGrid, IMyVoxelBase targetVoxel, bool safely, Action<Vector3D> updatedPosition, Action emptySourceMessage, Action emptyTargetMessage, Action noSafeLocationMessage) { // TODO: find a more accurate position to transport a ship to around a planet and asteroid. var worldOffset = targetVoxel.WorldMatrix.Translation - sourceGrid.GetPosition(); return MoveShipByOffset(sourceGrid, worldOffset, safely, updatedPosition, noSafeLocationMessage); }
void IMyVoxelMaps.FillInShape(IMyVoxelBase voxelMap, IMyVoxelShape voxelShape, byte materialIdx) { MyVoxelGenerator.RequestFillInShape(voxelMap, voxelShape, materialIdx); }
public static void RequestCutOutShape(IMyVoxelBase voxelMap, IMyVoxelShape voxelShape) { var map = voxelMap as MyVoxelBase; var shape = voxelShape as MyShape; if (map != null && shape != null) { shape.SendCutOutRequest(map.SyncObject); } }
/// <summary> /// Find the physical asteroid either of the specified name or in the user hot list; /// </summary> /// <param name="searchAsteroidName"></param> /// <param name="originalAsteroid"></param> /// <returns></returns> public static bool FindAsteroid(string searchAsteroidName, out IMyVoxelBase originalAsteroid) { var currentAsteroidList = new List<IMyVoxelBase>(); MyAPIGateway.Session.VoxelMaps.GetInstances(currentAsteroidList, v => v.StorageName.Equals(searchAsteroidName, StringComparison.InvariantCultureIgnoreCase)); if (currentAsteroidList.Count == 1) { originalAsteroid = currentAsteroidList[0]; return true; } else { MyAPIGateway.Session.VoxelMaps.GetInstances(currentAsteroidList, v => v.StorageName.IndexOf(searchAsteroidName, StringComparison.InvariantCultureIgnoreCase) >= 0); if (currentAsteroidList.Count == 1) { originalAsteroid = currentAsteroidList[0]; return true; } } int index; if (searchAsteroidName.Substring(0, 1) == "#" && Int32.TryParse(searchAsteroidName.Substring(1), out index) && index > 0 && index <= CommandAsteroidsList.AsteroidCache.Count) { originalAsteroid = CommandAsteroidsList.AsteroidCache[index - 1]; return true; } originalAsteroid = null; return false; }