public static void Log(string logMessage, Action<string> echo = null, IMyProgrammableBlock me = null, string label = null, IMyTextPanel mirrorLcd = null, bool truncateForLcd = true) { String output = ""; if(echo == null) { output = "\n"; output += logMessage; throw new Exception(output); } if(LogBuffer == null) { LogBuffer = new StringBuilder(); } if(label != null) { logMessage = label+": "+logMessage; } if(mirrorLcd != null) { string currentlyMirrored = mirrorLcd.GetPublicText(); if(truncateForLcd && LogBuffer.Length + logMessage.Length > LOG_MAX_LCD_LENGTH_CHARS) { StringBuilder lcdBuffer = new StringBuilder(LogBuffer.ToString()); int charAmountToOffset = fullLineCharsExceeding(lcdBuffer, logMessage.Length, LogBuffer.Length - (LOG_MAX_LCD_LENGTH_CHARS - logMessage.Length)); lcdBuffer.Remove(0, LogBuffer.Length - LOG_MAX_LCD_LENGTH_CHARS + charAmountToOffset - 2); lcdBuffer.AppendLine(); lcdBuffer.Append(logMessage); mirrorLcd.WritePublicText(lcdBuffer.ToString(), false); } else { string potentialNewLine = (currentlyMirrored.Length > 0)? "\n" : ""; mirrorLcd.WritePublicText(potentialNewLine+logMessage, true); } } if(LogBuffer.Length + logMessage.Length * 2 > LOG_MAX_ECHO_LENGTH_CHARS) { int charAmountToRemove = fullLineCharsExceeding(LogBuffer, logMessage.Length); LogBuffer.Remove(0, charAmountToRemove); LogBuffer.Append(output); } if(LogBuffer.Length > 0) { LogBuffer.AppendLine(); } LogBuffer.Append(logMessage); echo(LogBuffer.ToString()); }
public Elevator(IMyGridTerminalSystem grid, IMyProgrammableBlock me, Action<string> echo, TimeSpan elapsedTime) { GridTerminalSystem = grid; Echo = echo; ElapsedTime = elapsedTime; Me = me; }
public Example(IMyGridTerminalSystem grid, IMyProgrammableBlock me, Action<string> echo, TimeSpan elapsedTime) : base(grid, me, echo, elapsedTime) { EasyBlocks monitoredBlocks = Blocks; // The event will be added to all these blocks AddEvents( monitoredBlocks, delegate(EasyBlock block) { // When this function returns true, the event is triggered return block.Damage() > 1; // when the block is damage more than 1% }, damaged1Percent // this is called when the event is triggered ); }
private long start = 0; // Time at start of program #endregion Fields #region Constructors /*** Constructor ***/ public EasyAPI(IMyGridTerminalSystem grid, IMyProgrammableBlock me, Action<string> echo, TimeSpan elapsedTime) { this.clock = this.start = DateTime.Now.Ticks; this.delta = 0; this.GridTerminalSystem = EasyAPI.grid = grid; this.Echo = echo; this.ElapsedTime = elapsedTime; this.ArgumentActions = new Dictionary<string,List<Action>>(); this.Events = new List<IEasyEvent>(); this.Schedule = new List<EasyInterval>(); this.Intervals = new List<EasyInterval>(); // Get the Programmable Block that is running this script (thanks to LordDevious and LukeStrike) this.Self = new EasyBlock(me); this.Reset(); }
public Example(IMyGridTerminalSystem grid, IMyProgrammableBlock me, Action<string> echo, TimeSpan elapsedTime) : base(grid, me, echo, elapsedTime) { // Create menu this.menu = new EasyMenu("Test Menu", new [] { new EasyMenuItem("Play Sound", playSound), new EasyMenuItem("Door Status", new[] { new EasyMenuItem("Door 1", toggleDoor, doorStatus), new EasyMenuItem("Door 2", toggleDoor, doorStatus), new EasyMenuItem("Door 3", toggleDoor, doorStatus), new EasyMenuItem("Door 4", toggleDoor, doorStatus) }), new EasyMenuItem("Do Nothing") }); // Get blocks this.speaker = Blocks.Named("MenuSpeaker").FindOrFail("MenuSpeaker not found!"); this.lcd = new EasyLCD(Blocks.Named("MenuLCD").FindOrFail("MenuLCD not found!")); // Handle Arguments On("Up", delegate() { this.menu.Up(); doUpdates(); }); On("Down", delegate() { this.menu.Down(); doUpdates(); }); On("Choose", delegate() { this.menu.Choose(); doUpdates(); }); On("Back", delegate() { this.menu.Back(); doUpdates(); }); }
public Example(IMyGridTerminalSystem grid, IMyProgrammableBlock me, Action<string> echo, TimeSpan elapsedTime) : base(grid, me, echo, elapsedTime) { // Start your code here }
public InterGridComms(IMyIntergridCommunicationSystem comms, IngameTime time, IMyProgrammableBlock me) { commands = new Dictionary <string, Action <object> >(); keepaliveChann = comms.RegisterBroadcastListener("ServerKeepAlive"); this.comms = comms; this.time = time; this.me = me; }
public AppFileSystemObject(string name, IFileSystemObject parentFileSystemObject, IMyProgrammableBlock programmableBlock) : base(name, parentFileSystemObject) { ProgrammableBlock = programmableBlock; }
public void Main(string argument, UpdateType updateSource) { IMyPistonBase PistonOne = GridTerminalSystem.GetBlockWithName("Piston") as IMyPistonBase; IMyPistonBase PistonTwo = GridTerminalSystem.GetBlockWithName("Piston 2") as IMyPistonBase; IMyPistonBase PistonThree = GridTerminalSystem.GetBlockWithName("Piston 3") as IMyPistonBase; IMyCargoContainer StorageBlock = GridTerminalSystem.GetBlockWithName("Large Cargo Container") as IMyCargoContainer; IMyMotorAdvancedStator Rotor = GridTerminalSystem.GetBlockWithName("Advanced Rotor") as IMyMotorAdvancedStator; IMyBlockGroup Drills = GridTerminalSystem.GetBlockGroupWithName("Drillers"); IMyProgrammableBlock programmableBlock = GridTerminalSystem.GetBlockWithName("Programmable block") as IMyProgrammableBlock; IMyTextSurface screen = ((IMyTextSurfaceProvider)programmableBlock).GetSurface(0); screen.WriteText("1234"); if (Drills == null) { Echo("Drillers group not found"); return; } List <IMyTerminalBlock> listBlocks = new List <IMyTerminalBlock>(); Drills.GetBlocks(listBlocks); Echo($"{PistonOne.CustomName}"); Echo($"{PistonTwo.CustomName}"); Echo($"{PistonThree.CustomName}"); Echo($"{StorageBlock.CustomName}"); Echo($"{Rotor.CustomName}"); Echo($"Number of Drills: {listBlocks.Count}"); Echo($"Current Mass of {StorageBlock.CustomName}: {StorageBlock.Mass}"); var storageBlock = StorageBlock.GetInventory(); MyFixedPoint storageBlockVolume = storageBlock.CurrentVolume; float volume = (float)storageBlockVolume; float maxVolume = (float)storageBlock.MaxVolume; Echo($"Current Volume: {volume}"); if (Rotor == null) { Echo("Rotor Block Not Found"); return; } if (volume >= maxVolume) { Echo("[WARNING] Cargo Full"); Rotor.RotorLock = true; foreach (var drill in listBlocks) { var d = drill as IMyShipDrill; d.Enabled = false; } } else { Rotor.RotorLock = false; foreach (var drill in listBlocks) { var d = drill as IMyShipDrill; d.Enabled = true; } } //180/piRads double rotorAngle = Rotor.Angle * (180 / Math.PI); //double rotorAngle = 180 / (Math.PI * rotor.Angle); Echo("Rotor Angle: " + Math.Round(rotorAngle, 2)); if (rotorAngle < 40 && rotorAngle > 39.9) { if (PistonOne.CurrentPosition < 10) { PistonOne.MaxLimit += 1; } else if (PistonTwo.CurrentPosition < 10) { PistonTwo.MaxLimit += 1; } else if (PistonThree.CurrentPosition < 10) { PistonThree.MaxLimit += 1; } } }
/// <summary> /// 初始化主要文本面板 /// </summary> /// <param name="mainTextSurfaceNames"></param> /// <param name="myGridTerminalSystem"></param> /// <param name="me"></param> public static TextSurfacesModel InitTextSurface(IReadOnlyCollection <string> mainTextSurfaceNames, IMyGridTerminalSystem myGridTerminalSystem, IMyProgrammableBlock me) { var textSurfaces = new List <IMyTextSurface>(); foreach (string mainTextSurfaceName in mainTextSurfaceNames) { string[] trueNames = mainTextSurfaceName.Split('&'); if (trueNames.Length == 1) { var textSurface = myGridTerminalSystem.GetBlockWithName(trueNames[0]) as IMyTextSurface; textSurfaces.Add(textSurface); } else if (trueNames.Length == 2) { var index = Convert.ToInt32(trueNames[1]); var textSurfaceProvider = myGridTerminalSystem.GetBlockWithName(trueNames[0]) as IMyTextSurfaceProvider; if (textSurfaceProvider != null && textSurfaceProvider.SurfaceCount >= index) { textSurfaces.Add(textSurfaceProvider.GetSurface(index)); } } } textSurfaces.Add(me.GetSurface(0)); return(new TextSurfacesModel(textSurfaces)); }
public Example(IMyGridTerminalSystem grid, IMyProgrammableBlock me, Action <string> echo, TimeSpan elapsedTime) : base(grid, me, echo, elapsedTime) { // Create menu this.menu = new EasyMenu("Explore", new [] { new EasyMenuItem("Actions", delegate(EasyMenuItem actionsItem) { List <string> types = new List <string>(); for (int n = 0; n < Blocks.Count(); n++) { var block = Blocks.GetBlock(n); if (!types.Contains(block.Type())) { types.Add(block.Type()); } } types.Sort(); actionsItem.children.Clear(); for (int n = 0; n < types.Count; n++) { actionsItem.children.Add(new EasyMenuItem(types[n], delegate(EasyMenuItem typeItem) { typeItem.children.Clear(); var blocks = Blocks.OfType(typeItem.Text); for (int o = 0; o < blocks.Count(); o++) { var block = blocks.GetBlock(o); typeItem.children.Add(new EasyMenuItem(block.Name(), delegate(EasyMenuItem blockItem) { blockItem.children.Clear(); var actions = block.GetActions(); for (int p = 0; p < actions.Count; p++) { var action = actions[p]; blockItem.children.Add(new EasyMenuItem(action.Name + "", delegate(EasyMenuItem actionItem) { block.ApplyAction(action.Id); return(false); })); } blockItem.children.Sort(); return(true); })); } typeItem.children.Sort(); return(true); })); } actionsItem.children.Sort(); return(true); }) }); // Get blocks this.timer = Blocks.Named("MenuTimer").FindOrFail("MenuTimer not found!"); this.screen = Blocks.Named("MenuLCD").FindOrFail("MenuLCD not found!"); this.lcd = new EasyLCD(this.screen); Every(100 * Milliseconds, doUpdates); // Run doUpdates every 100 milliseconds }
public BMyKryptDebugSrvAppender(Program Assembly) { _debugSrv = Assembly.GridTerminalSystem.GetBlockWithName("DebugSrv") as IMyProgrammableBlock; }
public void ProcessCommand(string arg) { string[] command = arg.Split(new string[] { delimiter }, StringSplitOptions.None); int parse0 = -1; try { parse0 = int.Parse(command[0]); } catch { Echo("Non Numerical Value Detected"); Echo(command[0] + ""); } if (parse0 > 0) { parse0--; command[0] = parse0.ToString(); if (command[1] == "ABC(*&^%$#@!") { //Do Nothing } //insert receiving commands here /*else if (command[1] == "rawr") * { * IMyTextPanel textPanel = GridTerminalSystem.GetBlockWithName("Text panel") as IMyTextPanel; * textPanel.ShowPublicTextOnScreen(); * textPanel.WritePublicText("Raawwrr"); * textPanel.WritePublicText(textPanel.GetPublicText() + "\n" + tempArg[0]); * tempArg.RemoveAt(0); * }*/ else if (command[1] == "ALERT") { IMyBlockGroup group = GridTerminalSystem.GetBlockGroupWithName("Warning Lights"); List <IMyInteriorLight> lights = new List <IMyInteriorLight>(); group.GetBlocksOfType(lights); foreach (IMyInteriorLight light in lights) { light.ApplyAction("OnOff_On"); } Retransmit(command, parse0); tempArg.RemoveAt(0); } else if (command[1] == "DESdata") { IMyProgrammableBlock desComp = GridTerminalSystem.GetBlockWithName("DES Computer") as IMyProgrammableBlock; desComp.TryRun(arg); tempArg.RemoveAt(0); } //end of receiving commands else { //retransmit Retransmit(command, parse0); tempArg.RemoveAt(0); } } }
public Logger(Program program, IMyProgrammableBlock me) { Program = program; Surface = me.GetSurface(0); }
public Command(string name, IMyProgrammableBlock target, string param) : base(name) { this.target = target; this.param = param; }
private void init() { #region initialization oldPBName = Me.CustomName; unique_id = (new Random()).Next(); all_blocks_found = true; autopilot_en = true; location_name = "UNKNOWN"; // For spinner counter = 0; string parse = Me.CustomName.Replace(BLOCK_PREFIX, ""); int id1 = Me.CustomName.IndexOf('['); int id2 = Me.CustomName.IndexOf(']'); if (id1 >= 0 && id2 >= 0) { parse = parse.Substring(id1 + 1, id2 - id1 - 1); } else { parse = ""; } BaconArgs Args = BaconArgs.parse(parse); IS_BASE = (Args.getFlag('b') > 0); DOCK_LEFT = (Args.getFlag('l') > 0); IS_PLANET = (Args.getFlag('p') > 0); if (IS_PLANET) IS_BASE = true; List<string> nameArg = Args.getOption("name"); if (nameArg.Count > 0 && nameArg[0] != null) { location_name = nameArg[0]; } // Set all known blocks to null or clear lists lcdPanel = null; messageReceiver = null; WANProgram = null; connector = null; remoteControl = null; door = null; timer = null; landLight = null; mainGear = 0; gyros.Clear(); destinations.Clear(); gears.Clear(); // Get all blocks List<IMyTerminalBlock> blks = new List<IMyTerminalBlock>(); GridTerminalSystem.SearchBlocksOfName(BLOCK_PREFIX, blks, hasPrefix); num_blocks_found = blks.Count; // Assign blocks to variables as appropriate foreach (var blk in blks) { // LCD panel for printing if (blk is IMyTextPanel) { lcdPanel = blk as IMyTextPanel; lcdPanel.ShowPublicTextOnScreen(); lcdPanel.SetValueFloat("FontSize", 1.2f); } // Wico Area Network programmable block else if (blk is IMyProgrammableBlock && !blk.Equals(Me)) { WANProgram = blk as IMyProgrammableBlock; } // Autopilot else if (!IS_BASE && blk is IMyRemoteControl) { remoteControl = blk as IMyRemoteControl; } /* Ship or station connector for docking * Used to connect to station and for orientation info */ else if (!IS_PLANET && blk is IMyShipConnector) { connector = blk as IMyShipConnector; } /* Door used for docking; used for orientation information * since it's more obvious which way a door faces than a connector */ else if (!IS_PLANET && blk is IMyDoor) { door = blk as IMyDoor; } // Gyros for ship orientation else if (!IS_BASE && blk is IMyGyro) { IMyGyro g = blk as IMyGyro; gyros.Add(g); } // Timer block so that we can orient ship properly - requires multiple calls/sec else if (!IS_BASE && blk is IMyTimerBlock) { timer = blk as IMyTimerBlock; timer.SetValueFloat("TriggerDelay", 1.0f); } // Light (interior or spotlight) determines where we will land else if (IS_BASE && IS_PLANET && blk is IMyInteriorLight) { landLight = blk as IMyInteriorLight; } // Landing gear.... else if (!IS_BASE && blk is IMyLandingGear) { IMyLandingGear gear = blk as IMyLandingGear; gears.Add(gear); if (gear.CustomName.ToLower().Contains("main")) { mainGear = gears.Count - 1; } } } // Make sure all gyros reset resetGyros(); // Clear block list blks.Clear(); // Get text panel blocks used by Wico Area Network for communication GridTerminalSystem.GetBlocksOfType<IMyTextPanel>(blks, hasWANRPrefix); if (blks.Count == 0) { Echo("Error: Can't find message received text panel for Wico Area Network"); all_blocks_found = false; } else { messageReceiver = blks[0] as IMyTextPanel; messageReceiver.WritePublicTitle(""); messageReceiver.WritePrivateTitle("NAV"); } if (WANProgram == null) { Echo("Error: Can't find programming block for Wico Area Network"); all_blocks_found = false; } if (lcdPanel == null) { Echo("Error: Expect 1 LCD"); all_blocks_found = false; } if (!IS_PLANET && connector == null) { Echo("Error: Can't find any connectors to use for docking"); all_blocks_found = false; } if (!IS_BASE && remoteControl == null) { Echo("Error: Can't find any remote control blocks"); all_blocks_found = false; } if (!IS_PLANET && door == null) { Echo("Error: Can't find door"); all_blocks_found = false; } if (!IS_BASE && gyros.Count == 0) { Echo("Error: No gyros detected"); all_blocks_found = false; } if (!IS_BASE && timer == null) { Echo("Error: No timer found"); all_blocks_found = false; } if (IS_PLANET && landLight == null) { Echo("Error: No light for landing ship destination found"); all_blocks_found = false; } if (!IS_BASE && gears.Count == 0) { Echo("Warning: no landing gear found. You will not be able to land on planets"); } // Init communicator state machine comm = communicate().GetEnumerator(); // Clear autopilot state machine fly = null; #endregion }
void Initialize() // Handles the initialization of blocks. Is run at the end of each loop to ensure everything is there. { inventories.Clear(); // This must be done to avoid memory leaks. refineries.Clear(); furnaces.Clear(); assemblers.Clear(); reactors.Clear(); gasGenerators.Clear(); gatlings.Clear(); missileLaunchers.Clear(); lcds.Clear(); if (!Me.CustomName.ToLower().Contains(TAG.ToLower())) // If we have no tag at all. { Me.CustomName += " " + TAG; // Add a tag. }// else if (!Me.CustomName.Contains(TAG)) // We know we have a tag, but run this when the tag isn't exactly equal. { string customName = Me.CustomName; // Replacing the incorrect tag with the proper version. int index = customName.ToLower().IndexOf(TAG.ToLower()); customName = customName.Remove(index, TAG.Length); customName = customName.Insert(index, TAG); Me.CustomName = customName; }// GridTerminalSystem.SearchBlocksOfName(TAG, blocks); foreach (IMyTerminalBlock block in blocks) { if (!block.CustomName.Contains(TAG))// If the tag doesn't match up exactly, correct the tag. { string customName = block.CustomName; int index = customName.ToLower().IndexOf(TAG.ToLower()); customName = customName.Remove(index, TAG.Length); customName = customName.Insert(index, TAG); block.CustomName = customName; }// IMyRefinery refinery = block as IMyRefinery;// This will return null if the block isn't a refinery block. if (refinery != null) { if (refinery.BlockDefinition.SubtypeId.Equals(FURNACE_TYPE_ID))// Both Refinieries and Arc Furnaces are refineries. Seperate them by subtype. { furnaces.Add(refinery); } else { refineries.Add(refinery); } continue; }// IMyAssembler assembler = block as IMyAssembler; if (assembler != null) { assemblers.Add(assembler); continue; }// IMyReactor reactor = block as IMyReactor; if (reactor != null) { reactors.Add(reactor); continue; }// IMyGasGenerator gasGenerator = block as IMyGasGenerator; if (gasGenerator != null) { gasGenerators.Add(gasGenerator); continue; }// IMyLargeGatlingTurret gatlingTurret = block as IMyLargeGatlingTurret; IMySmallGatlingGun gatlingGun = block as IMySmallGatlingGun; if ((gatlingTurret != null) | (gatlingGun != null)) { gatlings.Add(block); continue; }// IMyLargeMissileTurret missileTurret = block as IMyLargeMissileTurret; IMySmallMissileLauncherReload smallLauncherReload = block as IMySmallMissileLauncherReload; if ((missileTurret != null) | (smallLauncherReload != null)) { missileLaunchers.Add(block); continue; }// IMySmallMissileLauncher missileLauncher = block as IMySmallMissileLauncher; if ((missileLauncher != null) & (block.BlockDefinition.SubtypeId.Equals("LargeMissileLauncher"))) { missileLaunchers.Add(block); continue; }// IMyProgrammableBlock programmableBlock = block as IMyProgrammableBlock; if (programmableBlock != null) { if (!programmableBlock.Equals(Me) & programmableBlock.IsWorking) // If the programmable block isn't the one running this instance and it is working. { if (programmableBlock.CustomName.ToLower().Contains(CONNECTED_PB_TAG.ToLower())) // Check if it has the connected PB tag. { if (!programmableBlock.CustomName.Contains(CONNECTED_PB_TAG)) { string customName = programmableBlock.CustomName; int index = customName.ToLower().IndexOf(CONNECTED_PB_TAG.ToLower()); customName = customName.Remove(index, CONNECTED_PB_TAG.Length); customName = customName.Insert(index, CONNECTED_PB_TAG); programmableBlock.CustomName = customName; }// connectedPBs.Add(programmableBlock); continue; } // else // Assume this PB is running the same script. { if (programmableBlock.CubeGrid.EntityId == Me.CubeGrid.EntityId) { Echo("ERROR: MORE THAN ONE IAN ON ONE GRID"); active = false;// Both PBs will disable themselves and show an error. continue; }// else if (programmableBlock.CubeGrid.GridSize > Me.CubeGrid.GridSize)// The PB with the biggest grid size will be dominant. { active = false; continue; } active = true;// None of the exceptions have occured, so we are free to resume functioning. This will ensure IAN plays nice with it's double. continue; }// } // } // IMyTextPanel panel = block as IMyTextPanel; if (panel != null) { lcds.Add(panel); } } // } //
public Program() { programmableBlock = Me; //Search for starter Group with this pb in it /* * List<IMyBlockGroup> allGroups = new List<IMyBlockGroup>(); * GridTerminalSystem.GetBlockGroups(allGroups); * bool found = false; * foreach (IMyBlockGroup group in allGroups) * { * List<IMyProgrammableBlock> pbsInList = new List<IMyProgrammableBlock>(); * group.GetBlocksOfType(pbsInList); * foreach (IMyProgrammableBlock pb in pbsInList) * { * if (pb.Equals(programmableBlock)) * { * starterBlocks = group; * found = true; * break; * } * } * if (found) * { * break; * } * } * if (!found) * { * Echo("Starter Group not found, is this Programmable Block in it?"); * return; * } * * //Starter group is found, trying to acquire the needed compoents * List<IMyTerminalBlock> tempBlocks = new List<IMyTerminalBlock>(); * try * { * starterBlocks.GetBlocksOfType<IMyCameraBlock>(tempBlocks); * visor = tempBlocks[0] as IMyCameraBlock; * visor.EnableRaycast = true; * Echo("Camera found and activ"); * } * catch (Exception) * { * Echo("Camera could not be found in starter group"); * return; * } * try * { * starterBlocks.GetBlocksOfType<IMyShipMergeBlock>(tempBlocks); * merge = tempBlocks[0] as IMyShipMergeBlock; * Echo("Merge Block found and activ"); * } * catch (Exception) * { * Echo("Merge Block could not be found in starter group"); * return; * } * try * { * starterBlocks.GetBlocksOfType<IMyRemoteControl>(tempBlocks); * control = tempBlocks[0] as IMyRemoteControl; * Echo("Remote Control found and activ"); * } * catch (Exception) * { * Echo("Remote Control could not be found in starter group"); * return; * } * try * { * starterBlocks.GetBlocksOfType<IMyRadioAntenna>(tempBlocks); * antenna = tempBlocks[0] as IMyRadioAntenna; * Echo("Radio Antenna found and activ"); * } * catch (Exception) * { * Echo("Antenna could not be found in starter group"); * return; * }*/ setupSuccess = true; //funcs = new TargetFuncs(this, visor); Echo("Setup completed, Missile ready to fire"); //Components found, setup complete, missile ready to fire }
// constructor (pass `this` as argument from the program) public Utils(MyGridProgram program) { launchCounter++; //print(string.Format("Started at {0}", System.DateTime.Now)); program.GridTerminalSystem.GetBlocks(blocks); foreach (var block in blocks) { var programmableBlock = block as IMyProgrammableBlock; if (programmableBlock != null && programmableBlock.IsRunning) { thisProgrammableBlock = programmableBlock; break; } } if (thisProgrammableBlock == null) { printHeader("Unknown"); Print("failed to find this programmable block"); } else { printHeader(thisProgrammableBlock.CustomName); var screenName = "Screen-" + thisProgrammableBlock.CustomName.Substring(3); int i = 0; while (true) { var panel1 = FindBlockIfExists <IMyTextPanel>(string.Format("{0}-{1}", screenName, i), FilterGrid.Current); if (panel1 != null) { screens.Add(panel1); } else { panel1 = FindBlockIfExists <IMyTextPanel>(string.Format("{0}-{1}w", screenName, i), FilterGrid.Current); if (panel1 != null) { screens.Add(panel1); screenIsWide = true; } else { panel1 = FindBlockIfExists <IMyTextPanel>(string.Format("{0}-{1}r", screenName, i), FilterGrid.Current); if (panel1 != null) { screens.Add(panel1); screenIsRaw = true; } else { break; } } } i++; } if (screens.Count == 0) { Print(string.Format("failed to find screen with prefix \"{0}\"", screenName)); } setupScreen(); } }
public HangarController(IMyGridTerminalSystem grid, IMyProgrammableBlock me, Action <string> echo, TimeSpan elapsedTime) { GridTerminalSystem = grid; Echo = echo; ElapsedTime = elapsedTime; Me = me; hangarDoors = new List <IMyDoor> [groups.Count]; interiorDoors = new List <IMyDoor> [groups.Count]; exteriorDoors = new List <IMyDoor> [groups.Count]; soundBlocks = new List <IMySoundBlock> [groups.Count]; warningLights = new List <IMyInteriorLight> [groups.Count]; airVents = new List <IMyAirVent> [groups.Count]; hangarOpen = new Boolean[groups.Count]; // Get list of groups on this station/ship List <IMyBlockGroup> BlockGroups = new List <IMyBlockGroup>(); GridTerminalSystem.GetBlockGroups(BlockGroups); // Search all groups that exist for the groups with name as specified in groups list for (int i = 0; i < BlockGroups.Count; i++) { int pos = groups.IndexOf(BlockGroups[i].Name); // If name is one of our candidates... if (pos != -1) { List <IMyTerminalBlock> blocks = BlockGroups[i].Blocks; // Define list of blocks for each group List <IMyDoor> hangarDoorList = new List <IMyDoor>(); List <IMyDoor> interiorDoorList = new List <IMyDoor>(); List <IMyDoor> exteriorDoorList = new List <IMyDoor>(); List <IMySoundBlock> soundBlockList = new List <IMySoundBlock>(); List <IMyInteriorLight> warningLightList = new List <IMyInteriorLight>(); List <IMyAirVent> airVentList = new List <IMyAirVent>(); // Go through all blocks and add to appropriate list // Also initialize to a sane known state e.g. closed, on... for (int j = 0; j < blocks.Count; j++) { IMyTerminalBlock block = blocks[j]; String blockType = block.DefinitionDisplayNameText; String blockName = block.CustomName; block.ApplyAction("OnOff_On"); if (blockType.Equals("Airtight Hangar Door")) { IMyDoor item = block as IMyDoor; item.ApplyAction("Open_Off"); hangarDoorList.Add(item); } else if ((blockType.Equals("Sliding Door") || blockType.Equals("Door")) && blockName.Contains("Interior")) { IMyDoor item = block as IMyDoor; item.ApplyAction("Open_Off"); interiorDoorList.Add(item); } else if ((blockType.Equals("Sliding Door") || blockType.Equals("Door")) && blockName.Contains("Exterior")) { IMyDoor item = block as IMyDoor; item.ApplyAction("Open_Off"); exteriorDoorList.Add(item); } else if (blockType.Equals("Sound Block")) { IMySoundBlock item = block as IMySoundBlock; item.ApplyAction("StopSound"); item.SetValueFloat("LoopableSlider", 10); soundBlockList.Add(item); } else if (blockType.Equals("Interior Light")) { IMyInteriorLight item = block as IMyInteriorLight; item.ApplyAction("OnOff_Off"); item.SetValueFloat("Blink Interval", 1); item.SetValueFloat("Blink Lenght", 50); item.SetValueFloat("Blink Offset", 0); item.SetValue <Color>("Color", Color.Red); warningLightList.Add(item); } else if (blockType.Contains("Air Vent")) { IMyAirVent item = block as IMyAirVent; item.ApplyAction("Depressurize_Off"); airVentList.Add(item); } } // Some cleanup hangarDoorList.TrimExcess(); interiorDoorList.TrimExcess(); exteriorDoorList.TrimExcess(); soundBlockList.TrimExcess(); warningLightList.TrimExcess(); airVentList.TrimExcess(); if (hangarDoorList.Count == 0) { Echo("Warning: no hangar doors detected for " + BlockGroups[i].Name); } else if (interiorDoorList.Count == 0) { Echo("Warning: no interior doors detected for " + BlockGroups[i].Name); } else if (soundBlockList.Count == 0) { Echo("Warning: no sound blocks detected for " + BlockGroups[i].Name); } else if (warningLightList.Count == 0) { Echo("Warning: no warning lights detected for " + BlockGroups[i].Name); } else if (airVentList.Count == 0) { Echo("Warning: no air vents detected for " + BlockGroups[i].Name); } // Now that we have populated lists add them to the correct position in the group list hangarDoors[pos] = hangarDoorList; interiorDoors[pos] = interiorDoorList; exteriorDoors[pos] = exteriorDoorList; soundBlocks[pos] = soundBlockList; warningLights[pos] = warningLightList; airVents[pos] = airVentList; hangarOpen[pos] = false; // Exterior doors have been requested to close so we set a check to lock them when they are in fact closed requests.Add(new requestTicket(pos, "lockExteriorDoors")); } } }
public void programmableStuff() { IMyProgrammableBlock prog = GridTerminalSystem.GetBlockWithName("MSGRecevier") as IMyProgrammableBlock; DebugPrintBlockActions(prog); }
// Expects the ini to have a line for [LCDConfig] public LCDConfigItem(IMyProgrammableBlock Me) : base(Me) { BlockName = _ini.Get(ConfigTitle, "BlockName").ToString(); IsProvider = _ini.Get(ConfigTitle, "IsProvider").ToBoolean(); ProviderScreenIndex = _ini.Get(ConfigTitle, "ProviderScreenIndex").ToInt32(); }
internal BatteryCollection(MyGridProgram grid, IMyProgrammableBlock cpu) : base(grid, cpu, b => b is IMyBatteryBlock) { }
public static void Initialize(GridProgramRef gridProgramRef) { if (gridProgramRef.GridTerminalSystem == null) { throw new ArgumentNullException("Passed GTS reference was null."); } if (gridProgramRef.Echo == null) { throw new ArgumentNullException("Passed Echo reference was null."); } if (gridProgramRef.Me == null) { throw new ArgumentNullException("Passed Me reference was null."); } GridProgramRef = gridProgramRef; GridTerminalSystem = gridProgramRef.GridTerminalSystem; Echo = gridProgramRef.Echo; Me = gridProgramRef.Me; Utils = gridProgramRef.Utils; // get data from customdata string[] splitted = Me.CustomData.Split(new char[] { '$' }); string[] componentNames = splitted[0].Split(new char[] { '*' }); for (var i = 0; i < componentNames.Length; i++) { componentNames[i] = "MyObjectBuilder_BlueprintDefinition/" + componentNames[i]; } //$SmallMissileLauncher*(null)=0:4,2:2,5:1,7:4,8:1,4:1*LargeMissileLauncher=0:35,2:8,5:30,7:25,8:6,4:4$ char[] asterisk = new char[] { '*' }; char[] equalsign = new char[] { '=' }; char[] comma = new char[] { ',' }; char[] colon = new char[] { ':' }; for (var i = 1; i < splitted.Length; i++) { // splitted[1 to n] are type names and all associated subtypes // blocks[0] is the type name, blocks[1 to n] are subtypes and component amounts string[] blocks = splitted[i].Split(asterisk); string typeName = "MyObjectBuilder_" + blocks[0]; for (var j = 1; j < blocks.Length; j++) { string[] compSplit = blocks[j].Split(equalsign); string blockName = typeName + '/' + compSplit[0]; // add a new dict for the block try { blueprints.Add(blockName, new Dictionary <string, int>()); } catch (Exception e) { Echo("Error adding block: " + blockName); } var components = compSplit[1].Split(comma); foreach (var component in components) { string[] amounts = component.Split(colon); int idx = Convert.ToInt32(amounts[0]); int amount = Convert.ToInt32(amounts[1]); string compName = componentNames[idx]; blueprints[blockName].Add(compName, amount); } } } }
private void try_register_handlers() { sync_helper.try_register_handlers(); screen_info.try_register_handlers(); if (!_entity_events_set && screen_info.settings_loaded && MyAPIGateway.Entities != null) { var existing_entities = new HashSet <IMyEntity>(); MyAPIGateway.Entities.GetEntities(existing_entities); foreach (IMyEntity cur_entity in existing_entities) { on_entity_added(cur_entity); } MyAPIGateway.Entities.OnEntityAdd += on_entity_added; MyAPIGateway.Entities.OnEntityRemove += on_entity_removed; _entity_events_set = true; } if (!screen_info.settings_loaded || MyAPIGateway.TerminalControls == null) { return; } if (!_ship_controller_controls_set) { if (_sample_controller?.GetProperty("DampenersOverride") == null) { return; } create_controller_widgets <IMyCockpit>(); create_controller_widgets <IMyRemoteControl>(); _ship_controller_controls_set = true; _sample_controller = null; } if (!_thruster_controls_set) { if (!screen_info.torque_disabled && _sample_thruster?.GetProperty("Override") == null) { return; } _thruster_controls_set = true; _sample_thruster = null; if (screen_info.torque_disabled) { return; } IMyTerminalControlSeparator thruster_line = MyAPIGateway.TerminalControls.CreateControl <IMyTerminalControlSeparator, IMyThrust>("TTDTWM_LINE1"); MyAPIGateway.TerminalControls.AddControl <IMyThrust>(thruster_line); create_switch <IMyThrust>("ActiveControl", "Steering", null, "On", "Off", "On", "Off", thruster_and_grid_tagger.is_under_active_control, thruster_and_grid_tagger.set_active_control, thruster_and_grid_tagger.is_active_control_available); create_switch <IMyThrust>("AntiSlip", "Thrust Trimming", null, "On", "Off", "On", "Off", thruster_and_grid_tagger.is_anti_slip, thruster_and_grid_tagger.set_anti_slip, thruster_and_grid_tagger.is_anti_slip_available); create_checkbox <IMyThrust>("DisableLinearInput", "Disable linear input", null, "On", "Off", thruster_and_grid_tagger.is_rotational_only, thruster_and_grid_tagger.toggle_linear_input, thruster_and_grid_tagger.is_active_control_available); create_switch <IMyThrust>("StaticLimit", "Thrust Limiter", null, "On", "Off", "On", "Off", thruster_and_grid_tagger.is_thrust_limiter_on, thruster_and_grid_tagger.set_thrust_limiter, thruster_and_grid_tagger.is_thrust_limiter_available); create_slider <IMyThrust>("ManualThrottle", "Manual throttle", thruster_and_grid_tagger.get_manual_throttle, thruster_and_grid_tagger.set_manual_throttle, thruster_and_grid_tagger.throttle_status, 0.0f, 100.0f, 5.0f, "IncreaseThrottle", "DecreaseThrottle", "Increase Manual Throttle", "Decrease Manual Throttle"); create_PB_property <float, IMyThrust>("BalancedLevel", thruster_and_grid_tagger.get_thrust_limit); } if (!_programmable_block_properties_set) { if (_sample_PB?.GetProperty("ShowInToolbarConfig") == null) { return; } create_PB_property <Func <string, string, bool>, IMyProgrammableBlock>("ComputeOrbitElements", get_ship_elements_calculator); create_PB_property <Func <string, Vector3D, Vector3D, bool>, IMyProgrammableBlock>("ComputeOrbitElementsFromVectors", get_vector_elements_calculator); create_PB_property <Func <string>, IMyProgrammableBlock>("GetReferenceBodyName", get_reference_name_fetcher); create_PB_property <Action <Dictionary <string, Vector3D> >, IMyProgrammableBlock>("GetPrimaryVectors", get_vector_fetcher); create_PB_property <Action <Dictionary <string, double> >, IMyProgrammableBlock>("GetPrimaryScalars", get_scalar_fetcher); create_PB_property <Action <Dictionary <string, double> >, IMyProgrammableBlock>("GetDerivedElements", get_derived_fetcher); create_PB_property <Action <double?, Dictionary <string, double> >, IMyProgrammableBlock>("GetPositionalElements", get_positional_fetcher); create_PB_property <Action <double, Dictionary <string, Vector3D> >, IMyProgrammableBlock>("GetStateVectors", get_state_vector_fetcher); create_PB_property <Func <double, double, double>, IMyProgrammableBlock>("ConvertTrueAnomalyToMean", get_true_to_mean_converter); create_PB_property <Func <double, double, double>, IMyProgrammableBlock>("ConvertMeanAnomalyToTrue", get_mean_to_true_converter); create_PB_property <Func <double, double, Vector3D>, IMyProgrammableBlock>("ComputeOrbitNormal", get_orbit_normal_calculator); create_PB_property <Func <Vector3D, Vector3D, Vector3D, double, double>, IMyProgrammableBlock>("ConvertRadialToTtrueAnomaly", get_radius_to_anomaly_converter); create_PB_property <Func <double, double, double, double, double, double, ValueTuple <double, double>?>, IMyProgrammableBlock> ("ComputeOrbitIntersections", get_intersection_calculator); _programmable_block_properties_set = true; _sample_PB = null; } _setup_complete = _ship_controller_controls_set && _thruster_controls_set && _programmable_block_properties_set && _entity_events_set && screen_info.settings_loaded && sync_helper.network_handlers_registered; }
bool _FindCoreOS() { List<IMyTerminalBlock> _blocks = new List<IMyTerminalBlock>(); // CoreOS has to be a TerminalBlock GridTerminalSystem.GetBlocksOfType<IMyProgrammableBlock>(_blocks); for (int i = 0; i < _blocks.Count; i++) { if (_blocks[i].CustomName.Contains(coreID)) { IMyProgrammableBlock _program = (IMyProgrammableBlock)_blocks[i]; SiosMainframe = _program; return true; } } return false; }
public GridProgramRef(IMyGridTerminalSystem gridTerminalSystem, UtilsClass utils, Action <string> echo, IMyProgrammableBlock me) { if (gridTerminalSystem == null) { throw new ArgumentNullException("Passed GTS reference was null."); } if (echo == null) { throw new ArgumentNullException("Passed Echo reference was null."); } if (me == null) { throw new ArgumentNullException("Passed Me reference was null."); } GridTerminalSystem = gridTerminalSystem; Utils = utils; Echo = echo; Me = me; }
private static void SetDestination(IMyCubeGrid grid, Vector3D destination) { bool bOldNav = false; // true=old way of NAV, false= new way // old= set gyro customname to NAV: // new = run PB directly with argument bool bKeenAutopilot = false; // force using keen autopilot if (ConvoySpeed != 10f) { ModLog.Info("Using test convoy speed of " + ConvoySpeed.ToString()); } var slimBlocks = new List <IMySlimBlock>(); grid.GetBlocks(slimBlocks, b => b.FatBlock is IMyProgrammableBlock); IMyProgrammableBlock NavPB = null; foreach (var slim in slimBlocks) { // var block = slim.FatBlock as IMyGyro; var block = slim.FatBlock as IMyProgrammableBlock; // ModLog.Info(" Found PB:" + block.CustomName); if (block.CustomName.Contains("NAV")) { if (block.CustomData.Contains("Assembly not found.")) { ModLog.Info("NAV computer not compiling:" + grid.CustomName); continue; } NavPB = block as IMyProgrammableBlock; } } // ModLog.Info("Set Destinatiion of:" + grid.CustomName); // C <comment> // S <max speed> // D <arrival distance> // W x:y:z // W <GPS> // set destination // block.CustomName = "NAV: C STARTED_DELIVERY; S 80; D 80 ; W " + destination.X + ":" + destination.Y + ":" + destination.Z; // ModLog.Info("Set Waypoint to: " + block.CustomName); string sCommand = "S " + ConvoySpeed.ToString("0") + "; D 80; W " + destination.X + ":" + destination.Y + ":" + destination.Z; if (!bOldNav && !bKeenAutopilot && NavPB != null) { // new way & not override keen autopilot and we found working nav pb // V31 Change to calling Nav module directly NavPB.Run(sCommand); bKeenAutopilot = false; } else if (!bKeenAutopilot && NavPB != null) { // old way and we found working nav PB bool bFound = false; slimBlocks.Clear(); grid.GetBlocks(slimBlocks, b => b.FatBlock is IMyGyro); foreach (var slim in slimBlocks) { var block = slim.FatBlock as IMyGyro; // using STARTED_DELIVERY as a way to find our grids! For autopilot it's a harmless comment. // NOTE: comment is not correct: it's not used as a way to find our grids // C <comment> // S <max speed> // D <arrival distance> // W x:y:z // W <GPS> // set destination block.CustomName = "NAV: " + sCommand;// C STARTED_DELIVERY; S 80; D 80 ; W " + destination.X + ":" + destination.Y + ":" + destination.Z; ModLog.Info("oldnav. Setting Destination for:" + grid.CustomName + " to:" + block.CustomName); // ModLog.Info("Set Waypoint to: " + block.CustomName); bFound = true; break; } if (!bFound) { ModLog.Info("No Gyro Found! Defaulting to Keen Autopilot. " + grid.CustomName); bKeenAutopilot = true; } } if (bKeenAutopilot || NavPB == null) { // force keen autopilot or didn't find working nav pb grid.GetBlocks(slimBlocks, b => b.FatBlock is IMyRemoteControl); foreach (var slim in slimBlocks) { var remoteControl = slim.FatBlock as IMyRemoteControl; remoteControl.ClearWaypoints(); remoteControl.AddWaypoint(destination, "Target"); remoteControl.SpeedLimit = ConvoySpeed; remoteControl.SetAutoPilotEnabled(true); } // throw exception if no remote found? (change to Inactive state...) } }
public ShipValue(ShipDisplayValue displayValue, IMyGridTerminalSystem GridTerminalSystem, IMyProgrammableBlock Me, Action <string> Echo) { this.Me = Me; this.GridTerminalSystem = GridTerminalSystem; this.DisplayValue = displayValue; this.Echo = Echo; this.ShipController = BlockUtils.GetShipController(GridTerminalSystem, Me); GetRelevantBlocks(); }
public Input(IMyProgrammableBlock programmableBlock) { this.programmableBlock = programmableBlock; }
public void SetRefExpSettings(IMyProgrammableBlock Me, EntityTracking_Module.refExpSettings refExpSettings) { this.refExpSettings = refExpSettings; this.Me = Me; }
} public class BMyKryptDebugSrvAppender : BMyAppenderBase { IMyProgrammableBlock i; Queue <string> j = new Queue <string>(); public BMyKryptDebugSrvAppender(Program a) { i = a.GridTerminalSystem.GetBlockWithName("DebugSrv") as IMyProgrammableBlock; }
public MeterAction(SurfaceMath sm, MeterDefinition def, Dictionary <Data, IData> shipData, List <IMyTerminalBlock> blocks, IMyGridTerminalSystem gts, IMyProgrammableBlock me) { this.def = def; this.shipData = shipData; if (def.textData == "") { def.textData = "OnOff"; } if (def.min == 0 && def.max == 0) { UseDataMinMax = true; } else { total = def.max - def.min; } foreach (string text in def.blocks) { if (text.StartsWith("*") && text.EndsWith("*")) { //Group. var group = gts.GetBlockGroupWithName(text.Trim('*')); if (group != null) { var groupBlocks = new List <IMyTerminalBlock>(); group.GetBlocks(groupBlocks); foreach (var block in groupBlocks) { if (block.IsSameConstructAs(me)) { this.blocks.Add(block); } } } } else { foreach (var block in blocks) { if (block.CustomName == text) { this.blocks.Add(block); break; } } } } }
public override void HandleCallback(string callback) { switch (callback) { case "unicast": MyIGCMessage message = Drone.NetworkService.GetUnicastListener().AcceptMessage(); if (message.Data == null) { Drone.LogToLcd($"\nNo Message"); } if (message.Tag == DockingRequestChannel) { Drone.LogToLcd("\nReceived Docking Request"); IMyShipConnector dockingPort = GetFreeDockingPort(); if (dockingPort == null) { Drone.LogToLcd("\nNo Free Docking Port"); } else { MyTuple <Vector3D, Vector3D, Vector3D> payload = new MyTuple <Vector3D, Vector3D, Vector3D>(); payload.Item1 = dockingPort.GetPosition() + dockingPort.WorldMatrix.Forward * 40; payload.Item2 = dockingPort.GetPosition() + 1.5 * dockingPort.WorldMatrix.Forward; Drone.LogToLcd($"\nClearance granted: {message.Source}"); Drone.LogToLcd($"\nApproach: {payload.Item1.ToString()}"); Drone.LogToLcd($"\nDocking Port: { payload.Item2.ToString()}"); Drone.Program.IGC.SendUnicastMessage(message.Source, DockingRequestChannel, payload); } } else if (message.Tag == "Notifications") { Drone.LogToLcd($"Received notification:{message.Data.ToString()}"); DroneKlaxon.LoopPeriod = 2f; DroneKlaxon.Play(); } else if (message.Tag == "survey_reports") { MyTuple <long, string, double, Vector3D, Vector3D, Vector3D> report = (MyTuple <long, string, double, Vector3D, Vector3D, Vector3D>)message.Data; Drone.LogToLcd($"Received survey_report: {report.ToString()}"); //TODO: This needs to be in a persistence layer, not the CustomData MyIni ini = new MyIni(); MyIniParseResult config; if (!ini.TryParse(Drone.Program.Me.CustomData, out config)) { throw new Exception($"Error parsing config: {config.ToString()}"); } //TODO: what about multiple deposits? ini.Set($"deposit {report.Item1.ToString()}", "deposit_type", report.Item2.ToString()); ini.Set($"deposit {report.Item1.ToString()}", "deposit_depth", report.Item3.ToString()); ini.Set($"deposit {report.Item1.ToString()}", "top_left_corner", report.Item4.ToString()); ini.Set($"deposit {report.Item1.ToString()}", "top_right_corner", report.Item5.ToString()); ini.Set($"deposit {report.Item1.ToString()}", "bottom_left_corner", report.Item6.ToString()); ini.Set($"deposit {report.Item1.ToString()}", "index", 0); Drone.Program.Me.CustomData = ini.ToString(); } else if (message.Tag == "tunnel_complete") { MyIni ini = new MyIni(); MyIniParseResult config; if (!ini.TryParse(Drone.Program.Me.CustomData, out config)) { throw new Exception($"Error parsing config: {config.ToString()}"); } int completedIndex = (int)message.Data; List <string> sections = new List <string>(); ini.GetSections(sections); IEnumerable <string> deposits = sections.Where(record => record.StartsWith("deposit")); string deposit; if (deposits != null && deposits.Count() != 0) { deposit = deposits.First(); } else { throw new Exception("No deposit data found!"); } ini.Set(deposit, "index", completedIndex + 1); Drone.Program.Me.CustomData = ini.ToString(); } break; case "docking_request_pending": ProcessDockingRequest(); break; case "recall_miner": Drone.LogToLcd("Recalling miner"); Drone.Program.IGC.SendUnicastMessage(MinerAddress, "recall", "recall"); break; case "recall_surveyor": Drone.LogToLcd("Recalling surveyor"); Drone.Program.IGC.SendUnicastMessage(SurveyorAddress, "recall", "recall"); break; case "deploy_miner": Drone.LogToLcd("Launching miner"); List <IMyProgrammableBlock> miners = new List <IMyProgrammableBlock>(); Drone.Grid().GetBlocksOfType(miners, pb => MyIni.HasSection(pb.CustomData, "miner")); //We only support one miner for now // Set the deposit details in the miners config IMyProgrammableBlock miner = miners.First(); MyIni minerConfig = new MyIni(); MyIniParseResult result; if (!minerConfig.TryParse(miner.CustomData, out result)) { Drone.LogToLcd(miner.CustomData); throw new Exception($"Error parsing config: {result.ToString()}"); } //Vector3D MiningSite = DepositCentre + 10 * Vector3D.Normalize(DepositNormal); //Vector3D TunnelEnd = DepositCentre - DepositDepth * Vector3D.Normalize(DepositNormal); //get deposit data from catalogue //calculate mining_site for next tunnel //calculate tunnel_end from mining_site and depth MyIni asteroidCatalogue = new MyIni(); asteroidCatalogue.TryParse(Drone.Program.Me.CustomData); Tunnel tunnel = new Tunnel(asteroidCatalogue); minerConfig.Set("miner", "mining_site", tunnel.StartingPoint.ToString()); minerConfig.Set("miner", "tunnel_end", tunnel.EndPoint.ToString()); minerConfig.Set("miner", "index", tunnel.TunnelIndex); miner.CustomData = minerConfig.ToString(); miner.TryRun("launch"); break; case "deploy_surveyor": Drone.LogToLcd("Launching surveyor"); List <IMyProgrammableBlock> surveyors = new List <IMyProgrammableBlock>(); Drone.Grid().GetBlocksOfType(surveyors, pb => MyIni.HasSection(pb.CustomData, "surveyor")); IMyProgrammableBlock surveyor = surveyors.First(); surveyor.TryRun("launch"); break; case "echo": Drone.LogToLcd("Echo"); DroneKlaxon.Play(); break; case "": // Just Ignore empty arguments break; default: Drone.LogToLcd($"\nDrone received unrecognized callback: {callback}"); break; } }
public void ControlDoors(IMyProgrammableBlock owner) { if (_InsideDoorTicks != -1) { --_InsideDoorTicks; } if (_OutsideDoorTicks != -1) { --_OutsideDoorTicks; } if (_InsideDoorTicks == 0) { _InsideDoor.CloseDoor(); _InsideDoorTicks = -1; _DoorNeedsClosing = false; } if (_OutsideDoorTicks == 0) { _OutsideDoor.CloseDoor(); _OutsideDoorTicks = -1; _DoorNeedsClosing = false; } int storedOxygenPercentage = Int32.Parse(owner.CustomData); if (_InsideDoor.Status == DoorStatus.Closed && _OutsideDoor.Status == DoorStatus.Closed && (storedOxygenPercentage > 95 || _AirVent.GetOxygenLevel() == 0.0f)) { _InsideDoor.Enabled = true; _OutsideDoor.Enabled = true; _InsideDoorTicks = -1; _OutsideDoorTicks = -1; _DoorNeedsClosing = false; } if (_OutsideDoor.Status == DoorStatus.Open || _OutsideDoor.Status == DoorStatus.Opening) { _InsideDoor.CloseDoor(); _InsideDoor.Enabled = false; if (!_DoorNeedsClosing) { _OutsideDoorTicks = DOOR_DELAY; _DoorNeedsClosing = true; } } if (_InsideDoor.Status == DoorStatus.Open || _InsideDoor.Status == DoorStatus.Opening) { _OutsideDoor.CloseDoor(); _OutsideDoor.Enabled = false; if (!_DoorNeedsClosing) { _InsideDoorTicks = DOOR_DELAY; _DoorNeedsClosing = true; } } }
public AutoDoorProgram(IMyGridTerminalSystem grid, IMyProgrammableBlock me, Action<string> echo, TimeSpan elapsedTime) { GridTerminalSystem = grid; Echo = echo; ElapsedTime = elapsedTime; Me = me; doors = new List<IMyDoor>(); sensors = new List<IMySensorBlock>(); List<IMyTerminalBlock> blocks = new List<IMyTerminalBlock>(); grid.SearchBlocksOfName(PREFIX, blocks); // Add some error handling for blocks not found for (int i = 0; i < blocks.Count; i++) { IMyTerminalBlock block = blocks[i]; String blockType = block.DefinitionDisplayNameText; String blockName = block.CustomName; //Echo("Processing block " + blockName); if (blockType.Equals("Sensor")) { IMySensorBlock sensor = block as IMySensorBlock; sensor.ApplyAction("OnOff_On"); List<ITerminalProperty> properties = new List<ITerminalProperty>(); sensor.GetProperties(properties); sensor.SetValueFloat("Back", SensorBack); sensor.SetValueFloat("Bottom", SensorBottom); sensor.SetValueFloat("Top", SensorTop); sensor.SetValueFloat("Left", SensorLeft); sensor.SetValueFloat("Right", SensorRight); sensor.SetValueFloat("Front", SensorFront); sensor.SetValueBool("Detect Asteroids", false); sensor.SetValueBool("Detect Enemy", false); sensor.SetValueBool("Detect Floating Objects", false); sensor.SetValueBool("Detect Friendly", true); sensor.SetValueBool("Detect Large Ships", false); sensor.SetValueBool("Detect Neutral", false); sensor.SetValueBool("Detect Owner", true); sensor.SetValueBool("Detect Players", true); sensor.SetValueBool("Detect Small Ships", false); sensor.SetValueBool("Detect Stations", false); sensor.SetValueBool("Audible Proximity Alert", false); sensors.Add(sensor); } else if (blockType.Equals("Sliding Door") || blockType.Equals("Door")) { IMyDoor door = block as IMyDoor; door.ApplyAction("Open_Off"); doors.Add(door); } else if (blockType.Equals("Rotor") || blockType.Equals("Advanced Rotor")) { rotor = block as IMyMotorStator; rotor.ApplyAction("OnOff_On"); rotor.SetValueFloat("Torque", 3.36E+07f); rotor.SetValueFloat("BrakingTorque", 3.36E+07f); rotor.SetValueFloat("Velocity", rotorSpeed); rotor.SetValueFloat("UpperLimit", float.PositiveInfinity); rotor.SetValueFloat("LowerLimit", float.NegativeInfinity); // Add config here } } }
void _FindMyseLF() { List<IMyTerminalBlock> _blocks = new List<IMyTerminalBlock>(); GridTerminalSystem.GetBlocksOfType<IMyProgrammableBlock>(_blocks); for (int i = 0; i < _blocks.Count; i++) { if (_blocks[i].CustomName.Contains(SIOS_PROGRAMBLOCK_ID)) { core = (IMyProgrammableBlock)_blocks[i]; Debug("Found myseLF - Generating awareness - I know who I am. I am!"); } } }
public AutoHoverController(IMyGridTerminalSystem gts, IMyProgrammableBlock pb) { Me = pb; GridTerminalSystem = gts; remote = GridTerminalSystem.GetBlockWithName(RemoteControlName) as IMyRemoteControl; gyro = GridTerminalSystem.GetBlockWithName(GyroName) as IMyGyro; if (!String.IsNullOrEmpty(TextPanelName)) screen = GridTerminalSystem.GetBlockWithName(TextPanelName) as IMyTextPanel; var list = new List<IMyTerminalBlock>(); GridTerminalSystem.GetBlocksOfType<IMyGyro>(list, x => x.CubeGrid == Me.CubeGrid && x != gyro); gyros = list.ConvertAll(x => (IMyGyro)x); gyros.Insert(0, gyro); gyros = gyros.GetRange(0, GyroCount); mode = "Hover"; setSpeed = 0; }
void GetBlocks() { List<IMyTerminalBlock> _blocks = new List<IMyTerminalBlock>(); LIGHT_CONFIGURATION = new Dictionary<IMyInteriorLight, Color>(); GridTerminalSystem.GetBlocksOfType<IMyTerminalBlock>(_blocks); for (int i = 0; i < _blocks.Count; i++) { if (_blocks[i].CustomName.Contains(platformID)) { ///////////////////// GETTING ASSEMBLERS ///////////////////// if (_blocks[i].CustomName.Contains(ASSEMBLER_ID)) { IMyAssembler _assembler = (IMyAssembler)_blocks[i]; assemblers.Add(_assembler); storage.Add(_assembler.GetInventory(0)); production.Add(_assembler.GetInventory(1)); } ////////////////////// GETTING REFINERIES ////////////////////// if (_blocks[i].CustomName.Contains(REFINERY_ID)) { IMyRefinery _refinery = (IMyRefinery)_blocks[i]; refineries.Add(_refinery); storage.Add(_refinery.GetInventory(0)); production.Add(_refinery.GetInventory(1)); } ////////////////// GETTING CONVEYOR SORTERS ///////////////// if (_blocks[i].CustomName.Contains(SORTER_ID)) sorters.Add((IMyConveyorSorter)_blocks[i]); /////////////////////// GETTING BATTERIES ////////////////////// if (_blocks[i].CustomName.Contains(BATTERY_ID)) batteries.Add((IMyBatteryBlock)_blocks[i]); /////////////////////// GETTING REACTORS ////////////////////// if (_blocks[i].CustomName.Contains(REACTOR_ID)) { IMyReactor _reactor = (IMyReactor)_blocks[i]; reactors.Add(_reactor); storage.Add(_reactor.GetInventory(0)); } /////////////////////// GETTING OXYGENS ////////////////////// if (_blocks[i].CustomName.Contains(OXYGEN_ID)) { IMyOxygenGenerator _oxygen = (IMyOxygenGenerator)_blocks[i]; oxygens.Add(_oxygen); } ////////////////////// GETTING OXYTANKS ////////////////////// if (_blocks[i].CustomName.Contains(OXY_TANK_ID)) { IMyOxygenTank _oxytank = (IMyOxygenTank)_blocks[i]; oxytanks.Add(_oxytank); } /////////////////////// GETTING AIRVENTS ////////////////////// if (_blocks[i].CustomName.Contains(AIR_VENT_ID)) { IMyAirVent _vent = (IMyAirVent)_blocks[i]; airvents.Add(_vent); } ///////////////////// GETTING INVENTORIES ///////////////////// if (_blocks[i].CustomName.Contains(STORAGE_ID)) storage.Add(((IMyInventoryOwner)_blocks[i]).GetInventory(0)); /////////////////// GETTING INTERIOR LIGHTS //////////////////// if (_blocks[i].CustomName.Contains(LIGHT_ID)) { lights.Add((IMyInteriorLight)_blocks[i]); Color _color = ((IMyInteriorLight)_blocks[i]).GetValue<Color>("Color"); LIGHT_CONFIGURATION.Add((IMyInteriorLight)_blocks[i], _color); } /////////////////// GETTING SOUND BLOCKS //////////////////// if (_blocks[i].CustomName.Contains(SPEAKER_ID)) speakers.Add((IMySoundBlock)_blocks[i]); /////////////////////// GETTING DOORS ////////////////////////// if (_blocks[i].CustomName.Contains(DOOR_ID)) doors.Add((IMyDoor)_blocks[i]); ///////////////////// GETTING SENSORS ////////////////////////// if (_blocks[i].CustomName.Contains(SENSOR_ID)) sensors.Add((IMySensorBlock)_blocks[i]); ///////////////////// GETTING TERMINALS /////////////////////// if (_blocks[i].CustomName.Contains(TERMINAL_ID)) terminals.Add(_blocks[i]); ///////////////////// GETTING TEXT PANELS ///////////////////// if (_blocks[i].CustomName.Contains(PANEL_ID)) { IMyTextPanel _panel = (IMyTextPanel)_blocks[i]; if (_panel.GetPublicTitle().Contains(SIOS_DEBUG_SCREEN_ID)) { //debugger.Add(_panel); //DEBUG_ENABLED = true; } else { if (!_panel.CustomName.Contains(SIOS_CONFIG_SCREEN_ID) && _panel.GetPublicTitle() == INFO_ID) { // _panel.ShowPublicTextOnScreen(); // _panel.SetValue("FontSize", 0.8f); // panels.Add(_panel); } } } ////////////////////// GETTING PROGRAMS ////////////////////// if (_blocks[i].CustomName.Contains(PROGRAM_ID)) { IMyProgrammableBlock _program = (IMyProgrammableBlock)_blocks[i]; if (_program.CustomName.Contains(SIOS_PROGRAMBLOCK_ID)) core = _program; else if (_program.CustomName.Contains(SIOS_ADDON_EDI_ID)) EDI = _program; else if (_program.CustomName.Contains(TRADER_ID)) traders.Add(_program); else programs.Add(_program); } ///////////////////// GETTING TIMERBLOCKS //////////////////// if (_blocks[i].CustomName.Contains(TIMER_ID)) { if (_blocks[i].CustomName.Contains(UPDATE_ID)) { IMyTimerBlock _update = (IMyTimerBlock)_blocks[i]; _update.GetActionWithName("Start").Apply(_update); } else timers.Add((IMyTimerBlock)_blocks[i]); } /////////////////// GETTING GATLING TURRETS ///////////////// if (_blocks[i].CustomName.Contains(GATTLING_TURRET_ID)) { gatlings.Add((IMyLargeGatlingTurret)_blocks[i]); } if (_blocks[i].CustomName.Contains(MISSILE_TURRET_ID)) { missiles.Add((IMyLargeMissileTurret)_blocks[i]); } if (_blocks[i].CustomName.Contains(TURRET_ID)) { turrets.Add((IMyLargeInteriorTurret)_blocks[i]); } } } Debug("Found: " + lights.Count + " lights"); BOOTED = true; }
public Example(IMyGridTerminalSystem grid, IMyProgrammableBlock me, Action <string> echo, TimeSpan elapsedTime) : base(grid, me, echo, elapsedTime) { // Start your code here }
public HangarController(IMyGridTerminalSystem grid, IMyProgrammableBlock me, Action<string> echo, TimeSpan elapsedTime) { GridTerminalSystem = grid; Echo = echo; ElapsedTime = elapsedTime; Me = me; hangarDoors = new List<IMyDoor>[groups.Count]; interiorDoors = new List<IMyDoor>[groups.Count]; exteriorDoors = new List<IMyDoor>[groups.Count]; soundBlocks = new List<IMySoundBlock>[groups.Count]; warningLights = new List<IMyInteriorLight>[groups.Count]; airVents = new List<IMyAirVent>[groups.Count]; hangarOpen = new Boolean[groups.Count]; // Get list of groups on this station/ship List<IMyBlockGroup> BlockGroups = new List<IMyBlockGroup>(); GridTerminalSystem.GetBlockGroups(BlockGroups); // Search all groups that exist for the groups with name as specified in groups list for (int i = 0; i < BlockGroups.Count; i++) { int pos = groups.IndexOf(BlockGroups[i].Name); // If name is one of our candidates... if (pos != -1) { List<IMyTerminalBlock> blocks = BlockGroups[i].Blocks; // Define list of blocks for each group List<IMyDoor> hangarDoorList = new List<IMyDoor>(); List<IMyDoor> interiorDoorList = new List<IMyDoor>(); List<IMyDoor> exteriorDoorList = new List<IMyDoor>(); List<IMySoundBlock> soundBlockList = new List<IMySoundBlock>(); List<IMyInteriorLight> warningLightList = new List<IMyInteriorLight>(); List<IMyAirVent> airVentList = new List<IMyAirVent>(); // Go through all blocks and add to appropriate list // Also initialize to a sane known state e.g. closed, on... for (int j = 0; j < blocks.Count; j++) { IMyTerminalBlock block = blocks[j]; String blockType = block.DefinitionDisplayNameText; String blockName = block.CustomName; block.ApplyAction("OnOff_On"); if (blockType.Equals("Airtight Hangar Door")) { IMyDoor item = block as IMyDoor; item.ApplyAction("Open_Off"); hangarDoorList.Add(item); } else if ((blockType.Equals("Sliding Door") || blockType.Equals("Door")) && blockName.Contains("Interior")) { IMyDoor item = block as IMyDoor; item.ApplyAction("Open_Off"); interiorDoorList.Add(item); } else if ((blockType.Equals("Sliding Door") || blockType.Equals("Door")) && blockName.Contains("Exterior")) { IMyDoor item = block as IMyDoor; item.ApplyAction("Open_Off"); exteriorDoorList.Add(item); } else if (blockType.Equals("Sound Block")) { IMySoundBlock item = block as IMySoundBlock; item.ApplyAction("StopSound"); item.SetValueFloat("LoopableSlider", 10); soundBlockList.Add(item); } else if (blockType.Equals("Interior Light")) { IMyInteriorLight item = block as IMyInteriorLight; item.ApplyAction("OnOff_Off"); item.SetValueFloat("Blink Interval", 1); item.SetValueFloat("Blink Lenght", 50); item.SetValueFloat("Blink Offset", 0); item.SetValue<Color>("Color", Color.Red); warningLightList.Add(item); } else if (blockType.Contains("Air Vent")) { IMyAirVent item = block as IMyAirVent; item.ApplyAction("Depressurize_Off"); airVentList.Add(item); } } // Some cleanup hangarDoorList.TrimExcess(); interiorDoorList.TrimExcess(); exteriorDoorList.TrimExcess(); soundBlockList.TrimExcess(); warningLightList.TrimExcess(); airVentList.TrimExcess(); if (hangarDoorList.Count == 0) { Echo("Warning: no hangar doors detected for " + BlockGroups[i].Name); } else if (interiorDoorList.Count == 0) { Echo("Warning: no interior doors detected for " + BlockGroups[i].Name); } else if (soundBlockList.Count == 0) { Echo("Warning: no sound blocks detected for " + BlockGroups[i].Name); } else if (warningLightList.Count == 0) { Echo("Warning: no warning lights detected for " + BlockGroups[i].Name); } else if (airVentList.Count == 0) { Echo("Warning: no air vents detected for " + BlockGroups[i].Name); } // Now that we have populated lists add them to the correct position in the group list hangarDoors[pos] = hangarDoorList; interiorDoors[pos] = interiorDoorList; exteriorDoors[pos] = exteriorDoorList; soundBlocks[pos] = soundBlockList; warningLights[pos] = warningLightList; airVents[pos] = airVentList; hangarOpen[pos] = false; // Exterior doors have been requested to close so we set a check to lock them when they are in fact closed requests.Add(new requestTicket(pos, "lockExteriorDoors")); } } }