Пример #1
0
        public void StartGooeyProgramming()
        {
            Log.DebugLog("entered");

            using (MainLock.AcquireSharedUsing())
            {
                m_currentCommand = null;
                m_listCommands   = true;
                m_commandList.Clear();
                m_syntaxErrors.Clear();

                MyTerminalControls.Static.CustomControlGetter += CustomControlGetter;
                m_block.AppendingCustomInfo += m_block_AppendingCustomInfo;

                Commands = AutopilotTerminal.GetAutopilotCommands(m_block).ToString();
                foreach (ACommand comm in ParseCommands(Commands))
                {
                    m_commandList.Add(comm);
                }
                if (m_syntaxErrors.Length != 0)
                {
                    m_block.UpdateCustomInfo();
                }
                m_block.RebuildControls();
            }
        }
Пример #2
0
        /// <summary>
        /// Get all the blocks on the target grid that are damaged
        /// </summary>
        private void GetDamagedBlocks()
        {
            m_damagedBlocks.Clear();
            m_projectedBlocks.Clear();

            // get physical blocks

            foreach (IMySlimBlock slim in Attached.AttachedGrid.AttachedSlimBlocks((IMyCubeGrid)m_currentGrid.Entity, Attached.AttachedGrid.AttachmentKind.Permanent, true))
            {
                if (slim.CurrentDamage > 0f || slim.BuildLevelRatio < 1f)
                {
                    m_damagedBlocks.Add(slim);
                }
            }

            // get projections

            HashSet <IMyEntity> projections = null;

            foreach (IMyCubeGrid grid in Attached.AttachedGrid.AttachedGrids((IMyCubeGrid)m_currentGrid.Entity, Attached.AttachedGrid.AttachmentKind.Permanent, true))
            {
                if (CubeGridCache.GetFor(grid).CountByType(typeof(MyObjectBuilder_Projector)) == 0)
                {
                    continue;
                }

                using (MainLock.AcquireSharedUsing())
                {
                    if (projections == null)
                    {
                        projections = new HashSet <IMyEntity>();
                        MyAPIGateway.Entities.GetEntities(projections, entity => entity is MyCubeGrid && ((MyCubeGrid)entity).Projector != null);

                        if (projections.Count == 0)
                        {
                            break;
                        }
                    }

                    foreach (MyCubeGrid proj in projections)
                    {
                        if (proj.Projector.CubeGrid == grid)
                        {
                            foreach (IMySlimBlock block in proj.CubeBlocks)
                            {
                                m_projectedBlocks.Add(block);
                            }
                        }
                    }
                }

                continue;
            }

            m_projectedBlocks.ApplyAdditions();

            Log.DebugLog("damaged blocks: " + m_damagedBlocks.Count + ", projected blocks: " + m_projectedBlocks.Count);
        }
Пример #3
0
        /// <summary>
        /// Get all the components that are in inventories on the autopilot ship.
        /// </summary>
        private void GetInventoryItems()
        {
            if (m_blocksWithInventory == null)
            {
                m_blocksWithInventory = new List <IMySlimBlock>();
                m_controlBlock.CubeGrid.GetBlocks_Safe(m_blocksWithInventory, slim => slim.FatBlock != null && (slim.FatBlock as MyEntity).HasInventory);
                Log.DebugLog("blocks with inventory: " + m_blocksWithInventory.Count);
            }

            m_components_inventory.Clear();
            foreach (IMySlimBlock slim in m_blocksWithInventory)
            {
                if (slim.FatBlock.Closed)
                {
                    continue;
                }

                MyEntity asEntity    = slim.FatBlock as MyEntity;
                int      inventories = asEntity.InventoryCount;
                Log.DebugLog("searching " + inventories + " inventories of " + slim.FatBlock.DisplayNameText);
                for (int i = 0; i < inventories; i++)
                {
                    List <MyPhysicalInventoryItem> allItems = null;
                    MainLock.UsingShared(() => allItems = asEntity.GetInventory(i).GetItems());

                    foreach (MyPhysicalInventoryItem item in allItems)
                    {
                        if (item.Content.TypeId != typeof(MyObjectBuilder_Component))
                        {
                            Log.DebugLog("skipping " + item.Content + ", not a component");
                            continue;
                        }

                        Log.DebugLog("item: " + item.Content.SubtypeName + ", amount: " + item.Amount);
                        int amount = (int)item.Amount;
                        if (amount < 1)
                        {
                            continue;
                        }

                        string name = item.Content.SubtypeName;
                        int    count;

                        if (!m_components_inventory.TryGetValue(name, out count))
                        {
                            count = 0;
                        }
                        count += amount;

                        m_components_inventory[name] = count;
                    }
                }
            }
        }
Пример #4
0
        public AutopilotActionList GetActions(string allCommands)
        {
            using (MainLock.AcquireSharedUsing())
            {
                Commands = allCommands;
                m_syntaxErrors.Clear();

                AutopilotActionList actList = new AutopilotActionList();
                GetActions(Commands, actList);
                if (m_syntaxErrors.Length != 0)
                {
                    m_block.UpdateCustomInfo();
                }
                return(actList);
            }
        }
Пример #5
0
 private void GetAllComponents(IMySlimBlock slim)
 {
     using (MainLock.AcquireSharedUsing())
     {
         foreach (MyCubeBlockDefinition.Component component in ((MySlimBlock)slim).BlockDefinition.Components)
         {
             int currentCount;
             if (!m_components_missing.TryGetValue(component.Definition.Id.SubtypeName, out currentCount))
             {
                 currentCount = 0;
             }
             currentCount += component.Count;
             m_components_missing[component.Definition.Id.SubtypeName] = currentCount;
             //Log.DebugLog("missing " + component.Definition.Id.SubtypeName + ": " + component.Count + ", total: " + currentCount, "GetAllComponents()");
         }
     }
 }
Пример #6
0
        /// <summary>
        /// Initializes if needed, issues updates.
        /// </summary>
        public override void UpdateAfterSimulation()
        {
            MainLock.MainThread_TryReleaseExclusive();
            try
            {
                switch (MangerStatus)
                {
                case Status.Not_Initialized:
                    //myLogger.debugLog("Not Initialized", "UpdateAfterSimulation()");
                    Init();
                    return;

                case Status.Terminated:
                    return;
                }
                foreach (KeyValuePair <uint, List <Action> > pair in UpdateRegistrar)
                {
                    if (Update % pair.Key == 0)
                    {
                        foreach (Action item in pair.Value)
                        {
                            try
                            { item.Invoke(); }
                            catch (Exception ex2)
                            {
                                myLogger.log("Script threw exception, unregistering: " + ex2, "UpdateAfterSimulation()", Logger.severity.ERROR);
                                UnRegisterForUpdates(pair.Key, item);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                myLogger.log("Exception: " + ex, "UpdateAfterSimulation()", Logger.severity.FATAL);
                MangerStatus = Status.Terminated;
            }
            finally
            {
                Update++;
                MainLock.MainThread_TryAcquireExclusive();
            }
        }
Пример #7
0
        public AutopilotActionList GetActions()
        {
            using (MainLock.AcquireSharedUsing())
            {
                if (!m_actionList.IsEmpty)
                {
                    m_actionList.Reset();
                    return(m_actionList);
                }
                m_syntaxErrors.Clear();

                Commands = AutopilotTerminal.GetAutopilotCommands(m_block).ToString();
                List <ACommand> commands = new List <ACommand>();
                GetActions(Commands, m_actionList);
                if (m_syntaxErrors.Length != 0)
                {
                    m_block.UpdateCustomInfo();
                }
                return(m_actionList);
            }
        }
Пример #8
0
        private void Update()
        {
            try
            {
                if (!controlEnabled)
                {
                    return;
                }

                turretPosition = myCubeBlock.GetPosition();
                //myLogger.debugLog("Turret Position: " + turretPosition, "Update()");
                turretMissileBubble = new BoundingSphereD(turretPosition, myTurretBase.Range / 10);

                double distToMissile;
                if (currentTargetIsMissile && canLase(lastTarget) && missileIsThreat(lastTarget, out distToMissile, false))
                {
                    //myLogger.debugLog("no need to switch targets", "UpdateThread()");
                    return;                     // no need to switch targets
                }

                IMyEntity bestTarget;
                if (getValidTargets() && getBestTarget(out bestTarget))
                {
                    if (CurrentState != State.HAS_TARGET || lastTarget != bestTarget)
                    {
                        CurrentState = State.HAS_TARGET;
                        lastTarget   = bestTarget;
                        myLogger.debugLog("new target = " + bestTarget.getBestName(), "UpdateThread()", Logger.severity.DEBUG);
                        MainLock.UsingShared(() => myTurretBase.TrackTarget(bestTarget));
                    }
                }
                else                 // no target
                if (CurrentState == State.HAS_TARGET && !currentTargetIsMissile)
                {
                    setNoTarget();
                }
            }
            catch (Exception e) { myLogger.log("Exception: " + e, "UpdateThread()", Logger.severity.ERROR); }
            finally { queued = false; }
        }
Пример #9
0
        public override void UpdateBeforeSimulation()
        {
            if (delayStart > 0)
            {
                delayStart--;
                return;
            }

            MainLock.MainThread_TryReleaseExclusive();
            try
            {
                if (isUpdating || terminated)
                {
                    return;
                }
                isUpdating = true;
                //MyAPIGateway.Parallel.Start(doUpdate, updateCallback);
                doUpdate();
                isUpdating = false;
            }
            finally { MainLock.MainThread_TryAcquireExclusive(); }
        }
Пример #10
0
        protected override void UnloadData()
        {
            base.UnloadData();
            if (MyAPIGateway.Entities != null)
            {
                MyAPIGateway.Entities.OnEntityAdd -= Entities_OnEntityAdd;
                MyAPIGateway.Entities.OnCloseAll  -= UnloadData;
            }

            if (!Globals.WorldClosed)
            {
                MainLock.MainThread_ReleaseExclusive();
                try
                {
                    AttributeFinder.InvokeMethodsWithAttribute <OnWorldClose>();
                }
                catch (Exception ex)
                {
                    // if world is closed by X button, expect an exception
                    Log.AlwaysLog("Exception while unloading: " + ex, Logger.severity.ERROR);
                }
                Globals.WorldClosed = true;
                Profiler.Write();
            }

            // in case SE doesn't clean up properly, clear all fields
            foreach (FieldInfo field in GetType().GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
            {
                if (!field.IsLiteral && !field.IsInitOnly)
                {
                    field.SetValue(this, null);
                }
            }

            ManagerStatus = Status.Terminated;
        }
Пример #11
0
        /// <summary>
        /// Test required elev/azim against min/max
        /// Test line segment between turret and target for other entities
        /// </summary>
        private bool canLase(IMyEntity target)
        {
            Vector3D targetPos = target.GetPosition();

            // Test elev/azim
            Vector3 relativeToBlock = RelativeVector3F.createFromWorld(targetPos - turretPosition, myCubeBlock.CubeGrid).getBlock(myCubeBlock);
            float   azimuth, elevation;

            Vector3.GetAzimuthAndElevation(Vector3.Normalize(relativeToBlock), out azimuth, out elevation);
            //myLogger.debugLog("for target = " + target.getBestName() + ", at " + target.GetPosition() + ", elevation = " + elevation + ", azimuth = " + azimuth, "canLase()");
            if (azimuth < minAzimuth || azimuth > maxAzimuth || elevation < minElevation || elevation > maxElevation)
            {
                return(false);
            }

            // if we are waiting on default targeting, ObstructingGrids will not be up-to-date
            if (CurrentState == State.WAIT_DTAT)
            {
                // default targeting may acquire an unowned block on a friendly grid
                IMyCubeGrid targetGrid = target as IMyCubeGrid;
                if (targetGrid == null)
                {
                    IMyCubeBlock targetAsBlock = target as IMyCubeBlock;
                    if (targetAsBlock != null)
                    {
                        targetGrid = targetAsBlock.CubeGrid;
                    }
                }


                List <IMyEntity> entitiesInRange = null;
                BoundingSphereD  range           = new BoundingSphereD(turretPosition, myTurretBase.Range + 200);
                MainLock.UsingShared(() => { entitiesInRange = MyAPIGateway.Entities.GetEntitiesInSphere(ref range); });

                foreach (IMyEntity entity in entitiesInRange)
                {
                    IMyCubeGrid asGrid = entity as IMyCubeGrid;
                    //if (asGrid != null)
                    //	myLogger.debugLog("checking entity: " + entity.getBestName(), "canLase()");
                    if (asGrid != null)
                    {
                        // default targeting may acquire an unowned block on a friendly grid
                        if (targetGrid != null && targetGrid == asGrid)
                        {
                            continue;
                        }

                        if (!myCubeBlock.canConsiderHostile(asGrid) && IsObstructing(asGrid, targetPos))
                        {
                            myLogger.debugLog("for target " + target.getBestName() + ", path from " + turretPosition + " to " + targetPos + ", obstructing entity = " + entity.getBestName(), "canLase()");
                            return(false);
                        }
                    }
                }
            }
            else
            {
                foreach (IMyCubeGrid grid in ObstructingGrids)
                {
                    //if (grid != null)
                    //	myLogger.debugLog("checking entity: " + grid.getBestName(), "canLase()");
                    if (IsObstructing(grid, targetPos))
                    {
                        myLogger.debugLog("for target " + target.getBestName() + ", path from " + turretPosition + " to " + targetPos + ", obstructing entity = " + grid.getBestName(), "canLase()");
                        return(false);
                    }
                }
            }

            return(true);
        }
Пример #12
0
        /// <summary>
        /// Fills validTarget_*
        /// </summary>
        private bool getValidTargets()
        {
            List <IMyEntity> entitiesInRange = null;
            BoundingSphereD  range           = new BoundingSphereD(turretPosition, myTurretBase.Range + 200);

            MainLock.UsingShared(() => { entitiesInRange = MyAPIGateway.Entities.GetEntitiesInSphere(ref range); });

            validTarget_missile   = new List <IMyEntity>();
            validTarget_meteor    = new List <IMyEntity>();
            validTarget_character = new List <IMyEntity>();
            validTarget_block     = new List <IMyEntity>();
            validTarget_CubeGrid  = new List <IMyEntity>();
            ObstructingGrids      = new List <IMyEntity>();

            if (!possibleTargets())
            {
                myLogger.debugLog("no possible targets", "getValidTargets()", Logger.severity.WARNING);
                return(false);
            }
            //if (EnemyNear)
            //	myLogger.debugLog("enemy near", "getValidTargets()");

            //myLogger.debugLog("initial entity count is " + entitiesInRange.Count, "getValidTargets()");

            foreach (IMyEntity entity in entitiesInRange)
            {
                if (entity.Transparent)                 // part of a ship / station being pasted
                {
                    continue;
                }

                IMyCubeBlock asBlock = entity as IMyCubeBlock;
                if (asBlock != null)
                {
                    if (asBlock.IsWorking && enemyNear() && targetGridFlagSet(asBlock.CubeGrid) && myCubeBlock.canConsiderHostile(asBlock))
                    {
                        validTarget_block.Add(entity);
                    }
                    continue;
                }
                IMyCubeGrid asGrid = entity as IMyCubeGrid;
                if (asGrid != null)
                {
                    if (myCubeBlock.canConsiderHostile(asGrid))
                    {
                        if (targetMoving && enemyNear() && targetGridFlagSet(asGrid))
                        {
                            validTarget_CubeGrid.Add(entity);
                        }
                    }
                    else                     // not hostile
                    {
                        ObstructingGrids.Add(entity);
                    }
                    continue;
                }
                if (entity is IMyMeteor)
                {
                    if (targetMeteors)
                    {
                        validTarget_meteor.Add(entity);
                    }
                    continue;
                }
                IMyPlayer asPlayer = entity as IMyPlayer;
                if (asPlayer != null)
                {
                    if (targetCharacters)
                    {
                        IMyPlayer matchingPlayer = (entity as IMyCharacter).GetPlayer_Safe();
                        if (myCubeBlock.canConsiderHostile(matchingPlayer.PlayerID))
                        {
                            validTarget_character.Add(entity);
                        }
                    }
                    continue;
                }
                if (entity is IMyFloatingObject || entity is IMyVoxelMap)
                {
                    continue;
                }

                // entity could be missile
                if (targetMissiles && enemyNear() && entity.ToString().StartsWith("MyMissile"))
                {
                    validTarget_missile.Add(entity);
                }
            }

            //myLogger.debugLog("target counts = " + validTarget_missile.Count + ", " + validTarget_meteor.Count + ", " + validTarget_character.Count + ", " + validTarget_block.Count, "getValidTargets()");
            return(validTarget_missile.Count > 0 || validTarget_meteor.Count > 0 || validTarget_character.Count > 0 || validTarget_block.Count > 0 || validTarget_CubeGrid.Count > 0);
        }
Пример #13
0
        public Cluster(List <IMyEntity> missiles, IMyEntity launcher)
        {
            Vector3 centre = Vector3.Zero;

            foreach (IMyEntity miss in missiles)
            {
                centre += miss.GetPosition();
            }
            centre /= missiles.Count;

            float masterDistSq = float.MaxValue;

            foreach (IMyEntity miss in missiles)
            {
                if (miss.Closed)
                {
                    Logger.DebugLog("missile is closed: " + miss.nameWithId());
                    continue;
                }
                if (miss.Physics == null)
                {
                    Logger.DebugLog("missile has no physics: " + miss.nameWithId());
                    continue;
                }

                float distSq = Vector3.DistanceSquared(centre, miss.GetPosition());
                if (distSq < masterDistSq)
                {
                    Master       = miss;
                    masterDistSq = distSq;
                }
            }

            if (Master == null)
            {
                return;
            }

            masterVelocity = Master.Physics.LinearVelocity;

            // master must initially have same orientation as launcher or rail will cause a rotation
            MatrixD masterMatrix = launcher.WorldMatrix;

            masterMatrix.Translation = Master.WorldMatrix.Translation;
            MainLock.UsingShared(() => Master.WorldMatrix = masterMatrix);

            Vector3 masterPos = Master.GetPosition();
            MatrixD masterInv = Master.WorldMatrixNormalizedInv;
            float   Furthest  = 0f;

            Slaves       = new List <IMyEntity>(missiles.Count - 1);
            SlaveOffsets = new List <Vector3>(missiles.Count - 1);
            foreach (IMyEntity miss in missiles)
            {
                if (miss == Master)
                {
                    continue;
                }
                Slaves.Add(miss);
                SlaveOffsets.Add(Vector3.Transform(miss.GetPosition(), masterInv));
                float distSq = Vector3.DistanceSquared(miss.GetPosition(), masterPos);
                Logger.DebugLog("slave: " + miss + ", offset: " + SlaveOffsets[SlaveOffsets.Count - 1], Rynchodon.Logger.severity.TRACE);
                if (distSq > Furthest)
                {
                    Furthest = distSq;
                }
            }
            Furthest = (float)Math.Sqrt(Furthest);
            for (int i = 0; i < SlaveOffsets.Count; i++)
            {
                SlaveOffsets[i] = SlaveOffsets[i] / Furthest;
            }

            MinOffMult  = Furthest * 2f;
            OffsetMulti = Furthest * 1e6f;             // looks pretty
            Logger.DebugLog("created new cluster, missiles: " + missiles.Count + ", slaves: " + Slaves.Count + ", offsets: " + SlaveOffsets.Count + ", furthest: " + Furthest, Rynchodon.Logger.severity.DEBUG);
        }
Пример #14
0
 private void GetMissingComponents(IMySlimBlock slim)
 {
     using (MainLock.AcquireSharedUsing())
         slim.GetMissingComponents(m_components_missing);
 }
Пример #15
0
        /// <summary>
        /// Initializes if needed, issues updates.
        /// </summary>
        public override void UpdateAfterSimulation()
        {
            MainLock.MainThread_ReleaseExclusive();
            try
            {
                switch (ManagerStatus)
                {
                case Status.Not_Initialized:
                    Init();
                    return;

                case Status.Initialized:
                    if (ServerSettings.ServerSettingsLoaded)
                    {
                        Log.DebugLog("Server settings loaded");
                        Start();
                    }
                    return;

                case Status.Terminated:
                    return;
                }
                Dictionary <Action, uint> Unregister = null;

                if (AddRemoveActions.Count != 0)
                {
                    try
                    { AddRemoveActions.PopHeadInvokeAll(); }
                    catch (Exception ex)
                    { Log.AlwaysLog("Exception in AddRemoveActions: " + ex, Logger.severity.ERROR); }
                }

                if (ExternalRegistrations.Count != 0)
                {
                    try
                    { ExternalRegistrations.PopHeadInvokeAll(); }
                    catch (Exception ex)
                    { Log.AlwaysLog("Exception in ExternalRegistrations: " + ex, Logger.severity.ERROR); }
                }

                foreach (KeyValuePair <uint, List <Action> > pair in UpdateRegistrar)
                {
                    if (Globals.UpdateCount % pair.Key == 0)
                    {
                        foreach (Action item in pair.Value)
                        {
                            try
                            {
                                Profiler.StartProfileBlock(item);
                                item.Invoke();
                                Profiler.EndProfileBlock();
                            }
                            catch (Exception ex2)
                            {
                                if (Unregister == null)
                                {
                                    Unregister = new Dictionary <Action, uint>();
                                }
                                if (!Unregister.ContainsKey(item))
                                {
                                    Log.AlwaysLog("Script threw exception, unregistering: " + ex2, Logger.severity.ERROR);
                                    Logger.DebugNotify("A script has been terminated", 10000, Logger.severity.ERROR);
                                    Unregister.Add(item, pair.Key);
                                }
                            }
                        }
                    }
                }

                if (Unregister != null)
                {
                    foreach (KeyValuePair <Action, uint> pair in Unregister)
                    {
                        UnRegisterForUpdates(pair.Value, pair.Key);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.AlwaysLog("Exception: " + ex, Logger.severity.FATAL);
                ManagerStatus = Status.Terminated;
            }
            finally
            {
                Globals.UpdateCount++;

                float instantSimSpeed = Globals.UpdateDuration / (float)(DateTime.UtcNow - m_lastUpdate).TotalSeconds;
                if (instantSimSpeed > 0.01f && instantSimSpeed < 1.1f)
                {
                    Globals.SimSpeed = Globals.SimSpeed * 0.9f + instantSimSpeed * 0.1f;
                }
                //Log.DebugLog("instantSimSpeed: " + instantSimSpeed + ", SimSpeed: " + Globals.SimSpeed);
                m_lastUpdate = DateTime.UtcNow;

                MainLock.MainThread_AcquireExclusive();
            }
        }
Пример #16
0
 public UpdateManager()
 {
     ThreadTracker.SetGameThread();
     Instance = this;
     MainLock.MainThread_AcquireExclusive();
 }