Exemplo n.º 1
0
        List <T> GetBlocksInGroup <T>(string groupName) where T : class
        {
            var groups = new List <IMyBlockGroup>();

            GridTerminalSystem.GetBlockGroups(groups);

            for (int i = 0; i < groups.Count; i++)
            {
                if (groups[i].Name == groupName)
                {
                    var groupBlocks = new List <IMyTerminalBlock>();
                    var result      = new List <T>();

                    groups[i].GetBlocks(groupBlocks);
                    for (int t = 0; t < groupBlocks.Count; t++)
                    {
                        result.Add(groupBlocks[t] as T);
                    }

                    return(result);
                }
            }

            return(null);
        }
Exemplo n.º 2
0
        private void getGarages()
        {
            garages = new List <GarageDoor>();
            List <IMyBlockGroup> groups = new List <IMyBlockGroup>();

            GridTerminalSystem.GetBlockGroups(groups);

            for (int i = 0; i < groups.Count; i++)
            {
                //if we find a group that represents a garage
                if (groups[i].Name.ToLower().Contains("garage"))
                {
                    /* The groups that represent a garage should be named as follows:
                     * garage SHIPGRIDNAME
                     * Therefore we need to split the name of the group and use the second word
                     * in the groupname as the name for the garage
                     * */
                    String[] nameParts = groups[i].Name.Split(' ');
                    List <IMyAirtightHangarDoor> temp = new List <IMyAirtightHangarDoor>();
                    groups[i].GetBlocksOfType(temp);
                    if (temp.Count > 0)
                    {
                        garages.Add(new GarageDoor(nameParts[1], temp));
                    }
                }
            }
        }
Exemplo n.º 3
0
        private List <T> getBlocksFromGroup <T>(string tag, IMyCubeGrid CubeGrid = null) where T : IMyTerminalBlock
        {
            List <IMyBlockGroup> Groups = new List <IMyBlockGroup>();
            List <T>             Blocks = new List <T>();

            GridTerminalSystem.GetBlockGroups(Groups);
            for (int i_Groups = 0; i_Groups < Groups.Count; i_Groups++)
            {
                IMyBlockGroup Group = Groups[i_Groups];
                if (Group.Name.Contains(tag))
                {
                    for (int i_Blocks = 0; i_Blocks < Group.Blocks.Count; i_Blocks++)
                    {
                        IMyTerminalBlock Block = Group.Blocks[i_Blocks];
                        if (Block is T && (CubeGrid == null || Block.CubeGrid.Equals(CubeGrid)))
                        {
                            object newBlock = Block;
                            Blocks.Add((T)newBlock);
                        }
                    }
                }
            }

            return(Blocks);
        }
Exemplo n.º 4
0
public Program()
{
    DBG = GridTerminalSystem.GetBlockWithName("DBG") as IMyTextPanel;
    DBG.ShowPublicTextOnScreen();
    DBG.WritePublicText("Отладочная консоль\n", false);

    List <IMyTerminalBlock> blocks = new List <IMyTerminalBlock>();

    GridTerminalSystem.GetBlocksOfType <IMyLightingBlock>(blocks);

    initLight(blocks);         // настройка всех ламп и прожекторов

    // создать группу
    //IMyBlockGroup group = GridTerminalSystem.GetBlockGroupWithName( "Группа");


    // печать имён всех групп корабля
    List <IMyBlockGroup> groups = new List <IMyBlockGroup>();

    GridTerminalSystem.GetBlockGroups(groups);
    foreach (IMyBlockGroup tut in groups)
    {
        DBG.WritePublicText(tut.Name.ToString() + "\n", true);
    }

    Echo("Вывод в терминал программного блока");

    // разпознавание присутствия хозяина в кокпите
    cocpit = GridTerminalSystem.GetBlockWithName("Кабина") as IMyCockpit;
}         // программ
Exemplo n.º 5
0
private void updateContainers()
{
    GridTerminalSystem.GetBlocksOfType <IMyCargoContainer>(containers);
    if (filter_staticGrids)
    {
        /*containers = containers.Where(X => X.CubeGrid.ToString().Contains(ourGrid)).ToList();*/
        containers = containers.FindAll(delegate(IMyCargoContainer c)
        {
            if (c.CubeGrid.ToString().Contains("Grid_S_"))
            {
                return(false);
            }
            return(true);
        });
    }
    if (group_mode)
    {
        GridTerminalSystem.GetBlockGroups(groups);
        groups = groups.FindAll(delegate(IMyBlockGroup g)
        {
            List <IMyCargoContainer> g_containers = new List <IMyCargoContainer>();
            g.GetBlocksOfType <IMyCargoContainer>(g_containers);
            for (int i = 0; i < g_containers.Count; i++)
            {
                containers.Remove(g_containers[i]);
            }
            if (g_containers.Count > 0)
            {
                return(true);
            }
            return(false);
        });
    }
    containers.Sort(delegate(IMyCargoContainer x, IMyCargoContainer y)
    {
        if (x.CustomName == null && y.CustomName == null)
        {
            return(0);
        }
        else if (x.CustomName == null)
        {
            return(-1);
        }
        else if (y.CustomName == null)
        {
            return(1);
        }
        else
        {
            return(x.CustomName.CompareTo(y.CustomName));
        }
    });
    offset          = 0;
    totalContainers = containers.Count;
}
Exemplo n.º 6
0
        /// <summary>
        /// Returns list of blocks of a group.
        /// </summary>
        /// <param name="groupName">Name of block group.</param>
        /// <returns>List of blocks of <paramref name="groupName"/> or <see langword="null"/> if group not found.</returns>
        List <IMyTerminalBlock> GetBlockGroup(string groupName)
        {
            var groups = new List <IMyBlockGroup>();

            GridTerminalSystem.GetBlockGroups(groups);
            for (int i = 0; i < groups.Count; i++)
            {
                if (groups[i].Name.Equals(groupName))
                {
                    return(groups[i].Blocks);
                }
            }
            return(null);
        }
Exemplo n.º 7
0
public void Reload()
{
    Echo("Reloading...");
    // Clear
    Groups  = new Dictionary <string, Group>();
    Screens = new List <Screen>();
    // Check Groups
    var blockGroups = new List <IMyBlockGroup>();

    GridTerminalSystem.GetBlockGroups(blockGroups);
    for (var i = 0; i < blockGroups.Count; i++)
    {
        var screens = new List <IMyTextPanel>();
        blockGroups[i].GetBlocksOfType(screens);
        var group = new Group();
        if (screens.Count > 0)
        {
            group.Name         = blockGroups[i].Name;
            Groups[group.Name] = group;
        }
        for (var j = 0; j < screens.Count; j++)
        {
            group.Screens.Add(new Screen(screens[j]));
        }
    }
    // check screens
    var lcds = new List <IMyTextPanel>();

    GridTerminalSystem.GetBlocksOfType(lcds);
    for (var i = 0; i < lcds.Count; i++)
    {
        if (!GroupsContains(lcds[i]))
        {
            Screens.Add(new Screen(lcds[i]));
        }
    }
    // debug
    Echo("Groups : ");
    var l = Groups.Keys.ToList();

    for (var i = 0; i < l.Count; i++)
    {
        Echo(l[i]);
    }
    Echo("Screens : ");
    for (var i = 0; i < Screens.Count; i++)
    {
        Echo(Screens[i].TextPanel.CustomName);
    }
}
Exemplo n.º 8
0
        bool powerDownThrusters(string sFThrust)
        {
            List <IMyBlockGroup> groups = new List <IMyBlockGroup>(); GridTerminalSystem.GetBlockGroups(groups); for (int groupIndex = 0; groupIndex < groups.Count; groupIndex++)

            {
                if (groups[groupIndex].Name == sFThrust)
                {
                    List <IMyTerminalBlock> thrusters = null;
                    groups[groupIndex].GetBlocks(thrusters, localGridFilter);
                    return(powerDownThrusters(thrusters) > 0);
                }
            }
            return(false);
        }
Exemplo n.º 9
0
        public List <IMyTerminalBlock> GetBlocksOfGroup(string tag)
        {
            List <IMyTerminalBlock> Lights = new List <IMyTerminalBlock>();
            List <IMyBlockGroup>    Groups = new List <IMyBlockGroup>();

            GridTerminalSystem.GetBlockGroups(Groups, g => g.Name.Contains(tag));
            foreach (IMyBlockGroup Group in Groups)
            {
                List <IMyTerminalBlock> Buffer = new List <IMyTerminalBlock>();
                Group.GetBlocks(Buffer, x => x.CubeGrid.Equals(Me.CubeGrid) && x is IMyLightingBlock);
                Lights.AddRange(Buffer);
                Buffer.Clear();
            }

            return(Lights);
        }
Exemplo n.º 10
0
        void updateLcd(float level, int num, int num2, int num3)
        {
            List <IMyBlockGroup> groups = new List <IMyBlockGroup>();

            GridTerminalSystem.GetBlockGroups(groups);
            IMyTextPanel lcd;

            for (int i = 0; i < groups.Count; i++)
            {
                IMyBlockGroup group = groups[i];
                if (group.Name == panelGroup)
                {
                    List <IMyTerminalBlock> groupBlocks = new List <IMyTerminalBlock>();
                    group.GetBlocks(groupBlocks);
                    for (int j = 0; j < groupBlocks.Count; j++)
                    {
                        lcd = groupBlocks[j] as IMyTextPanel;
                        lcd.SetValue("FontSize", 1.7f);
                        lcd.ShowPublicTextOnScreen();
                        lcd.WritePublicText("Oxygen Production:\n");
                        if (state == on)
                        {
                            lcd.WritePublicText("  Activated", true);
                        }
                        else
                        {
                            lcd.WritePublicText("  Deactivated", true);
                        }

                        string minPerc = (float)((int)(minLevel * 10000)) / 100 + "%";
                        string maxPerc = (float)((int)(maxLevel * 10000)) / 100 + "%";
                        lcd.WritePublicText("  -  [" + minPerc + "~" + maxPerc + "]\n", true);


                        lcd.WritePublicText("OxygenTanks Level:\n", true);
                        lcd.WritePublicText("  " + (float)((int)(level * 10000)) / 100 + "%\n", true);
                        lcd.WritePublicText("OxygenTanks Count:\n", true);
                        lcd.WritePublicText("  " + num + "\n", true);
                        lcd.WritePublicText("OxygenGenerator Count:\n", true);
                        lcd.WritePublicText("  " + num2 + "\n", true);
                        lcd.WritePublicText("AirVent Count:\n", true);
                        lcd.WritePublicText("  " + num3, true);
                    }
                }
            }
        }
Exemplo n.º 11
0
        public Program()
        {
            _PanelTextSurface             = Me.GetSurface(0);
            _PanelTextSurface.ContentType = VRage.Game.GUI.TextPanel.ContentType.TEXT_AND_IMAGE;
            _PanelTextSurface.FontSize    = 2;
            _PanelTextSurface.Alignment   = VRage.Game.GUI.TextPanel.TextAlignment.CENTER;
            Runtime.UpdateFrequency       = UpdateFrequency.Update1;

            List <IMyBlockGroup> airlockGroups = new List <IMyBlockGroup>();

            GridTerminalSystem.GetBlockGroups(airlockGroups, (IMyBlockGroup blockGroup) => blockGroup.Name.ToLower().StartsWith("airlock"));

            foreach (IMyBlockGroup blockGroup in airlockGroups)
            {
                _AirLocks.Add(new AirLock(blockGroup));
            }
        }
Exemplo n.º 12
0
        public void Init()
        {
            List <IMyBlockGroup> tempList = new List <IMyBlockGroup>();

            GridTerminalSystem.GetBlockGroups(tempList, x => x.Name.Contains(groupTag));
            foreach (var group in tempList)
            {
                Fapdrive drive = new Fapdrive(group, sideATag, sideBTag);
                Echo($"Registering fapdrive with:\n{drive.driveRotors.Count} rotors and {drive.sideA.Count + drive.sideB.Count} containers");
                fapDrives.Add(drive);
            }

            controller = GridTerminalSystem.GetBlockWithName(shipControllerName) as IMyShipController;

            Echo($"Drives found: {fapDrives.Count}");
            init = true;
        }
Exemplo n.º 13
0
        void groupApplyAction(string sGroup, string sAction)
        {
            List <IMyBlockGroup> groups = new List <IMyBlockGroup>(); GridTerminalSystem.GetBlockGroups(groups); for (int groupIndex = 0; groupIndex < groups.Count; groupIndex++)

            {
                if (groups[groupIndex].Name == sGroup)
                {
                    List <IMyTerminalBlock> theBlocks = null;
                    groups[groupIndex].GetBlocks(theBlocks, (x1 => x1.CubeGrid == Me.CubeGrid));
                    ; for (int iIndex = 0; iIndex < theBlocks.Count; iIndex++)
                    {
                        theBlocks[iIndex].ApplyAction(sAction);
                    }
                    return;
                }
            }
            return;
        }
Exemplo n.º 14
0
        bool powerUpThrusters(string sFThrust, int iPower = 100, int iTypes = thrustAll)
        {
            if (iPower > 100)
            {
                iPower = 100;
            }
            List <IMyBlockGroup> groups = new List <IMyBlockGroup>();

            GridTerminalSystem.GetBlockGroups(groups);
            for (int groupIndex = 0; groupIndex < groups.Count; groupIndex++)
            {
                if (groups[groupIndex].Name == sFThrust)
                {
                    List <IMyTerminalBlock> thrusters = null;
                    groups[groupIndex].GetBlocks(thrusters, localGridFilter);
                    return(powerUpThrusters(thrusters, iPower, iTypes) > 0);
                }
            }
            return(false);
        }
Exemplo n.º 15
0
        public Program()
        {
            Runtime.UpdateFrequency = UpdateFrequency.Update1;

            #region serializer
            nameSerializer.AddValue("GravgunGroupTag", x => x, "[Gravgun]");

            string customDat = Me.CustomData;
            nameSerializer.FirstSerialization(ref customDat);
            Me.CustomData = customDat;
            nameSerializer.DeSerialize(Me.CustomData);
            #endregion

            var blockGroups = new List <IMyBlockGroup>();
            GridTerminalSystem.GetBlockGroups(blockGroups, x => x.Name.Contains(GravgunGroupTag));

            foreach (var blockGroup in blockGroups)
            {
                gravGuns.Add(new GravgunControl(blockGroup));
            }
        }
Exemplo n.º 16
0
        //METHOD: InitializeGroups
        private void InitializeGroups()
        {
            GeneralGetterList.Clear();
            _command_groups.Clear();
            ClearFoundBlocks();
            _time_since_last_refresh = 0;

            List <IMyBlockGroup> groups = new List <IMyBlockGroup>();

            GridTerminalSystem.GetBlockGroups(groups,
                                              group => System.Text.RegularExpressions.Regex.IsMatch(
                                                  group.Name,
                                                  COMMAND_GROUP_NAME_PATTERN,
                                                  System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                                              );

            foreach (IMyBlockGroup group in groups)
            {
                _command_groups.Add(new CommandGroup(group, this));
            }
        }
Exemplo n.º 17
0
        List <IMyTerminalBlock> findThrusters(string sGroup)
        {
            List <IMyTerminalBlock> lthrusters = new List <IMyTerminalBlock>();
            List <IMyBlockGroup>    groups     = new List <IMyBlockGroup>();

            GridTerminalSystem.GetBlockGroups(groups);
            for (int groupIndex = 0; groupIndex < groups.Count; groupIndex++)
            {
                if (groups[groupIndex].Name == sGroup)
                {
                    List <IMyTerminalBlock> thrusters = null;
                    groups[groupIndex].GetBlocks(thrusters, localGridFilter);
                    for (int thrusterIndex = 0; thrusterIndex < thrusters.Count; thrusterIndex++)
                    {
                        lthrusters.Add(thrusters[thrusterIndex]);
                    }
                    break;
                }
            }
            return(lthrusters);
        }
Exemplo n.º 18
0
        bool GrabBlockGroups()
        {
            sequenceGroups.Clear();
            cachedSequenceGroups.Clear();

            GridTerminalSystem.GetBlockGroups(sequenceGroups, x => x.Name.ToLower().Contains(salvoGroupNameTag.ToLower()));

            if (sequenceGroups.Count == 0)
            {
                Echo($"----------------------------------\nERROR: No groups containing the\n name tag '{salvoGroupNameTag}' were found");
                return(false);
            }

            //removes salvo groups that dont exist any more
            salvoGroups.RemoveAll(x => !sequenceGroups.Contains(x.ThisGroup));

            //Update existing salvo groups
            foreach (var group in salvoGroups)
            {
                group.GetBlocks();
            }

            //add groups that currently exist and are already initialized to a list
            foreach (var salvoGroup in salvoGroups)
            {
                cachedSequenceGroups.Add(salvoGroup.ThisGroup);
            }

            //Echo($"cachedSequenceGroups: {cachedSequenceGroups.Count}");

            foreach (var group in sequenceGroups)
            {
                if (!cachedSequenceGroups.Contains(group))
                {
                    salvoGroups.Add(new WeaponSalvoGroup(group, this));                     //add groups that now exist, but were not initialized
                }
            }
            return(true);
        }
        private List <IMyTerminalBlock> findBlocksByTag(string tag)
        {
            if (!findBlocksByTagCache.ContainsKey(tag))
            {
                List <IMyTerminalBlock> matches = new List <IMyTerminalBlock>();
                GridTerminalSystem.GetBlocksOfType <IMyTerminalBlock>(matches, (b => b.CustomName.Contains(tag)));

                List <IMyBlockGroup> groupMatches = new List <IMyBlockGroup>();
                GridTerminalSystem.GetBlockGroups(groupMatches, (g => g.Name.Contains(tag)));
                foreach (IMyBlockGroup group in groupMatches)
                {
                    List <IMyTerminalBlock> buffer = new List <IMyTerminalBlock>();
                    group.GetBlocksOfType <IMyTerminalBlock>(buffer, (b => !matches.Contains(b)));
                    matches.AddRange(buffer);
                    buffer.Clear();
                }

                findBlocksByTagCache.Add(tag, matches);
            }

            return(findBlocksByTagCache[tag]);
        }
Exemplo n.º 20
0
        void RefreshBlocks()
        {
            //Get an occupied ship controller to reference for orientation.
            GridTerminalSystem.GetBlocksOfType(controllers);
            foreach (IMyShipController control in controllers)
            {
                if (control.CanControlShip)
                {
                    mainControl = control;
                    if (control.IsUnderControl)
                    {
                        break;
                    }
                }
            }

            GridTerminalSystem.GetBlockGroups(enginesRaw, engine => engine.Name.Contains(engineTag));
            foreach (IMyBlockGroup engineRaw in enginesRaw)
            {
                engines.Add(new Engine(engineRaw));
            }
        }
Exemplo n.º 21
0
        public void Init()
        {
            List <IMyBlockGroup> gunGroups = new List <IMyBlockGroup>();

            GridTerminalSystem.GetBlockGroups(gunGroups, x => x.Name.Contains(GravgunGroupTag));
        }
Exemplo n.º 22
0
void Main(string arg)
{
    Echo(DateTime.Now.ToString("HH\\:mm\\:ss\\.fff"));

    //profileStart();
    _log.Clear();
    _debug.Clear();

    //
    batMax = batCur = batIn = batOut = otherBatIn = otherBatOut = 0;
    slrMax = slrCur = slrOut = slrPitchMax = slrPitchCur = 0;
    uint slrPnls      = 0;
    uint slrPitchPnls = 0;

    float tmpMax = 0;
    float tmpCur = 0;
    float tmpOut = 0;
    int   tagIdx;

    //
    Action <IMySolarPanel, bool> sumSolar = (IMySolarPanel slrPnl, bool useTagged) => {
        slrPnls += 1;
        slrMax  += (tmpMax = getSolarPanelMaximumPower(slrPnl));
        slrCur  += (tmpCur = Watt(slrPnl.MaxOutput));
        slrOut  += (tmpOut = Watt(slrPnl.CurrentOutput));
        if (useTagged)
        {
            slrPitchPnls += 1;
            slrPitchMax  += tmpMax;
            slrPitchCur  += tmpCur;
        }
    };
    Action <IMyBatteryBlock> sumBattery = (IMyBatteryBlock btyBlk) => {
        batIn  += Watt(btyBlk.CurrentInput);
        batOut += Watt(btyBlk.CurrentOutput);
        batCur += Watt(btyBlk.CurrentStoredPower);
        batMax += Watt(btyBlk.MaxStoredPower);
    };

    //profileStep("a2");
    IMyMotorStator  rtr;
    IMyBatteryBlock bb;
    IMySolarPanel   pnl;
    IMyTextPanel    tp;

    // Loop through the grid's block-list "only once" per program-run.
    GridTerminalSystem.GetBlocksOfType <IMyTerminalBlock>(blockList, blk => {
        if (blk.IsFunctional)
        {
            if (null != (pnl = blk as IMySolarPanel))
            {
                tagIdx = blk.CustomName.IndexOf(TAG_PREFIX);
                if (tagIdx > -1 && NameContains(blk, TAG_SOLARPANEL_IGNORE))
                {
                    // Ignore it
                }
                else if (tagIdx > -1 && NameContains(blk, TAG_SOLARPANEL_YAW))
                {
                    solarYaws.Add(pnl);
                }
                else
                {
                    sumSolar(pnl, (tagIdx > -1 && NameContains(blk, TAG_SOLARPANEL_PITCH)));
                }
            }
            else if (null != (bb = blk as IMyBatteryBlock))
            {
                if (SameGrid(Me, blk))
                {
                    sumBattery(bb);
                    batteries.Add(bb);
                }
                else
                {
                    otherBatIn  += Watt(bb.CurrentInput);
                    otherBatOut += Watt(bb.CurrentOutput);
                }
            }
            else if (null != (rtr = blk as IMyMotorStator))
            {
                if (blk.CustomName.IndexOf(TAG_PREFIX) > -1)
                {
                    if (NameContains(blk, TAG_ROTOR_YAW))
                    {
                        rotorYaw.Add(rtr);
                    }
                    else if (NameContains(blk, TAG_ROTOR_PITCH_LEFT))
                    {
                        rotorPitchL.Add(rtr);
                    }
                    else if (NameContains(blk, TAG_ROTOR_PITCH_RIGHT))
                    {
                        rotorPitchR.Add(rtr);
                    }
                }
            }
            else if (null != (tp = blk as IMyTextPanel))
            {
                if (NameContains(blk, TAG_LCDPANEL_INFO))
                {
                    lcdPanel.Add(tp);
                }
                else if (NameContains(blk, TAG_LCDPANEL_IMAGE))
                {
                    lcdImage.Add(tp);
                }
            }
        }
        return(false);        // Do not add any blocks to `blockList`, as we do not use it anyway.
    });
    //profileStep("a3");

    // Simple sanity check
    bool allOk = true;

    if (solarYaws.Count != 1)
    {
        allOk = false;
        Echo("ERROR: No exact '" + TAG_SOLARPANEL_YAW + "' solar-panel found!");
    }
    else
    {
        solarYaw = solarYaws[0];
    }
    solarYaws.Clear();
    if (rotorYaw.Count <= 0)
    {
        allOk = false;
        Echo("ERROR: No '" + TAG_ROTOR_YAW + "' rotor found!");
    }
    if (!allOk)
    {
        return;
    }
    if (rotorPitchL.Count <= 0 && rotorPitchR.Count <= 0)
    {
        //allOk = false;
        Echo("WARNING: No '" + TAG_ROTOR_PITCH_LEFT + "' nor '" + TAG_ROTOR_PITCH_RIGHT + "' rotors found!");
    }

    memory.load(this);

    if (arg == "reset")
    {
        Storage = "";
        SetYawSpeed(0);
        UpdatePitchAngle(0);
        powerHistory.clear();
        return;
    }

    // If no explicit named 'PITCH' solar-panels, then use all that was detected
    if (slrPitchPnls <= 0)
    {
        slrPitchMax = slrMax;
        slrPitchCur = slrCur;
    }

    //profileStep("a4");

    bool hasDayLight = false;

    if (slrPitchMax > 0f)
    {
        hasDayLight = (slrPitchCur / slrPitchMax > 0.8f);
    }
    if (hasDayLight != memory.getBool("hasDayLight", !hasDayLight))
    {
        const string ON  = "OnOff_On";
        const string OFF = "OnOff_Off";

        GridTerminalSystem.GetBlocksOfType <IMyTerminalBlock>(blockList, blk => {
            if (NameContains(blk, TAG_DAYLIGHT_ENABLE))
            {
                blk.ApplyAction(hasDayLight ? ON : OFF);
            }
            else if (NameContains(blk, TAG_DAYLIGHT_DISABLE))
            {
                blk.ApplyAction(!hasDayLight ? ON : OFF);
            }
            return(false);
        });

        List <IMyBlockGroup>    blkGrps = new List <IMyBlockGroup>();
        List <IMyTerminalBlock> blks    = new List <IMyTerminalBlock>();
        GridTerminalSystem.GetBlockGroups(blkGrps, x => x.Name.Contains(TAG_DAYLIGHT_ENABLE));
        blkGrps.ForEach(g => {
            g.GetBlocks(blks);
            blks.ForEach(blk => blk.ApplyAction(hasDayLight ? ON : OFF));
        });
        GridTerminalSystem.GetBlockGroups(blkGrps, x => x.Name.Contains(TAG_DAYLIGHT_DISABLE));
        blkGrps.ForEach(g => {
            g.GetBlocks(blks);
            blks.ForEach(blk => blk.ApplyAction(!hasDayLight ? ON : OFF));
        });

        memory.setBool("hasDayLight", hasDayLight);
    }

    //
    float slrYawMax = getSolarPanelMaximumPower(solarYaw);
    float slrYawCur = solarYaw.MaxOutput * 1000000f;

    float factor      = (slrYawMax > 0 ? slrYawCur / slrYawMax : 0f); // avoid division-by-zero
    float yawAlignPct = (1f - factor);
    float multiply    = 1 + MyMath.FastSin(factor);
    float yawSpeed    = Math.Min(factor * multiply, 1.0f) * (YAW_ROTATE_ANTICLOCKWISE ? -1f : 1f);

    Debug("YawFactor=" + factor);
    Debug("YawSpeed=" + yawSpeed);
    if (Math.Abs(yawSpeed) < 0.01f)
    {
        yawSpeed = 0;
    }

    SetYawSpeed(yawSpeed);
    //profileStep("a5");

    //
    float pitchAlignPct    = (slrPitchMax > 0 ? (slrPitchCur / slrPitchMax) : 1f);  // avoid division-by-zero
    float pitchWantedAngle = memory.getFloat("pitchWantedAngle", 0f);

    // If yaw alignment less than 80% optimal, then reset pitch.
    if (yawAlignPct < 0.8f)
    {
        pitchWantedAngle = 0f;
        pitchState       = 0;
    }
    //profileStep("a5b");

    float pitchAnglePrecision = UpdatePitchAngle(MathHelper.ToRadians(pitchWantedAngle), true);

    //profileStep("a6");

    if (pitchAnglePrecision > 0.99f)
    {
        float pitchPrevAngle = pitchWantedAngle;

        if (pitchAlignPct < 0.01f)
        {
            pitchState       = 0;
            pitchWantedAngle = 0f;
            powerHistory.clear();
        }
        else if (yawAlignPct > 0.85f)
        {
            /*
             *      float newAngle = Math.Max(1f, 5f * (1f - pitchAlignPct));
             *      switch (pitchState++) {
             *      case 0: // Initiate "search"
             *              pitchSearchAngles.Enqueue(Math.Max(-90f, pitchWantedAngle - newAngle));
             *              pitchSearchAngles.Enqueue(Math.Min( 90f, pitchWantedAngle + newAngle));
             *              pitchWantedAngle = pitchSearchAngles.Dequeue();
             *              break;
             *      case 1:
             *              pitchWantedAngle = pitchSearchAngles.Dequeue();
             *              break;
             *      case 2:
             *              pitchWantedAngle = powerHistory.getBestAngle();
             *              pitchState = 0;
             *              break;
             *      }
             */
            switch (pitchState++)
            {
            case 0:             // Initiate "search"
                pitchWantedAngle = powerHistory.getBestAngle();
                pitchSearchAngles.Enqueue(Math.Max(-90f, pitchWantedAngle - 2f));
                pitchSearchAngles.Enqueue(Math.Min(90f, pitchWantedAngle + 2f));
                break;

            case 1:
                pitchWantedAngle = pitchSearchAngles.Dequeue();
                break;

            case 2:
                pitchWantedAngle = pitchSearchAngles.Dequeue();
                break;

            case 3:
                pitchWantedAngle = powerHistory.getBestAngle();
                pitchSearchAngles.Enqueue(Math.Max(-90f, pitchWantedAngle - 1f));
                pitchSearchAngles.Enqueue(Math.Min(90f, pitchWantedAngle + 1f));
                pitchState = 1;
                break;
            }
        }

        powerHistory.append(pitchPrevAngle, slrPitchCur);

        memory.setInt("pitchState", pitchState);
    }

    UpdatePitchAngle(MathHelper.ToRadians(pitchWantedAngle));

    memory.setFloat("pitchWantedAngle", pitchWantedAngle);

    Debug("pitchState=" + pitchState);

    // Batteries discharge/recharge management
    if (true)
    {
        bool allRecharging  = true;
        bool allDischarging = true;
        batteries.ForEach(b => {
            if (b.Enabled)
            {
                allRecharging  &= b.OnlyRecharge;
                allDischarging &= b.OnlyDischarge;
            }
        });

        bool change      = false;
        bool doRecharge  = false;
        bool doDischarge = false;
        if (allDischarging && slrCur > batOut)
        {
            change = doRecharge = true;
            //} else if (allRecharging && ((slrCur - batIn)/slrCur > 0.5f)) {
        }
        else if (allRecharging && batIn < slrCur * 0.1f)
        {
            change = doDischarge = true;
        }
        if (change)
        {
            batteries.ForEach(b => {
                if (b.Enabled)
                {
                    if (doRecharge != b.OnlyRecharge)
                    {
                        b.ApplyAction("Recharge");
                    }
                    if (doDischarge != b.OnlyDischarge)
                    {
                        b.ApplyAction("Discharge");
                    }
                }
            });
        }
    }

    //
    //profileStep("a7");
    memory.save(this);

    //
    //profileStep("a8");
    Log("Batteries: " + powerAsString(batCur, 3) + "h of " + powerAsString(batMax, 3) + "h");
    Log("    Grid In/Out: +" + powerAsString(batIn, 3) + " / -" + powerAsString(batOut, 3));
    Log("  Other In/Out: +" + powerAsString(otherBatIn, 3) + " / -" + powerAsString(otherBatOut, 3));
    Log("SolarPower: " + powerAsString(slrOut, 3) + " of " + powerAsString(slrCur, 3));
    Log("  Yaw-rotation is: " + (YAW_ROTATE_ANTICLOCKWISE ? "Anti-clockwise" : "Clockwise"));
    Log("  Alignment yaw : " + (yawAlignPct * 100f).ToString("N1") + "% (" + powerAsString(slrYawCur) + ")");
    Log("  Alignment pitch: " + (pitchAlignPct * 100f).ToString("N1") + "% (" + powerAsString(slrPitchCur) + ")");
    if (slrPitchPnls > 0)
    {
        Log("  Using " + slrPitchPnls + " tagged panel" + (slrPitchPnls != 1 ? "s" : "") + " for pitch alignment");
    }
    Log("  SolarPanels optimum max: " + powerAsString(slrMax, 3));

    lcdImage.ForEach(p => {
        p.ClearImagesFromSelection();
        int pct = (int)(pitchAlignPct * 100);
        pct     = pct - (pct % 5);
        p.AddImageToSelection(string.Format("Incline {0}", pct.ToString("D3")));
    });
    lcdImage.Clear();

    //
    if (debugOn)
    {
        Log("\n<<-- DebugInfo -->>");
        Log(_debug.ToString(), false);
        _debug.Clear();
    }
    string txt = _log.ToString();

    _log.Clear();
    //-- Echo is now nerfed, as it causes huge FPS-drops apparently.
    //Echo(txt);

    //profileStep("a9");

    // Clean up
    solarYaw = null;
    rotorYaw.Clear();
    rotorPitchL.Clear();
    rotorPitchR.Clear();
    batteries.Clear();
    //profileStep("a0");

    //txt = profileEnd();

    lcdPanel.ForEach(p => p.WritePublicText(txt));
    lcdPanel.Clear();
}
Exemplo n.º 23
0
        public void Main(string argument)
        {
            int index = 0;

            string[] temp = Me.CustomData.TrimEnd('\n').Split(',', '\n');
            GridTerminalSystem.GetBlockGroups(abrazors, abrazor => abrazor.Name.Contains(abrazorgrouptag));
            foreach (IMyBlockGroup abrazor in abrazors)
            {
                if (cannonActive.Count <= index)
                {
                    cannonActive.Insert(index, false);
                }
                if (step.Count <= index)
                {
                    step.Insert(index, 0);
                }

                abrazor.GetBlocksOfType(fireIndicators);
                foreach (IMyUserControllableGun fireIndicator in fireIndicators)
                {
                    if (fireIndicator.IsShooting)
                    {
                        cannonActive[index] = true;
                        break;
                    }
                    else
                    {
                        cannonActive[index] = false;
                    }
                }

                if (fireIndicators.Count == 0)
                {
                    abrazor.GetBlocksOfType(endDrivers, endDriver => endDriver.CustomName.Contains("Rotor End"));
                    foreach (IMyMotorStator endDriver in endDrivers)
                    {
                        for (int i = 0; i < temp.Length / 2; i++)
                        {
                            if (temp[i * 2 + 1] == endDriver.CustomName.Substring(0, 4))
                            {
                                if (temp[i * 2] == "run")
                                {
                                    cannonActive[index] = true;
                                }
                                if (temp[i * 2] == "stop")
                                {
                                    cannonActive[index] = false;
                                }
                            }
                        }
                    }
                }

                if (cannonActive[index] || step[index] == 0)
                {
                    abrazor.GetBlocksOfType(endDrivers, endDriver => endDriver.CustomName.Contains("Rotor End"));
                    abrazor.GetBlocksOfType(cannonDrivers);
                    abrazor.GetBlocksOfType(recoilDampers);
                    CycleCannon(cannonDrivers, endDrivers, recoilDampers, step[index], cannonActive[index], massAmount);
                }
                if (cannonActive[index] && step[index] == 0)
                {
                    step[index] = 1;
                }
                else
                {
                    step[index] = 0;
                }

                index = index + 1;
            }
        }
Exemplo n.º 24
0
        void Main(string argument)
        {
            List <IMyBlockGroup> groups = new List <IMyBlockGroup>();

            GridTerminalSystem.GetBlockGroups(groups);

            int   num      = 0;
            int   num2     = 0;
            int   num3     = 0;
            float sum      = 0;
            float newLevel = 0;

            for (int i = 0; i < groups.Count; i++)
            {
                IMyBlockGroup group = groups[i];
                if (group.Name == tankGroup)
                {
                    List <IMyTerminalBlock> groupBlocks = new List <IMyTerminalBlock>();
                    group.GetBlocks(groupBlocks);
                    for (int j = 0; j < groupBlocks.Count; j++)
                    {
                        IMyGasTank tank = groupBlocks[j] as IMyGasTank;
                        num++;
                        sum += (float)tank.FilledRatio;
                    }
                }
            }

            if (num == 0)
            {
                newLevel = 0;
            }
            else
            {
                newLevel = sum / num;
            }

            if (state == none || (state == on && newLevel >= maxLevel) || (state == off && newLevel <= minLevel))
            {
                if (newLevel >= maxLevel)
                {
                    state = off;
                }
                else
                {
                    state = on;
                }
            }

            for (int i = 0; i < groups.Count; i++)
            {
                IMyBlockGroup group = groups[i];
                if (group.Name == generatorGroup)
                {
                    List <IMyTerminalBlock> groupBlocks = new List <IMyTerminalBlock>();
                    group.GetBlocks(groupBlocks);
                    for (int j = 0; j < groupBlocks.Count; j++)
                    {
                        IMyFunctionalBlock gen = groupBlocks[j] as IMyFunctionalBlock;
                        gen.Enabled = (state == on);
                        num2++;
                    }
                }
            }
            for (int i = 0; i < groups.Count; i++)
            {
                IMyBlockGroup group = groups[i];
                if (group.Name == ventGroup)
                {
                    List <IMyTerminalBlock> groupBlocks = new List <IMyTerminalBlock>();
                    group.GetBlocks(groupBlocks);
                    for (int j = 0; j < groupBlocks.Count; j++)
                    {
                        IMyAirVent vent = groupBlocks[j] as IMyAirVent;
                        vent.ApplyAction("Depressurize_On");
                        vent.Enabled = (state == on);
                        num3++;
                    }
                }
            }

            updateLcd(newLevel, num, num2, num3);
        }
Exemplo n.º 25
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();
        }
Exemplo n.º 26
0
 public void Main(string argument)
 {
     try
     {
         argument = argument.ToLower();
         Echo("Called with '" + argument + "'");
         Echo("Scanning for groups");
         List <IMyBlockGroup> blockGroups = new List <IMyBlockGroup>();
         GridTerminalSystem.GetBlockGroups(blockGroups);
         Echo("Found " + blockGroups.Count + " groups");
         for (int g = 0; g < blockGroups.Count; g++)
         {
             if (blockGroups[g].Name.Contains(groupTag))
             {
                 var blockGroup = blockGroups[g];
                 if (!panelSets.ContainsKey(blockGroup.Name))
                 {
                     var blocks = new List <IMyTextPanel>();
                     blockGroup.GetBlocksOfType(blocks);
                     if (blocks.Count > 0)
                     {
                         bool configured = false;
                         List <ScrollablePanel> panels = new List <ScrollablePanel>();
                         for (int i = 0; i < blocks.Count; i++)
                         {
                             var block     = blocks[i];
                             var panelData = new ScrollablePanel(blocks[i]);
                             if (panelData.configured == true)
                             {
                                 configured = true;
                             }
                             panels.Add(panelData);
                         }
                         if (configured)
                         {
                             panels.Sort();
                             panelSets.Add(blockGroup.Name, panels);
                         }
                         else
                         {
                             for (int i = 0; i < panels.Count; i++)
                             {
                                 var panelData = panels[i];
                                 if (panelData.index == 0)
                                 {
                                     panelData.block.WritePublicText(string.Join("", blockGroup.Name, " Auto id#", i + 1));
                                     panelData.index = i + 1;
                                 }
                                 else
                                 {
                                     panelData.block.WritePublicText(string.Join("", blockGroup.Name, " id#", panelData.index));
                                 }
                                 panelData.block.CustomName = panelData.block.GetPublicText();
                                 panelData.block.ShowPublicTextOnScreen();
                                 panelData.block.SetValueFloat("FontSize", 1f);
                                 panelData.write();
                             }
                         }
                     }
                 }
             }
         }
         Echo("Going to update " + panelSets.Count + " groups");
         for (int i = 0; i < panelSets.Count; i++)
         {
         }
     }
     catch (System.Exception ex)
     {
         Echo("I Crashed:\n");
         Echo(ex.Message + "\n");
         Echo(ex.StackTrace + "\n");
     }
 }
Exemplo n.º 27
0
        public IEnumerator <bool> Init()
        {
            control = GridTerminalSystem.GetBlockWithName(controllerName) as IMyShipController;
            if (control == null)
            {
                Echo($"no shipcontroller found with name {controllerName}!");
                yield return(false);
            }

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

            GridTerminalSystem.GetBlocksOfType(lcds, x => x.CustomName.Contains(lcdStatusTag));
            statusWriter = new StatusWriter(lcds);


            targetTracker = new EntityTracking_Module(GTSUtils, control, null);
            foreach (var tracker in targetTracker.ObjectTrackers)
            {
                var turretTracker = tracker as TurretTracking;
                if (turretTracker != null)
                {
                    turretTracker.earlyReturn = true;
                }
            }
            targetTracker.onEntityDetected += OnEntityDetected;

            gridCannonTargeting = new PhysicsTargeting(control, ingameTime, maxProjectileVel);
            gridCannonTargeting.onRoutineFinish += OnTargetSolvedRotor;
            gridCannonTargeting.onRoutineFail   += OnTargetingFailRotor;
            gridCannonTargeting.onTargetTimeout += OnTargetTimeoutRotor;

            missileCannonTargeting = new PhysicsTargeting(control, ingameTime, maxMissileVel);
            missileCannonTargeting.onRoutineFinish += OnTargetSolvedMissile;
            missileCannonTargeting.onRoutineFail   += OnTargetingFailMissile;
            missileCannonTargeting.onTargetTimeout += OnTargetTimeoutMissile;
            missileCannonTargeting.IgnoreGravity    = true;
            missileCannonTargeting.ForwardAccel     = maxMissileAccel;

            basicTargeting = new QuarticTargeting(Vector3D.Zero, Vector3D.Zero, maxGatlingBulletVel);

            switch (groupType)
            {
            case "BlockGroup":
                List <IMyBlockGroup> groups = new List <IMyBlockGroup>();
                GridTerminalSystem.GetBlockGroups(groups, x => x.Name.Contains(rotorTurretGroupTag));
                foreach (var group in groups)
                {
                    AddRotorTurret(group);
                    yield return(true);
                }
                groups.Clear();
                GridTerminalSystem.GetBlockGroups(groups, x => x.Name.Contains(gatlingTurretGroupTag));
                foreach (var group in groups)
                {
                    AddGatlingTurret(group);
                    yield return(true);
                }
                groups.Clear();
                GridTerminalSystem.GetBlockGroups(groups, x => x.Name.Contains(missileTurretGroupTag));
                foreach (var group in groups)
                {
                    AddMissileTurret(group);
                    yield return(true);
                }
                break;

            case "NameTag":
                List <IMyMotorStator> rotors = new List <IMyMotorStator>();
                GridTerminalSystem.GetBlocksOfType(rotors, x => x.CustomName.Contains(rotorTurretGroupTag));
                foreach (var stator in rotors)
                {
                    AddRotorTurret(stator);
                    yield return(true);
                }
                rotors.Clear();
                GridTerminalSystem.GetBlocksOfType(rotors, x => x.CustomName.Contains(gatlingTurretGroupTag));
                foreach (var stator in rotors)
                {
                    AddGatlingTurret(stator);
                    yield return(true);
                }
                rotors.Clear();
                GridTerminalSystem.GetBlocksOfType(rotors, x => x.CustomName.Contains(missileTurretGroupTag));
                foreach (var stator in rotors)
                {
                    AddMissileTurret(stator);
                    yield return(true);
                }
                break;

            case "Any":
                List <IMyBlockGroup> groupsA = new List <IMyBlockGroup>();
                GridTerminalSystem.GetBlockGroups(groupsA, x => x.Name.Contains(rotorTurretGroupTag));
                foreach (var group in groupsA)
                {
                    AddRotorTurret(group);
                    yield return(true);
                }
                groupsA.Clear();
                GridTerminalSystem.GetBlockGroups(groupsA, x => x.Name.Contains(gatlingTurretGroupTag));
                foreach (var group in groupsA)
                {
                    AddGatlingTurret(group);
                    yield return(true);
                }
                groupsA.Clear();
                GridTerminalSystem.GetBlockGroups(groupsA, x => x.Name.Contains(missileTurretGroupTag));
                foreach (var group in groupsA)
                {
                    AddMissileTurret(group);
                    yield return(true);
                }

                List <IMyMotorStator> rotorsA = new List <IMyMotorStator>();
                GridTerminalSystem.GetBlocksOfType(rotorsA, x => x.CustomName.Contains(rotorTurretGroupTag));
                foreach (var stator in rotorsA)
                {
                    AddRotorTurret(stator);
                    yield return(true);
                }
                rotorsA.Clear();
                GridTerminalSystem.GetBlocksOfType(rotorsA, x => x.CustomName.Contains(gatlingTurretGroupTag));
                foreach (var stator in rotorsA)
                {
                    AddGatlingTurret(stator);
                    yield return(true);
                }
                rotorsA.Clear();
                GridTerminalSystem.GetBlocksOfType(rotorsA, x => x.CustomName.Contains(missileTurretGroupTag));
                foreach (var stator in rotorsA)
                {
                    AddMissileTurret(stator);
                    yield return(true);
                }
                break;
            }

            statusWriter.UpdateCannonCount(rotorTurretGroups.Count, 0, 0);
            initialized = true;
        }
Exemplo n.º 28
0
        void RefreshSolarTrackerList()
        {
            solarTrackers.Clear();
            var groups = new List <IMyBlockGroup>();

            GridTerminalSystem.GetBlockGroups(groups);

            foreach (IMyBlockGroup group in groups)
            {
                if (!group.Name.Contains(nameTag))
                {
                    continue;
                }

                List <IMySolarPanel> solarPanels = new List <IMySolarPanel>();
                group.GetBlocksOfType <IMySolarPanel>(solarPanels);
                Echo("Group " + group.Name + ":");
                if (solarPanels.Count == 0)
                {
                    Echo("Contains no solar panel");
                    continue;
                }

                List <IMyMotorStator> rotors = new List <IMyMotorStator>();
                group.GetBlocksOfType <IMyMotorStator>(rotors);
                IMyMotorStator rotorAzimuth     = null;
                IMyMotorStator rotorInclination = null;
                foreach (IMyMotorStator rotor in rotors)
                {
                    if (rotor.CustomName.Contains("Azimuth") ||
                        rotor.CustomName.Contains("Phi"))
                    {
                        if (rotor.CubeGrid == Me.CubeGrid)
                        {
                            rotorAzimuth = rotor;
                        }
                        else
                        {
                            Echo("Rotor for azimuth \""
                                 + rotor.CustomName
                                 + "\" is in a different grid");
                        }
                    }
                    else if (rotor.CustomName.Contains("Inclination") ||
                             rotor.CustomName.Contains("Theta"))
                    {
                        rotorInclination = rotor;
                    }
                }
                if (rotorAzimuth == null)
                {
                    Echo("Contains no Azimuth/Phi rotor");
                    continue;
                }
                if (rotorInclination == null)
                {
                    Echo("Contains no Inclination/Theta rotor");
                    continue;
                }

                List <IMyTextPanel> textPanels = new List <IMyTextPanel>();
                group.GetBlocksOfType <IMyTextPanel>(textPanels);
                IMyTextPanel textPanel = null;
                if (textPanels.Count > 0)
                {
                    textPanel = textPanels[0];
                }

                solarTrackers.Add(
                    new SolarTracker(
                        solarPanels[0],
                        rotorInclination,
                        rotorAzimuth,
                        textPanel
                        )
                    );

                Echo("Is a valid solar tracker");
            }
        }
Exemplo n.º 29
0
        void Main(string args)
        {
            debug("BEGIN");
            if (args.Trim().Length > 0)
            {
                GROUP_TAG = args;
            }

            debug("Groupname: " + GROUP_TAG);

            List <IMyTerminalBlock> Blocks = new List <IMyTerminalBlock>();

            GridTerminalSystem.GetBlocksOfType <IMyRemoteControl>(Blocks, (x => x.IsWorking && x.CubeGrid.Equals(Me.CubeGrid)));
            if (Blocks.Count > 0)
            {
                IMyRemoteControl RC = Blocks[0] as IMyRemoteControl;
                debug("Using Remotecontrol: " + RC.CustomName);
                List <IMyBlockGroup> Groups = new List <IMyBlockGroup>();
                GridTerminalSystem.GetBlockGroups(Groups);
                Blocks.Clear();
                for (int i = 0; i < Groups.Count; i++)
                {
                    if (Groups[i].Name.Contains(GROUP_TAG))
                    {
                        for (int j = 0; j < Groups[i].Blocks.Count; j++)
                        {
                            if (
                                ((Groups[i].Blocks[j] is IMyRadioAntenna) || (Groups[i].Blocks[j] is IMyBeacon)) &&
                                Groups[i].Blocks[j].IsFunctional &&
                                Groups[i].Blocks[j].CubeGrid.Equals(Me.CubeGrid)
                                )
                            {
                                Blocks.Add(Groups[i].Blocks[j]);
                            }
                        }
                    }
                }

                Vector3D PlayerPos;
                Vector3D PbPos = RC.GetPosition();
                RC.GetNearestPlayer(out PlayerPos);
                debug("Nearest Player: (" + String.Format("{0:0}", Vector3D.Distance(PlayerPos, PbPos)) + " m)" + PlayerPos.ToString());
                debug("Functional Antennas/Beacons: " + Blocks.Count.ToString());
                for (int i = 0; i < Blocks.Count; i++)
                {
                    IMyTerminalBlock RA = Blocks[i] as IMyTerminalBlock;
                    int    d_pos        = RA.CustomName.IndexOf("DEBUG");
                    string d_name       = RA.CustomName.Trim();
                    if (d_pos > -1)
                    {
                        d_name = RA.CustomName.Substring(0, d_pos).Trim();
                        RA.SetCustomName(d_name);
                    }

                    double radius = 0.0;
                    if (RA is IMyRadioAntenna)
                    {
                        radius = Convert.ToDouble((RA as IMyRadioAntenna).Radius);
                    }
                    else if (RA is IMyBeacon)
                    {
                        radius = Convert.ToDouble((RA as IMyBeacon).Radius);
                    }

                    double cutOffPoint = radius * CUT_OFF_FACTOR;
                    double distance    = Vector3D.Distance(PlayerPos, PbPos);
                    string info        = "% (radius: " + String.Format("{0:0}", radius) + " m; cut-off point: " + String.Format("{0:0}", cutOffPoint) + " m; distance: " + String.Format("{0:0}", distance) + " m)";
                    if (distance < cutOffPoint)
                    {
                        info = "Enable: " + info;
                        //  RA.ApplyAction("OnOff_On");
                    }
                    else
                    {
                        info = "Disable '" + info;
                        //  RA.ApplyAction("OnOff_Off");
                    }
                    Echo(info.Replace("%", RA.CustomName));

                    if (DEBUG)
                    {
                        d_pos  = RA.CustomName.IndexOf("DEBUG");
                        d_name = RA.CustomName.Trim();
                        if (d_pos > -1)
                        {
                            d_name = RA.CustomName.Substring(0, d_pos).Trim();
                        }
                        RA.SetCustomName(d_name + " DEBUG: " + info.Replace("%", ""));
                    }
                }
            }
            else
            {
                debug("Remote Control not found.");
            }
            debug("END");
        }