Ejemplo n.º 1
0
        public void UpdateActiveControlDictionary(MyCubeBlock block, long playerId, bool updateAdd)
        {
            var grid = block?.CubeGrid;

            if (block == null || grid == null)
            {
                return;
            }
            GridAi trackingAi;

            if (updateAdd) //update/add
            {
                if (GridTargetingAIs.TryGetValue(grid, out trackingAi))
                {
                    trackingAi.ControllingPlayers[playerId] = block;
                    trackingAi.ControllingPlayers.ApplyAdditionsAndModifications();
                }
            }
            else //remove
            {
                if (GridTargetingAIs.TryGetValue(grid, out trackingAi))
                {
                    trackingAi.ControllingPlayers.TryGetValue(playerId, out block);
                }
            }
        }
 private void UpdatePlacer()
 {
     if (!Placer.Visible)
     {
         Placer = null;
     }
     if (!MyCubeBuilder.Static.DynamicMode && MyCubeBuilder.Static.HitInfo.HasValue)
     {
         var    hit  = MyCubeBuilder.Static.HitInfo.Value as IHitInfo;
         var    grid = hit.HitEntity as MyCubeGrid;
         GridAi gridAi;
         if (grid != null && GridTargetingAIs.TryGetValue(grid, out gridAi))
         {
             if (MyCubeBuilder.Static.CurrentBlockDefinition != null)
             {
                 var         subtypeIdHash = MyCubeBuilder.Static.CurrentBlockDefinition.Id.SubtypeId;
                 WeaponCount weaponCount;
                 if (gridAi.WeaponCounter.TryGetValue(subtypeIdHash, out weaponCount))
                 {
                     if (weaponCount.Current >= weaponCount.Max && weaponCount.Max > 0)
                     {
                         MyCubeBuilder.Static.NotifyPlacementUnable();
                         MyCubeBuilder.Static.Deactivate();
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 3
0
        private bool ClientAiDataUpdate(PacketObj data)
        {
            var packet       = data.Packet;
            var myGrid       = MyEntities.GetEntityByIdOrDefault(packet.EntityId) as MyCubeGrid;
            var aiSyncPacket = (AiDataPacket)packet;

            if (myGrid == null)
            {
                return(Error(data, Msg($"Grid: {packet.EntityId}")));
            }

            GridAi ai;

            if (GridTargetingAIs.TryGetValue(myGrid, out ai))
            {
                if (ai.MIds[(int)packet.PType] < packet.MId)
                {
                    ai.MIds[(int)packet.PType] = packet.MId;

                    ai.Data.Repo.Sync(aiSyncPacket.Data);
                }
                else
                {
                    Log.Line($"ClientAiDataUpdate: mid fail - senderId:{packet.SenderId} - mId:{ai.MIds[(int)packet.PType]} >= {packet.MId}");
                }

                data.Report.PacketValid = true;
            }
            else
            {
                return(Error(data, Msg($"GridAi not found, is marked:{myGrid.MarkedForClose}, has root:{GridToMasterAi.ContainsKey(myGrid)}")));
            }

            return(true);
        }
Ejemplo n.º 4
0
        private void InitComp(MyCubeBlock cube, bool thread = true)
        {
            using (cube.Pin())
            {
                if (cube.MarkedForClose)
                {
                    return;
                }
                GridAi gridAi;
                if (!GridTargetingAIs.TryGetValue(cube.CubeGrid, out gridAi))
                {
                    gridAi = GridAiPool.Get();
                    gridAi.Init(cube.CubeGrid, this);
                    GridTargetingAIs.TryAdd(cube.CubeGrid, gridAi);
                }

                var blockDef = ReplaceVanilla && VanillaIds.ContainsKey(cube.BlockDefinition.Id) ? VanillaIds[cube.BlockDefinition.Id] : cube.BlockDefinition.Id.SubtypeId;

                var weaponComp = new WeaponComponent(this, gridAi, cube, blockDef);
                if (gridAi != null && gridAi.WeaponBase.TryAdd(cube, weaponComp))
                {
                    if (!gridAi.WeaponCounter.ContainsKey(blockDef))
                    {
                        gridAi.WeaponCounter.TryAdd(blockDef, WeaponCountPool.Get());
                    }

                    CompsToStart.Add(weaponComp);
                    if (thread)
                    {
                        CompsToStart.ApplyAdditions();
                    }
                }
            }
        }
        private void PlayerControlAcquired(MyEntity lastEnt)
        {
            var    cube = lastEnt as MyCubeBlock;
            GridAi gridAi;

            if (cube != null && GridTargetingAIs.TryGetValue(cube.CubeGrid, out gridAi))
            {
                gridAi.TurnManualShootOff();
            }
        }
Ejemplo n.º 6
0
        private void PlayerControlNotify(MyEntity entity)
        {
            var    cube = entity as MyCubeBlock;
            GridAi gridAi;

            if (cube != null && GridTargetingAIs.TryGetValue(cube.CubeGrid, out gridAi))
            {
                if (HandlesInput && gridAi.AiOwner == 0)
                {
                    MyAPIGateway.Utilities.ShowNotification($"Ai computer is not owned, take ownership of grid weapons! - current ownerId is: {gridAi.AiOwner}", 10000);
                }
            }
        }
Ejemplo n.º 7
0
        private void CustomControlHandler(IMyTerminalBlock block, List <IMyTerminalControl> controls)
        {
            var    cube = (MyCubeBlock)block;
            GridAi gridAi;

            if (GridTargetingAIs.TryGetValue(cube.CubeGrid, out gridAi))
            {
                gridAi.LastTerminal = block;
                WeaponComponent comp;
                if (gridAi.WeaponBase.TryGetValue(cube, out comp) && comp.Platform.State == MyWeaponPlatform.PlatformState.Ready)
                {
                    gridAi.LastWeaponTerminal   = block;
                    gridAi.WeaponTerminalAccess = true;

                    int rangeControl = -1;
                    IMyTerminalControl wcRangeControl = null;
                    for (int i = controls.Count - 1; i >= 0; i--)
                    {
                        if (controls[i].Id.Equals("Range"))
                        {
                            rangeControl = i;
                            controls.RemoveAt(i);
                        }
                        else if (controls[i].Id.Equals("WC_Range"))
                        {
                            wcRangeControl = controls[i];
                            controls.RemoveAt(i);
                        }
                    }

                    if (rangeControl != -1)
                    {
                        controls.RemoveAt(rangeControl);
                    }

                    if (wcRangeControl != null)
                    {
                        if (rangeControl != -1)
                        {
                            controls.Insert(rangeControl, wcRangeControl);
                        }

                        else
                        {
                            controls.Add(wcRangeControl);
                        }
                    }
                }
            }
        }
Ejemplo n.º 8
0
        private void PlayerControlAcquired(MyEntity lastEnt)
        {
            var    cube = lastEnt as MyCubeBlock;
            GridAi gridAi;

            if (cube != null && GridTargetingAIs.TryGetValue(cube.CubeGrid, out gridAi))
            {
                CoreComponent comp;
                if (gridAi.WeaponBase.TryGetValue(cube, out comp))
                {
                    comp.RequestShootUpdate(CoreComponent.ShootActions.ShootOff, comp.Session.DedicatedServer ? 0 : -1);
                }
            }
        }
Ejemplo n.º 9
0
        private bool ClientFakeTargetUpdate(PacketObj data)
        {
            var packet = data.Packet;

            data.ErrorPacket.NoReprocess = true;
            var targetPacket = (FakeTargetPacket)packet;
            var myGrid       = MyEntities.GetEntityByIdOrDefault(packet.EntityId) as MyCubeGrid;

            GridAi ai;

            if (myGrid != null && GridTargetingAIs.TryGetValue(myGrid, out ai))
            {
                if (ai.MIds[(int)packet.PType] < packet.MId)
                {
                    ai.MIds[(int)packet.PType] = packet.MId;

                    long playerId;
                    if (SteamToPlayer.TryGetValue(packet.SenderId, out playerId))
                    {
                        FakeTarget dummyTarget;
                        if (PlayerDummyTargets.TryGetValue(playerId, out dummyTarget))
                        {
                            dummyTarget.Update(targetPacket.Pos, ai, null, targetPacket.TargetId);
                        }
                        else
                        {
                            return(Error(data, Msg("Player dummy target not found")));
                        }
                    }
                    else
                    {
                        return(Error(data, Msg("SteamToPlayer missing Player")));
                    }
                }
                else
                {
                    Log.Line($"ClientFakeTargetUpdate: mid fail - senderId:{packet.SenderId} - mId:{ai.MIds[(int)packet.PType]} >= {packet.MId}");
                }

                data.Report.PacketValid = true;
            }
            else
            {
                return(Error(data, Msg($"GridId: {packet.EntityId}", myGrid != null), Msg("Ai")));
            }

            return(true);
        }
Ejemplo n.º 10
0
        private void DrawDisabledGuns()
        {
            if (Tick600 || Tick60 && QuickDisableGunsCheck)
            {
                QuickDisableGunsCheck         = false;
                _nearbyGridsTestSphere.Center = CameraPos;
                _gridsNearCamera.Clear();
                _uninitializedBlocks.Clear();

                MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref _nearbyGridsTestSphere, _gridsNearCamera);
                for (int i = _gridsNearCamera.Count - 1; i >= 0; i--)
                {
                    var grid = _gridsNearCamera[i] as MyCubeGrid;
                    if (grid?.Physics != null && !grid.MarkedForClose && !grid.IsPreview && !grid.Physics.IsPhantom)
                    {
                        var fatBlocks = grid.GetFatBlocks();
                        for (int j = 0; j < fatBlocks.Count; j++)
                        {
                            var block = fatBlocks[j];
                            if (block.IsFunctional && WeaponPlatforms.ContainsKey(block.BlockDefinition.Id))
                            {
                                GridAi gridAi;
                                if (!GridTargetingAIs.TryGetValue(block.CubeGrid, out gridAi) || !gridAi.WeaponBase.ContainsKey(block))
                                {
                                    _uninitializedBlocks.Add(block);
                                }
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < _uninitializedBlocks.Count; i++)
            {
                var badBlock = _uninitializedBlocks[i];
                if (badBlock.InScene)
                {
                    var lookSphere = new BoundingSphereD(badBlock.PositionComp.WorldAABB.Center, 30f);
                    if (Camera.IsInFrustum(ref lookSphere))
                    {
                        MyOrientedBoundingBoxD blockBox;
                        SUtils.GetBlockOrientedBoundingBox(badBlock, out blockBox);
                        DsDebugDraw.DrawBox(blockBox, _uninitializedColor);
                    }
                }
            }
        }
        internal bool UpdateLocalAiAndCockpit()
        {
            InGridAiBlock      = false;
            ActiveControlBlock = ControlledEntity as MyCubeBlock;
            ActiveCockPit      = ActiveControlBlock as MyCockpit;

            var activeBlock = ActiveCockPit ?? ActiveControlBlock;

            if (activeBlock != null && (GridTargetingAIs.TryGetValue(activeBlock.CubeGrid, out TrackingAi) || GridToMasterAi.TryGetValue(activeBlock.CubeGrid, out TrackingAi)))
            {
                InGridAiBlock = true;
                MyCubeBlock oldBlock;
                TrackingAi.ControllingPlayers.TryGetValue(PlayerId, out oldBlock);
                TrackingAi.ControllingPlayers[PlayerId] = ActiveControlBlock;
                TrackingAi.ControllingPlayers.ApplyAdditionsAndModifications();

                if (HandlesInput && oldBlock != ActiveControlBlock)
                {
                    SendActiveControlUpdate(activeBlock, true);
                }
            }
            else
            {
                if (TrackingAi != null)
                {
                    TrackingAi.Focus.IsFocused(TrackingAi);

                    MyCubeBlock oldBlock;
                    if (HandlesInput && TrackingAi.ControllingPlayers.TryGetValue(PlayerId, out oldBlock))
                    {
                        SendActiveControlUpdate(oldBlock, false);
                    }

                    TrackingAi.ControllingPlayers.Remove(PlayerId, true);
                    TrackingAi.ControllingPlayers.ApplyRemovals();
                }

                TrackingAi         = null;
                ActiveCockPit      = null;
                ActiveControlBlock = null;
            }
            return(InGridAiBlock);
        }
Ejemplo n.º 12
0
        private bool ServerMarkedTargetUpdate(PacketObj data)
        {
            var packet       = data.Packet;
            var targetPacket = (FakeTargetPacket)packet;
            var myGrid       = MyEntities.GetEntityByIdOrDefault(packet.EntityId) as MyCubeGrid;

            if (myGrid == null)
            {
                return(Error(data, Msg($"GridId:{packet.EntityId} - entityExists:{MyEntities.EntityExists(packet.EntityId)}")));
            }


            GridAi ai;
            long   playerId;

            if (GridTargetingAIs.TryGetValue(myGrid, out ai) && SteamToPlayer.TryGetValue(packet.SenderId, out playerId))
            {
                GridAi.FakeTargets fakeTargets;
                uint[]             mIds;
                if (PlayerMIds.TryGetValue(packet.SenderId, out mIds) && mIds[(int)packet.PType] < packet.MId && PlayerDummyTargets.TryGetValue(playerId, out fakeTargets))
                {
                    mIds[(int)packet.PType] = packet.MId;

                    fakeTargets.PaintedTarget.Sync(targetPacket, ai);
                    PacketsToClient.Add(new PacketInfo {
                        Entity = myGrid, Packet = targetPacket
                    });

                    data.Report.PacketValid = true;
                }
                else
                {
                    Log.Line($"ServerFakeTargetUpdate: MidsHasSenderId:{PlayerMIds.ContainsKey(packet.SenderId)} - midsNull:{mIds == null} - senderId:{packet.SenderId}");
                }
            }
            else
            {
                return(Error(data, Msg($"GridAi not found, is marked:{myGrid.MarkedForClose}, has root:{GridToMasterAi.ContainsKey(myGrid)}")));
            }

            return(true);
        }
        internal void SetTarget(MyEntity entity, GridAi ai)
        {
            TrackingAi = ai;
            TrackingAi.Focus.AddFocus(entity, ai);

            GridAi gridAi;

            TargetArmed = false;
            var grid = entity as MyCubeGrid;

            if (grid != null && GridTargetingAIs.TryGetValue(grid, out gridAi))
            {
                TargetArmed = true;
            }
            else
            {
                TargetInfo info;
                if (!ai.Targets.TryGetValue(entity, out info))
                {
                    return;
                }
                ConcurrentDictionary <BlockTypes, ConcurrentCachingList <MyCubeBlock> > typeDict;

                if (info.IsGrid && GridToBlockTypeMap.TryGetValue((MyCubeGrid)info.Target, out typeDict))
                {
                    ConcurrentCachingList <MyCubeBlock> fatList;
                    if (typeDict.TryGetValue(WeaponDefinition.TargetingDef.BlockTypes.Offense, out fatList))
                    {
                        TargetArmed = fatList.Count > 0;
                    }
                    else
                    {
                        TargetArmed = false;
                    }
                }
                else
                {
                    TargetArmed = false;
                }
            }
        }
Ejemplo n.º 14
0
        private void CustomControlHandler(IMyTerminalBlock block, List <IMyTerminalControl> controls)
        {
            LastTerminal = block;

            var    cube = (MyCubeBlock)block;
            GridAi gridAi;

            if (GridTargetingAIs.TryGetValue(cube.CubeGrid, out gridAi))
            {
                gridAi.LastTerminal = block;
                CoreComponent comp;
                if (gridAi.WeaponBase.TryGetValue(cube, out comp) && comp.Platform.State == CorePlatform.PlatformState.Ready)
                {
                    TerminalMon.HandleInputUpdate(comp);
                    IMyTerminalControl wcRangeControl = null;
                    for (int i = controls.Count - 1; i >= 0; i--)
                    {
                        var control = controls[i];
                        if (control.Id.Equals("Range"))
                        {
                            controls.RemoveAt(i);
                        }
                        else if (control.Id.Equals("UseConveyor"))
                        {
                            controls.RemoveAt(i);
                        }
                        else if (control.Id.Equals("WC_Range"))
                        {
                            wcRangeControl = control;
                            controls.RemoveAt(i);
                        }
                    }

                    if (wcRangeControl != null)
                    {
                        controls.Add(wcRangeControl);
                    }
                }
            }
        }
Ejemplo n.º 15
0
        private bool ClientFakeTargetUpdate(PacketObj data)
        {
            var packet = data.Packet;

            data.ErrorPacket.NoReprocess = true;
            var targetPacket = (FakeTargetPacket)packet;
            var myGrid       = MyEntities.GetEntityByIdOrDefault(packet.EntityId) as MyCubeGrid;

            GridAi ai;

            if (myGrid != null && GridTargetingAIs.TryGetValue(myGrid, out ai))
            {
                long playerId;
                if (SteamToPlayer.TryGetValue(packet.SenderId, out playerId))
                {
                    FakeTargets dummyTargets;
                    if (PlayerDummyTargets.TryGetValue(playerId, out dummyTargets))
                    {
                        dummyTargets.ManualTarget.Sync(targetPacket, ai);
                        dummyTargets.PaintedTarget.Sync(targetPacket, ai);
                    }
                    else
                    {
                        return(Error(data, Msg("Player dummy target not found")));
                    }
                }
                else
                {
                    return(Error(data, Msg("SteamToPlayer missing Player")));
                }

                data.Report.PacketValid = true;
            }
            else
            {
                return(Error(data, Msg($"GridId: {packet.EntityId}", myGrid != null), Msg("Ai")));
            }

            return(true);
        }
Ejemplo n.º 16
0
        private bool ServerActiveControlUpdate(PacketObj data)
        {
            var packet  = data.Packet;
            var dPacket = (BoolUpdatePacket)packet;
            var cube    = MyEntities.GetEntityByIdOrDefault(packet.EntityId) as MyCubeBlock;

            if (cube == null)
            {
                return(Error(data, Msg("Cube")));
            }

            GridAi ai;
            long   playerId = 0;

            if (GridToMasterAi.TryGetValue(cube.CubeGrid, out ai) && SteamToPlayer.TryGetValue(packet.SenderId, out playerId))
            {
                uint[] mIds;
                if (PlayerMIds.TryGetValue(packet.SenderId, out mIds) && mIds[(int)packet.PType] < packet.MId)
                {
                    mIds[(int)packet.PType] = packet.MId;

                    ai.Construct.UpdateConstructsPlayers(cube, playerId, dPacket.Data);
                    data.Report.PacketValid = true;
                }
                else
                {
                    Log.Line($"ServerActiveControlUpdate: MidsHasSenderId:{PlayerMIds.ContainsKey(packet.SenderId)} - midsNull:{mIds == null} - senderId:{packet.SenderId}");
                }
            }
            else
            {
                Log.Line($"ServerActiveControlUpdate: ai:{ai != null} - targetingAi:{GridTargetingAIs.ContainsKey(cube.CubeGrid)} - masterAi:{GridToMasterAi.ContainsKey(cube.CubeGrid)} - IdToComp:{IdToCompMap.ContainsKey(cube.EntityId)} - {cube.BlockDefinition.Id.SubtypeName} - playerId:{playerId}({packet.SenderId}) - marked:{cube.MarkedForClose}({cube.CubeGrid.MarkedForClose}) - active:{dPacket.Data}");
            }

            return(true);
        }
Ejemplo n.º 17
0
        private bool CompRestricted(CoreComponent comp)
        {
            var grid = comp.MyCube?.CubeGrid;

            GridAi ai;

            if (grid == null || !GridTargetingAIs.TryGetValue(grid, out ai))
            {
                return(false);
            }

            MyOrientedBoundingBoxD b;
            BoundingSphereD        s;
            MyOrientedBoundingBoxD blockBox;

            SUtils.GetBlockOrientedBoundingBox(comp.MyCube, out blockBox);

            if (IsWeaponAreaRestricted(comp.MyCube.BlockDefinition.Id.SubtypeId, blockBox, grid, comp.MyCube.EntityId, ai, out b, out s))
            {
                if (!DedicatedServer)
                {
                    if (comp.MyCube.OwnerId == PlayerId)
                    {
                        MyAPIGateway.Utilities.ShowNotification($"Block {comp.MyCube.DisplayNameText} was placed too close to another gun", 10000);
                    }
                }

                if (IsServer)
                {
                    comp.MyCube.CubeGrid.RemoveBlock(comp.MyCube.SlimBlock);
                }
                return(true);
            }

            return(false);
        }
Ejemplo n.º 18
0
        private void ProcessDbsCallBack()
        {
            try
            {
                DsUtil.Start("db");
                for (int d = 0; d < DbsToUpdate.Count; d++)
                {
                    var db = DbsToUpdate[d];

                    db.TargetingInfo.Clean();

                    if (db.MyPlanetTmp != null)
                    {
                        db.MyPlanetInfo();
                    }

                    foreach (var sub in db.PrevSubGrids)
                    {
                        db.SubGrids.Add(sub);
                    }
                    if (db.SubGridsChanged)
                    {
                        db.SubGridChanges();
                    }

                    for (int i = 0; i < db.SortedTargets.Count; i++)
                    {
                        var tInfo = db.SortedTargets[i];
                        tInfo.Target   = null;
                        tInfo.MyAi     = null;
                        tInfo.MyGrid   = null;
                        tInfo.TargetAi = null;
                        TargetInfoPool.Return(db.SortedTargets[i]);
                    }
                    db.SortedTargets.Clear();
                    db.Targets.Clear();

                    var newEntCnt = db.NewEntities.Count;
                    db.SortedTargets.Capacity = newEntCnt;
                    for (int i = 0; i < newEntCnt; i++)
                    {
                        var detectInfo = db.NewEntities[i];
                        var ent        = detectInfo.Parent;
                        if (ent.Physics == null)
                        {
                            continue;
                        }

                        var    grid     = ent as MyCubeGrid;
                        GridAi targetAi = null;

                        if (grid != null)
                        {
                            GridTargetingAIs.TryGetValue(grid, out targetAi);
                        }

                        var targetInfo = TargetInfoPool.Get();
                        targetInfo.Init(ref detectInfo, db.MyGrid, db, targetAi);

                        db.SortedTargets.Add(targetInfo);
                        db.Targets[ent] = targetInfo;

                        if (targetInfo.Target == db.Focus.Target[0] || targetInfo.Target == db.Focus.Target[1] || targetInfo.DistSqr < db.MaxTargetingRangeSqr && targetInfo.DistSqr < db.TargetingInfo.ThreatRangeSqr && targetInfo.OffenseRating > 0 && (targetInfo.EntInfo.Relationship != MyRelationsBetweenPlayerAndBlock.Friends || targetInfo.EntInfo.Relationship == MyRelationsBetweenPlayerAndBlock.FactionShare))
                        {
                            db.TargetingInfo.TargetInRange  = true;
                            db.TargetingInfo.ThreatRangeSqr = targetInfo.DistSqr;
                        }
                    }
                    db.NewEntities.Clear();
                    db.SortedTargets.Sort(TargetCompare);
                    db.TargetAis.Clear();
                    db.TargetAis.AddRange(db.TargetAisTmp);
                    db.TargetAisTmp.Clear();

                    db.Obstructions.Clear();
                    db.Obstructions.AddRange(db.ObstructionsTmp);
                    db.ObstructionsTmp.Clear();

                    if (db.PlanetSurfaceInRange)
                    {
                        db.StaticsInRangeTmp.Add(db.MyPlanet);
                    }
                    db.StaticsInRange.Clear();
                    db.StaticsInRange.AddRange(db.StaticsInRangeTmp);
                    db.StaticsInRangeTmp.Clear();
                    db.StaticEntitiesInRange = db.StaticsInRange.Count > 0;
                    db.MyStaticInfo();

                    db.DbReady        = db.SortedTargets.Count > 0 || db.TargetAis.Count > 0 || Tick - db.LiveProjectileTick < 3600 || db.LiveProjectile.Count > 0 || db.ControllingPlayers.Keys.Count > 0 || db.FirstRun;
                    db.MyShield       = db.MyShieldTmp;
                    db.NaturalGravity = db.FakeShipController.GetNaturalGravity();
                    db.ShieldNear     = db.ShieldNearTmp;
                    db.BlockCount     = db.MyGrid.BlocksCount;
                    db.Concealed      = ((uint)db.MyGrid.Flags & 4) > 0;

                    if (db.ScanBlockGroups || db.WeaponTerminalReleased())
                    {
                        db.ReScanBlockGroups();
                    }

                    db.FirstRun = false;
                }
                DbsToUpdate.Clear();
                DsUtil.Complete("db", true);
                DbCallBackComplete = true;
            }
            catch (Exception ex) { Log.Line($"Exception in ProcessDbsCallBack: {ex}"); }
        }
Ejemplo n.º 19
0
        internal void PurgeAll()
        {
            PurgedAll = true;
            FutureEvents.Purge((int)Tick);


            foreach (var comp in CompsToStart)
            {
                if (comp?.Platform != null)
                {
                    CloseComps(comp.MyCube);
                }
            }

            foreach (var readd in CompReAdds)
            {
                if (!readd.Ai.Closed)
                {
                    readd.Ai.AiForceClose();
                }
                if (readd.Comp?.Platform != null)
                {
                    CloseComps(readd.Comp.MyCube);
                }
            }

            foreach (var comp in CompsDelayed)
            {
                if (comp?.Platform != null)
                {
                    CloseComps(comp.MyCube);
                }
            }

            foreach (var gridAi in DelayedAiClean)
            {
                if (!gridAi.Closed)
                {
                    gridAi.AiForceClose();
                }
            }

            PlatFormPool.Clean();
            CompsToStart.ClearImmediate();
            DelayedAiClean.ClearImmediate();

            CompsDelayed.Clear();
            CompReAdds.Clear();
            GridAiPool.Clean();


            PurgeTerminalSystem(this);
            HudUi.Purge();
            TerminalMon.Purge();
            foreach (var reports in Reporter.ReportData.Values)
            {
                foreach (var report in reports)
                {
                    report.Clean();
                    Reporter.ReportPool.Return(report);
                }
                reports.Clear();
            }
            Reporter.ReportData.Clear();
            Reporter.ReportPool.Clean();

            PacketsToClient.Clear();
            PacketsToServer.Clear();

            AcqManager.Clean();

            CleanSounds(true);

            foreach (var e in Emitters)
            {
                e.StopSound(true);
            }
            foreach (var e in Av.HitEmitters)
            {
                e.StopSound(true);
            }
            foreach (var e in Av.FireEmitters)
            {
                e.StopSound(true);
            }
            foreach (var e in Av.TravelEmitters)
            {
                e.StopSound(true);
            }

            Emitters.Clear();
            Av.HitEmitters.Clear();
            Av.FireEmitters.Clear();
            Av.TravelEmitters.Clear();

            foreach (var item in EffectedCubes)
            {
                var cubeid     = item.Key;
                var blockInfo  = item.Value;
                var functBlock = blockInfo.FunctBlock;

                if (functBlock == null || functBlock.MarkedForClose)
                {
                    _effectPurge.Enqueue(cubeid);
                    continue;
                }

                functBlock.EnabledChanged -= ForceDisable;
                functBlock.Enabled         = blockInfo.FirstState;
                functBlock.SetDamageEffect(false);
                if (HandlesInput)
                {
                    functBlock.AppendingCustomInfo -= blockInfo.AppendCustomInfo;
                }
                _effectPurge.Enqueue(cubeid);
            }

            while (_effectPurge.Count != 0)
            {
                EffectedCubes.Remove(_effectPurge.Dequeue());
            }

            Av.Glows.Clear();
            Av.AvShotPool.Clean();

            DeferedUpBlockTypeCleanUp(true);
            BlockTypeCleanUp.Clear();

            foreach (var map in GridToInfoMap.Keys)
            {
                RemoveGridFromMap(map);
            }

            GridToInfoMap.Clear();
            GridMapPool.Clean();

            DirtyGridsTmp.Clear();

            foreach (var structure in WeaponPlatforms.Values)
            {
                foreach (var system in structure.WeaponSystems)
                {
                    system.Value.PreFirePairs.Clear();
                    system.Value.FireWhenDonePairs.Clear();
                    system.Value.FirePerShotPairs.Clear();
                    system.Value.RotatePairs.Clear();
                    system.Value.ReloadPairs.Clear();
                    foreach (var ammo in system.Value.AmmoTypes)
                    {
                        ammo.AmmoDef.Const.PrimeEntityPool?.Clean();
                        ammo.AmmoDef.Const.HitDefaultSoundPairs.Clear();
                        ammo.AmmoDef.Const.HitVoxelSoundPairs.Clear();
                        ammo.AmmoDef.Const.HitShieldSoundPairs.Clear();
                        ammo.AmmoDef.Const.HitFloatingSoundPairs.Clear();
                        ammo.AmmoDef.Const.HitPlayerSoundPairs.Clear();
                        ammo.AmmoDef.Const.TravelSoundPairs.Clear();
                        ammo.AmmoDef.Const.CustomSoundPairs.Clear();
                    }
                }

                structure.WeaponSystems.Clear();
            }
            WeaponPlatforms.Clear();

            foreach (var gridToMap in GridToBlockTypeMap)
            {
                foreach (var map in gridToMap.Value)
                {
                    ConcurrentListPool.Return(map.Value);
                }
                gridToMap.Value.Clear();
                BlockTypePool.Return(gridToMap.Value);
            }
            GridToBlockTypeMap.Clear();

            foreach (var playerGrids in PlayerEntityIdInRange)
            {
                playerGrids.Value.Clear();
            }

            PlayerEntityIdInRange.Clear();
            DirtyGridInfos.Clear();

            DsUtil.Purge();
            DsUtil2.Purge();

            ShootingWeapons.Clear();
            WeaponToPullAmmo.Clear();
            AmmoToPullQueue.Clear();
            ChargingWeaponsIndexer.Clear();
            WeaponsToRemoveAmmoIndexer.Clear();
            ChargingWeapons.Clear();
            Hits.Clear();
            HomingWeapons.Clear();
            GridToMasterAi.Clear();
            Players.Clear();
            IdToCompMap.Clear();
            AllArmorBaseDefinitions.Clear();
            HeavyArmorBaseDefinitions.Clear();
            AllArmorBaseDefinitions.Clear();
            AcquireTargets.Clear();
            LargeBlockSphereDb.Clear();
            SmallBlockSphereDb.Clear();
            AnimationsToProcess.Clear();
            _subTypeIdToWeaponDefs.Clear();
            WeaponDefinitions.Clear();
            SlimsSortedList.Clear();
            _destroyedSlims.Clear();
            _destroyedSlimsClient.Clear();
            _slimHealthClient.Clear();
            _slimsSet.Clear();
            _turretDefinitions.Clear();
            _tmpNearByBlocks.Clear();

            foreach (var av in Av.AvShots)
            {
                av.GlowSteps.Clear();
                Av.AvShotPool.Return(av);
            }
            Av.AvShotPool.Clean();
            Av.AvBarrels1.Clear();
            Av.AvBarrels2.Clear();
            Av.AvShots.Clear();
            Av.HitSounds.Clear();

            foreach (var errorpkt in ClientSideErrorPkt)
            {
                errorpkt.Packet.CleanUp();
            }
            ClientSideErrorPkt.Clear();

            GridEffectPool.Clean();
            GridEffectsPool.Clean();
            BlockTypePool.Clean();
            ConcurrentListPool.Clean();

            TargetInfoPool.Clean();
            PacketObjPool.Clean();

            InventoryMoveRequestPool.Clean();
            WeaponCoreBlockDefs.Clear();
            VanillaIds.Clear();
            VanillaCoreIds.Clear();
            WeaponCoreFixedBlockDefs.Clear();
            WeaponCoreTurretBlockDefs.Clear();
            VoxelCaches.Clear();
            ArmorCubes.Clear();

            foreach (var p in Projectiles.ProjectilePool)
            {
                p.Info?.AvShot?.AmmoEffect?.Stop();
            }

            Projectiles.ShrapnelToSpawn.Clear();
            Projectiles.ShrapnelPool.Clean();
            Projectiles.FragmentPool.Clean();
            Projectiles.ActiveProjetiles.Clear();
            Projectiles.ProjectilePool.Clear();
            Projectiles.HitEntityPool.Clean();
            Projectiles.VirtInfoPool.Clean();

            DbsToUpdate.Clear();
            GridTargetingAIs.Clear();

            DsUtil          = null;
            DsUtil2         = null;
            SlimsSortedList = null;
            Settings        = null;
            StallReporter   = null;
            TerminalMon     = null;
            Physics         = null;
            Camera          = null;
            Projectiles     = null;
            TrackingAi      = null;
            UiInput         = null;
            TargetUi        = null;
            Placer          = null;
            TargetGps       = null;
            SApi.Unload();
            SApi                = null;
            Api                 = null;
            ApiServer           = null;
            Reporter            = null;
            WeaponDefinitions   = null;
            AnimationsToProcess = null;
            ProjectileTree.Clear();
            ProjectileTree     = null;
            Av                 = null;
            HudUi              = null;
            AllDefinitions     = null;
            SoundDefinitions   = null;
            ActiveCockPit      = null;
            ActiveControlBlock = null;
            ControlledEntity   = null;
            TmpStorage         = null;
        }
        internal void PurgeAll()
        {
            FutureEvents.Purge((int)Tick);
            PurgeTerminalSystem();

            foreach (var reports in Reporter.ReportData.Values)
            {
                foreach (var report in reports)
                {
                    report.Clean();
                    Reporter.ReportPool.Return(report);
                }
                reports.Clear();
            }
            Reporter.ReportData.Clear();
            Reporter.ReportPool.Clean();

            PacketsToClient.Clear();
            PacketsToServer.Clear();

            foreach (var suit in (PacketType[])Enum.GetValues(typeof(PacketType)))
            {
                foreach (var pool in PacketPools.Values)
                {
                    pool.Clean();
                }
                PacketPools.Clear();
            }

            foreach (var item in _effectedCubes)
            {
                var cubeid     = item.Key;
                var blockInfo  = item.Value;
                var functBlock = blockInfo.FunctBlock;
                var cube       = blockInfo.CubeBlock;

                if (cube == null || cube.MarkedForClose)
                {
                    _effectPurge.Enqueue(cubeid);
                    continue;
                }

                functBlock.EnabledChanged -= ForceDisable;
                functBlock.Enabled         = blockInfo.FirstState;
                cube.SetDamageEffect(false);
                _effectPurge.Enqueue(cubeid);
            }

            while (_effectPurge.Count != 0)
            {
                _effectedCubes.Remove(_effectPurge.Dequeue());
            }

            Av.Glows.Clear();
            Av.AvShotPool.Clean();

            DeferedUpBlockTypeCleanUp(true);
            BlockTypeCleanUp.Clear();

            foreach (var map in GridToFatMap.Keys)
            {
                RemoveGridFromMap(map);
            }

            GridToFatMap.Clear();
            FatMapPool.Clean();

            DirtyGridsTmp.Clear();

            foreach (var structure in WeaponPlatforms.Values)
            {
                foreach (var system in structure.WeaponSystems)
                {
                    foreach (var ammo in system.Value.WeaponAmmoTypes)
                    {
                        ammo.AmmoDef.Const.PrimeEntityPool?.Clean();
                    }
                }

                structure.WeaponSystems.Clear();
            }
            WeaponPlatforms.Clear();

            foreach (var gridToMap in GridToBlockTypeMap)
            {
                foreach (var map in gridToMap.Value)
                {
                    map.Value.ClearImmediate();
                    ConcurrentListPool.Return(map.Value);
                }
                gridToMap.Value.Clear();
                BlockTypePool.Return(gridToMap.Value);
            }
            GridToBlockTypeMap.Clear();

            foreach (var playerGrids in PlayerEntityIdInRange)
            {
                playerGrids.Value.Clear();
            }

            PlayerEntityIdInRange.Clear();

            DirtyGrids.Clear();

            DsUtil.Purge();
            DsUtil2.Purge();

            _effectActive = false;
            ShootingWeapons.Clear();
            AcquireTargets.Clear();
            RemoveEffectsFromGrid.Clear();
            WeaponAmmoPullQueue.Clear();
            AmmoToPullQueue.Clear();
            Hits.Clear();
            AllArmorBaseDefinitions.Clear();
            HeavyArmorBaseDefinitions.Clear();
            AllArmorBaseDefinitions.Clear();
            AcquireTargets.Clear();
            ChargingWeapons.Clear();
            LargeBlockSphereDb.Clear();
            SmallBlockSphereDb.Clear();
            AnimationsToProcess.Clear();
            _subTypeIdToWeaponDefs.Clear();
            WeaponDefinitions.Clear();
            SlimsSortedList.Clear();
            _destroyedSlims.Clear();
            _destroyedSlimsClient.Clear();
            _slimHealthClient.Clear();
            _slimsSet.Clear();
            _turretDefinitions.Clear();

            foreach (var comp in CompsToStart)
            {
                PlatFormPool.Return(comp.Platform);
                comp.Platform = null;
            }

            foreach (var readd in CompReAdds)
            {
                PlatFormPool.Return(readd.Comp.Platform);
                readd.Comp.Platform = null;
            }
            foreach (var comp in CompsDelayed)
            {
                PlatFormPool.Return(comp.Platform);
                comp.Platform = null;
            }
            PlatFormPool.Clean();
            CompsToStart.ClearImmediate();

            CompsDelayed.Clear();
            CompReAdds.Clear();
            GridAiPool.Clean();

            Av.RipMap.Clear();
            foreach (var mess in Av.KeensBrokenParticles)
            {
                Av.KeenMessPool.Return(mess);
            }

            Av.KeensBrokenParticles.Clear();

            foreach (var av in Av.AvShots)
            {
                av.GlowSteps.Clear();
                Av.AvShotPool.Return(av);
            }
            Av.AvShotPool.Clean();
            Av.AvBarrels1.Clear();
            Av.AvBarrels2.Clear();
            Av.AvShots.Clear();
            Av.HitSounds.Clear();

            foreach (var errorpkt in ClientSideErrorPktList)
            {
                errorpkt.Packet.CleanUp();
            }
            ClientSideErrorPktList.Clear();

            GridEffectPool.Clean();
            GridEffectsPool.Clean();
            BlockTypePool.Clean();
            ConcurrentListPool.Clean();

            GroupInfoPool.Clean();
            TargetInfoPool.Clean();

            Projectiles.Clean();
            WeaponCoreBlockDefs.Clear();
            VanillaIds.Clear();
            VanillaCoreIds.Clear();
            WeaponCoreFixedBlockDefs.Clear();
            WeaponCoreTurretBlockDefs.Clear();

            foreach (var p in Projectiles.ProjectilePool)
            {
                p.AmmoEffect?.Stop();
            }

            Projectiles.ShrapnelToSpawn.Clear();
            Projectiles.ShrapnelPool.Clean();
            Projectiles.FragmentPool.Clean();
            Projectiles.ActiveProjetiles.ApplyChanges();
            Projectiles.ActiveProjetiles.Clear();
            Projectiles.ProjectilePool.Clear();
            Projectiles.HitEntityPool.Clean();
            Projectiles.CleanUp.Clear();
            Projectiles.VirtInfoPool.Clean();

            DbsToUpdate.Clear();
            GridTargetingAIs.Clear();

            DsUtil          = null;
            DsUtil2         = null;
            SlimsSortedList = null;
            Enforced        = null;
            StallReporter   = null;
            Proccessor      = null;
            Physics         = null;
            Camera          = null;
            Projectiles     = null;
            TrackingAi      = null;
            UiInput         = null;
            TargetUi        = null;
            Placer          = null;
            WheelUi         = null;
            TargetGps       = null;
            SApi.Unload();
            SApi                = null;
            Api                 = null;
            ApiServer           = null;
            Reporter            = null;
            WeaponDefinitions   = null;
            AnimationsToProcess = null;
            ProjectileTree.Clear();
            ProjectileTree     = null;
            Av                 = null;
            HudUi              = null;
            AllDefinitions     = null;
            SoundDefinitions   = null;
            ActiveCockPit      = null;
            ActiveControlBlock = null;
            ControlledEntity   = null;
        }
Ejemplo n.º 21
0
        private void DrawDisabledGuns()
        {
            if (Tick600 || Tick60 && QuickDisableGunsCheck)
            {
                QuickDisableGunsCheck         = false;
                _nearbyGridsTestSphere.Center = CameraPos;
                _gridsNearCamera.Clear();
                _uninitializedBlocks.Clear();
                _debugBlocks.Clear();

                MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref _nearbyGridsTestSphere, _gridsNearCamera);
                for (int i = _gridsNearCamera.Count - 1; i >= 0; i--)
                {
                    var grid = _gridsNearCamera[i] as MyCubeGrid;
                    if (grid?.Physics != null && !grid.MarkedForClose && !grid.IsPreview && !grid.Physics.IsPhantom)
                    {
                        var fatBlocks = grid.GetFatBlocks();
                        for (int j = 0; j < fatBlocks.Count; j++)
                        {
                            var block = fatBlocks[j];
                            if (block.IsFunctional && WeaponPlatforms.ContainsKey(block.BlockDefinition.Id))
                            {
                                GridAi          gridAi;
                                WeaponComponent comp;
                                if (!GridTargetingAIs.TryGetValue(block.CubeGrid, out gridAi) || !gridAi.WeaponBase.TryGetValue(block, out comp))
                                {
                                    _uninitializedBlocks.Add(block);
                                }
                                else if (comp != null && comp.Data.Repo.Base.Set.Overrides.Debug)
                                {
                                    _debugBlocks.Add(comp);
                                }
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < _uninitializedBlocks.Count; i++)
            {
                var badBlock = _uninitializedBlocks[i];
                if (badBlock.InScene)
                {
                    var lookSphere = new BoundingSphereD(badBlock.PositionComp.WorldAABB.Center, 30f);
                    if (Camera.IsInFrustum(ref lookSphere))
                    {
                        MyOrientedBoundingBoxD blockBox;
                        SUtils.GetBlockOrientedBoundingBox(badBlock, out blockBox);
                        DsDebugDraw.DrawBox(blockBox, _uninitializedColor);
                    }
                }
            }

            for (int i = 0; i < _debugBlocks.Count; i++)
            {
                var comp = _debugBlocks[i];
                if (comp.MyCube.InScene)
                {
                    var lookSphere = new BoundingSphereD(comp.MyCube.PositionComp.WorldAABB.Center, 100f);

                    if (Camera.IsInFrustum(ref lookSphere))
                    {
                        foreach (var w in comp.Platform.Weapons)
                        {
                            if (!w.AiEnabled && w.ActiveAmmoDef.AmmoDef.Trajectory.Guidance == WeaponDefinition.AmmoDef.TrajectoryDef.GuidanceType.Smart)
                            {
                                w.SmartLosDebug();
                            }
                        }
                    }
                }
            }
        }
        internal void EntityControlUpdate()
        {
            var lastControlledEnt = ControlledEntity;

            ControlledEntity = (MyEntity)MyAPIGateway.Session.ControlledObject;

            var entityChanged = lastControlledEnt != null && lastControlledEnt != ControlledEntity;

            if (entityChanged)
            {
                if (lastControlledEnt is MyCockpit || lastControlledEnt is MyRemoteControl)
                {
                    PlayerControlAcquired(lastControlledEnt);
                }

                if (ControlledEntity is IMyGunBaseUser && !(lastControlledEnt is IMyGunBaseUser))
                {
                    var    cube = (MyCubeBlock)ControlledEntity;
                    GridAi gridAi;
                    if (GridTargetingAIs.TryGetValue(cube.CubeGrid, out gridAi))
                    {
                        WeaponComponent comp;
                        if (gridAi.WeaponBase.TryGetValue(cube, out comp))
                        {
                            GunnerBlackList = true;
                            comp.State.Value.CurrentPlayerControl.PlayerId    = PlayerId;
                            comp.State.Value.CurrentPlayerControl.ControlType = ControlType.Camera;
                            ActiveControlBlock = (MyCubeBlock)ControlledEntity;
                            var controlStringLeft = MyAPIGateway.Input.GetControl(MyMouseButtonsEnum.Left).GetGameControlEnum().String;
                            MyVisualScriptLogicProvider.SetPlayerInputBlacklistState(controlStringLeft, PlayerId, false);
                            var controlStringRight = MyAPIGateway.Input.GetControl(MyMouseButtonsEnum.Right).GetGameControlEnum().String;
                            MyVisualScriptLogicProvider.SetPlayerInputBlacklistState(controlStringRight, PlayerId, false);
                            var controlStringMiddle = MyAPIGateway.Input.GetControl(MyMouseButtonsEnum.Middle).GetGameControlEnum().String;
                            MyVisualScriptLogicProvider.SetPlayerInputBlacklistState(controlStringMiddle, PlayerId, false);

                            if (HandlesInput && MpActive)
                            {
                                SendControlingPlayer(comp);
                            }
                        }
                    }
                }
                else if (!(ControlledEntity is IMyGunBaseUser) && lastControlledEnt is IMyGunBaseUser)
                {
                    if (GunnerBlackList)
                    {
                        GunnerBlackList = false;
                        var controlStringLeft = MyAPIGateway.Input.GetControl(MyMouseButtonsEnum.Left).GetGameControlEnum().String;
                        MyVisualScriptLogicProvider.SetPlayerInputBlacklistState(controlStringLeft, PlayerId, true);
                        var controlStringRight = MyAPIGateway.Input.GetControl(MyMouseButtonsEnum.Right).GetGameControlEnum().String;
                        MyVisualScriptLogicProvider.SetPlayerInputBlacklistState(controlStringRight, PlayerId, true);
                        var controlStringMiddle = MyAPIGateway.Input.GetControl(MyMouseButtonsEnum.Middle).GetGameControlEnum().String;
                        MyVisualScriptLogicProvider.SetPlayerInputBlacklistState(controlStringMiddle, PlayerId, true);
                        var    oldCube = lastControlledEnt as MyCubeBlock;
                        GridAi gridAi;
                        if (oldCube != null && GridTargetingAIs.TryGetValue(oldCube.CubeGrid, out gridAi))
                        {
                            WeaponComponent comp;
                            if (gridAi.WeaponBase.TryGetValue(oldCube, out comp))
                            {
                                comp.State.Value.CurrentPlayerControl.PlayerId    = -1;
                                comp.State.Value.CurrentPlayerControl.ControlType = ControlType.None;
                                ActiveControlBlock = null;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 23
0
        public bool IsWeaponAreaRestricted(MyStringHash subtype, MyOrientedBoundingBoxD cubeBoundingBox, MyCubeGrid myGrid, long ignoredEntity, GridAi gridAi, out MyOrientedBoundingBoxD restrictedBox, out BoundingSphereD restrictedSphere)
        {
            _tmpNearByBlocks.Clear();
            GridAi ai;

            if (gridAi == null)
            {
                if (!GridToMasterAi.ContainsKey(myGrid))
                {
                    restrictedSphere = new BoundingSphereD();
                    restrictedBox    = new MyOrientedBoundingBoxD();
                    return(false);
                }
                ai = GridToMasterAi[myGrid];
            }
            else
            {
                ai = gridAi;
            }

            CalculateRestrictedShapes(subtype, cubeBoundingBox, out restrictedBox, out restrictedSphere);
            var queryRadius = Math.Max(restrictedBox.HalfExtent.AbsMax(), restrictedSphere.Radius);

            if (queryRadius < 0.01)
            {
                return(false);
            }

            var restriction = WeaponAreaRestrictions[subtype];
            var checkBox    = restriction.RestrictionBoxInflation > 0;
            var checkSphere = restriction.RestrictionRadius > 0;
            var querySphere = new BoundingSphereD(cubeBoundingBox.Center, queryRadius);

            myGrid.Hierarchy.QuerySphere(ref querySphere, _tmpNearByBlocks);

            foreach (var grid in ai.SubGrids)
            {
                if (grid == myGrid || !GridTargetingAIs.ContainsKey(grid))
                {
                    continue;
                }
                grid.Hierarchy.QuerySphere(ref querySphere, _tmpNearByBlocks);
            }

            for (int l = 0; l < _tmpNearByBlocks.Count; l++)
            {
                var cube = _tmpNearByBlocks[l] as MyCubeBlock;
                if (cube == null || cube.EntityId == ignoredEntity || !WeaponCoreBlockDefs.ContainsKey(cube.BlockDefinition.Id.SubtypeId.String))
                {
                    continue;
                }

                if (!restriction.CheckForAnyWeapon && cube.BlockDefinition.Id.SubtypeId != subtype)
                {
                    continue;
                }

                if (checkBox)
                {
                    var cubeBox = new MyOrientedBoundingBoxD(cube.PositionComp.LocalAABB, cube.PositionComp.WorldMatrixRef);
                    if (restrictedBox.Contains(ref cubeBox) != ContainmentType.Disjoint)
                    {
                        return(true);
                    }
                }

                if (checkSphere && restrictedSphere.Contains(cube.PositionComp.WorldAABB) != ContainmentType.Disjoint)
                {
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 24
0
        internal void EntityControlUpdate()
        {
            var lastControlledEnt = ControlledEntity;

            ControlledEntity = (MyEntity)MyAPIGateway.Session.ControlledObject;

            var entityChanged = lastControlledEnt != null && lastControlledEnt != ControlledEntity;

            if (entityChanged)
            {
                if (lastControlledEnt is MyCockpit || lastControlledEnt is MyRemoteControl)
                {
                    PlayerControlAcquired(lastControlledEnt);
                }

                if (ControlledEntity is MyCockpit || ControlledEntity is MyRemoteControl)
                {
                    PlayerControlNotify(ControlledEntity);
                }

                if (ControlledEntity is IMyGunBaseUser && !(lastControlledEnt is IMyGunBaseUser))
                {
                    var    cube = (MyCubeBlock)ControlledEntity;
                    GridAi gridAi;
                    if (GridTargetingAIs.TryGetValue(cube.CubeGrid, out gridAi))
                    {
                        CoreComponent comp;
                        if (gridAi.WeaponBase.TryGetValue(cube, out comp))
                        {
                            GunnerBlackList = true;
                            if (IsServer)
                            {
                                comp.Data.Repo.Base.State.PlayerId = PlayerId;
                                comp.Data.Repo.Base.State.Control  = ControlMode.Camera;
                            }
                            ActiveControlBlock = (MyCubeBlock)ControlledEntity;
                            var controlStringLeft = MyAPIGateway.Input.GetControl(MyMouseButtonsEnum.Left).GetGameControlEnum().String;
                            MyVisualScriptLogicProvider.SetPlayerInputBlacklistState(controlStringLeft, PlayerId, false);
                            var controlStringRight = MyAPIGateway.Input.GetControl(MyMouseButtonsEnum.Right).GetGameControlEnum().String;
                            MyVisualScriptLogicProvider.SetPlayerInputBlacklistState(controlStringRight, PlayerId, false);
                            var controlStringMenu = MyAPIGateway.Input.GetControl(UiInput.MouseButtonMenu).GetGameControlEnum().String;
                            MyVisualScriptLogicProvider.SetPlayerInputBlacklistState(controlStringMenu, PlayerId, false);

                            if (HandlesInput && MpActive)
                            {
                                SendPlayerControlRequest(comp, PlayerId, ControlMode.Camera);
                            }
                        }
                    }
                }
                else if (!(ControlledEntity is IMyGunBaseUser) && lastControlledEnt is IMyGunBaseUser)
                {
                    if (GunnerBlackList)
                    {
                        GunnerBlackList = false;
                        var controlStringLeft = MyAPIGateway.Input.GetControl(MyMouseButtonsEnum.Left).GetGameControlEnum().String;
                        MyVisualScriptLogicProvider.SetPlayerInputBlacklistState(controlStringLeft, PlayerId, true);
                        var controlStringRight = MyAPIGateway.Input.GetControl(MyMouseButtonsEnum.Right).GetGameControlEnum().String;
                        MyVisualScriptLogicProvider.SetPlayerInputBlacklistState(controlStringRight, PlayerId, true);
                        var controlStringMenu = MyAPIGateway.Input.GetControl(UiInput.MouseButtonMenu).GetGameControlEnum().String;
                        MyVisualScriptLogicProvider.SetPlayerInputBlacklistState(controlStringMenu, PlayerId, true);
                        var    oldCube = lastControlledEnt as MyCubeBlock;
                        GridAi gridAi;
                        if (oldCube != null && GridTargetingAIs.TryGetValue(oldCube.CubeGrid, out gridAi))
                        {
                            CoreComponent comp;
                            if (gridAi.WeaponBase.TryGetValue(oldCube, out comp))
                            {
                                if (IsServer)
                                {
                                    comp.Data.Repo.Base.State.PlayerId = -1;
                                    comp.Data.Repo.Base.State.Control  = ControlMode.None;
                                }

                                if (HandlesInput && MpActive)
                                {
                                    SendPlayerControlRequest(comp, -1, ControlMode.None);
                                }

                                ActiveControlBlock = null;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 25
0
        private void ProcessDbsCallBack()
        {
            try
            {
                DsUtil.Start("db");
                for (int d = 0; d < DbsToUpdate.Count; d++)
                {
                    var db = DbsToUpdate[d];
                    using (db.Ai.DbLock.AcquireExclusiveUsing())
                    {
                        var ai = db.Ai;
                        if (ai.MyGrid.MarkedForClose || ai.MarkedForClose || db.Version != ai.Version)
                        {
                            ai.ScanInProgress = false;
                            continue;
                        }

                        if (ai.MyPlanetTmp != null)
                        {
                            ai.MyPlanetInfo();
                        }

                        foreach (var sub in ai.PrevSubGrids)
                        {
                            ai.SubGrids.Add((MyCubeGrid)sub);
                        }
                        if (ai.SubGridsChanged)
                        {
                            ai.SubGridChanges(false, true);
                        }

                        ai.TargetingInfo.Clean(ai);
                        ai.CleanSortedTargets();
                        ai.Targets.Clear();

                        var newEntCnt = ai.NewEntities.Count;
                        ai.SortedTargets.Capacity = newEntCnt;
                        for (int i = 0; i < newEntCnt; i++)
                        {
                            var detectInfo = ai.NewEntities[i];
                            var ent        = detectInfo.Parent;
                            if (ent.Physics == null)
                            {
                                continue;
                            }

                            var    grid     = ent as MyCubeGrid;
                            GridAi targetAi = null;

                            if (grid != null)
                            {
                                GridTargetingAIs.TryGetValue(grid, out targetAi);
                            }

                            var targetInfo = TargetInfoPool.Get();
                            targetInfo.Init(ref detectInfo, ai.MyGrid, ai, targetAi);

                            ai.SortedTargets.Add(targetInfo);
                            ai.Targets[ent] = targetInfo;

                            var checkFocus = ai.Construct.Data.Repo.FocusData.HasFocus && targetInfo.Target?.EntityId == ai.Construct.Data.Repo.FocusData.Target[0] || targetInfo.Target?.EntityId == ai.Construct.Data.Repo.FocusData.Target[1];

                            if (targetInfo.Drone)
                            {
                                ai.TargetingInfo.DroneAdd(ai, targetInfo);
                            }

                            if (ai.RamProtection && targetInfo.DistSqr < 136900 && targetInfo.IsGrid)
                            {
                                ai.TargetingInfo.RamProximity = true;
                            }

                            if (targetInfo.DistSqr < ai.MaxTargetingRangeSqr && (checkFocus || targetInfo.OffenseRating > 0))
                            {
                                if (checkFocus || targetInfo.DistSqr < ai.TargetingInfo.ThreatRangeSqr && targetInfo.EntInfo.Relationship == MyRelationsBetweenPlayerAndBlock.Enemies)
                                {
                                    ai.TargetingInfo.ThreatInRange  = true;
                                    ai.TargetingInfo.ThreatRangeSqr = targetInfo.DistSqr;
                                }

                                if (checkFocus || targetInfo.DistSqr < ai.TargetingInfo.OtherRangeSqr && targetInfo.EntInfo.Relationship != MyRelationsBetweenPlayerAndBlock.Enemies)
                                {
                                    ai.TargetingInfo.OtherInRange  = true;
                                    ai.TargetingInfo.OtherRangeSqr = targetInfo.DistSqr;
                                }

                                if (targetInfo.Drone && targetInfo.DistSqr < ai.TargetingInfo.DroneRangeSqr)
                                {
                                    ai.TargetingInfo.DroneInRange  = true;
                                    ai.TargetingInfo.DroneRangeSqr = targetInfo.DistSqr;
                                }
                            }
                        }

                        ai.NewEntities.Clear();
                        ai.SortedTargets.Sort(TargetCompare);
                        ai.TargetAis.Clear();
                        ai.TargetAis.AddRange(ai.TargetAisTmp);
                        ai.TargetAisTmp.Clear();

                        ai.Obstructions.Clear();
                        ai.Obstructions.AddRange(ai.ObstructionsTmp);
                        ai.ObstructionsTmp.Clear();

                        ai.MyShield           = null;
                        ai.ShieldNear         = false;
                        ai.FriendlyShieldNear = false;
                        if (ai.NearByShieldsTmp.Count > 0)
                        {
                            ai.NearByShield();
                        }

                        ai.StaticsInRange.Clear();
                        ai.StaticsInRange.AddRange(ai.StaticsInRangeTmp);
                        ai.StaticsInRangeTmp.Clear();
                        ai.StaticEntitiesInRange = ai.StaticsInRange.Count > 0;
                        ai.MyStaticInfo();

                        ai.NaturalGravity = ai.FakeShipController.GetNaturalGravity();
                        ai.BlockCount     = ai.MyGrid.BlocksCount;
                        ai.NearByEntities = ai.NearByEntitiesTmp;

                        if (!ai.TargetingInfo.ThreatInRange && ai.LiveProjectile.Count > 0)
                        {
                            ai.TargetingInfo.ThreatInRange  = true;
                            ai.TargetingInfo.ThreatRangeSqr = 0;
                        }

                        ai.TargetingInfo.SomethingInRange = ai.TargetingInfo.ThreatInRange || ai.TargetingInfo.OtherInRange;

                        ai.DbReady = ai.SortedTargets.Count > 0 || ai.TargetAis.Count > 0 || Tick - ai.LiveProjectileTick < 3600 || ai.LiveProjectile.Count > 0 || ai.Construct.RootAi.Data.Repo.ControllingPlayers.Count > 0 || ai.FirstRun;

                        MyCubeBlock activeCube;
                        ai.AiSleep = ai.Construct.RootAi.Data.Repo.ControllingPlayers.Count <= 0 && (!ai.TargetingInfo.ThreatInRange && !ai.TargetingInfo.OtherInRange || !ai.TargetNonThreats && ai.TargetingInfo.OtherInRange) && (ai.Data.Repo.ActiveTerminal <= 0 || MyEntities.TryGetEntityById(ai.Data.Repo.ActiveTerminal, out activeCube) && activeCube != null && !ai.SubGrids.Contains(activeCube.CubeGrid));

                        ai.DbUpdated      = true;
                        ai.FirstRun       = false;
                        ai.ScanInProgress = false;
                    }
                }
                DbsToUpdate.Clear();
                DsUtil.Complete("db", true);
                DbUpdating = false;
            }
            catch (Exception ex) { Log.Line($"Exception in ProcessDbsCallBack: {ex}"); }
        }