Beispiel #1
0
 public void setSound(IMySoundBlock speaker, bool value)
 {
     speakerGroup.GetBlocksOfType <IMySoundBlock>(speakerList);
     speaker.SelectedSound = soundName;
     speaker.LoopPeriod    = loopTime;
     if (value)
     {
         if (endLoop == null)
         {
             ITerminalAction action;
             action = speaker.GetActionWithName("OnOff_On");
             action.Apply(speaker);
             endLoop = DateTime.Now.AddSeconds(loopTime);
             speaker.Play();
         }
         else
         {
             if (endLoop <= DateTime.Now)
             {
                 ITerminalAction action;
                 action = speaker.GetActionWithName("OnOff_On");
                 action.Apply(speaker);
                 endLoop = DateTime.Now;
                 speaker.Play();
             }
         }
     }
     else
     {
         endLoop = null;
         speaker.Stop();
     }
 }
Beispiel #2
0
 public void setSound(IMySoundBlock speaker, bool value)
 {
     speaker.SelectedSound = "Alert 1";
     speaker.LoopPeriod    = soundLength;
     if (value)
     {
         if (alarmStarted == null)
         {
             ITerminalAction action;
             action = speaker.GetActionWithName("OnOff_On");
             action.Apply(speaker);
             alarmStarted = DateTime.Now;
             speaker.Play();
         }
         else
         {
             TimeSpan delta = DateTime.Now.Subtract(alarmStarted.Value);   // If the warning time has elapsed, start the welders
             if (delta.TotalSeconds > (soundLength - .9))
             {
                 ITerminalAction action;
                 action = speaker.GetActionWithName("OnOff_On");
                 action.Apply(speaker);
                 alarmStarted = DateTime.Now;
                 speaker.Play();
             }
         }
     }
     else
     {
         alarmStarted = null;
         speaker.Stop();
     }
 }
 public void play()
 {
     if (soundBlock != null)
     {
         soundBlock.Play();
     }
 }
 // TODO: Workaround for sounds being distorted when calling IMySoundBlock.Play() on a block which is already playing.
 // https://support.keenswh.com/spaceengineers/general/topic/improvements-to-imysoundblock-interface
 public static void PlaySound(this IMySoundBlock soundBlock, String sound)
 {
     if (soundBlock.SelectedSound != sound)
     {
         soundBlock.SelectedSound = sound;
         soundBlock.Play();
     }
 }
 protected override void Enable()
 {
     if (soundBlock != null)
     {
         soundBlock.Enabled = true;
         soundBlock.Play();
     }
 }
Beispiel #6
0
 private void UpdateFurnaceState()
 {
     if (furnaceDoor == null)
     {
         return;
     }
     if (furnaceState != FurnaceState.Working && furnaceDoor.Status == DoorStatus.Open)
     {
         var grids = FindGridsInsideFurnace();
         ChangeFurnaceState(grids.Count == 0 ? FurnaceState.Waiting : FurnaceState.LoadedUp);
     }
     else if (furnaceDoor.Status == DoorStatus.Closed)
     {
         if (furnaceState == FurnaceState.Working)
         {
             if (furnaceWorkingCountdown == 0)
             {
                 SetFurnaceDoorsEnabled(true);
                 ChangeFurnaceState(FurnaceState.Waiting);
                 speaker.Stop();
                 furnaceOutput.MoveAllContentsTo(output);
                 foreach (var spotlight in furnaceSpotlights)
                 {
                     spotlight.Intensity = 1.0f;
                 }
             }
             else
             {
                 furnaceWorkingCountdown--;
             }
         }
         else
         {
             var grids = FindGridsInsideFurnace();
             if (grids.Count > 0)
             {
                 SetFurnaceDoorsEnabled(false);
                 speaker.Play();                         // Has the lava sound on it
                 PlayRandomAudio(AudioClip.WeCrushDown, AudioClip.WhereIsThatFrom, AudioClip.DontBreatheIn);
                 MeltGrids(grids);
                 ChangeFurnaceState(FurnaceState.Working);
                 furnaceWorkingCountdown = FurnaceWorkingTime;
                 foreach (var spotlight in furnaceSpotlights)
                 {
                     spotlight.Intensity = 4.9f;
                 }
             }
             else
             {
                 ChangeFurnaceState(FurnaceState.Waiting);
             }
         }
     }
 }
Beispiel #7
0
        //Initialiser
        #region Setup Stages
        Program()
        {
            //Sets Runtime
            Runtime.UpdateFrequency = Global_Timestep == 0.16? UpdateFrequency.Update10 : UpdateFrequency.Update1;

            //Setup String
            string SetupString = "Rdavs Guided Missile Script Hints Tips & Setup \n================================================== \n \n \nSystem Setup \n=================== \n \nTo Set Up The Ship: \n------------------------ \n- Put this Code Into a P-block \n- Install a sound block (optional) \n- Install a turret called #A# (seeker turret) \n- Recompile if prompted to 'reset' \n- To fire from the toolbar 'run' this Pb with \n  the argument 'Fire' \n \n\nTo Set Up A Missile: \n--------------------------- \n- Every Missile Requires: \n    ~ 1 gyro\n    ~ Forward thrusters \n    ~ 1 Merge Block \n    ~ 1 battery/power source \n    ~ Warheads (optional) \n    ~ Side thrusters (if in gravity)\n \n- Call everything on missile #A# \n- Weld/paste missile onto launching ship \n- Same missile design can be pasted multiple times \n- Missile(s) are now ready to fire!\n\n \n\nSystem Usage \n=================== \n \nMove to engagement distance (800m), a distinctive  \ntarget lock bleeping will sound from the sound block. \n(if sound block installed) \n \n'Run' The programmable block with the argument  \n'Fire' this will launch the next available missile.  \nthis action can be bound to the toolbar of any cockpit. \n \nA ship can have up to 100 missiles active at any one  \npoint, missile setup for every missile is identical  \nand thus missiles can be printed, copy pasted, etc. \n\n- NOTE:\n- For ALL missiles the weight of the missile\n  (can be found in the 'info' tab in kg)\n  should be written as a number into the \n  custom data of the missiles gyro.\n  This is not compulsory but is necessary for\n  accurate guidance.\n\n\nTroubleshooting: \n============================\n\nif you find that your missiles are:\n\n - Sinking and hit the ground in gravity\n - Miss the target / have sub par guidance\n - Not tracking an enemy\n - Not firing at all\n\nHere are some of the most common faults:\n\n- Check the terminal of the PB, this might show\n  some useful error readouts\n\n- Boost the acceleration of the missile! \n  (especially if unable to hit targets)\n\n- Ensure the turret (called #A#) is turned on \n  and set to attack enemy targets, what this turret\n  targets is what the script will track\n\n- The weight of the missile should be input\n  into the gyros custom data,\n\n- Lateral (side) thrusters are not compulsory but\n  are very useful at helping the guidance\n  especially in natural gravity\n\n \n \nHints & Tips \n=================== \n \n  \nPerformance Tips:  \n------------------------ \n \n- Use light and fast missiles for best small ship  \n  tracking capability, the key to a good hit rate is \n  good missile design!\n \n- For 'best' target tracking ensure your missile has  \n  at least 3x the acceleration of the ship you are  \n  intending to take out. \n \n- Lateral (sideways) thrusters can be used for better  \n  gravity correction and handling. \n \n \nUsage Tips: \n---------------------- \n \n- ID'ing the target can be done with common sense, (ie looking \n  at what the seeker turret is currently looking at) \n \n- you can fire a missile without lock to 'laser guide it'  \n  (ie it follows where you are pointing your ship) \n  towards an enemy, once close tracking will engage \n \n- The missile will (by default) not engage guidance until further  \n  than the ships radius away from where it launched. This should  \n  make it practical for launch tubes/ not damaging the launching ship.  \n\n- If a customn launch distance is required this can be changed by changing\n  the 'launch distance' value in the code shortly after the introduction\n\n- An extra seeker turret can be put on the missile itself (must be called #A#)\n  this missile will then use that turret to guide itself.\n\n- The missile tracking is good but as with anything depends on the pilots\n  ability to use them well, read up on real-world missile usage to help \n  boost your hit rate.\n\n\n\n  \n";

            Me.CustomData = SetupString;

            //Sets ShipSize
            ThisShipSize = (Me.CubeGrid.WorldVolume.Radius);
            ThisShipSize = LaunchDist == 0 ? ThisShipSize : LaunchDist;

            //Collects First Turret
            List <IMyTerminalBlock> TempCollection = new List <IMyTerminalBlock>();

            GridTerminalSystem.GetBlocksOfType <IMyLargeTurretBase>(TempCollection, a => a.CustomName.Contains(MissileTag) && a.DetailedInfo != "NoUse");
            if (TempCollection.Count > 0)
            {
                Turret = TempCollection[0] as IMyLargeTurretBase;
            }

            //Collects Sound/Alarm
            List <IMyTerminalBlock> TempCollection2 = new List <IMyTerminalBlock>();

            GridTerminalSystem.GetBlocksOfType <IMySoundBlock>(TempCollection2, a => a.DetailedInfo != "NoUse");
            if (TempCollection2.Count > 0)
            {
                Alarm = TempCollection2[0] as IMySoundBlock;
                Alarm.SelectedSound = "SoundBlockAlert2";
                Alarm.LoopPeriod    = 99999;
                Alarm.Play();
                Alarm.Enabled = false;
            }

            //Collects RC Unit
            List <IMyTerminalBlock> TempCollection3 = new List <IMyTerminalBlock>();

            GridTerminalSystem.GetBlocksOfType <IMyShipController>(TempCollection3, a => a.DetailedInfo != "NoUse");
            if (TempCollection3.Count > 0)
            {
                RC = TempCollection3[0] as IMyShipController;
            }

            //Collects TOW CameraBlock
            List <IMyTerminalBlock> TempCollection4 = new List <IMyTerminalBlock>();

            GridTerminalSystem.GetBlocksOfType <IMyCameraBlock>(TempCollection3, a => a.DetailedInfo == "#A#");
            if (TempCollection3.Count > 0)
            {
                TOWCamera = TempCollection3[0] as IMyCameraBlock; TOWCamera.EnableRaycast = true;
            }
        }
Beispiel #8
0
        public void Main(string argument, UpdateType updateSource)
        {
            Runtime.UpdateFrequency = UpdateFrequency.Update10;
            IMyTextPanel display = GridTerminalSystem.GetBlockWithName("LCD Panel [Status]") as IMyTextPanel;

            IMyBlockGroup hangarLights = GridTerminalSystem.GetBlockGroupWithName("Hangar Lights");

            IMyBlockGroup hangarDoors = GridTerminalSystem.GetBlockGroupWithName("Hangar Doors");

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

            hangarDoors.GetBlocksOfType <IMyAirtightHangarDoor>(doors);

            bool missing = false;

            if (hangarDoors == null) //Returns if doors not found
            {
                Echo("Doors not found");
                missing = true;
            }

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

            hangarLights.GetBlocksOfType <IMyInteriorLight>(lights);

            if (hangarLights == null) //Returns if lights not found
            {
                Echo("Lights not found");
                missing = true;
            }

            IMyTimerBlock timer = GridTerminalSystem.GetBlockWithName("[Hangar] Timer Block") as IMyTimerBlock;

            if (timer == null) //Returns if timer not found
            {
                Echo("Timer not found");
                missing = true;
            }

            IMyAirVent vent = GridTerminalSystem.GetBlockWithName("[Hangar] Air Vent") as IMyAirVent;

            if (vent == null) //Returns if vent not found
            {
                Echo("Vent not found");
                missing = true;
            }

            IMySoundBlock speaker = GridTerminalSystem.GetBlockWithName("[Hangar] Sound Block") as IMySoundBlock;

            if (speaker == null) //Returns if speaker not found
            {
                Echo("Speaker not found");
                missing = true;
            }

            if (missing == true)
            {
                return;
            }

            UnifyLights(lights);               //Turns all lights on

            speaker.SelectedSound = "Alert 1"; //Set speaker sound

            if (!timer.IsCountingDown)         //Program will skip over if the timer is counting down
            {
                if (timer.TriggerDelay == 10)  //Program will disable timer if the timer is set to 10 (end of hanagar door stage).
                {
                    NormalLights(lights);
                    display.FontSize = 4.4F;
                    Echo("All is well");
                    display.WritePublicTitle("All is well");
                    timer.Enabled      = true;
                    timer.TriggerDelay = 15;
                    speaker.LoopPeriod = 10;
                    speaker.Stop();
                    Runtime.UpdateFrequency = UpdateFrequency.None;
                }
                else //Program will start hangar toggle process else wise
                {
                    if (vent.CanPressurize && !vent.Depressurize) //If the vent needs to depressurize, start depressurize sequence
                    {
                        vent.Depressurize  = true;
                        timer.Enabled      = true;
                        timer.TriggerDelay = 15;
                        timer.StartCountdown();
                        speaker.LoopPeriod = 25;
                        speaker.Play();
                        WarningLights(lights);
                        return;
                    }
                    WarningLights(lights);
                    ToggleDoors(doors);
                    display.FontSize = 3;
                    Echo("!!!CAUTION!!!");
                    display.WritePublicTitle("!!!CAUTION!!!");
                    timer.TriggerDelay = 10;
                    timer.StartCountdown();
                    vent.Depressurize = false;
                    if (speaker.LoopPeriod != 25)
                    {
                        speaker.LoopPeriod = 10;
                        speaker.Play();
                    }
                }
            }
        }
Beispiel #9
0
        public void Main(string argument, UpdateType updateSource)
        {
            soundBlock = (IMySoundBlock)GridTerminalSystem.GetBlockWithName(AlarmBlockName);
            Runtime.UpdateFrequency = UpdateFrequency.Update100;


            IMyTextPanel MessagePanel = (IMyTextPanel)GridTerminalSystem.GetBlockWithName(messagePanelName);



            // If setupcomplete is false, run Setup method.
            if (!setupcomplete)
            {
                Echo("Running setup.");
                Setup();
                SaveData();
            }
            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);

                foreach (var item in listeners)
                {
                    Echo("Somone listen");
                }
                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);

                    MessagePanel.WriteText("Error");

                    if (knownIp.Contains(sender.ToString()))
                    {
                        Echo("Here222");
                        Gates("y");
                        MessagePanel.WriteText(messagetext);
                    }
                    else if (messagetext.Contains(acceptCode))
                    {
                        MessagePanel.WriteText("Err33or");
                        soundBlock.Play();

                        MessagePanel.WriteText("accepted part 2");


                        Echo("Accepted");

                        Gates("y");


                        if (knownIp.Contains(sender.ToString()))
                        {
                            MessagePanel.WriteText("accepted part 3");
                        }
                        else
                        {
                            knownIp.Add(sender.ToString());
                            MessagePanel.WriteText(messagetext);
                        }

                        TextMessage = "";
                        for (int i = 0; i < knownIp.Count; i++)
                        {
                            TextMessage += $"{knownIp[i]}\n";
                        }

                        userIpPanel.WriteText(TextMessage);
                    }
                    else
                    {
                        Echo("Im here");
                        MessagePanel.WriteText("Acces denied" + "\n" + TextMessage);
                        Gates("n");
                    }
                }
            }
        }
Beispiel #10
0
        void Main(string arg, UpdateType uType)
        {
            if (uType == UpdateType.Update1)
            {
                Tick++;

                /*   if (radio.Listen())
                 * {
                 *         radar.correctedTargetLocation = radio.targetpos;
                 *         radar.Lock();
                 *         (gts.GetBlockWithName("Cockpit") as IMyCockpit).GetSurface(0).WriteText("radio", false);
                 *         if (radar.Locked)
                 *         {
                 *                 sound.Play();
                 *                 sound.Play();
                 *                 LASER_GUIDED = false;
                 *         }
                 * }*/
                radar.Update();
                lcd.WriteText("LOCKED: " + radar.Locked, false);
                lcd.WriteText("\nTarget: " + radar.CurrentTarget.Name + ", tick: " + radar.LastLockTick, true);
                lcd.WriteText("\nDistance: " + Math.Round(radar.TargetDistance), true);
                lcd.WriteText("\nVelocity: " + Math.Round(radar.CurrentTarget.Velocity.Length()), true);
                if (radar.Locked)
                {
                    arta.AimCannons(radar.correctedTargetLocation, radar.CurrentTarget.Velocity);
                }
                foreach (Torpedo t in Torpedos)
                {
                    if (t.status == 2)
                    {
                        t.Update(radar.CurrentTarget, CENTER_SHOT ? radar.CurrentTarget.Position : radar.T, cockpit.GetPosition(), cockpit.WorldMatrix.Forward);
                    }
                }
                if (WolfPack)
                {
                    if ((Tick - WolfPackStart + 1) % WOLF_PACK_WELDING_TIME == 0)
                    {
                        CleanGarbage();
                        InitializeTorpedos();
                    }
                    if ((radar.Locked) && ((Tick - WolfPackStart - 1) % WOLF_PACK_WELDING_TIME == 0))
                    {
                        foreach (Torpedo t in Torpedos)
                        {
                            Echo("\nTry Launch: ");
                            Echo("\nWPI: " + WolfPackIndex);
                            if (t.status == 1)
                            {
                                WolfPackIndex--;
                                t.Launch(WolfPackDelays[WolfPackIndex]);
                                break;
                            }
                        }
                        if (WolfPackIndex <= 0)
                        {
                            WolfPack = false;
                        }
                    }
                }
                Echo("Runtime: " + Runtime.LastRunTimeMs);
            }
            else
            {
                switch (arg)
                {
                case "Lock":
                    radar.Lock(true, 20000);
                    if (radar.Locked)
                    {
                        arta.AimPoint = radar.CurrentTarget.Position;
                        sound.Play();
                        sound.Play();
                        LASER_GUIDED            = false;
                        Runtime.UpdateFrequency = UpdateFrequency.Update1;
                    }
                    else
                    {
                        lcd.WriteText("NO TARGET", false);
                        Runtime.UpdateFrequency = UpdateFrequency.None;
                    }
                    break;

                case "RadioON":
                    radio.TurnON();
                    Runtime.UpdateFrequency = UpdateFrequency.Update1;
                    break;

                case "Laser":
                    LASER_GUIDED            = true;
                    Runtime.UpdateFrequency = UpdateFrequency.Update1;
                    break;

                case "CenterShot":
                    CENTER_SHOT = !CENTER_SHOT;
                    break;

                case "Init":
                    CleanGarbage();
                    InitializeTorpedos();
                    break;

                case "SpotterCam":
                    SpotterCam = gts.GetBlockWithName("SpotterCam") as IMyCameraBlock;
                    if (SpotterCam != null)
                    {
                        SpotterCam.EnableRaycast = true;
                        Echo("SpotterCam detected");
                    }
                    break;

                case "Spot":
                    if (SpotterCam != null)
                    {
                        Echo("Spotting");
                        MyDetectedEntityInfo spotterInfo = SpotterCam.Raycast(15000, 0, 0);
                        if (!spotterInfo.IsEmpty())
                        {
                            Echo("Target Spotted");
                            radar.correctedTargetLocation = spotterInfo.Position;
                            radar.Lock();
                            if (radar.Locked)
                            {
                                Echo("Target Locked");
                                Runtime.UpdateFrequency = UpdateFrequency.Update1;
                                sound.Play();
                                sound.Stop();
                                sound.Play();
                                sound.Stop();
                                LASER_GUIDED = false;
                            }
                        }
                    }
                    break;

                case "Stop":
                    radar.StopLock();
                    Runtime.UpdateFrequency = UpdateFrequency.None;
                    break;

                case "Launch":
                    if ((radar.Locked) || (LASER_GUIDED))
                    {
                        foreach (Torpedo t in Torpedos)
                        {
                            Echo("\nTry Launch: ");
                            if (t.status == 1)
                            {
                                Echo("1 go");
                                t.Launch();
                                break;
                            }
                        }
                    }
                    else
                    {
                        Echo("No Target Lock");
                    }
                    break;

                case "Test":
                    Echo("\n Test:" + VerticalDelay(5000.0f, 1700.0f, 300));
                    break;

                case "CCT":
                    Runtime.UpdateFrequency = UpdateFrequency.Update1;
                    arta.tensor_calculation = true;
                    arta.tensor_calc_step   = 0;
                    break;

                case "Pack":
                    if (radar.Locked)
                    {
                        WolfPackDelays.Clear();
                        WolfPackDelays.Add(LAUNCH_DELAY);
                        for (int x = 0; x < WOLF_PACK_COUNT - 1; x++)
                        {
                            WolfPackDelays.Add(VerticalDelay((float)radar.TargetDistance, (float)(WOLF_PACK_WELDING_TIME - WOLF_PACK_INTERVAL) * 1.666667f, WolfPackDelays[WolfPackDelays.Count - 1]));
                        }
                        WolfPack      = true;
                        WolfPackStart = Tick;
                        WolfPackIndex = WOLF_PACK_COUNT;
                    }
                    break;

                default:
                    break;
                }
            }
        }
        //Main Functions

        public void SwitchRedAlert()
        {
            List <IMyLightingBlock> rotatLights  = GetRotatingLights();
            List <IMyLightingBlock> alarmLights  = GetAlarmLights();
            List <IMyLightingBlock> switchLights = GetSwtchLights();
            List <IMyLightingBlock> otherLights  = GetOtherLights();
            List <IMyLightingBlock> sredLights   = GetSredLights();
            IMySoundBlock           alarmBlock   = GridTerminalSystem.GetBlockWithName(SOUND_BLOCK) as IMySoundBlock;

            onAlert = !onAlert;

            if (onAlert)     // turn the <s> F*****g Furries </s> on
            {
                ChangeLightsColor(otherLights, new Color(60, 0, 0));
                ChangeLightsColor(switchLights, new Color(0, 0, 255));
                ChangeLightsColor(alarmLights, new Color(0, 0, 255));
                ChangeLightsColor(sredLights, new Color(60, 0, 0));
                ChangeLightsStatus(rotatLights, true);
                ChangeLightsStatus(alarmLights, true);
                if (alarmBlock != null)
                {
                    alarmBlock.Play();
                }
                foreach (IMyLightingBlock l in otherLights)
                {
                    l.BlinkLength          = 50f;
                    l.BlinkIntervalSeconds = 2;
                }
                foreach (IMyLightingBlock l in switchLights)
                {
                    l.BlinkLength          = 50f;
                    l.BlinkIntervalSeconds = 2;
                }
                SetWeapons(true);
                CloseAllDoors();
                Output("\nRED ALERT");
                if (EnergyControl != null)
                {
                    EnergyControl.TryRun("COMBAT");
                }
            }
            else     // turn the <s> F*****g Furries </s> off
            {
                ChangeLightsColor(otherLights, new Color(255, 255, 255));
                ChangeLightsColor(switchLights, new Color(255, 255, 255));
                ChangeLightsColor(sredLights, new Color(255, 255, 255));
                ChangeLightsStatus(rotatLights, false);
                ChangeLightsStatus(alarmLights, false);
                if (alarmBlock != null)
                {
                    alarmBlock.Stop();
                }
                foreach (IMyLightingBlock l in otherLights)
                {
                    l.BlinkIntervalSeconds = 0;
                    l.BlinkOffset          = 50f;
                }
                foreach (IMyLightingBlock l in switchLights)
                {
                    l.BlinkIntervalSeconds = 0;
                }
                Output("\nIN ORDER");
                if (EnergyControl != null)
                {
                    EnergyControl.TryRun("NORMAL");
                }
            }
        }
Beispiel #12
0
            public override void HandleCallback(string callback)
            {
                switch (callback)
                {
                case "unicast":
                    MyIGCMessage message = Drone.NetworkService.GetUnicastListener().AcceptMessage();

                    if (message.Data == null)
                    {
                        Drone.LogToLcd($"\nNo Message");
                    }

                    if (message.Tag == DockingRequestChannel)
                    {
                        Drone.LogToLcd("\nReceived Docking Request");
                        IMyShipConnector dockingPort = GetFreeDockingPort();

                        if (dockingPort == null)
                        {
                            Drone.LogToLcd("\nNo Free Docking Port");
                        }
                        else
                        {
                            MyTuple <Vector3D, Vector3D, Vector3D> payload = new MyTuple <Vector3D, Vector3D, Vector3D>();
                            payload.Item1 = dockingPort.GetPosition() + dockingPort.WorldMatrix.Forward * 40;
                            payload.Item2 = dockingPort.GetPosition() + 1.5 * dockingPort.WorldMatrix.Forward;

                            Drone.LogToLcd($"\nClearance granted: {message.Source}");
                            Drone.LogToLcd($"\nApproach: {payload.Item1.ToString()}");
                            Drone.LogToLcd($"\nDocking Port: { payload.Item2.ToString()}");

                            Drone.Program.IGC.SendUnicastMessage(message.Source, DockingRequestChannel, payload);
                        }
                    }
                    else if (message.Tag == "Notifications")
                    {
                        Drone.LogToLcd($"Received notification:{message.Data.ToString()}");
                        DroneKlaxon.LoopPeriod = 2f;
                        DroneKlaxon.Play();
                    }
                    else if (message.Tag == "survey_reports")
                    {
                        MyTuple <long, string, double, Vector3D, Vector3D, Vector3D> report = (MyTuple <long, string, double, Vector3D, Vector3D, Vector3D>)message.Data;
                        Drone.LogToLcd($"Received survey_report: {report.ToString()}");

                        //TODO: This needs to be in a persistence layer, not the CustomData
                        MyIni            ini = new MyIni();
                        MyIniParseResult config;
                        if (!ini.TryParse(Drone.Program.Me.CustomData, out config))
                        {
                            throw new Exception($"Error parsing config: {config.ToString()}");
                        }

                        //TODO: what about multiple deposits?
                        ini.Set($"deposit {report.Item1.ToString()}", "deposit_type", report.Item2.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "deposit_depth", report.Item3.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "top_left_corner", report.Item4.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "top_right_corner", report.Item5.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "bottom_left_corner", report.Item6.ToString());
                        ini.Set($"deposit {report.Item1.ToString()}", "index", 0);

                        Drone.Program.Me.CustomData = ini.ToString();
                    }
                    else if (message.Tag == "tunnel_complete")
                    {
                        MyIni ini = new MyIni();

                        MyIniParseResult config;
                        if (!ini.TryParse(Drone.Program.Me.CustomData, out config))
                        {
                            throw new Exception($"Error parsing config: {config.ToString()}");
                        }

                        int completedIndex = (int)message.Data;

                        List <string> sections = new List <string>();
                        ini.GetSections(sections);
                        IEnumerable <string> deposits = sections.Where(record => record.StartsWith("deposit"));
                        string deposit;

                        if (deposits != null && deposits.Count() != 0)
                        {
                            deposit = deposits.First();
                        }
                        else
                        {
                            throw new Exception("No deposit data found!");
                        }

                        ini.Set(deposit, "index", completedIndex + 1);
                        Drone.Program.Me.CustomData = ini.ToString();
                    }

                    break;

                case "docking_request_pending":
                    ProcessDockingRequest();
                    break;

                case "recall_miner":
                    Drone.LogToLcd("Recalling miner");
                    Drone.Program.IGC.SendUnicastMessage(MinerAddress, "recall", "recall");
                    break;

                case "recall_surveyor":
                    Drone.LogToLcd("Recalling surveyor");
                    Drone.Program.IGC.SendUnicastMessage(SurveyorAddress, "recall", "recall");
                    break;

                case "deploy_miner":
                    Drone.LogToLcd("Launching miner");

                    List <IMyProgrammableBlock> miners = new List <IMyProgrammableBlock>();
                    Drone.Grid().GetBlocksOfType(miners, pb => MyIni.HasSection(pb.CustomData, "miner"));

                    //We only support one miner for now
                    // Set the deposit details in the miners config
                    IMyProgrammableBlock miner   = miners.First();
                    MyIni            minerConfig = new MyIni();
                    MyIniParseResult result;
                    if (!minerConfig.TryParse(miner.CustomData, out result))
                    {
                        Drone.LogToLcd(miner.CustomData);
                        throw new Exception($"Error parsing config: {result.ToString()}");
                    }

                    //Vector3D MiningSite = DepositCentre + 10 * Vector3D.Normalize(DepositNormal);
                    //Vector3D TunnelEnd = DepositCentre - DepositDepth * Vector3D.Normalize(DepositNormal);

                    //get deposit data from catalogue
                    //calculate mining_site for next tunnel
                    //calculate tunnel_end from mining_site and depth
                    MyIni asteroidCatalogue = new MyIni();
                    asteroidCatalogue.TryParse(Drone.Program.Me.CustomData);
                    Tunnel tunnel = new Tunnel(asteroidCatalogue);

                    minerConfig.Set("miner", "mining_site", tunnel.StartingPoint.ToString());
                    minerConfig.Set("miner", "tunnel_end", tunnel.EndPoint.ToString());
                    minerConfig.Set("miner", "index", tunnel.TunnelIndex);
                    miner.CustomData = minerConfig.ToString();

                    miner.TryRun("launch");
                    break;

                case "deploy_surveyor":
                    Drone.LogToLcd("Launching surveyor");

                    List <IMyProgrammableBlock> surveyors = new List <IMyProgrammableBlock>();
                    Drone.Grid().GetBlocksOfType(surveyors, pb => MyIni.HasSection(pb.CustomData, "surveyor"));
                    IMyProgrammableBlock surveyor = surveyors.First();

                    surveyor.TryRun("launch");
                    break;

                case "echo":
                    Drone.LogToLcd("Echo");
                    DroneKlaxon.Play();
                    break;

                case "":
                    // Just Ignore empty arguments
                    break;

                default:
                    Drone.LogToLcd($"\nDrone received unrecognized callback: {callback}");
                    break;
                }
            }