Beispiel #1
0
 public Program()
 {
     allblocks = new List <IMyTerminalBlock>();
     GridTerminalSystem.GetBlocks(allblocks);
 }
        public Program()
        {
            // ======== ======== ======== ======== ======== ======== ======== ========
            // SETUP
            // ======== ======== ======== ======== ======== ======== ======== ========
            // Batteries to observe (group name, single block, or "" for all):
            string Batteries = "";

            // Name of a cockpit, or "" to use the first one found:
            string Cockpit = "Cockpit";

            // Display number to use (0 for center panel):
            int DisplayNum = 0;

            // Display text:
            string Format =
                "MWh:\n" +
                "{0:0.00} of {1:0.00}\n" +
                "Charge:\n" +
                "{2:0.0}%\n";

            // ======== ======== ======== ======== ======== ======== ======== ========
            // END OF SETUP
            // ======== ======== ======== ======== ======== ======== ======== ========

            try {
                sFormat = Format;

                gBattery = new Battery(this, Batteries);

                if (Cockpit == string.Empty)
                {
                    List <IMyCockpit> block_list = new List <IMyCockpit>();

                    GridTerminalSystem.GetBlocksOfType(block_list, x => x.IsSameConstructAs(Me));

                    if (block_list.Count > 0)
                    {
                        gCockpit = block_list[0];
                    }
                    else
                    {
                        throw new Exception("No cockpit found.");
                    }
                }
                else if ((gCockpit = GridTerminalSystem.GetBlockWithName(Cockpit) as IMyCockpit) == null || !gCockpit.IsSameConstructAs(Me))
                {
                    throw new Exception($"No blocks found with argument: '{Cockpit}'");
                }

                if (DisplayNum >= 0 && DisplayNum < gCockpit.SurfaceCount)
                {
                    gSurface             = gCockpit.GetSurface(DisplayNum);
                    gSurface.ContentType = ContentType.TEXT_AND_IMAGE;
                }
                else
                {
                    throw new Exception($"Variable 'DisplayNum' is out of range: 0 - {gCockpit.SurfaceCount - 1}");
                }

                Runtime.UpdateFrequency = UpdateFrequency.Update100;
            }
            catch (Exception e) {
                Echo(e.Message);

                if (gBattery != null)
                {
                    Echo(string.Format(sFormat, gBattery.CurrentPower, gBattery.MaxPower, gBattery.Percentage));
                }
            }
        }
Beispiel #3
0
        public Program()
        {
            // fill pistons dictionary
            {
                string[] strPistonNames = new string[9];
                strPistonNames[0] = "Piston_top_down";
                strPistonNames[1] = "Piston_top_up";
                strPistonNames[2] = "Piston_module_creation_top_1";
                strPistonNames[3] = "Piston_module_creation_top_2";
                strPistonNames[4] = "Piston_module_grabber_side";
                strPistonNames[5] = "Piston_module_grabber_front";
                strPistonNames[6] = "Piston_module_grabber_back";
                strPistonNames[7] = "Piston_holder_front";
                strPistonNames[8] = "Piston_holder_back";

                for (int i = 0; i < strPistonNames.Length; i++)
                {
                    if ((GridTerminalSystem.GetBlockWithName(strPistonNames[i]) as IMyPistonBase) == null)
                    {
                        throw new Exception("Error - Piston with name: " + strPistonNames[i] + " does not exist!");
                    }
                    Pistons.Add(strPistonNames[i], new Piston(strPistonNames[i], this));
                }
            }

            // fill merge blocks dictionary
            {
                string[] strMergeBlocks = new string[5];
                strMergeBlocks[0] = "Merge_module_creation";
                strMergeBlocks[1] = "Merge_module_grabber_front";
                strMergeBlocks[2] = "Merge_module_grabber_back";
                strMergeBlocks[3] = "Merge_holder_front";
                strMergeBlocks[4] = "Merge_holder_back";

                for (int i = 0; i < strMergeBlocks.Length; i++)
                {
                    if ((GridTerminalSystem.GetBlockWithName(strMergeBlocks[i]) as IMyShipMergeBlock) == null)
                    {
                        throw new Exception("Error - Merge Block with name: " + strMergeBlocks[i] + " does not exist!");
                    }
                    MergeBlocks.Add(strMergeBlocks[i], new MergeBlock(strMergeBlocks[i], this));
                }
            }

            // fill drills list
            GridTerminalSystem.GetBlocksOfType <IMyShipDrill>(Drills);
            if (Drills.Count == 0)
            {
                throw new Exception("No attached drills detected");
            }

            // initialize connectors
            {
                string connectorTopName = "Connector_base";
                connectorDrillTop = new Connector(connectorTopName, this);
                if (!connectorDrillTop.isValid)
                {
                    throw new Exception("Connector with the name " + connectorTopName + " does not exist");
                }

                // drill connector only needed for first module
                // after first module this connector should be replaced with the top connector
                // of the last added module - see StateMachine.StatePrepareForNewModule.Perform()
                string connectorBottomName = "Connector_drill";
                connectorDrillBottom = new Connector(connectorBottomName, this);
                if (!connectorDrillBottom.isValid)
                {
                    throw new Exception("Connector with the name " + connectorBottomName + " does not exist");
                }
            }

            // initialize welder
            {
                Welder = GridTerminalSystem.GetBlockWithName("Welder_module_creation") as IMyShipWelder;
                if (Welder == null)
                {
                    throw new Exception("Welder with the name Welder_module_creation does not exist");
                }
            }

            // initialize Rotor
            {
                string rotorName = "Rotor_drills";
                Rotor = GridTerminalSystem.GetBlockWithName(rotorName) as IMyMotorStator;
                if (Rotor == null)
                {
                    Echo("Rotor with the name " + rotorName + " not found");
                }
            }

            // initialize states
            drillState       = new States.DrillState();
            moduleBuildState = new States.ModuleBuildState();

            // initialize state machine
            stateMachine = new StateMachine(this);


            // load data
            if (!Load())
            {
                Echo("could not load saved data - set state to default values");
                // first start of script
                drillState.State       = States.eDrillState.eInvalidMax;
                moduleBuildState.State = States.eModuleBuildState.eInvalidMax;
                connectorDrillBottom   = new Connector("Connector_drill", this);
            }
        }
        public void Main(string input)
        {
            lcds = SearchBlocksWithName <IMyTextPanel>(lcdSearchName);
            ClearOutput();

            if (input == "start")
            {
                Runtime.UpdateFrequency = UpdateFrequency.Update10;
                Autopilot = true;
            }

            IMyShipController controlBlock = (IMyShipController)GridTerminalSystem.GetBlockWithName(ShipControllerName);

            double altitude             = 0;
            bool   InsideNaturalGravity = controlBlock.TryGetPlanetElevation(MyPlanetElevation.Surface, out altitude);

            Vector3D velocity3D = controlBlock.GetShipVelocities().LinearVelocity;

            if (!InsideNaturalGravity)
            {
                if (Autopilot)
                {
                    WriteLine("Waiting for entering natural gravity");
                    if (input == "stop")
                    {
                        Autopilot = false;
                        WriteLine("Autopilot deactivated (manually)");
                    }
                }
                return;
            }
            else
            {
                if (Autopilot && AutoFall)
                {
                    if (!AutoFallUsed)
                    {
                        input        = "fall";
                        AutoFallUsed = true;
                    }
                }
            }

            List <IMyThrust> thrusters        = GetBlocksInGroup <IMyThrust>(HydrogenThrustersGroupName);
            ThrustController thrustController = new ThrustController(thrusters);

            gyros          = GetBlocksOfType <IMyGyro>();
            gyroController = new GyroController(controlBlock, gyros, Base6Directions.Direction.Down, RotationSpeedLimit);

            Vector3D gravity         = controlBlock.GetNaturalGravity();
            Vector3D position        = controlBlock.GetPosition();                   // ship coords
            double   gravityStrength = gravity.Length();                             // gravity in m/s^2
            double   totalMass       = controlBlock.CalculateShipMass().TotalMass;   // ship total mass including cargo mass
            double   baseMass        = controlBlock.CalculateShipMass().BaseMass;    // mass of the ship without cargo
            double   cargoMass       = totalMass - baseMass;                         // mass of the cargo
            double   actualMass      = baseMass + (cargoMass / InventoryMultiplier); // the mass the game uses for physics calculation
            double   shipWeight      = actualMass * gravityStrength;                 // weight in newtons of the ship
            double   velocity        = controlBlock.GetShipSpeed();                  // ship velocity
            double   brakeDistance   = CalculateBrakeDistance(gravityStrength, actualMass, altitude, thrustController.availableThrust, velocity);
            double   brakeAltitude   = StopAltitude + brakeDistance;                 // at this altitude the ship will start slowing Down

            if (Autopilot)
            {
                gyroController.Align(gravity);

                if (input == "fall")
                {
                    // This is a workaround to a game bug (ship speed greater than speed limit when free falling in natural gravity)
                    // Pros: your ship will not crash. Cons: you will waste a tiny amount of hydrogen.
                    thrustController.ApplyThrust(1);
                }

                if (altitude <= (brakeAltitude + AltitudeMargin))
                {
                    // BRAKE!!!
                    thrustController.ApplyFullThrust(); // Maybe just enable dampeners
                }

                if (altitude <= (StopAltitude + DisableMargin + AltitudeMargin))
                {
                    if (velocity < StopSpeed)
                    {
                        gyroController.Stop();
                        WriteLine("Autopilot deactivated (automatically)");
                    }

                    if (SmartDeactivation)
                    {
                        if (OldVelocity3D.X * velocity3D.X < 0 || OldVelocity3D.Y * velocity3D.Y < 0 || OldVelocity3D.Z * velocity3D.Z < 0)
                        {
                            gyroController.Stop();
                            WriteLine("Autopilot deactivated (automatically)");
                        }
                    }
                }
            }

            OldVelocity3D = velocity3D;

            if (input == "stop")
            {
                Runtime.UpdateFrequency = UpdateFrequency.None;
                gyroController.Stop();
                thrustController.Stop();
                WriteLine("Autopilot deactivated (manually)");
            }
        }
Beispiel #5
0
        private void UpdateOreStatus(IMyTextSurface surface)
        {
            List <IMyTerminalBlock> blocks = new List <IMyTerminalBlock>();

            GridTerminalSystem.GetBlocks(blocks);

            OreStats stats = new OreStats();

            stats.iron = 0;

            foreach (var block in blocks)
            {
                if (block.HasInventory)
                {
                    for (int inv = 0; inv < block.InventoryCount; ++inv)
                    {
                        List <MyInventoryItem> items = new List <MyInventoryItem>();
                        block.GetInventory(inv).GetItems(items);
                        foreach (var item in items)
                        {
                            if (item.Type.TypeId == "MyObjectBuilder_Ingot")
                            {
                                switch (item.Type.SubtypeId)
                                {
                                case "Iron":
                                    stats.iron += item.Amount.RawValue;
                                    break;

                                case "Nickel":
                                    stats.nickel += item.Amount.RawValue;
                                    break;

                                case "Cobalt":
                                    stats.cobalt += item.Amount.RawValue;
                                    break;

                                case "Magnesium":
                                    stats.magnesium += item.Amount.RawValue;
                                    break;

                                case "Silicon":
                                    stats.silicon += item.Amount.RawValue;
                                    break;

                                case "Silver":
                                    stats.silver += item.Amount.RawValue;
                                    break;

                                case "Gold":
                                    stats.gold += item.Amount.RawValue;
                                    break;

                                case "Platinum":
                                    stats.platinum += item.Amount.RawValue;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            surface.WriteText(String.Format(
                                  "- Ingots\nIron {0}\nNickel {1}\nCrobale {2}\nMagnesium {3}\nSilicon {4}\nSilver {5}\nGold {6}\nPlatinum {7}",
                                  OreStats.Repr(stats.iron),
                                  OreStats.Repr(stats.nickel),
                                  OreStats.Repr(stats.cobalt),
                                  OreStats.Repr(stats.magnesium),
                                  OreStats.Repr(stats.silicon),
                                  OreStats.Repr(stats.silver),
                                  OreStats.Repr(stats.gold),
                                  OreStats.Repr(stats.platinum)
                                  ));
        }
Beispiel #6
0
        public IEnumerator <bool> ProgramInit()
        {
            #region serializer
            nameSerializer = new INISerializer("HaE MissileBase");
            nameSerializer.AddValue("missileTag", x => x, "[HaE Missile]");
            nameSerializer.AddValue("siloDoorTag", x => x, "[HaE SiloDoor]");
            nameSerializer.AddValue("missileStatusLCDTag", x => x, "[HaE MissileStatus]");
            nameSerializer.AddValue("targetingCameraName", x => x, "TargetingCamera");
            nameSerializer.AddValue("controllername", x => x, "controller");
            nameSerializer.AddValue("IgnoreTag", x => x, "[IgnoreTracker]");
            nameSerializer.AddValue("targetingCastLength", x => double.Parse(x), 3000);

            if (Me.CustomData == "")
            {
                string temp = Me.CustomData;
                nameSerializer.FirstSerialization(ref temp);
                Me.CustomData = temp;
            }
            else
            {
                nameSerializer.DeSerialize(Me.CustomData);
            }

            yield return(true);

            #endregion

            #region fetchblocks
            GridTerminalSystemUtils GTS = new GridTerminalSystemUtils(Me, GridTerminalSystem);
            missiles = new MissileManager(GTS, this, missileTag);
            yield return(true);

            var antennas = new List <IMyRadioAntenna>();
            GTS.GetBlocksOfTypeOnGrid(antennas);
            yield return(true);

            var camera     = GridTerminalSystem.GetBlockWithName(targetingCameraName) as IMyCameraBlock;
            var controller = GridTerminalSystem.GetBlockWithName(controllername) as IMyShipController;
            yield return(true);

            #endregion

            #region initModules
            if (antennas.Count > 0)
            {
                commsHandler = new CommsHandler(this, antennas.First());
            }
            else
            {
                commsHandler = new CommsHandler(this, null);
            }

            var commands = new Commands(this, commsHandler);
            commands.RegisterCommands();

            silos = new MissileSilos(GTS, this, siloDoorTag);
            yield return(true);

            if (camera != null && controller != null)
            {
                entityTrackingModule = new EntityTracking_Module(GTS, controller, camera, IgnoreTag);

                ITracking cameraTracker = null;
                foreach (ITracking tracker in entityTrackingModule.ObjectTrackers)
                {
                    var camT = tracker as LidarTracking;
                    if (camT != null)
                    {
                        cameraTracker = camT;
                    }
                }
                entityTrackingModule.ObjectTrackers.Clear();
                entityTrackingModule.ObjectTrackers.Add(cameraTracker);

                entityTrackingModule.onEntityDetected += OnEntityDetected;
            }
            else
            {
                Echo($"camera: {camera != null}\ncontroller: {controller != null}");
            }

            yield return(true);

            var lcds = new List <IMyTextPanel>();
            GridTerminalSystem.GetBlocksOfType(lcds, x => x.CustomName.Contains(missileStatusLCDTag));
            statusWriter = new StatusWriter(this, lcds);
            #endregion

            initialized = true;
        }
Beispiel #7
0
 public IMyEntity GetBlock(String name)
 {
     return(GridTerminalSystem.GetBlockWithName(name));
 }
Beispiel #8
0
        void doTechnikerCalcsandDisplay()
        {
            double stoppingDistance = calculateStoppingDistance(thrustBackwardList, velocityShip, 0);

            StringBuilder sb          = new StringBuilder();
            double        targetRange = 0; // no target

            //    StatusLog("clear", textPanelReport);
            StatusLog(OurName + " Control", textPanelReport);

            string output = "";

            output += "Velocity: " + velocityShip.ToString("N0") + "m/s";

            Echo(output);
            StatusLog(output, textPanelReport);

            if (bCreative)
            {
                Echo("Creative!");
            }
            //           Echo("Cargomult=" + cargoMult);

            sb.Clear();
            sb.AppendLine();


            if (bLongRange)
            {
                sb.Append("Long Range Scan Active");
            }
            else
            {
                sb.Append("Normal Range Scan Active");
            }
            sb.AppendLine();

            string s = "";

            if (lastDetectedInfo.IsEmpty())
            {
                sb.Append("No Target Found");
                sb.AppendLine();

                sb.Append("Next scanner Range: " + currentScan.ToString("N0") + " m");
                sb.AppendLine();

                StatusLog("clear", textRangeReport);
                StatusLog("No Target found", textRangeReport);
            }
            else
            {
                Echo("EntityID: " + lastDetectedInfo.EntityId);
                Echo("Name: " + lastDetectedInfo.Name);
                sb.Append("Name: " + lastDetectedInfo.Name);
                //sb.AppendLine();
                sb.Append(" - ");
                sb.Append("Type: " + lastDetectedInfo.Type);
                sb.AppendLine();
                sb.Append("Relationship: " + lastDetectedInfo.Relationship);
                if (lastDetectedInfo.HitPosition.HasValue && lastCamera != null)
                {
                    sb.AppendLine();
                    double distance = Vector3D.Distance(lastCamera.GetPosition(), lastDetectedInfo.HitPosition.Value);
                    if (lastDetectedInfo.Name == "Asteroid")
                    {
                        // calculate range to outter edge of boudning box of asteroid.
                        targetRange  = Vector3D.Distance(lastCamera.GetPosition(), lastDetectedInfo.Position);
                        targetRange -= lastDetectedInfo.BoundingBox.Size.X / 2; // half of bounding box.
                        Echo("adjTargetRange=" + targetRange.ToString("0.0"));
                    }
                    else
                    {
                        targetRange = distance;
                    }

                    if (distance > 1000)
                    {
                        s += (distance / 1000).ToString("RANGE:   0000.0km");
                    }
                    else
                    {
                        s += (distance).ToString("RANGE:     00000m ");
                    }


                    StatusLog("clear", textRangeReport);
                    StatusLog(s, textRangeReport);

                    sb.Append("Distance: " + niceDoubleMeters(distance));
                    sb.AppendLine();

                    sb.Append("Safe Range: " + niceDoubleMeters(targetRange));
                    sb.AppendLine();
                }
                //		sb.AppendLine();
                //		sb.Append("TimeStamp: " + lastDetectedInfo.TimeStamp.ToString());
            }
            s = "";
            if (stoppingDistance > 1000)
            {
                s += (stoppingDistance / 1000).ToString("STOP DIST: 000.0km");
            }
            else
            {
                s += (stoppingDistance).ToString("STOP DIST: 00000m ");
            }
            StatusLog(s, textRangeReport);

            double maxRange = findMaxCameraRange(cameraForwardList);

            if (maxRange < currentScan)
            {
                sb.AppendLine();
                sb.Append("Awaiting Available Range");
                sb.AppendLine();

                sb.Append(progressBar(maxRange / currentScan * 100));
                sb.AppendLine();
            }

            sb.AppendLine();
            sb.Append(detectedEntities.Count.ToString() + " detected items");


            if (dGravity > 0)
            {
                StatusLog("GRAVITY WELL", textPanelReport);
            }

            if (AnyConnectorIsConnected())
            {
                StatusLog("Docked!", textPanelReport);
            }
            else
            {
                StatusLog(doEStopCheck(targetRange, stoppingDistance), textPanelReport);
            }

            // rotor status code for Techniker
            output = "";
            IMyMotorStator drillrotor;

            drillrotor = (IMyMotorStator)GridTerminalSystem.GetBlockWithName("Advanced Rotor L Drills");

            if (drillrotor != null)
            {
                output += "\nDrill Arm -";
                double angle = MathHelper.ToDegrees(drillrotor.Angle);
                if (angle > 178)
                {
                    output += " Stowed";
                }
                else if (angle < 1)
                {
                    output += " Deployed";
                }
                else
                {
                    output += " Moving";
                }

                /*
                 * if (drillrotor.SafetyLock)
                 *  output += " - (Locked)";
                 * else
                 *  output += " - Unlocked";
                 */
            }

            IMyMotorStator toolrotor;

            toolrotor = (IMyMotorStator)GridTerminalSystem.GetBlockWithName("Advanced Rotor R Tools");
            if (toolrotor != null)
            {
                output += "\nTool Arm -";
                double angle = MathHelper.ToDegrees(toolrotor.Angle);
                if (angle > 178)
                {
                    output += " Deployed";
                }
                else if (angle < 1)
                {
                    output += " Stowed";
                }
                else
                {
                    output += " Moving";
                }

                /*
                 * if (toolrotor.SafetyLock)
                 *  output += " - (Locked)";
                 * else
                 *  output += " - Unlocked";
                 */
            }
            //	output = "Drill rotor=" + angle.ToString("0.0");

            if (output != "")
            {
                Echo(output);
                StatusLog(output, textPanelReport);
            }

            // output main status.
            StatusLog(sb.ToString(), textPanelReport);
            //	Echo(sb.ToString());

            sb.Clear();
        }
Beispiel #9
0
        public void Main(string argument)
        {
            // Calculate Power Storage
            List <IMyBatteryBlock> batteries = new List <IMyBatteryBlock>();

            GridTerminalSystem.GetBlocksOfType(batteries);
            float maxVal = 0;
            float val    = 0;

            foreach (IMyBatteryBlock battery in batteries)
            {
                maxVal += battery.MaxStoredPower;
                val    += battery.CurrentStoredPower;
            }
            // p = A * 100 / G
            float pBatteries = val * 100 / maxVal;

            // Calculate Hydrogen Storage
            List <IMyGasTank> gasTanks = new List <IMyGasTank>();

            GridTerminalSystem.GetBlocksOfType(gasTanks);
            maxVal = 0;
            val    = 0;
            foreach (IMyGasTank tank in gasTanks)
            {
                if (tank.BlockDefinition.SubtypeId.ToLower().Contains("hydrogentank"))
                {
                    maxVal += tank.Capacity;
                    val    += tank.FilledRatio * tank.Capacity;
                }
            }
            // p = A * 100 / G
            float pHydrogen = val * 100 / maxVal;

            // Calculate Storage Capacity
            List <IMyCargoContainer> cargoContainers = new List <IMyCargoContainer>();

            GridTerminalSystem.GetBlocksOfType(cargoContainers);
            MyFixedPoint cargoMaxVal = 0;
            MyFixedPoint cargoVal    = 0;

            foreach (IMyCargoContainer cargoContainer in cargoContainers)
            {
                cargoMaxVal += cargoContainer.GetInventory().MaxVolume;
                cargoVal    += cargoContainer.GetInventory().CurrentVolume;
            }
            // p = A * 100 / G
            float pCargo = cargoVal.RawValue * 100 / cargoMaxVal.RawValue;

            // Build string to show
            string supplyString = "SUPPLY" + '\n'
                                  + "Energy: [";

            for (int i = 0; i < 20; i++)
            {
                if (i < pBatteries / 5)
                {
                    supplyString += '#';
                }
                else
                {
                    supplyString += '-';
                }
            }

            supplyString += "] " + (int)pBatteries + "%" + '\n';

            supplyString += "Hydrogen: [";

            for (int i = 0; i < 20; i++)
            {
                if (i < pHydrogen / 5)
                {
                    supplyString += '#';
                }
                else
                {
                    supplyString += '-';
                }
            }

            supplyString += "] " + (int)pHydrogen + "%" + '\n';

            supplyString += "Cargo: [";

            for (int i = 0; i < 20; i++)
            {
                if (i < pCargo / 5)
                {
                    supplyString += '#';
                }
                else
                {
                    supplyString += '-';
                }
            }

            supplyString += "] " + (int)pCargo + "%" + '\n';
            supplyString += "" + cargoVal + '/' + cargoMaxVal + " L" + '\n';

            List <IMyTextPanel> panels = new List <IMyTextPanel>();

            GridTerminalSystem.GetBlocksOfType(panels);

            foreach (IMyTextPanel panel in panels)
            {
                if (panel.CustomData.ToLower().Equals("supply"))
                {
                    panel.WritePublicText(supplyString);
                }
            }
        }
Beispiel #10
0
        //        void Main(string sArgument)
        void Main(string sArgument, UpdateType ut)
        {
            Echo(sBanner + tick());
            if (bDebugUpdate)
            {
                Echo(ut.ToString() + " : " + (int)ut);
            }
            bWantFast   = false;
            bWantMedium = false;
            //ProfilerGraph();

            if (dProjectorCheckLast > dProjectorCheckWait)
            {
                dProjectorCheckLast = 0;

                bWorkingProjector = false;
                var list = new List <IMyTerminalBlock>();
                GridTerminalSystem.GetBlocksOfType <IMyProjector>(list, localGridFilter);
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].IsWorking)
                    {
                        if (list[i].CustomName.Contains("!WCC") || list[i].CustomData.Contains("!WCC"))
                        {
                            continue;                                                                             // ignore
                        }
                        Echo("Working local Projector found!");
                        //            init = false;
                        //            sInitResults = "";
                        bWorkingProjector = true;
                    }
                }
            }
            else
            {
//                Echo("Delay Projector Check");
                if (dProjectorCheckLast < 0)
                {
                    // first-time init
//                    dProjectorCheckLast = Me.EntityId % dProjectorCheckWait; // randomize initial check
                    dProjectorCheckLast = dProjectorCheckWait + 5; // force check
                }
                dProjectorCheckLast += Runtime.TimeSinceLastRun.TotalSeconds;
            }

            sPassedArgument = "";
            double newgridBaseMass = 0;

            if (shipOrientationBlock is IMyShipController)
            {
                if (dGridCheckLast > dGridCheckWait || !init)
                {
                    //                  Echo("DO Grid Check");
                    dGridCheckLast = 0;

                    MyShipMass myMass;
                    myMass = ((IMyShipController)shipOrientationBlock).CalculateShipMass();

                    newgridBaseMass = myMass.BaseMass;
//                    Echo("New=" + newgridBaseMass + " CurrentM=" + gridBaseMass);
//                    if (myMass.BaseMass == 0)  Echo("No Mass--Station?");
                    if (newgridBaseMass != gridBaseMass && gridBaseMass > 0)
                    {
                        Echo("MASS CHANGE");
                        StatusLog(OurName + ":" + moduleName + ":MASS CHANGE", textLongStatus, true);
                        // check for an error and retry
//                        if (bStartupError && !bWasInit)
                        {
                            // keep trying
                            init                 = false;
                            sInitResults         = "";
                            dErrorGridReInitLast = 0;
                        }
                    }
                }
                else
                {
//                    Echo("Delay Grid Check");
                    if (dGridCheckLast < 0)
                    {
                        // first-time init
                        //                    dGridCheckLast = Me.EntityId % dGridCheckWait; // randomize initial check
                        dGridCheckLast = dGridCheckWait + 5; // force check
                    }
                    dGridCheckLast += Runtime.TimeSinceLastRun.TotalSeconds;
                    newgridBaseMass = gridBaseMass; // assume it's the old mass for now
                }
            }
            else
            {
//                Echo("No anchorPosition to check");
                gridBaseMass = newgridBaseMass = -1;
                // check for an error and retry
                if (bStartupError && !bWasInit)
                {
                    // keep trying
                    init                 = false;
                    sInitResults         = "";
                    dErrorGridReInitLast = 0;
                }
            }
            if (dErrorGridReInitLast > dErrorGridReInitWait)
            {
                dErrorGridReInitLast = 0;
                if (bStartupError)
                {
                    sArgument = "init";
                    Echo("RESCAN!");
                    dErrorGridReInitLast = 0;
                }
            }
            else
            {
                if (bStartupError)
                {
                    Echo("Waiting for Rescan:" + dErrorGridReInitLast.ToString("0.0") + "(" + dErrorGridReInitWait.ToString("0.0") + ")");
                    dErrorGridReInitLast += Runtime.TimeSinceLastRun.TotalSeconds;
                }
            }

            if (
                (sArgument == "init" && currentInit == 0) ||
                (Math.Abs(newgridBaseMass - gridBaseMass) > 1 && gridBaseMass > 0 && currentInit == 0)
                //             || (currentInit == 0 && calcGridSystemChanged())
                )
            {
                Log("INIT or GRID/MASS CHANGE!");

                Echo("Arg init or grid/mass change!");
                sInitResults         = "";
                dErrorGridReInitLast = dErrorGridReInitWait + 5;
                init            = false;
                currentInit     = 0;
                sStartupError   = "";
                sPassedArgument = "init";
            }
            Log("clear");


            if (!init)
            {
                if (bWorkingProjector)
                {
                    Log("Construction in Progress\nTurn off projector to continue");
                    StatusLog("Construction in Progress\nTurn off projector to continue", textPanelReport);
                }
                else
                {
                }
                bWantFast = true;
                if (currentInit == 0)
                {
                    bStartupError = false;
                    sStartupError = "";
                }
                doInit();
                if (bStartupError)
                {
                    bWantFast = false;
                }
                bWasInit = true;
                if (init)
                {
                    sArgument            = "";
                    dErrorGridReInitLast = 0;
                }
            }
            else
            {
                if (bSupportSubModules)
                {
                    Deserialize();
                }
                sPassedArgument = sArgument;

                if (bWasInit)
                {
                    StatusLog(DateTime.Now.ToString() + " " + sInitResults, textLongStatus, true);
                }

                //               IMyTerminalBlock anchorOrientation = shipOrientationBlock;
                if (shipOrientationBlock != null)
                {
//                    vCurrentPos = shipOrientationBlock.GetPosition();
                }

                // calculate(get) ship velocity and natural gravity
                if (shipOrientationBlock is IMyShipController)
                {
                    velocityShip = ((IMyShipController)shipOrientationBlock).GetShipSpeed();

                    Vector3D vNG     = ((IMyShipController)shipOrientationBlock).GetNaturalGravity();
                    double   dLength = vNG.Length();
                    dGravity = dLength / 9.81;
                }
                else
                {
                    dGravity = -1.0;
                }

                if (
                    (ut & (UpdateType.Trigger | UpdateType.Terminal)) > 0 ||
                    (ut & (UpdateType.Trigger)) > 0 || // script run by a mod
                    (ut & (UpdateType.Terminal)) > 0 || // script run by a mod
                    (ut & (UpdateType.Mod)) > 0 || // script run by a mod
                    (ut & (UpdateType.Script)) > 0    // this pb run by another script (PB)
                    )
                {
                    // pay attention to argument
                    if (moduleProcessArguments(sArgument))
                    {
                        Serialize();
                        UpdateAllPanels();
                        return;
                    }
                }
                else if ((ut & (UpdateType.IGC)) > 0)
                {
                    // antenna message
                    if (!moduleProcessAntennaMessage(sArgument))
                    {
                        antReceive(sArgument);
                    }
                    Serialize();
                    doTriggerMain(); // run ourselves again
                    UpdateAllPanels();
                    return;
                }
                else
                {
                    // it should be one of the update types...
                    //            if ((ut & (UpdateType.Once | UpdateType.Update1 | UpdateType.Update10 | UpdateType.Update100)) > 0)
                    sArgument = ""; // else ignore argument

                    /*
                     * // check for an error and retry
                     * if(bStartupError && !bWasInit)
                     * {
                     *  // keep trying
                     *  init = false;
                     *  sInitResults = "";
                     * }
                     */
                }

                /*
                 * if (processArguments(sArgument))
                 * {
                 *  UpdateAllPanels();
                 *  return;
                 * }
                 */
                processPendingReceives();
                processPendingSends();
                moduleDoPreModes();

                doModes();
            }
            if (bSupportSubModules)
            {
                Serialize();
            }

            //            if ((anchorPosition == null || SaveFile == null ))
            if (bSupportSubModules)
            {
                if ((SaveFile == null))
                {
//                    Echo("Cannot use sub-modules; missing controller and/or SaveFile");
                }
                else
                {
                    if (
                        (ut & (UpdateType.Trigger | UpdateType.Terminal)) > 0 || // Timer or toolbar or 'run'
                        (ut & (UpdateType.Mod)) > 0 || // script run by a mod
                        (ut & (UpdateType.Script)) > 0 || // this pb run by another script (PB)
                        dSubmoduleTriggerLast > dSubmoduleTriggerWait
                        // || init // always run after init done
                        || bWasInit // run first time after init
                        )
                    {
//                        Echo("Trigger sub-module!");
                        dSubmoduleTriggerLast = 0;
                        doSubModuleTimerTriggers(sSubModuleTimer);
                    }
                    else
                    {
//                        Echo("Delay for sub-module trigger");
                        dSubmoduleTriggerLast += Runtime.TimeSinceLastRun.TotalSeconds;
                    }
                }
            }
            else
            {
                Echo("Submodules turned off");
            }

            if (bWantFast)
            {
                Echo("FAST!");
                Runtime.UpdateFrequency |= ufFast;
            }
            else
            {
                Runtime.UpdateFrequency &= ~(ufFast);
            }
            if (bWantMedium)
            {
                Echo("MEDIUM");
                Runtime.UpdateFrequency |= UpdateFrequency.Update10;
            }
            else
            {
                Runtime.UpdateFrequency &= ~(UpdateFrequency.Update10);
            }


            if (bCraftOperation)
            {
                Echo(craftOperation());
            }

            modulePostProcessing();
            UpdateAllPanels();
            bWasInit = false;
        }
Beispiel #11
0
        void Main()
        {
            IMyTextSurface screen                = GridTerminalSystem.GetBlockWithName("LCD Solar Array") as IMyTextSurface;
            IMyMotorStator rotorRight            = GridTerminalSystem.GetBlockWithName("Rotor Solar Right") as IMyMotorStator;
            IMyMotorStator rotorLeft             = GridTerminalSystem.GetBlockWithName("Rotor Solar Left") as IMyMotorStator;
            IMyBlockGroup  solarArrayRightBlocks = GridTerminalSystem.GetBlockGroupWithName("Solar Array Right");
            IMyBlockGroup  solarArrayLeftBlocks  = GridTerminalSystem.GetBlockGroupWithName("Solar Array Left");

            if (solarArrayRightBlocks == null)
            {
                Echo("[Error] Right Solar Array Group Null");
            }
            if (solarArrayLeftBlocks == null)
            {
                Echo("[Error] Left Solar Array Group Null");
            }
            //IMyTextSurface surface = GridTerminalSystem.GetBlockWithName("LCD Panel") as IMyTextSurface;
            IMyBatteryBlock battery = GridTerminalSystem.GetBlockWithName("Battery") as IMyBatteryBlock;
            //float pwrNow;
            //float pwrLast;
            double rotorRightAngle = Math.Round((rotorRight.Angle * 180) / 3.14, 2); //1rad × 180/π = 57.296°
            double rotorLeftAngle  = Math.Round((rotorLeft.Angle * 180) / 3.14);     //1rad × 180/π = 57.296°
            List <IMySolarPanel> solarArrayRight = new List <IMySolarPanel>();
            List <IMySolarPanel> solarArrayLeft  = new List <IMySolarPanel>();

            solarArrayRightBlocks.GetBlocksOfType <IMySolarPanel>(solarArrayRight);
            solarArrayLeftBlocks.GetBlocksOfType <IMySolarPanel>(solarArrayLeft);
            float         solarRightInPower     = (float)Math.Round(solarArrayRight[0].CurrentOutput * 1000, 2); //kW
            float         solarLeftInPower      = (float)Math.Round(solarArrayLeft[0].CurrentOutput * 1000);     //kW
            float         lastPowerReadingLeft  = 0;
            float         lastPowerReadingRight = 0;
            bool          leftRotating          = false;
            bool          rightRotating         = true;
            StringBuilder sb = new StringBuilder();

            sb.AppendLine($"Total Power Generated: {GetTotalPower(solarArrayLeft, solarArrayRight)} kW");
            //sb.AppendLine($"Right Array Solar Count: {solarArrayRight.Count}");
            sb.AppendLine($"Left Array Solar Count: {solarArrayLeft.Count}");
            //sb.AppendLine($"Right Panel Sample Charge: {Math.Round(solarRightInPower, 2)} kw");
            sb.AppendLine($"Left Panel Sample Charge: {Math.Round(solarLeftInPower, 2)} kw");
            sb.AppendLine($"Left Rotor Angle: {rotorLeftAngle}");
            sb.AppendLine($"Left Rotor Angle Rounded: {Math.Round(rotorLeftAngle)}");
            if (Storage == null)
            {
                sb.AppendLine("Storage Empty");
                lastPowerReadingLeft  = 0;
                lastPowerReadingRight = 0;
            }
            else
            {
                string[] retrievedFromStorage = Storage.Split(',');
                sb.AppendLine($"Length Of Storage: {retrievedFromStorage.Length}");
                sb.AppendLine($"StorageLeft Reading: {retrievedFromStorage[0]} isRotatingLeft: {retrievedFromStorage[2]}");
                if (retrievedFromStorage.Length < 4)
                {
                    sb.AppendLine("Storage String Cannot be Parsed");
                }
                else
                {
                    sb.AppendLine($"{retrievedFromStorage[0]} {retrievedFromStorage[1]} {retrievedFromStorage[2]} {retrievedFromStorage[3]}");
                    lastPowerReadingLeft  = float.Parse(retrievedFromStorage[0]);
                    lastPowerReadingRight = float.Parse(retrievedFromStorage[1]);
                    leftRotating          = bool.Parse(retrievedFromStorage[2]);
                    rightRotating         = bool.Parse(retrievedFromStorage[3]);
                }
            }
            //If no sun return to 0 degrees
            if (solarLeftInPower == 0)
            {
                sb.AppendLine("Setting Left Array");
                if (rotorLeftAngle == 45)
                {
                    rotorLeft.TargetVelocityRPM = 0;
                    leftRotating = false;
                }
                else if (rotorLeftAngle > 180)
                {
                    rotorLeft.TargetVelocityRPM = 1;
                }
                else
                {
                    rotorLeft.TargetVelocityRPM = -1;
                }
            }
            else if (solarLeftInPower < lastPowerReadingLeft)
            {
                sb.AppendLine($"LeftIn Power < lastPower Reading");
                if (leftRotating)
                {
                    rotorLeft.ApplyAction("Reverse");
                }
                else
                {
                    rotorLeft.TargetVelocityRPM = -.25f;
                }
            }
            else
            {
                sb.AppendLine($"LeftIn Power >= lastPower Reading");
                sb.AppendLine("Stopped Left Array");
                rotorLeft.TargetVelocityRPM = 0;
            }
            string storageString = $"{solarLeftInPower},{solarRightInPower},{leftRotating.ToString()},{rightRotating.ToString()}";

            Storage = storageString;
            screen.WriteText(sb.ToString());
        }
public void Main()
{
    double elev;
    var    myCurrentCockpit = GridTerminalSystem.GetBlockWithName("Cockpit") as IMyCockpit;

    myCurrentCockpit.TryGetPlanetElevation(MyPlanetElevation.Surface, out elev);
    y_t = elev;
    Echo("y_t:" + y_t.ToString());

    e_t = r_t - y_t;

    //integral
    //first approach from 0 to now (bad results, assume the settings would never change)
    //i_t += e_t;
    if (i_t_list_points.Count < i_t_num_points)
    {
        i_t_list_points.Add(e_t);
    }
    else
    {
        i_t_list_points.RemoveAt(0);
        i_t_list_points.Add(e_t);
    }
    i_t = 0;
    foreach (var it in i_t_list_points)
    {
        i_t += it;
    }
    i_t = i_t / 10;
    Echo("i_t:" + i_t.ToString());

    //derivative
    //TODO: figure the time delta
    var dts = Runtime.TimeSinceLastRun.TotalSeconds;

    Echo("dts:" + dts.ToString());
    d_t     = (d_t_m_1 - e_t) / dts;
    d_t_m_1 = e_t;
    Echo("d_t:" + d_t.ToString());


    //TODO:need update for i and d
    u_t = K_p * e_t + T_i * i_t + T_d * d_t;
    Echo("u_t:" + u_t.ToString());

    //applying what the pid processed
    var cs = new List <IMyThrust>();

    GridTerminalSystem.GetBlocksOfType(cs);
    foreach (var c in cs)
    {
        //Echo(c.CustomName + " " + c.GridThrustDirection);
        //Vector3I upVect = new
        if (c.GridThrustDirection.Y == -1)
        {
            //c.ThrustOverridePercentage += Convert.ToSingle(Math.Pow(Convert.ToSingle(Math.Abs(minAlt - elev)),2));
            c.ThrustOverridePercentage += Convert.ToSingle(u_t);
        }

        /*
         * //disabled by default, prone to ship crashes !!!
         * if (c.GridThrustDirection.Y == 1)
         * {
         *  c.ThrustOverridePercentage -= Convert.ToSingle(u_t);
         * }
         */
    }
}
Beispiel #13
0
        public void Main(string argument, UpdateType updateSource)
        {
            IList <string> splitargs = argument.Split().Select(s => s.Trim()).ToList();

            if (panel == null)
            {
                IMyCockpit seat = (IMyCockpit)GridTerminalSystem.GetBlockWithName("Rld Control Seat");
                initDiagPanel(seat.GetSurface(0));
            }

            if (angleHinges == null)
            {
                initHinges();
            }

            if (angleHinges.Count > 0)
            {
                StringBuilder output      = new StringBuilder();
                int           count       = 0;
                bool          allAtTarget = true;
                angleHinges.ForEach(i =>
                {
                    float angleDegrees = i.Angle / radiansPerDegree;
                    float angleTarget  = 0;

                    if (i.TargetVelocityRPM > 0)
                    {
                        angleTarget = i.UpperLimitDeg;
                    }
                    else if (i.TargetVelocityRPM < 0)
                    {
                        angleTarget = i.LowerLimitDeg;
                    }


                    float delta = Math.Abs(angleDegrees - angleTarget);
                    if (delta > epsilon)
                    {
                        allAtTarget = false;
                    }

                    output.Append($"{i.CustomName} : {Math.Round(angleDegrees, 3)} / {Math.Round(angleTarget, 3)} - {delta}");

                    count++;
                    if (count < angleHinges.Count)
                    {
                        output.Append("\n");
                    }
                });

                if (allAtTarget)
                {
                    angleHinges.ForEach(i =>
                    {
                        i.TargetVelocityRPM *= -1;
                    });
                }


                panel.WriteText(output.ToString());
            }
        }
        public void Main(string argument, UpdateType updateSource)
        {
            // The main entry point of the script, invoked every time
            // one of the programmable block's Run actions are invoked,
            // or the script updates itself. The updateSource argument
            // describes where the update came from. Be aware that the
            // updateSource is a  bitfield  and might contain more than
            // one update type.
            //
            // The method itself is required, but the arguments above
            // can be removed if not needed.


            // Define the variables
            var    LCD            = GetBlocksFromGroup("Oxygen LCD Panels");                                     // lcd group name: Oxygen LCD Panels
            var    airVents       = SearchBlocksByName("Air Vent");                                              // Air vents name: Air Vent
            var    timer          = GridTerminalSystem.GetBlockWithName("Timer Block Oxygen") as IMyTimerBlock;  //nameoftimerblock
            var    alarm          = GridTerminalSystem.GetBlockWithName("Oxygen Alarm") as IMyFunctionalBlock;   //nameofsoundblock
            var    alarma         = GridTerminalSystem.GetBlockWithName("Emergency Lights") as IMyInteriorLight; //nameoflight
            var    pressureStatus = "Pressurized";
            string LCDText        = " Life Support System:\r\n\r\n";
            var    LCDColour      = Color.White;

            // Check the air vents
            for (int i = 0; i < airVents.Count; i++)
            {
                string pressureInfo = airVents[i].DetailedInfo;
                if (pressureInfo.IndexOf("Not pressurized") != -1)
                {
                    if (pressureStatus == "Pressurized")
                    {
                        LCDText += "                ----------- ALERT ----------- \r\n\r\n";
                    }
                    LCDText       += airVents[i].CustomName.Substring(8) + " depressurised \r\n";
                    LCDColour      = Color.Red;
                    pressureStatus = "Depressurized";
                }
            }//plays sound on sound blocks named Oxygen Alarm

            if (pressureStatus == "Depressurized")
            {
                alarm.GetActionWithName("PlaySound").Apply(alarm);
                List <IMyTerminalBlock> allDoors = new List <IMyTerminalBlock>();
                GridTerminalSystem.GetBlocksOfType <IMyDoor>(allDoors);
                for (int i = 0; i < allDoors.Count; i++)
                {
                    allDoors[i].GetActionWithName("Open_Off").Apply(allDoors[i]);
                }
            }
            else
            {
                LCDText += " All " + airVents.Count + " zones are currently pressurised";
                //set lights to off
                //alarma.GetActionWithName("OnOff_Off").Apply(alarma);
            }

            SetText(LCD, LCDText, LCDColour);

            // Restart the event handler
            timer.GetActionWithName("Start").Apply(timer);
        }
Beispiel #15
0
        void Main(string arguments)
        {
            GridTerminalSystem.GetBlockGroups(BlockGroups);
            GridTerminalSystem.GetBlocks(Blocks);

            Ores       = new Dictionary <string, float>();
            Ingots     = new Dictionary <string, float>();
            Components = new Dictionary <string, float>();
            Ammo       = new Dictionary <string, float>();

            foreach (var block in Blocks)
            {
                if (block.HasInventory)
                {
                    for (int j = 0; j < block.InventoryCount; j++)
                    {
                        var inv = block.GetInventory(j);
                        EvaluateInv(inv);
                    }
                }
            }

            AllPanels = new List <List <List <IMyTextPanel> > >();

            RessourcesPanels = new List <List <IMyTextPanel> >();
            AllPanels.Add(RessourcesPanels);

            OrePanels = new List <List <IMyTextPanel> >();
            AllPanels.Add(OrePanels);

            IngotPanels = new List <List <IMyTextPanel> >();
            AllPanels.Add(IngotPanels);

            ComponentPanels = new List <List <IMyTextPanel> >();
            AllPanels.Add(ComponentPanels);

            AmmoPanels = new List <List <IMyTextPanel> >();
            AllPanels.Add(AmmoPanels);

            StatusPanels = new List <List <IMyTextPanel> >();
            AllPanels.Add(StatusPanels);

            SortPanels();

            EvaluateBlockInvPanels(GetTextPanels());


            int panelCount = 0;

            //clear all panels first
            for (int i = 0; i < AllPanels.Count; i++)
            {
                for (int j = 0; j < AllPanels[i].Count; j++)
                {
                    for (int k = 0; k < AllPanels[i][j].Count; k++)
                    {
                        IMyTextPanel panel = AllPanels[i][j][k];
                        panel.WriteText("");
                        panelCount++;
                    }
                }
            }

            List <IMyTerminalBlock> keys = new List <IMyTerminalBlock>(BlockInvPanels.Keys);

            for (int i = 0; i < keys.Count; i++)
            {
                for (int j = 0; j < BlockInvPanels[keys[i]].Count; j++)
                {
                    for (int k = 0; k < BlockInvPanels[keys[i]][j].Count; k++)
                    {
                        IMyTextPanel panel = BlockInvPanels[keys[i]][j][k];
                        panel.WriteText("");
                        panelCount++;
                    }
                }
            }

            if (panelCount == 0)
            {
                Echo("No Panels found. :(");
                return;
            }

            DebugString.AppendLine(string.Format("Counts -> Ore: {0}, Ing: {1}, Com: {2}, Amm: {3}", OrePanels.Count, IngotPanels.Count, ComponentPanels.Count, AmmoPanels.Count));

            if (Ores.Count > 0)
            {
                Dictionary <string, float> sortedOres = new Dictionary <string, float>(Ores);

                OreText.Add("Ores -:");
                OreText.Add("");

                List <string> oreKeys = new List <string>(sortedOres.OrderBy(x => x.Value).Select(x => x.Key).ToArray());
                for (int i = 0; i < oreKeys.Count; i++)
                {
                    string key = oreKeys[i];
                    OreText.Add(formatDisplay(key, sortedOres[key].ToString(NumberFormat)));
                }
            }
            else
            {
                OreText.Add("No ores found.");
            }

            if (Ingots.Count > 0)
            {
                Dictionary <string, float> sortedIngots = new Dictionary <string, float>(Ingots);

                IngotText.Add("Ingots:");
                IngotText.Add("");

                List <string> ingotKeys = new List <string>(sortedIngots.OrderBy(x => x.Value).Select(x => x.Key).ToArray());
                for (int i = 0; i < ingotKeys.Count; i++)
                {
                    string key = ingotKeys[i];
                    IngotText.Add(formatDisplay(key, sortedIngots[key].ToString(NumberFormat)));
                }
            }
            else
            {
                IngotText.Add("No ingots found.");
            }

            if (Components.Count > 0)
            {
                Dictionary <string, float> sortedComponents = new Dictionary <string, float>(Components);

                ComponentText.Add("Components:");
                ComponentText.Add("");

                List <string> componentKeys = new List <string>(sortedComponents.OrderBy(x => x.Value).Select(x => x.Key).ToArray());
                for (int i = 0; i < componentKeys.Count; i++)
                {
                    string key = componentKeys[i];
                    ComponentText.Add(formatDisplay(key, sortedComponents[key].ToString(IntFormat)));
                }
            }
            else
            {
                ComponentText.Add("No components found.");
            }

            if (Ammo.Count > 0)
            {
                SortedDictionary <string, float> sortedAmmo = new SortedDictionary <string, float>(Ammo);

                AmmoText.Add("Ammo:");
                AmmoText.Add("");

                List <string> ammoKeys = new List <string>(sortedAmmo.Keys);
                for (int i = 0; i < ammoKeys.Count; i++)
                {
                    string key = ammoKeys[i];
                    AmmoText.Add(formatDisplay(key, sortedAmmo[key].ToString(NumberFormat)));
                }
            }
            else
            {
                AmmoText.Add("No ammo found.");
            }

            StatusText.Add(string.Format("[{0:000.00%}] Oxygen tanks", GetStockpiledOxygen()));
            StatusText.Add(string.Format("[{0:000.00%}] Batteries", GetBatteryPower()));
            StatusText.Add(string.Format("[{0:000.00%}] Container", GetCargoSpace()));

            Display();

            if (Debug)
            {
                Echo(DebugString.ToString());
                DebugString.Clear();
            }

            OreText.Clear();
            IngotText.Clear();
            ComponentText.Clear();
            AmmoText.Clear();
            StatusText.Clear();
        }
        public void Main(string argument)
        {
            //Variables
            var info = new Dictionary <string, Dictionary <string, object> >();
            List <IMyTerminalBlock> crates = new List <IMyTerminalBlock>();
            IMyTextPanel            oreDisplay;
            IMyTextPanel            matDisplay;
            IMyTextPanel            cmpDisplay;
            IMyTextPanel            allDisplay;
            IMyTextPanel            debugDisplay;
            string debugStr = "";

            //Get display instances
            oreDisplay   = GetTextPanelWithName("lcdOreDisplay");
            matDisplay   = GetTextPanelWithName("lcdMaterialDisplay");
            cmpDisplay   = GetTextPanelWithName("lcdComponentDisplay");
            allDisplay   = GetTextPanelWithName("lcdAllItemsDisplay");
            debugDisplay = GetTextPanelWithName("lctDebugDisplay");
            //Fill Cargo Container List
            GridTerminalSystem.GetBlocksOfType <IMyCargoContainer>(crates);

            //Get inventories
            foreach (IMyCargoContainer cc in crates)
            {
                if (cc.CubeGrid.CustomName != Me.CubeGrid.CustomName)
                {
                    continue;
                }
                IMyInventory inv   = cc.GetInventory(0);
                var          items = inv.GetItems();
                items.Sort(SortItems);
                foreach (IMyInventoryItem item in items)
                {
                    var uid = item.Content.SubtypeId.ToString();
                    if (!info.ContainsKey(uid))
                    {
                        info.Add(uid, new Dictionary <string, object>()
                        {
                            { "name", item.Content.SubtypeId },
                            { "iqty", item.Amount.RawValue / INVQTY_MUTIPLIER },
                        });
                    }
                    else
                    {
                        info[uid]["iqty"] = ((double)info[uid]["iqty"]) + (item.Amount.RawValue / INVQTY_MUTIPLIER);
                    }
                }
            }
            string sHeader = "Available  ".PadLeft(AVAILABLE_AMOUNT_LENGTH, ' ') + " Resource Name";
            string s = "", sAll =
                $"All Items\n{sHeader}\n",
                   sOre = $"Ores\n{sHeader}\n",
                   sMat = $"Materials\n{sHeader}\n",
                   sCmp = $"Components\n{sHeader}\n";
            var sorted  = info.ToList();

            sorted.Sort((a, b) => (double)a.Value["iqty"] > (double)b.Value["iqty"] ? 1 : (double)a.Value["iqty"] < (double)b.Value["iqty"] ? -1 : 0);
            foreach (var kvp in sorted)
            {
                String name = FormatItemDisplayName($"{kvp.Value["name"]}");
                s = $"{FormatItemQty((double)kvp.Value["iqty"]).PadLeft(AVAILABLE_AMOUNT_LENGTH, ' ')} {name} ({kvp.Key})" + $"\n";
                if (IsOre(kvp.Key))
                {
                    sOre += s;
                }
                else if (IsMaterial(kvp.Key))
                {
                    sMat += s;
                }
                else if (IsComponent(kvp.Key))
                {
                    sCmp += s;
                }
                if (!IsOre(kvp.Key) && !IsMaterial(kvp.Key) && !IsComponent(kvp.Key))
                {
                    sAll += s;
                }
            }


            foreach (var id in matDisplayIds.Where(a => !info.ContainsKey(a)))
            {
                var name = FormatItemDisplayName($"{id}");
                sMat += $"{"NONE".PadLeft(AVAILABLE_AMOUNT_LENGTH, ' ')} {name} ({id})" + $"\n";
            }

            if (oreDisplay != null)
            {
                oreDisplay.WritePublicText(sOre, false);
            }
            if (matDisplay != null)
            {
                matDisplay.WritePublicText(sMat, false);
            }
            if (cmpDisplay != null)
            {
                cmpDisplay.WritePublicText(sCmp, false);
            }
            if (allDisplay != null)
            {
                allDisplay.WritePublicText(sAll, false);
            }
            if (debugDisplay != null)
            {
                debugDisplay.WritePublicText(debugStr, false);
            }
        }
Beispiel #17
0
        public void Main(string arg)
        {
            RController = GridTerminalSystem.GetBlockWithName(RC) as IMyShipController;
            if (RController == null)
            {
                Echo(RCFailedMSG);
                RCFailed = true;
                Status   = "Failed";
                return;
            }

            RControllers = GridTerminalSystem.GetBlockWithName(RC) as IMyRemoteControl;
            if (RControllers == null)
            {
                Echo(RCFailedMSG);
                RCFailed = true;
                Status   = "Failed";
                return;
            }

            var CCruise = GridTerminalSystem.GetBlockWithName(CC) as IMyProgrammableBlock;

            if (CCruise == null)
            {
                Echo(CCFailedMSG);
                CCFailed = true;
                Status   = "Failed";
                return;
            }

            RGyro = GridTerminalSystem.GetBlockWithName(Gyro) as IMyGyro;
            if (RGyro == null)
            {
                Echo(GyroFailedMSG);
                GyroFailed = true;
                Status     = "Failed";
                return;
            }

            RGyros = GridTerminalSystem.GetBlockWithName(Gyro) as IMyFunctionalBlock;
            if (RGyros == null)
            {
                Echo(GyroFailedMSG);
                GyroFailed = true;
                Status     = "Failed";
                return;
            }

            RCon = GridTerminalSystem.GetBlockWithName(Cargo) as IMyCargoContainer;
            if (RCon == null)
            {
                Echo(RConFailedMSG);
                RConFailed = true;
                Status     = "Failed";
                return;
            }

            LAntenna = GridTerminalSystem.GetBlockWithName(LA) as IMyLaserAntenna;
            if (LAntenna == null)
            {
                Echo(LAFailedMSG);
                LAFailed = true;
                Status   = "Failed";
                return;
            }

            LGear = GridTerminalSystem.GetBlockWithName(LG) as IMyTimerBlock;
            if (LGear == null)
            {
                Echo(LGFailedMSG);
                LGFailed = true;
                Status   = "Failed";
                return;
            }

            CCUp = GridTerminalSystem.GetBlockWithName(CCU) as IMyTimerBlock;
            if (CCUp == null)
            {
                Echo(CCTsFailedMSG);
                CCTsFailed = true;
                Status     = "Failed";
                return;
            }
            CCOff = GridTerminalSystem.GetBlockWithName(CCO) as IMyTimerBlock;
            if (CCOff == null)
            {
                Echo(CCTsFailedMSG);
                CCTsFailed = true;
                Status     = "Failed";
                return;
            }
            CCDown = GridTerminalSystem.GetBlockWithName(CCD) as IMyTimerBlock;
            if (CCDown == null)
            {
                Echo(CCTsFailedMSG);
                CCTsFailed = true;
                Status     = "Failed";
                return;
            }
            GridTerminalSystem.GetBlocksOfType(thrustersUP, x => x.WorldMatrix.Forward == RControllers.WorldMatrix.Up);
            if (thrustersUP.Count == 0)
            {
                Echo($"Error: No lift-off thrusters were found!");
            }
            GridTerminalSystem.GetBlocksOfType(thrustersDOWN, x => x.WorldMatrix.Forward == RControllers.WorldMatrix.Down);
            if (thrustersDOWN.Count == 0)
            {
                Echo($"Error: No lift-off thrusters were found!");
            }
            var shipMass = RController.CalculateShipMass();

            TotalMass  = shipMass.TotalMass;
            AutoEnable = RControllers.IsAutoPilotEnabled;
            RController.TryGetPlanetElevation(MyPlanetElevation.Sealevel, out Elev);
            velo          = RController.GetShipSpeed();
            Position      = RController.GetPosition();
            Gravity       = (RController.GetNaturalGravity().Length());
            GravityG      = (RController.GetNaturalGravity().Length() / 9.81);
            thrustSumUP   = 0;
            thrustSumDOWN = 0;
            foreach (var block in thrustersUP)
            {
                thrustSumUP += block.MaxEffectiveThrust;
            }
            foreach (var block in thrustersDOWN)
            {
                thrustSumDOWN += block.MaxEffectiveThrust;
            }
            if (Status == "Launched")
            {
                TargetGravity = (PlanetGravity * (Math.Pow((MaxR / (TargetAltitude + MinR)), 7)));
                Accel         = ((thrustSumUP / TotalMass) + TargetGravity); //Stopping force
                AccelTime     = ((0 - velo) / -Accel);                       //Seconds to stop
                stopDistance  = ((velo * AccelTime) + ((-Accel * (AccelTime * AccelTime)) / 2));
            }
            if (Status == "Return")
            {
                Accel        = ((thrustSumDOWN / TotalMass) - PlanetGravity); //Stopping force
                AccelTime    = ((0 - velo) / -Accel);                         //Seconds to stop
                stopDistance = ((velo * AccelTime) + ((-Accel * (AccelTime * AccelTime)) / 2));
            }
            Echo(Ship + " Control Pro");
            Echo("Status: " + Status);
            Echo("Altitude: " + Math.Round(Elev, 2) + "/" + TargetAltitude);
            Echo("Speed: " + Math.Round(velo, 2));
            Echo("Total Weight: " + TotalMass);
            Echo("Gravity: " + Math.Round(GravityG, 2) + "G");
            string msg = ("Ship" + ":" + Ship + "," + "Status" + ":" + Status + "," + "Elevation" + ":" + Elev + "," + "Position" + ":" + Position + "," + "Speed" + ":" + velo + "," + "Target" + ":" + TargetAltitude + ",");

            LAntenna.TransmitMessage(msg);
            var keyValuePairs = arg.Split(',').Select(x => x.Split(':')).Where(x => x.Length == 2).ToDictionary(x => x.First(), x => x.Last());

            //Echo(thrustSumDOWN.ToString());
            //Echo(thrustersDOWN.Count.ToString());
            //Echo(thrustSumUP.ToString());
            //Echo(thrustersUP.Count.ToString());

            if (Status == "Failed")
            {
                if (RCFailed == true)
                {
                    Echo(RCFailedMSG); return;
                }
                if (CCFailed == true)
                {
                    Echo(CCFailedMSG); return;
                }
                if (GyroFailed == true)
                {
                    Echo(GyroFailedMSG); return;
                }
                if (LAFailed == true)
                {
                    Echo(LAFailedMSG); return;
                }
                if (LGFailed == true)
                {
                    Echo(LGFailedMSG); return;
                }
                if (RConFailed == true)
                {
                    Echo(RConFailedMSG); return;
                }
                if (CCTsFailed == true)
                {
                    Echo(CCTsFailedMSG); return;
                }
                Status = "Failed";
                return;
            }

            if (arg.Contains("Target"))
            {
                TargetAltitudeSetter = keyValuePairs["Target"];
                TargetAltitude       = int.Parse(TargetAltitudeSetter);
                NotReady();
            }
            if (!Init)
            {
                Status = "Initalizing..."; NotReady();
            }
            if (arg == "Reset")
            {
                Status = "Not Ready"; NotReady();
            }
            if (arg == "Ready")
            {
                Status = "Ready"; Ready();
            }
            if (arg == "Launch")
            {
                Status = "Launching"; Launch();
            }
            if (arg == "Launched")
            {
                Status = "Launched"; Climb();
            }
            if (arg == "Seperate")
            {
                Status = "Seperation"; Seperation();
            }
            if (arg == "Return")
            {
                Status = "Return"; Return();
            }
            if (arg == "Approach")
            {
                Status = "Approaching"; Approach();
            }
            if (arg == "Land")
            {
                Status = "Landing"; Land();
            }
            if (arg == "Landed")
            {
                Status = "Landed";
            }

            if (Status == "Launching")
            {
                Launch();
            }
            if (Status == "Launched")
            {
                Climb();
            }
            if (Status == "Seperation")
            {
                Seperation();
            }
            if (Status == "Return")
            {
                Return();
            }
            if (Status == "Approaching")
            {
                Approach();
            }
            if (Status == "Landing")
            {
                Land();
            }
            if (Status == "Landed")
            {
                Status = "Landed";
            }
        }
Beispiel #18
0
        bool Init()
        {
            #region controller and settings

            var controllers = new List <IMyShipController>();
            GridTerminalSystem.GetBlocksOfType(controllers, x => x.IsSameConstructAs(Me));

            bool cruiseEnabledInSettings = false;
            bool alignEnabledInSettings  = false;

            Settings = new MyIni();
            if (Settings.TryParse(Storage))
            {
                if (Settings.ContainsSection(SettingsHeader))
                {
                    targetSpeed                 = Settings.Get(SettingsHeader, SettingsTargetSpeed).ToSingle(targetSpeed);
                    thrustDirection             = (Base6Directions.Direction)Settings.Get(SettingsHeader, SettingsSelectedThrusters).ToInt32((int)thrustDirection);
                    targetAltAscending          = Settings.Get(SettingsHeader, SettingsTargetAltAscending).ToDouble(targetAltAscending);
                    targetAltDescending         = Settings.Get(SettingsHeader, SettingsTargetAltDescending).ToDouble(targetAltDescending);
                    disableCruiseExitingGravity = Settings.Get(SettingsHeader, SettingsDisableCruiseExitingGravity).ToBoolean(disableCruiseExitingGravity);
                    disableAlignExitingGravity  = Settings.Get(SettingsHeader, SettingsDisableAlignExitingGravity).ToBoolean(disableAlignExitingGravity);
                    useSeaLevel                 = Settings.Get(SettingsHeader, SettingsUseSeaLevel).ToBoolean(useSeaLevel);
                    worldTopSpeed               = Settings.Get(SettingsHeader, SettingsWorldTopSpeed).ToSingle(worldTopSpeed);

                    cruiseEnabledInSettings = Settings.Get(SettingsHeader, SettingsCruiseEnabled).ToBoolean();
                    alignEnabledInSettings  = Settings.Get(SettingsHeader, SettingsCruiseEnabled).ToBoolean();

                    var parts = Settings.Get(SettingsHeader, SettingsController).ToString().Split(';');
                    if (parts.Length == 3)
                    {
                        GetController(controllers, new Vector3I(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2])));
                    }
                }
            }



            //If fetching controller from storage failed, try to set up a new.
            if (MainController == null)
            {
                if (!GetController(controllers))
                {
                    Errors["no controller"] = "No ship controller found. Can't resume. Sit in one for a few seconds.";
                    return(false);
                }
            }
            if (MainController != null)
            {
                Errors.Remove("no controller");
            }

            Settings.Set(SettingsHeader, SettingsController, $"{MainController.Position.X};{MainController.Position.Y};{MainController.Position.Z}");
            SaveSettings();

            //screen = (MainController as IMyTextSurfaceProvider).GetSurface(0);
            //screen.ContentType = ContentType.TEXT_AND_IMAGE;

            //var sprites = new List<string>();
            //screen.GetSprites(sprites);
            //Me.CustomData = "";
            //foreach (var item in sprites)
            //{
            //	Me.CustomData += item + "\n";
            //}

            #endregion



            var allBlocks = new List <IMyTerminalBlock>();
            GridTerminalSystem.GetBlocksOfType(allBlocks, x => x.IsSameConstructAs(Me));

            List <IMyGyro>        gyros     = new List <IMyGyro>();
            List <IMyThrust>      thrusters = new List <IMyThrust>();
            List <IMyTextSurface> screens   = new List <IMyTextSurface>();

            foreach (var item in allBlocks)
            {
                //if(item is IMyProjector)
                //{
                //	proj = new ProjectorVisualization(item as IMyProjector, Vector3I.Zero);
                //}

                if (item is IMyGyro)
                {
                    gyros.Add(item as IMyGyro);
                }

                if (item is IMyThrust)
                {
                    thrusters.Add(item as IMyThrust);
                }
                if (item as IMyTextSurfaceProvider != null)
                {
                    if (item.CustomName.Contains("#ACC"))
                    {
                        int screennr = 0;
                        var parts    = item.CustomName.Split('@');
                        if (parts.Length > 1)
                        {
                            for (int i = 0; i < parts.Length; i++)
                            {
                                if (parts[i].EndsWith("#ACC") && parts.Length > i + 1)
                                {
                                    int.TryParse(new string(parts[i + 1].TakeWhile(char.IsDigit).ToArray()), out screennr);
                                }
                            }
                        }
                        screens.Add((item as IMyTextSurfaceProvider).GetSurface(screennr));
                        screens[screens.Count - 1].ContentType = ContentType.SCRIPT;
                        screens[screens.Count - 1].Script      = "";
                    }
                }
            }

            if (screens.Count > 0)
            {
                LCDs = new Screens(screens);
            }

            if (gyros.Count > 0)
            {
                Align = new Aligner(MainController, gyros);
                if (alignEnabledInSettings)
                {
                    StartAlign(true);
                }
            }

            if (thrusters.Count > 0)
            {
                Cruise = new CruiseControl(MainController, thrusters);
                if (cruiseEnabledInSettings)
                {
                    StartCruiseControl(true);
                }
            }
            return(true);
        }
Beispiel #19
0
        void Main()
        {
            // Get blocks
            var blocks = new List <IMyTerminalBlock>();

            // Get the antenna
            GridTerminalSystem.GetBlocksOfType <IMyRadioAntenna>(blocks);

            if (blocks.Count > 0)
            {
                IMyTerminalBlock Block = blocks[0];

                // Get time now
                var  Time1   = System.DateTime.Now;
                long OldTime = 0;

                // We pull this here to prevent conversions being *too* weird
                long CurrentTime = Time1.ToBinary();

                // Store the current name
                String CurrentName = Block.CustomName;

                // Get the fragments (or get one fragment)
                String[] Fragments = CurrentName.Split('|');

                // Get coordinates (VRageMath.Vector3D, so pull it in the ugly way)
                double x = Math.Round(Block.GetPosition().GetDim(0), 4);
                double y = Math.Round(Block.GetPosition().GetDim(1), 4);
                double z = Math.Round(Block.GetPosition().GetDim(2), 4);

                // Allocate this here
                double X = 0;
                double Y = 0;
                double Z = 0;

                // Start with "the unknown" speed, stored in m/s
                double Speed = 0.0;

                // Total distance moved
                double Distance = 0;

                // Do we actually have fragments?
                if (Fragments.Length == 3)
                {
                    // Yes? Excellent.
                    OldTime = Convert.ToInt64(Fragments[1]);

                    // Vomit a bit here because this is how we have to store variables at the moment ...
                    string[] Coords = Fragments[2].Split(',');
                    X = Math.Round(Convert.ToDouble(Coords[0]), 4);
                    Y = Math.Round(Convert.ToDouble(Coords[1]), 4);
                    Z = Math.Round(Convert.ToDouble(Coords[2]), 4);

                    // Nothing fancy here
                    Distance = System.Math.Sqrt(
                        ((x - X) * (x - X)) + ((y - Y) * (y - Y)) + ((z - Z) * (z - Z))
                        );
                }

                // If the base coordinates
                if (Distance != 0 && X != 0 && Y != 0 && Z != 0 && OldTime != 0)
                {
                    // Update time
                    var Time0 = System.DateTime.FromBinary(OldTime);

                    // We have 's' for m/s.
                    var TimeDelta = (Time1 - Time0).TotalSeconds;

                    // We have our distance
                    Speed = Distance / TimeDelta;
                    Speed = Math.Round(Convert.ToDouble(Speed), 4);
                }

                // Speed|Time|X,Y,Z
                String NewName = Speed.ToString() + "|" +
                                 CurrentTime.ToString() + "|" +
                                 x.ToString() + "," + y.ToString() + "," + z.ToString();

                // Store it
                Block.CustomName = NewName;

                // Show it on the HUD so we can check it
                Block.ShowOnHUD = true;
            }
        }
Beispiel #20
0
    //MyFunctions,Methods

    //ФУНКЦИИ УПРАВЛЕНИЯ ДВИЖЕНИЕМ
    //Управление тягой движков.
    public void ThrustOverride(string groupName, bool on_off)
    {
        //Берём все движки из "Engines" и закидываем их в thrustList.
        thrustGroup = GridTerminalSystem.GetBlockGroupWithName(groupName);
        thrustGroup.GetBlocksOfType <IMyThrust>(thrustList);

        gyroList = new List <IMyGyro>();
        GridTerminalSystem.GetBlocksOfType <IMyGyro>(gyroList);

        //Поиск блока Remote Control, получение массы, вектора движения и гравитации.
        if (FindBlockByPartOfName(nameRemCon).Count == 1)
        {
            remCon = FindBlockByPartOfName(nameRemCon)[0] as IMyShipController;
            MyShipMass rawMass = remCon.CalculateShipMass();
            mass = rawMass.PhysicalMass;

            gravityVector = remCon.GetNaturalGravity();
            Display("GravityVector:\r\n" + gravityVector.ToString(), nameStateLCD);
            Vector3D gravityNorm       = Vector3D.Normalize(gravityVector);
            double   gravityNormDouble = gravityVector.Normalize();
            Display("GravityNorm: " + gravityNormDouble.ToString(), nameStateLCD);
            gravity          = Convert.ToSingle(gravityNormDouble);
            velocityVector   = remCon.GetShipVelocities().LinearVelocity;
            verticalVelocity = -(float)gravityNorm.Dot(velocityVector);
        }
        else if (FindBlockByPartOfName(nameRemCon).Count > 1)
        {
            Display("Warning! \r\n We find more than \r\n 1 blocks Remote control:", nameDebugLCD);
            foreach (IMyRemoteControl remCon in FindBlockByPartOfName(nameRemCon))
            {
                string data = remCon.CustomName;
                Display(data, nameDebugLCD);
            }
        }
        else
        {
            Display("Warning! \r\n You don't have remote control blocks!", nameDebugLCD);
        }


        if (on_off)
        {
            Display("EnginesElevating - on", nameStateLCD);
            GetMyPos();

            /*В последний раз я переписал парсер, такое ощещение, что в предыдущий раз я вообще не понимал как он должен работать. =)
             * Сейчас пытаюсь выяснить как правильно найти разницу в координатах платформы и структуры, для управления тягой движков.
             * Получилось получить направление вектора вверх, но пока непонятно как это можно использовать.
             * Update: Вероятно, можно получить вектор расстояния (координаты структуры - координаты платформы) и с помощью скалярного произведения
             * на вектор вверх, получить нужное значение, для управления высотой.
             */
            //Достаём из панели и записываем координаты в переменные.
            string floorPos    = GetTextValueMultiline(nameFloorPosStorage, floorSensorName + GetFloorNumber() + @"](?>\S+\s)+\S+");
            string PlatformPos = GetTextValueMultiline(namePlatformPosStorage, sensorName + @"](?>\S+\s)+\S+");
            //Парсим строки с координатам.(Достаём оттуда числовые значения XYZ)
            List <float> floorPosParsed = new List <float>();
            floorPosParsed = CoordParser(GetTextValueMultiline(nameFloorPosStorage, floorSensorName + GetFloorNumber() + @"](?>\S+\s)+\S+"));
            List <float> platformPosParsed = new List <float>();
            platformPosParsed = CoordParser(GetTextValueMultiline(namePlatformPosStorage, sensorName + @"](?>\S+\s)+\S+"));
            //Получаем вектор вверх и сразу парсим его.
            List <float> upVectorParsed = new List <float>();
            upVectorParsed = CoordParser(remCon.WorldMatrix.Up.ToString()); Display("RemConVectorUp: " + remCon.WorldMatrix.Up.ToString(), nameParserLCD);

            //Объявляем вектор расстояния и присваиваем ему нужные значения.
            Vector3D distanceVector;
            distanceVector.X = floorPosParsed[0] - platformPosParsed[0];
            distanceVector.Y = floorPosParsed[1] - platformPosParsed[1];
            distanceVector.Z = floorPosParsed[2] - platformPosParsed[2];

            //Объявляем вектор вверх и присваиваем ему уже полученный.
            Vector3D vectorUp = remCon.WorldMatrix.Up;

            //С помощью скалярного произведения, получаем вертикальную проекцию для управления двигателями.
            verticalProject = (float)distanceVector.Dot(vectorUp);
            Display(verticalProject.ToString(), nameParserLCD);

            //Расчёт необходимой силы для подъёма. - данной силы недостаточно даже для удерживания платформы на месте
            force = (float)((1 + (verticalProject - verticalVelocity) * kA) * gravityVector.Length() * mass);

            /*"Эксперимент с батарейкой"
             * string BatVectorUP = "X:0.880934000015259 Y:-0.431211113929749 Z:0.194967776536942}";
             * List<float> BatVectorUPParsed = new List<float>();
             * BatVectorUPParsed = CoordParser(BatVectorUP);
             * string BatPos = "X:53535.6127123895 Y:-26681.3688097174 Z:12106.9409922019}";
             * //string PlPos = "X: 53534.4160012206 Y: -26683.558898142 Z: 12107.9450289915}";
             * //BatPos - PlPos = X-1.2 Y-2.2 Z1
             * //(BatPos - PlPos)*BatVectorUP = X - 0.96 Y 0,88 Z0,1
             * List<float> BatPosParsed = new List<float>();
             * BatPosParsed = CoordParser(BatPos);
             * string BatPosNorm = "X: " + (BatPosParsed[0] / BatVectorUPParsed[0]).ToString() + " Y: " + (BatPosParsed[1] / BatVectorUPParsed[1]).ToString() + " Z: " + (BatPosParsed[2] / BatVectorUPParsed[2]).ToString();
             * Display("BatVectorUP: " + BatVectorUP, nameParserLCD);
             * Display("BatPos: " + BatPos, nameParserLCD);
             * Display("BatPosNorm: " + BatPosNorm, nameParserLCD);
             *
             *
             * foreach (IMyGyro gyro in gyroList)
             * {
             *  Display("Gyro1VectorUp: " + gyro.WorldMatrix.Up.ToString(), nameParserLCD);
             *  List<float> gyroUpVectorParsed = new List<float>();
             *  gyroUpVectorParsed = CoordParser(gyro.WorldMatrix.Up.ToString());
             *  string differenceUpVectors = "X: " + (gyroUpVectorParsed[0] - upVectorParsed[0]).ToString() + " Y: " + (gyroUpVectorParsed[1] - upVectorParsed[1]).ToString() + " Z: " + (gyroUpVectorParsed[2] - upVectorParsed[2]).ToString();
             *  Display("DifferenceUpVectors: " + differenceUpVectors, nameParserLCD);
             * }*/

            engineState = "FloorNum: " + GetTextValueInline("SetFloorLevel", nameLCDfloorLevel) + "\n";
            engineState = engineState + "FloorNum: " + GetFloorNumber() + "\n";
            engineState = engineState + "FloorCoords: " + floorPos + "\n";
            engineState = engineState + "PlatformCoords: " + PlatformPos + "\n";
            engineState = engineState + "CoordParser: " + floorPosParsed.Count + "\n";
            engineState = engineState + "CoordParsedY: " + floorPosParsed[1] + "\n";

            foreach (IMyThrust thrust in thrustList)
            {
                //Управление двигателями.
                float correction = ((force / thrustList.Count) / 100f) * (thrust.MaxThrust - thrust.MaxEffectiveThrust) / (thrust.MaxThrust / 100f); //Поправка на высоту, для атмо двигателей. 20640
                //correction = correction - ((correction / 10000f) * 15);

                thrust.ThrustOverride = (force / thrustList.Count);
                if (thrust.ThrustOverride == 0)
                {
                    thrust.ThrustOverride = 1;
                }

                //Выводим состояние движков на панель.

                remCon = FindBlockByPartOfName(nameRemCon)[0] as IMyShipController;
                float g = (float)remCon.GetNaturalGravity().Length();
                float octopusGravityData = thrust.MaxEffectiveThrust / mass - g;

                /*for (int i = 0; i < CoordParser(GetTextValueMultiline(nameFloorPosStorage, floorSensorName + GetFloorNumber() + @"](?>\S+\s)+\S+")).Count; i++)
                 * {
                 *  coordParsed += CoordParser(GetTextValueMultiline(nameFloorPosStorage, floorSensorName + GetFloorNumber() + @"](?>\S+\s)+\S+"))[i].ToString();
                 * }*/

                engineState = engineState + "MET: " + thrust.MaxEffectiveThrust.ToString() + "\n";
                engineState = engineState + "MT: " + thrust.MaxThrust.ToString() + "\n";
                engineState = engineState + "CORR: " + correction.ToString() + "\n";
                engineState = engineState + "OCTOP_G_DATA: " + g.ToString() + "\n";
                engineState = engineState + "TO: " + thrust.ThrustOverride.ToString() + "\n";
                //engineState = engineState + "FM: " + ForceMultiply(CoordParser(GetTextValueMultiline(floorSensorName + GetFloorNumber(), nameFloorPosStorage))[1], CoordParser(GetTextValueMultiline(sensorName, namePlatformPosStorage))[1]).ToString();
            }
            Display(engineState, nameStateLCD);
        }
        else if (!on_off)
        {
            Display("EnginesElevating - off", nameStateLCD);

            foreach (IMyThrust thrust in thrustList)
            {
                //Управление двигателями.
                thrust.ThrustOverride = 0;

                //Выводим состояние движков на панель.
                string text = thrust.ThrustOverride.ToString();
                Display(text, nameStateLCD);
            }
        }
    }
public void Main()
{
    var debugString = "";

    double elev;

    /*
     * var myCurrentCockpit = GridTerminalSystem.GetBlockWithName("Cockpit") as IMyCockpit;
     * var listShipController = new List<IMyShipController>();
     * if (listShipController == null)
     * { Echo("nope"); return; }
     * var myCurrentCockpit = listShipController[0];
     */
    //var listRemoteController = new List<IMyRemoteControl>();
    //IMyRemoteControl

    List <IMyShipController> listRemoteController = new List <IMyShipController>();

    GridTerminalSystem.GetBlocksOfType <IMyShipController>(listRemoteController);

    if (listRemoteController == null)
    {
        Echo("no IMyShipController available"); return;
    }

    var myCurrentCockpit = listRemoteController[0];

    myCurrentCockpit.TryGetPlanetElevation(MyPlanetElevation.Surface, out elev);

    double altitudeError = wantedAltitude - elev;

    double dts = Runtime.TimeSinceLastRun.TotalSeconds;

    //public double Control(double error, double timeStep)
    //todo change this
    //double dir = altRegulator.Control(altitudeError, dts);

    Echo("elev:" + elev);
    //PhysicalMass	Gets the physical mass of the ship, which accounts for inventory multiplier.
    var physMass_kg = myCurrentCockpit.CalculateShipMass().PhysicalMass;

    debugString += " " + "physMass_kg:" + physMass_kg;
    debugString += "\n" + "elev:" + elev;

    //figuring out the available thrust
    //IMyThrust.MaxEffectiveThrust
    //IMyThrust.CurrentThrust_N
    double maxEffectiveThrust_N = 0;
    double currentThrust_N      = 0;
    var    cs = new List <IMyThrust>();

    GridTerminalSystem.GetBlocksOfType(cs);
    foreach (var c in cs)
    {
        maxEffectiveThrust_N += c.MaxEffectiveThrust; currentThrust_N += c.CurrentThrust;
    }
    debugString += "\n" + "maxEffectiveThrust_N:" + maxEffectiveThrust_N;
    debugString += "\n" + "currentThrust_N:" + currentThrust_N;

    debugString += "\n" + "physMass_kg:" + physMass_kg;

    double physMass_N = physMass_kg * g_constant;

    debugString += "\n" + "physMass_N:" + physMass_N;


    //BaseMass Gets the base mass of the ship.
    //totalMass Gets the total mass of the ship, including cargo.
    //PhysicalMass Gets the physical mass of the ship, which accounts for inventory multiplier.


    var totalMass_kg = myCurrentCockpit.CalculateShipMass().TotalMass;

    debugString += "\n" + "totalMass_kg:" + totalMass_kg;

    var thr_to_weight_ratio = maxEffectiveThrust_N / physMass_N;

    debugString += "\n" + "thr_to_weight_ratio:" + thr_to_weight_ratio;

    double thrustLeft_N = currentThrust_N - physMass_N;

    debugString += "\n" + "thrustLeft_N:" + thrustLeft_N;

    double a_z_ms_2 = thrustLeft_N / physMass_kg;

    debugString += "\n" + "a_z_ms_2:" + a_z_ms_2;

    alt          = elev;
    debugString += "\n" + "dts:" + dts;

    //errorDerivative = (error - lastError) / timeStep;
    alt_speed_ms_1 = (alt - last_alt) / dts;
    debugString   += "\n" + "alt_speed_ms_1:" + alt_speed_ms_1;

    alt_acc_ms_2 = (alt_speed_ms_1 - last_alt_speed_ms_1) / dts;
    debugString += "\n" + "alt_acc_ms_2:" + alt_acc_ms_2;

    last_alt            = alt;
    last_alt_speed_ms_1 = alt_speed_ms_1;
    //TODO code here

    //public double Control(double error, double timeStep)
    // double speedError = 0;
    double speedError   = alt_speed_ms_1 - 0;
    double controlSpeed = altRegulator.Control(speedError, dts);

    debugString += "\n" + "controlSpeed:" + controlSpeed;

    var massOfShip = myCurrentCockpit.CalculateShipMass().PhysicalMass;

    debugString += "\n" + "massOfShip:" + massOfShip;

    var control = altRegulator.Control(altitudeError, dts);

    debugString += "\n" + "control:" + control;

    //applying what the pid processed
    //var cs = new List<IMyThrust>();
    GridTerminalSystem.GetBlocksOfType(cs);
    Echo(cs.ToString());

    foreach (var c in cs)
    {
        //Echo("c.GridThrustDirection:"+ c.GridThrustDirection);
        double temp_thr_n = .5f * physMass_N * c.MaxThrust / c.MaxEffectiveThrust + physMass_N * control;
        c.ThrustOverride = Convert.ToSingle(temp_thr_n);
        //that will balance the f_mass and f_thusters
        //c.ThrustOverride = Convert.ToSingle(.5f * physMass_N * c.MaxThrust / c.MaxEffectiveThrust + control * 100);
        //debugString += "\n" + "1f * physMass_N  * c.MaxEffectiveThrust / c.MaxThrust\n:" + (.5f * physMass_N * c.MaxThrust / c.MaxEffectiveThrust + physMass_N * control / physMass_kg);
        //debugString += "\n" + "c.ThrustOverride:" + c.ThrustOverride;
        if (c.GridThrustDirection.Y == -1)
        {
            /*
             * //c.ThrustOverride = Convert.ToSingle(0.25f * physMass_N);
             * //debugString += "\n" + "0.25f * physMass_N:" + 0.25f * physMass_N;
             * //debugString += "\n" + "c.ThrustOverride:" + c.ThrustOverride;
             *
             * //c.MaxThrust / c.MaxEffectiveThrust is needed because you need to the thrusters efficiency
             * //MaxEffectiveThrust is the current max thrust / MaxThrust is the max thrust at sea level
             * //c.ThrustOverride = Convert.ToSingle(0.25f * physMass_N * c.MaxThrust / c.MaxEffectiveTQhrust);
             * c.ThrustOverride = Convert.ToSingle(.5f * physMass_N * c.MaxThrust / c.MaxEffectiveThrust + control*100);
             * debugString += "\n" + "1f * physMass_N  * c.MaxEffectiveThrust / c.MaxThrust\n:" + (.5f * physMass_N * c.MaxThrust / c.MaxEffectiveThrust + control *100);
             * debugString += "\n" + "c.ThrustOverride:" + c.ThrustOverride;
             */
        }
    }

    //debugString += "\n" + "c.ThrustOverride:" + c.ThrustOverride;


    //lcd display
    var textPanel = GridTerminalSystem.GetBlockWithName("textPanel") as IMyTextPanel;

    if (textPanel == null)
    {
        Echo("no lcd panel named textPanel");
    }
    else
    {
        //textPanel.FontSize = 1.2f;
        //textPanel.FontSize = 1f;
        textPanel.WriteText(debugString, false);
    }



    List <IMyRadioAntenna> listRadioAntenna = new List <IMyRadioAntenna>();

    GridTerminalSystem.GetBlocksOfType <IMyRadioAntenna>(listRadioAntenna);

    if (listRadioAntenna == null)
    {
        Echo("no IMyRadioAntenna available");
    }
    else
    {
        listRadioAntenna[0].HudText = "altitude is:" + elev.ToString();
    }


    //IMyTerminalBlock.CustomName and IMyCubeGrid.CustomName are what you want
}
Beispiel #22
0
        public void startMining(List <IMyTerminalBlock> drillList, List <IMyTerminalBlock> pistonList, List <IMyTerminalBlock> rotorList)
        {
            if (!isMiningDown && !workFinished)
            {
                //Piston settings
                float maxPistonExtend = getMaxPistonExtend(pistonList, false);
                float pistonSpeed     = 0.003f;

                //Rotor settings
                float rotorTorque       = 33599988f;
                float rotorVelocityArm  = 1f;
                float rotorVelocityHead = 3f;

                isMiningDown = true;

                //Pasting drill settings & enabling them
                for (int i = 0; i < drillList.Count; i++)
                {
                    IMyShipDrill drillList_X = GridTerminalSystem.GetBlockWithName(drillList[i].CustomName) as IMyShipDrill;
                    if (drillList_X.CustomName.Contains(drillNameTag))
                    {
                        drillList_X.Enabled = true;
                    }
                }

                //Pasting piston settings & enabling them
                for (int i = 0; i < pistonList.Count; i++)
                {
                    IMyPistonBase pistonList_X = GridTerminalSystem.GetBlockWithName(pistonList[i].CustomName) as IMyPistonBase;
                    if (pistonList_X.CustomName.Contains(pistonNameTag) && !pistonList_X.CustomName.Contains("Extender"))
                    {
                        pistonList_X.SetValue("Velocity", pistonSpeed);
                        pistonList_X.Enabled = true;
                    }
                }

                //Pasting advanced rotor settings & enabling them
                for (int i = 0; i < rotorList.Count; i++)
                {
                    IMyMotorAdvancedStator rotorList_X = GridTerminalSystem.GetBlockWithName(rotorList[i].CustomName) as IMyMotorAdvancedStator;
                    if (rotorList_X.CustomName.Contains(rotorNameTag))
                    {
                        if (rotorList_X.CustomName.Contains("Arm"))
                        {
                            rotorList_X.TargetVelocityRPM = rotorVelocityArm;
                            rotorList_X.Torque            = rotorTorque;
                            rotorList_X.BrakingTorque     = rotorTorque;
                            rotorList_X.Enabled           = true;
                        }
                        if (rotorList_X.CustomName.Contains("Head"))
                        {
                            rotorList_X.Torque            = rotorTorque;
                            rotorList_X.BrakingTorque     = rotorTorque;
                            rotorList_X.TargetVelocityRPM = rotorVelocityHead;
                            rotorList_X.Enabled           = true;
                        }
                        Echo("Rotor: " + i.ToString());
                    }
                }
            }
        }
Beispiel #23
0
        private void UpdateGasStatus(IMyTextSurface surface)
        {
            // Hydrogen
            List <IMyGasTank> gasTanks = new List <IMyGasTank>();

            GridTerminalSystem.GetBlockGroupWithName("Hydrogen Tanks").GetBlocksOfType(gasTanks);

            float hydrogen_max    = 0.0f;
            float hydrogen_stored = 0.0f;

            foreach (var tank in gasTanks)
            {
                hydrogen_max    += tank.Capacity;
                hydrogen_stored += (float)tank.FilledRatio * tank.Capacity;
            }

            hydrogen_max    /= 1000;
            hydrogen_stored /= 1000;

            int    hydrogen_percentage = Convert.ToInt32(100 * hydrogen_stored / hydrogen_max);
            int    num_bars            = (hydrogen_percentage * 20) / 100;
            string hydrogen_bars       = new string('|', num_bars);

            if (num_bars < 20)
            {
                hydrogen_bars += new string(' ', 20 - num_bars);
            }

            // Oxygen
            List <IMyGasTank> oxygenTanks = new List <IMyGasTank>();

            GridTerminalSystem.GetBlockGroupWithName("Oxygen Tanks").GetBlocksOfType(oxygenTanks);

            float oxygen_max    = 0.0f;
            float oxygen_stored = 0.0f;

            foreach (var tank in oxygenTanks)
            {
                oxygen_max    += tank.Capacity;
                oxygen_stored += (float)tank.FilledRatio * tank.Capacity;
            }

            oxygen_max    /= 1000;
            oxygen_stored /= 1000;

            int oxygen_percentage = Convert.ToInt32(100 * oxygen_stored / oxygen_max);

            num_bars = (oxygen_percentage * 20) / 100;
            string oxygen_bars = new string('|', num_bars);

            if (num_bars < 20)
            {
                oxygen_bars += new string(' ', 20 - num_bars);
            }

            surface.WriteText(String.Format(
                                  "- Hydrogen\nStored: {0:0.##} m³\nMax: {1:0.##} m³\n[{2}] {3} %\n- Oxygen\nStored: {4:0.##} m³\nMax: {5:0.##} m³\n[{6}] {7} %",
                                  hydrogen_stored,
                                  hydrogen_max,
                                  hydrogen_bars,
                                  hydrogen_percentage,
                                  oxygen_stored,
                                  oxygen_max,
                                  oxygen_bars,
                                  oxygen_percentage
                                  ));
        }
        public void Main(string argument, UpdateType updateSource)
        {
            bool no_battery = true;

            blocks.Clear();
            textPanels.Clear();
            GridTerminalSystem.GetBlocks(blocks);
            foreach (IMyTerminalBlock block in blocks)
            {
                if (block is IMyTextPanel)
                {
                    IMyTextPanel text_panel = (IMyTextPanel)block;
                    if (text_panel.CustomData.Trim() == "showBatteryStates")
                    {
                        textPanels.Add(text_panel);
                    }
                }
                else if (block is IMyBatteryBlock)
                {
                    IMyBatteryBlock battery  = (IMyBatteryBlock)block;
                    bool            has_flag = false;
                    textBuilder.Append(battery.CustomName);
                    textBuilder.Append(": ");
                    textBuilder.Append(Math.Round((battery.CurrentStoredPower * 100.0f) / battery.MaxStoredPower).ToString());
                    textBuilder.Append("% ( ");
                    textBuilder.Append(GetWattString(battery.CurrentStoredPower * 1000.0f));
                    textBuilder.Append("h");
                    textBuilder.Append(" / ");
                    textBuilder.Append(GetWattString(battery.MaxStoredPower * 1000.0f));
                    textBuilder.AppendLine("h )");
                    textBuilder.Append("\tOutput: ");
                    textBuilder.Append(GetWattString(battery.CurrentOutput * 1000.0f));
                    textBuilder.Append(" / ");
                    textBuilder.AppendLine(GetWattString(battery.MaxOutput * 1000.0f));
                    textBuilder.Append("\tInput: ");
                    textBuilder.Append(GetWattString(battery.CurrentInput * 1000.0f));
                    textBuilder.Append(" / ");
                    textBuilder.AppendLine(GetWattString(battery.MaxInput * 1000.0f));
                    textBuilder.Append("Flags: ");
                    AppendFlag("W", battery.IsWorking, ref has_flag);
                    AppendFlag("C", battery.IsCharging, ref has_flag);
                    AppendFlag("H", battery.IsBeingHacked, ref has_flag);
                    if (has_flag)
                    {
                        textBuilder.Append(" )");
                    }
                    textBuilder.AppendLine();
                    no_battery = false;
                }
            }
            if (no_battery)
            {
                textBuilder.Append("No battery found!");
            }
            string text = textBuilder.ToString();

            textBuilder.Clear();
            foreach (IMyTextPanel text_panel in textPanels)
            {
                text_panel.WriteText(text);
            }
        }
Beispiel #25
0
        private void UpdateBatteryStatus(IMyTextSurface surface)
        {
            List <IMyBatteryBlock> batteries = new List <IMyBatteryBlock>();

            GridTerminalSystem.GetBlockGroupWithName("Base Batteries").GetBlocksOfType <IMyBatteryBlock>(batteries);

            float max_stored     = 0.0f;
            float current_stored = 0.0f;
            float current_input  = 0.0f;
            float current_output = 0.0f;

            foreach (var battery in batteries)
            {
                max_stored     += battery.MaxStoredPower;
                current_stored += battery.CurrentStoredPower;
                current_input  += battery.CurrentInput;
                current_output += battery.CurrentOutput;
            }

            float  change       = current_input - current_output;
            float  hours        = 0.0f;
            string battery_life = "";

            if (change > 0)
            {
                // Towards full charge
                float remaining_MWh = max_stored - current_stored;
                hours        = remaining_MWh / change;
                battery_life = "Recharged in: ";
            }
            else
            {
                // Towards empty
                hours        = current_stored / (-change);
                battery_life = "Depleted in: ";
            }

            if (hours >= 1)
            {
                battery_life += Convert.ToInt32(hours).ToString() + " h";
            }
            else
            {
                float minutes = hours * 60;
                if (minutes >= 1)
                {
                    battery_life += Convert.ToInt32(minutes).ToString() + " m";
                }
                else
                {
                    battery_life += Convert.ToInt32(minutes * 60).ToString() + " s";
                }
            }

            string input_unit = "MW";

            if (current_input < 1.0f)
            {
                current_input *= 1000.0f;
                input_unit     = "kW";
            }

            string output_unit = "MW";

            if (current_output < 1.0f)
            {
                current_output *= 1000.0f;
                output_unit     = "kW";
            }

            int    percentage = Convert.ToInt32(100 * current_stored / max_stored);
            int    num_bars   = (percentage * 20) / 100;
            string bars       = new string('|', num_bars);

            if (num_bars < 20)
            {
                bars += new string(' ', 20 - num_bars);
            }

            surface.WriteText(String.Format(
                                  "- Power\nIn: {0:0.##} {1}\nOut: {2:0.##} {3}\nStored: {4:0.##} MWh\nMax: {5:0.##} MWh\n\n{6}\n[{7}] {8} %",
                                  current_input,
                                  input_unit,
                                  current_output,
                                  output_unit,
                                  current_stored,
                                  max_stored,
                                  battery_life,
                                  bars,
                                  percentage
                                  ));
        }
Beispiel #26
0
        public void Main(string argument, UpdateType updateSource)
        {
            Runtime.UpdateFrequency = UpdateFrequency.Update100 | UpdateFrequency.Update10;
            IMyTextPanel     textPanel     = (IMyTextPanel)GridTerminalSystem.GetBlockWithName(lcdName);
            IMyRemoteControl remoteControl = (IMyRemoteControl)GridTerminalSystem.GetBlockWithName(remoteControllerName);

            // If setupcomplete is false, run Setup method.
            if (!setupcomplete)
            {
                Echo("Running setup.");
                Setup();
            }
            else
            {
                // To create a listener, we use IGC to access the relevant method.
                // We pass the same tag argument we used for our message.
                IGC.RegisterBroadcastListener(broadcastChannel);


                // Create a list for broadcast listeners.
                List <IMyBroadcastListener> listeners = new List <IMyBroadcastListener>();

                // The method argument below is the list we wish IGC to populate with all Listeners we've made.
                // Our Listener will be at index 0, since it's the only one we've made so far.
                IGC.GetBroadcastListeners(listeners);

                if (listeners[0].HasPendingMessage)
                {
                    // Let's create a variable for our new message.
                    // Remember, messages have the type MyIGCMessage.
                    MyIGCMessage message = new MyIGCMessage();

                    // Time to get our message from our Listener (at index 0 of our Listener list).
                    // We do this with the following method:
                    message = listeners[0].AcceptMessage();


                    // A message is a struct of 3 variables. To read the actual data,
                    // we access the Data field, convert it to type string (unboxing),
                    // and store it in the variable messagetext.
                    string messagetext = message.Data.ToString();



                    // We can also access the tag that the message was sent with.
                    string messagetag = message.Tag;

                    //Here we store the "address" to the Programmable Block (our friend's) that sent the message.
                    long sender = message.Source;

                    //Do something with the information!
                    Echo("Message received with tag" + messagetag + "\n\r");
                    Echo("from address " + sender.ToString() + ": \n\r");
                    Echo(messagetext);



                    allmessage += $"\n new message \n {messagetext}\n{messagetext.Split(':')[2]}";
                    textPanel.WriteText(allmessage);

                    List <MyWaypointInfo> myWaypoints = new List <MyWaypointInfo>();

                    string gpsname = messagetext.Split(':')[1];
                    double x       = 0;
                    double y       = 0;
                    double z       = 0;
                    try
                    {
                        x = Convert.ToDouble(messagetext.Split(':')[2]);
                        y = Convert.ToDouble(messagetext.Split(':')[3]);
                        z = Convert.ToDouble(messagetext.Split(':')[4]);
                    }
                    catch (Exception e)
                    {
                        Echo(e.Message);
                    }



                    Echo(messagetext.Split('1')[0]);

                    myWaypoints.Add(new MyWaypointInfo(gpsname, x, y, z));

                    remoteControl.ClearWaypoints();

                    remoteControl.AddWaypoint(myWaypoints[0]);

                    remoteControl.SetCollisionAvoidance(true);

                    remoteControl.SetAutoPilotEnabled(true);
                }
            }

            int textlength = textPanel.GetText().Length;

            if (textlength > 100)
            {
                allmessage = "";
            }
        }
 public Program()
 {
     Help();
     GridTerminalSystem.GetBlocks(LastKnownBlocks);
 }
Beispiel #28
0
        void AddLockRoom(string[] args)
        {
            string key = args[0];

            // init
            if (!_configs.ContainsKey(key))
            {
                Configuration config = new Configuration();
                config.airVent   = GridTerminalSystem.GetBlockWithName(args[0]) as IMyAirVent;
                config.outerDoor = GridTerminalSystem.GetBlockWithName(args[1]) as IMyDoor;
                config.innerDoor = GridTerminalSystem.GetBlockWithName(args[2]) as IMyDoor;
                config.timer     = GridTerminalSystem.GetBlockWithName(args[3]) as IMyTimerBlock;

                bool error = false;
                if (config.airVent == null)
                {
                    Echo("Could not find Air Vent with name '" + args[0] + "'.");
                    error = true;
                }
                if (config.outerDoor == null)
                {
                    Echo("Could not find Door with name '" + args[1] + "'.");
                    error = true;
                }
                if (config.innerDoor == null)
                {
                    Echo("Could not find Door with name '" + args[2] + "'.");
                    error = true;
                }
                if (config.timer == null)
                {
                    Echo("Could not find Timer Block with name '" + args[3] + "'.");
                    error = true;
                }
                if (error)
                {
                    return;
                }

                // every thing fine

                config.State = OuterClosingEnter;
                _configs.Add(key, config);
                _lastKey      = key;
                _openPosition = Command.CloseOutside;
                UpdateStorage();

                Echo("Added new Air Lock Room.");
                PrintOpenInnerUsage();
                PrintOpenOuterUsage();

                // execute for initial setup
                _configs[key].State(key);
            }
            else
            {
                Configuration config = _configs[key];
                Echo("This Air Lock Room has already been saved and is ready to use.");
                PrintOpenInnerUsage();
                PrintOpenOuterUsage();
                GetLockRoom(key);
            }
        }
Beispiel #29
0
        void Main()
        {
            var blocks = new List <IMyTerminalBlock>();

            GridTerminalSystem.GetBlocksOfType <IMySensorBlock>(blocks);

            if (blocks.Count == 0)
            {
                throw new Exception();
            }

            var block = blocks[0] as IMySensorBlock;

            debug.Append("LeftExtend = ").Append(block.LeftExtend).AppendLine();
            debug.Append("RightExtend = ").Append(block.RightExtend).AppendLine();
            debug.Append("TopExtend = ").Append(block.TopExtend).AppendLine();
            debug.Append("BottomExtend = ").Append(block.BottomExtend).AppendLine();
            debug.Append("FrontExtend = ").Append(block.FrontExtend).AppendLine();
            debug.Append("BackExtend = ").Append(block.BackExtend).AppendLine();

            debug.Append("DetectPlayers = ").Append(block.DetectPlayers).AppendLine();
            debug.Append("DetectFloatingObjects = ").Append(block.DetectFloatingObjects).AppendLine();
            debug.Append("DetectSmallShips = ").Append(block.DetectSmallShips).AppendLine();
            debug.Append("DetectLargeShips = ").Append(block.DetectLargeShips).AppendLine();
            debug.Append("DetectStations = ").Append(block.DetectStations).AppendLine();
            debug.Append("DetectAsteroids = ").Append(block.DetectAsteroids).AppendLine();
            debug.Append("DetectOwner = ").Append(block.DetectOwner).AppendLine();
            debug.Append("DetectFriendly = ").Append(block.DetectFriendly).AppendLine();
            debug.Append("DetectNeutral = ").Append(block.DetectNeutral).AppendLine();
            debug.Append("DetectEnemy = ").Append(block.DetectEnemy).AppendLine();

            var properties = new List <ITerminalProperty>();

            block.GetProperties(properties);
            for (int i = 0; i < properties.Count; ++i)
            {
                var property = properties[i];
                debug.Append(property.Id);
                debug.Append(" (").Append(block.GetDefaultValue <float>(property.Id)).Append(") [");
                debug.Append(block.GetMininum <float>(property.Id)).Append(',').Append(block.GetMaximum <float>(property.Id)).Append("] : ");
                debug.Append(property.TypeName);
                if (i < properties.Count - 1)
                {
                    debug.Append(", ");
                }
                if (i % 10 == 9)
                {
                    debug.AppendLine();
                }
            }
            debug.AppendLine();

            var actions = new List <ITerminalAction>();

            block.GetActions(actions);
            debug.Append("Actions:").AppendLine();
            List <string> actionNames = new List <string>();

            for (int i = 0; i < actions.Count; ++i)
            {
                var action = actions[i];
                debug.Append(action.Id);
                actionNames.Add(action.Id);

                if (i < actions.Count - 1)
                {
                    debug.Append(", ");
                }
                if (i % 10 == 9)
                {
                    debug.AppendLine();
                }
            }

            for (int i = 0; i < actionNames.Count; ++i)
            {
                block.GetActionWithName(actionNames[i]);
            }

            HashSet <Sensors.Action> .Enumerator enumerator = Sensors.Action.GetEnumerator();
            while (enumerator.MoveNext())
            {
                block.GetActionWithName(enumerator.Current.Name);
            }

            Debug(debug.ToString());
            debug.Clear();
        }
        public void UpdateStatusPanels()
        {
            for (int key = 0; key < areaStatusPanels.Count; key++)
            {
                string           areaPrefix    = areaStatusPanels[key].CustomName.Substring(0, areaStatusPanels[key].CustomName.Length - areaStatusPanelName.Length);
                IMyShipConnector areaConnector = GridTerminalSystem.GetBlockWithName(areaPrefix + "Connector") as IMyShipConnector;
                StringBuilder    panelOut      = new StringBuilder();
                float            totalHydrogen = 0;
                float            totalOxygen   = 0;

                panelOut.Append(areaPrefix.Substring(0, areaPrefix.Length - 1).ToUpper());
                panelOut.Append("\n\n");

                if (areaConnector != null && areaConnector.Status == MyShipConnectorStatus.Connected && areaConnector.OtherConnector == craneConnector)
                {
                    panelOut.Append("ARM DOCKED\n\n");
                }
                else
                {
                    panelOut.Append("ARM NOT DOCKED\n\n");
                }

                List <IMyGasTank> hydrogenTanks = new List <IMyGasTank>();
                GridTerminalSystem.GetBlocksOfType(hydrogenTanks, hydrogenTank => hydrogenTank.CustomName.Contains(areaPrefix + "Pad Hydrogen"));
                if (hydrogenTanks.Count > 0)
                {
                    for (int hKey = 0; hKey < hydrogenTanks.Count; hKey++)
                    {
                        totalHydrogen += (float)hydrogenTanks[hKey].FilledRatio;
                    }

                    panelOut.Append(hydrogenTanks.Count.ToString());
                    panelOut.Append("x H2 | ");
                    panelOut.Append(Math.Floor((totalHydrogen / hydrogenTanks.Count) * 100).ToString("000.##"));
                    panelOut.Append("%\n");
                }
                else
                {
                    panelOut.Append("0x H2 | ERR!\n");
                }

                List <IMyGasTank> oxygenTanks = new List <IMyGasTank>();
                GridTerminalSystem.GetBlocksOfType(oxygenTanks, oxygenTank => oxygenTank.CustomName.Contains(areaPrefix + "Pad Oxygen"));
                if (oxygenTanks.Count > 0)
                {
                    for (int oKey = 0; oKey < oxygenTanks.Count; oKey++)
                    {
                        totalOxygen += (float)oxygenTanks[oKey].FilledRatio;
                    }

                    panelOut.Append(oxygenTanks.Count.ToString());
                    panelOut.Append("x O2 | ");
                    panelOut.Append(Math.Floor((totalOxygen / oxygenTanks.Count) * 100).ToString("000.##"));
                    panelOut.Append("%");
                }
                else
                {
                    panelOut.Append("0x O2 | ERR!");
                }

                areaStatusPanels[key].WriteText(panelOut, false);
            }
        }