예제 #1
0
 public static bool RemoveColliderData_Prefix(PlanetPhysics __instance)
 {
     //Collider does not need to be removed if player is not on the planet
     if (SimulatedWorld.Initialized && __instance.planet.id != GameMain.mainPlayer.planetId)
     {
         return(false);
     }
     return(true);
 }
예제 #2
0
    private void Spawn(Vector3 pos, Quaternion rot)
    {
        PlanetPhysics spw    = Instantiate <PlanetPhysics>(obj, pos, rot);
        PickUp        pickUp = spw.GetComponent <PickUp>();

        pickUp.Init();
        pickUp.SetColor(colors[Random.Range(0, colors.Length)]);
        spw.target = target;
    }
예제 #3
0
 public static bool RemoveColliderData_Prefix(PlanetPhysics __instance)
 {
     //Collider does not need to be removed if player is not on the planet
     if (Multiplayer.IsActive && __instance.planet.id != GameMain.mainPlayer.planetId)
     {
         return(false);
     }
     return(true);
 }
예제 #4
0
    private float G = 0.5f;    //6.673e-11f;

    void Awake()
    {
        S = this;
    }
예제 #5
0
        public void ProcessPacket(CreatePrebuildsRequest packet, NebulaConnection conn)
        {
            PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId);

            if (planet.factory == null)
            {
                Log.Warn($"planet.factory was null create new one");
                planet.factory = GameMain.data.GetOrCreateFactory(planet);
            }

            PlayerAction_Build pab = GameMain.mainPlayer.controller?.actionBuild;

            if (pab != null)
            {
                //Make backup of values that are overwritten
                List <BuildPreview> tmpList   = pab.buildPreviews;
                bool tmpConfirm               = pab.waitConfirm;
                UnityEngine.Vector3    tmpPos = pab.previewPose.position;
                UnityEngine.Quaternion tmpRot = pab.previewPose.rotation;

                PlanetFactory     tmpFactory       = null;
                NearColliderLogic tmpNearcdLogic   = null;
                PlanetPhysics     tmpPlanetPhysics = null;
                float             tmpBuildArea     = GameMain.mainPlayer.mecha.buildArea;
                PlanetData        tmpData          = null;
                bool loadExternalPlanetData        = GameMain.localPlanet != planet;

                //Load temporary planet data, since host is not there
                if (loadExternalPlanetData)
                {
                    tmpFactory       = (PlanetFactory)AccessTools.Field(typeof(PlayerAction_Build), "factory").GetValue(GameMain.mainPlayer.controller.actionBuild);
                    tmpNearcdLogic   = (NearColliderLogic)AccessTools.Field(typeof(PlayerAction_Build), "nearcdLogic").GetValue(GameMain.mainPlayer.controller.actionBuild);
                    tmpPlanetPhysics = (PlanetPhysics)AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").GetValue(pab);
                    tmpData          = GameMain.mainPlayer.planetData;
                }

                //Create Prebuilds from incomming packet and prepare new position
                pab.buildPreviews = packet.GetBuildPreviews();
                pab.waitConfirm   = true;
                using (FactoryManager.EventFromServer.On())
                {
                    FactoryManager.EventFactory = planet.factory;
                    pab.previewPose.position    = new UnityEngine.Vector3(packet.PosePosition.x, packet.PosePosition.y, packet.PosePosition.z);
                    pab.previewPose.rotation    = new UnityEngine.Quaternion(packet.PoseRotation.x, packet.PoseRotation.y, packet.PoseRotation.z, packet.PoseRotation.w);

                    //Check if some mandatory variables are missing
                    if (planet.physics == null || planet.physics.colChunks == null)
                    {
                        planet.physics = new PlanetPhysics(planet);
                        planet.physics.Init();
                    }
                    if (BeltManager.GetCargoTraffic(planet.factory.cargoTraffic) == null)
                    {
                        planet.factory.cargoTraffic.CreateRenderingBatches();
                    }
                    if (planet.aux == null)
                    {
                        planet.aux = new PlanetAuxData(planet);
                    }

                    //Set temporary Local Planet / Factory data that are needed for original methods CheckBuildConditions() and CreatePrebuilds()
                    AccessTools.Field(typeof(PlayerAction_Build), "factory").SetValue(GameMain.mainPlayer.controller.actionBuild, planet.factory);
                    AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").SetValue(GameMain.mainPlayer.controller.actionBuild, planet.physics);
                    AccessTools.Field(typeof(PlayerAction_Build), "nearcdLogic").SetValue(GameMain.mainPlayer.controller.actionBuild, planet.physics.nearColliderLogic);
                    AccessTools.Property(typeof(global::Player), "planetData").SetValue(GameMain.mainPlayer, planet, null);

                    //Check if prebuilds can be build (collision check, height check, etc)
                    GameMain.mainPlayer.mecha.buildArea = float.MaxValue;
                    bool canBuild;
                    using (FactoryManager.IgnoreBasicBuildConditionChecks.On())
                    {
                        canBuild  = pab.CheckBuildConditions();
                        canBuild &= CheckBuildingConnections(pab.buildPreviews, planet.factory.entityPool, planet.factory.prebuildPool);
                    }

                    if (canBuild)
                    {
                        FactoryManager.PacketAuthor = packet.AuthorId;
                        pab.CreatePrebuilds();
                        FactoryManager.PacketAuthor = -1;
                    }

                    //Revert changes back to the original planet
                    if (loadExternalPlanetData)
                    {
                        planet.physics.Free();
                        planet.physics = null;
                        AccessTools.Property(typeof(global::Player), "planetData").SetValue(GameMain.mainPlayer, tmpData, null);
                        AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").SetValue(GameMain.mainPlayer.controller.actionBuild, tmpPlanetPhysics);
                        AccessTools.Field(typeof(PlayerAction_Build), "factory").SetValue(GameMain.mainPlayer.controller.actionBuild, tmpFactory);
                        AccessTools.Field(typeof(PlayerAction_Build), "nearcdLogic").SetValue(GameMain.mainPlayer.controller.actionBuild, tmpNearcdLogic);
                    }

                    GameMain.mainPlayer.mecha.buildArea = tmpBuildArea;
                    FactoryManager.EventFactory         = null;
                }

                pab.buildPreviews        = tmpList;
                pab.waitConfirm          = tmpConfirm;
                pab.previewPose.position = tmpPos;
                pab.previewPose.rotation = tmpRot;
            }
        }
        public static void DetermineBuildPreviews_Postfix(PlayerAction_Build __instance, PlanetFactory ___factory, PlanetAuxData ___planetAux, NearColliderLogic ___nearcdLogic, Player ___player)
        {
            // Do we have cached inserters?
            var ci = cachedInserters;

            if (CopyInserters.copyEnabled && ci.Count > 0 && !__instance.multiLevelCovering)
            {
                var bpCount = __instance.buildPreviews.Count;

                for (int i = 0; i < bpCount; i++)
                {
                    BuildPreview buildPreview = __instance.buildPreviews[i];

                    if (!buildPreview.item.prefabDesc.isInserter)
                    {
                        foreach (var cachedInserter in ci)
                        {
                            var positionData = GetPositions(__instance, ___factory, ___planetAux, ___nearcdLogic, buildPreview, cachedInserter);

                            var bp = BuildPreview.CreateSingle(LDB.items.Select(cachedInserter.protoId), LDB.items.Select(cachedInserter.protoId).prefabDesc, true);
                            bp.ResetInfos();


                            bp.lrot  = buildPreview.lrot * cachedInserter.rot;
                            bp.lrot2 = buildPreview.lrot * cachedInserter.rot2;


                            if (buildPreview.lpos == Vector3.zero)
                            {
                                bp.lpos  = buildPreview.lpos + buildPreview.lrot * positionData.posDelta;
                                bp.lpos2 = buildPreview.lpos + buildPreview.lrot * positionData.pos2Delta;
                            }
                            else
                            {
                                bp.lpos  = positionData.absoluteInserterPos;
                                bp.lpos2 = positionData.absoluteInserterPos2;
                            }



                            if (positionData.condition == null)
                            {
                                positionData.condition = EBuildCondition.Ok;

                                Vector3 lpos    = positionData.absoluteInserterPos;
                                Vector3 lpos2   = positionData.absoluteInserterPos2;
                                Vector3 forward = lpos2 - lpos;

                                Pose pose;
                                pose.position = Vector3.Lerp(lpos, lpos2, 0.5f);
                                pose.rotation = Quaternion.LookRotation(forward, lpos.normalized);


                                var colliderData = bp.desc.buildColliders[0];
                                colliderData.ext = new Vector3(colliderData.ext.x, colliderData.ext.y, Vector3.Distance(lpos2, lpos) * 0.5f + colliderData.ext.z - 0.5f);

                                if (cachedInserter.otherIsBelt)
                                {
                                    if (cachedInserter.incoming)
                                    {
                                        colliderData.pos.z -= 0.4f;
                                        colliderData.ext.z += 0.4f;
                                    }
                                    else
                                    {
                                        colliderData.pos.z += 0.4f;
                                        colliderData.ext.z += 0.4f;
                                    }
                                }

                                if (colliderData.ext.z < 0.1f)
                                {
                                    colliderData.ext.z = 0.1f;
                                }
                                colliderData.pos = pose.position + pose.rotation * colliderData.pos;
                                colliderData.q   = pose.rotation * colliderData.q;


                                //int mask = 165888;// the following is equivalent but explicitly states layers affected
                                int mask            = Convert.ToInt32(LayerMaskConstants.layer12 | LayerMaskConstants.layer16 | LayerMaskConstants.layer18);
                                int collisionsFound = Physics.OverlapBoxNonAlloc(colliderData.pos, colliderData.ext, _tmp_cols, colliderData.q, mask, QueryTriggerInteraction.Collide);

                                int collisionLimit = cachedInserter.otherIsBelt ? 0 : 1;

                                if (collisionsFound > collisionLimit)
                                {
                                    PlanetPhysics physics2 = ___player.planetData.physics;
                                    for (int j = 0; j < collisionsFound; j++)
                                    {
                                        physics2.GetColliderData(_tmp_cols[j], out ColliderData colliderData2);
                                        if (colliderData2.objId != 0)
                                        {
                                            if (colliderData2.usage == EColliderUsage.Build)
                                            {
                                                positionData.condition = EBuildCondition.Collide;
                                            }
                                        }
                                    }
                                }
                            }

                            bp.condition = (EBuildCondition)positionData.condition;

                            if (bp.condition == EBuildCondition.Ok)
                            {
                                if (cachedInserter.incoming)
                                {
                                    bp.inputObjId = positionData.otherId;
                                }
                                else
                                {
                                    bp.outputObjId = positionData.otherId;
                                }
                            }

                            __instance.AddBuildPreview(bp);
                        }
                    }
                }

                SwapPositionCache();
            }
        }
예제 #7
0
        public static void PlayerAction_Build_GameTick_Postfix(ref PlayerAction_Build __instance)
        {
            if (bpMode)
            {
                bool removeMode = VFInput.control;

                if (circleGizmo != null)
                {
                    circleGizmo.color  = removeMode ? REMOVE_SELECTION_GIZMO_COLOR : ADD_SELECTION_GIZMO_COLOR;
                    circleGizmo.radius = MultiBuild.selectionRadius;

                    if (__instance.groundTestPos != Vector3.zero)
                    {
                        circleGizmo.position = __instance.groundTestPos;
                    }
                }

                if (VFInput._buildConfirm.pressing)
                {
                    circleGizmo.color = removeMode ? REMOVE_SELECTION_GIZMO_COLOR : ADD_SELECTION_GIZMO_COLOR;

                    // target only buildings
                    int mask  = 131072;
                    int found = Physics.OverlapBoxNonAlloc(__instance.groundTestPos, new Vector3(MultiBuild.selectionRadius, 100f, MultiBuild.selectionRadius), _tmp_cols, Maths.SphericalRotation(__instance.groundTestPos, 0f), mask, QueryTriggerInteraction.Collide);

                    PlanetPhysics planetPhysics = __instance.player.planetData.physics;
                    for (int i = 0; i < found; i++)
                    {
                        planetPhysics.GetColliderData(_tmp_cols[i], out ColliderData colliderData);
                        if (colliderData.objId > 0)
                        {
                            var entityId = colliderData.objId;
                            if (removeMode)
                            {
                                if (bpSelection.ContainsKey(entityId))
                                {
                                    bpSelection[entityId].Close();
                                    bpSelection.Remove(entityId);
                                }
                            }
                            else if (!bpSelection.ContainsKey(entityId))
                            {
                                var       entityData = __instance.factory.entityPool[entityId];
                                ItemProto itemProto  = LDB.items.Select((int)entityData.protoId);
                                var       gizmo      = BoxGizmo.Create(entityData.pos, entityData.rot, itemProto.prefabDesc.selectCenter, itemProto.prefabDesc.selectSize);
                                gizmo.multiplier      = 1f;
                                gizmo.alphaMultiplier = itemProto.prefabDesc.selectAlpha;
                                gizmo.fadeInScale     = gizmo.fadeOutScale = 1.3f;
                                gizmo.fadeInTime      = gizmo.fadeOutTime = 0.05f;
                                gizmo.fadeInFalloff   = gizmo.fadeOutFalloff = 0.5f;
                                gizmo.color           = Color.white;

                                gizmo.Open();

                                bpSelection.Add(entityId, gizmo);
                            }
                        }
                    }
                }
            }
        }
예제 #8
0
        public static InserterPosition GetPositions(PlayerAction_Build actionBuild, InserterCopy copiedInserter, float yawRad, int pasteIndex, bool connectToPasted)
        {
            var pastedEntities = BlueprintManager.pastedEntities;
            var player         = actionBuild.player;

            var pastedReferenceEntityId = BlueprintManager_Paste.PASTE_INDEX_MULTIPLIER * pasteIndex + copiedInserter.referenceBuildingId;

            var pastedReferenceEntity             = pastedEntities[pastedReferenceEntityId];
            var pastedReferenceEntityBuildPreview = pastedReferenceEntity.buildPreview;

            Quaternion absoluteBuildingRot    = pastedReferenceEntity.pose.rotation;
            Vector3    absoluteBuildingPos    = pastedReferenceEntity.pose.position;
            Vector2    absoluteBuildingPosSpr = absoluteBuildingPos.ToSpherical();

            var     posDelta            = copiedInserter.posDelta.Rotate(yawRad, copiedInserter.posDeltaCount);
            Vector3 absoluteInserterPos = absoluteBuildingPosSpr
                                          .ApplyDelta(posDelta, copiedInserter.posDeltaCount)
                                          .ToCartesian(GameMain.localPlanet.realRadius + 0.2f);

            var     pos2Delta            = copiedInserter.pos2Delta.Rotate(yawRad, copiedInserter.pos2DeltaCount);
            Vector3 absoluteInserterPos2 = absoluteBuildingPosSpr
                                           .ApplyDelta(pos2Delta, copiedInserter.pos2DeltaCount)
                                           .ToCartesian(GameMain.localPlanet.realRadius + 0.2f);

            if (pastedReferenceEntity.sourceBuilding == null)
            {
                absoluteBuildingRot = Maths.SphericalRotation(absoluteBuildingPos, yawRad * Mathf.Rad2Deg);
            }

            Quaternion absoluteInserterRot  = absoluteBuildingRot * copiedInserter.rot;
            Quaternion absoluteInserterRot2 = absoluteBuildingRot * copiedInserter.rot2;

            int startSlot = copiedInserter.startSlot;
            int endSlot   = copiedInserter.endSlot;

            short pickOffset   = copiedInserter.pickOffset;
            short insertOffset = copiedInserter.insertOffset;

            var referenceObjId = pastedReferenceEntity.objId;

            var otherPastedId = 0;
            var otherEntityId = 0;

            var otherObjId = 0;

            var pastedPickTargetId   = BlueprintManager_Paste.PASTE_INDEX_MULTIPLIER * pasteIndex + copiedInserter.pickTarget;
            var pastedInsertTargetId = BlueprintManager_Paste.PASTE_INDEX_MULTIPLIER * pasteIndex + copiedInserter.insertTarget;


            if (pastedEntities.ContainsKey(pastedPickTargetId) && pastedEntities.ContainsKey(pastedInsertTargetId))
            {
                // cool we copied both source and target of the inserters
                otherPastedId = pastedPickTargetId == pastedReferenceEntityId ? pastedInsertTargetId : pastedPickTargetId;
                otherObjId    = pastedEntities[otherPastedId].objId;
            }
            else
            {
                // Find the other entity at the target location
                var nearcdLogic = actionBuild.nearcdLogic;
                var factory     = actionBuild.factory;
                // Find the desired belt/building position
                // As delta doesn't work over distance, re-trace the Grid Snapped steps from the original
                // to find the target belt/building for this inserters other connection

                var     otherPosDelta = copiedInserter.otherPosDelta.Rotate(yawRad, copiedInserter.otherPosDeltaCount);
                Vector3 testPos       = absoluteBuildingPosSpr
                                        .ApplyDelta(otherPosDelta, copiedInserter.otherPosDeltaCount)
                                        .SnapToGrid();

                if (connectToPasted)
                {
                    var compatibleType = copiedInserter.otherIsBelt ? EPastedType.BELT : EPastedType.BUILDING;
                    foreach (var pastedEntity in BlueprintManager.pastedEntities.Values)
                    {
                        // find the first compatible entity that will not been removed, that has in the same/previous/next pasteIndex and that is near enough
                        if (pastedEntity.type == compatibleType &&
                            pastedEntity.status != EPastedStatus.REMOVE &&
                            pastedEntity.pasteId != pastedReferenceEntityId &&
                            Math.Abs(pastedEntity.pasteIndex - pasteIndex) <= 1 &&
                            Vector3.Distance(pastedEntity.pose.position, testPos) < 0.2)
                        {
                            // found a pasted entity that we can connect to !
                            otherPastedId = pastedEntity.pasteId;
                            otherObjId    = pastedEntity.objId;
                            break;
                        }
                    }
                }

                if (otherObjId == 0)
                {
                    int[] _nearObjectIds = new int[256];

                    // find building nearby
                    int found = nearcdLogic.GetBuildingsInAreaNonAlloc(testPos, 0.2f, _nearObjectIds, false);

                    // find nearest building
                    float maxDistance = 1f;

                    for (int x = 0; x < found; x++)
                    {
                        var       id = _nearObjectIds[x];
                        float     distance;
                        ItemProto proto;
                        if (id == 0 || id == pastedReferenceEntityBuildPreview.objId)
                        {
                            continue;
                        }
                        else if (id > 0)
                        {
                            EntityData entityData = factory.entityPool[id];
                            proto = LDB.items.Select((int)entityData.protoId);
                            // ignore buildings without inserter poses
                            if (!proto.prefabDesc.isBelt && proto.prefabDesc.insertPoses.Length == 0)
                            {
                                continue;
                            }

                            distance = Vector3.Distance(entityData.pos, testPos);
                        }
                        else
                        {
                            PrebuildData prebuildData = factory.prebuildPool[-id];
                            proto = LDB.items.Select((int)prebuildData.protoId);

                            // ignore unbuilt belts and buildings without inserter poses
                            if (proto.prefabDesc.isBelt || proto.prefabDesc.insertPoses.Length == 0)
                            {
                                continue;
                            }

                            distance = Vector3.Distance(prebuildData.pos, testPos);
                        }

                        // ignore entitites that ore not (built) belts or don't have inserterPoses
                        if ((proto.prefabDesc.isBelt == copiedInserter.otherIsBelt || proto.prefabDesc.insertPoses.Length > 0) && distance < maxDistance)
                        {
                            otherObjId  = otherEntityId = id;
                            maxDistance = distance;
                        }
                    }
                }
            }



            if (otherObjId != 0)
            {
                if (copiedInserter.incoming)
                {
                    InserterPoses.CalculatePose(actionBuild, otherObjId, referenceObjId);
                }
                else
                {
                    InserterPoses.CalculatePose(actionBuild, referenceObjId, otherObjId);
                }


                bool hasNearbyPose = false;

                if (actionBuild.posePairs.Count > 0)
                {
                    float minDistance = 1000f;
                    PlayerAction_Build.PosePair bestFit = new PlayerAction_Build.PosePair();

                    for (int j = 0; j < actionBuild.posePairs.Count; ++j)
                    {
                        var posePair = actionBuild.posePairs[j];
                        if (
                            (copiedInserter.incoming && copiedInserter.endSlot != posePair.endSlot && copiedInserter.endSlot != -1) ||
                            (!copiedInserter.incoming && copiedInserter.startSlot != posePair.startSlot && copiedInserter.startSlot != -1)
                            )
                        {
                            continue;
                        }
                        float startDistance = Vector3.Distance(posePair.startPose.position, absoluteInserterPos);
                        float endDistance   = Vector3.Distance(posePair.endPose.position, absoluteInserterPos2);
                        float poseDistance  = startDistance + endDistance;

                        if (poseDistance < minDistance)
                        {
                            minDistance   = poseDistance;
                            bestFit       = posePair;
                            hasNearbyPose = true;
                        }
                    }
                    if (hasNearbyPose)
                    {
                        // if we were able to calculate a close enough sensible pose
                        // use that instead of the (visually) imprecise default

                        absoluteInserterPos  = bestFit.startPose.position;
                        absoluteInserterPos2 = bestFit.endPose.position;

                        absoluteInserterRot  = bestFit.startPose.rotation;
                        absoluteInserterRot2 = bestFit.endPose.rotation * Quaternion.Euler(0.0f, 180f, 0.0f);

                        pickOffset   = (short)bestFit.startOffset;
                        insertOffset = (short)bestFit.endOffset;

                        startSlot = bestFit.startSlot;
                        endSlot   = bestFit.endSlot;

                        posDelta  = bestFit.startPose.position.ToSpherical() - absoluteBuildingPosSpr;
                        pos2Delta = bestFit.endPose.position.ToSpherical() - absoluteBuildingPosSpr;
                    }
                }
            }

            InserterPosition position = new InserterPosition()
            {
                copiedInserter      = copiedInserter,
                absoluteBuildingPos = absoluteBuildingPos,
                absoluteBuildingRot = absoluteBuildingRot,

                posDelta             = posDelta,
                pos2Delta            = pos2Delta,
                absoluteInserterPos  = absoluteInserterPos,
                absoluteInserterPos2 = absoluteInserterPos2,

                absoluteInserterRot  = absoluteInserterRot,
                absoluteInserterRot2 = absoluteInserterRot2,

                pickOffset   = pickOffset,
                insertOffset = insertOffset,

                startSlot = startSlot,
                endSlot   = endSlot,

                condition = EBuildCondition.Ok
            };

            if (otherEntityId != 0)
            {
                Vector3 forward = absoluteInserterPos2 - absoluteInserterPos;

                Pose pose;
                pose.position = Vector3.Lerp(absoluteInserterPos, absoluteInserterPos2, 0.5f);
                pose.rotation = Quaternion.LookRotation(forward, absoluteInserterPos.normalized);


                var colliderData = copiedInserter.itemProto.prefabDesc.buildColliders[0];
                colliderData.ext = new Vector3(colliderData.ext.x, colliderData.ext.y, Vector3.Distance(absoluteInserterPos2, absoluteInserterPos) * 0.5f + colliderData.ext.z - 0.5f);

                if (copiedInserter.otherIsBelt)
                {
                    if (copiedInserter.incoming)
                    {
                        colliderData.pos.z -= 0.4f;
                        colliderData.ext.z += 0.4f;
                    }
                    else
                    {
                        colliderData.pos.z += 0.4f;
                        colliderData.ext.z += 0.4f;
                    }
                }

                if (colliderData.ext.z < 0.1f)
                {
                    colliderData.ext.z = 0.1f;
                }
                colliderData.pos = pose.position + pose.rotation * colliderData.pos;
                colliderData.q   = pose.rotation * colliderData.q;


                int        mask            = 165888;
                Collider[] _tmp_cols       = new Collider[16];
                int        collisionsFound = Physics.OverlapBoxNonAlloc(colliderData.pos, colliderData.ext, _tmp_cols, colliderData.q, mask, QueryTriggerInteraction.Collide);

                PlanetPhysics physics2 = player.planetData.physics;
                for (int j = 0; j < collisionsFound; j++)
                {
                    physics2.GetColliderData(_tmp_cols[j], out ColliderData colliderData2);
                    if (colliderData2.objId != 0 && colliderData2.objId != otherEntityId && colliderData2.usage == EColliderUsage.Build)
                    {
                        position.condition = EBuildCondition.Collide;
                        otherPastedId      = 0;
                        otherEntityId      = 0;

                        break;
                    }
                }
            }

            position.inputEntityId = copiedInserter.incoming ? otherEntityId : 0;
            position.inputPastedId = copiedInserter.incoming ? otherPastedId : pastedReferenceEntityId;

            position.outputEntityId = copiedInserter.incoming ? 0 : otherEntityId;
            position.outputPastedId = copiedInserter.incoming ? pastedReferenceEntityId : otherPastedId;

            return(position);
        }
예제 #9
0
        public static void FlattenTerrainReformALT(this PlanetFactory planetFactory, Vector3 center, float radius, int reformSize, bool veinBuried, float localRadius, float realRadius, float fade0 = 3f)
        {
            if (planetFactory.tmp_ids == null)
            {
                planetFactory.tmp_ids = new int[1024];
            }
            if (planetFactory.tmp_entity_ids == null)
            {
                planetFactory.tmp_entity_ids = new int[1024];
            }
            Array.Clear(planetFactory.tmp_ids, 0, planetFactory.tmp_ids.Length);
            Array.Clear(planetFactory.tmp_entity_ids, 0, planetFactory.tmp_entity_ids.Length);
            Vector3       zero = Vector3.zero;
            PlanetRawData data = planetFactory.planet.data;

            ushort[] heightData = data.heightData;
            float    f          = ((float)(int)heightData[data.QueryIndex(center)] - realRadius * 100f + 20f) * 0.01f * 2f;

            //f = Mathf.Min(9f, Mathf.Abs(f));
            f      = Mathf.Min(5f, Mathf.Abs(f));
            fade0 += f;
            float areaRadius = radius + fade0;
            short num        = (short)(realRadius * 100f + 20f);
            bool  levelized  = planetFactory.planet.levelized;
            int   num2       = Mathf.RoundToInt((center.magnitude - 0.2f - realRadius) / 1.33333325f);
            int   num3       = num2 * 133 + num - 60;
            float num4       = localRadius * 100f - 20f;

            foreach (KeyValuePair <int, int> tmp_levelChange in planetFactory.tmp_levelChanges)
            {
                /*
                 * if (tmp_levelChange.Value <= 0)
                 * {
                 *  continue;
                 * }
                 */
                ushort num5 = heightData[tmp_levelChange.Key];
                if (levelized)
                {
                    if (num5 >= num3)
                    {
                        if (data.GetModLevel(tmp_levelChange.Key) < 3)
                        {
                            data.SetModPlane(tmp_levelChange.Key, num2);
                        }
                        planetFactory.planet.AddHeightMapModLevel(tmp_levelChange.Key, tmp_levelChange.Value);
                    }
                }
                else
                {
                    Debug.Log("AddHeightMapModLevel: " + tmp_levelChange.Key + ", " + tmp_levelChange.Value);
                    planetFactory.planet.AddHeightMapModLevelALT(tmp_levelChange.Key, tmp_levelChange.Value);
                }
                if ((float)(int)num5 < num4)
                {
                    planetFactory.planet.landPercentDirty = true;
                }
            }
            if (planetFactory.planet.UpdateDirtyMeshes())
            {
                planetFactory.RenderLocalPlanetHeightmap();
            }
            radius -= (float)reformSize * 0.15f;
            NearColliderLogic nearColliderLogic = planetFactory.planet.physics.nearColliderLogic;
            int   vegetablesInAreaNonAlloc      = nearColliderLogic.GetVegetablesInAreaNonAlloc(center, areaRadius, planetFactory.tmp_ids);
            float num6 = radius * radius;

            for (int i = 0; i < vegetablesInAreaNonAlloc; i++)
            {
                int num7 = planetFactory.tmp_ids[i];
                zero  = planetFactory.vegePool[num7].pos;
                zero -= center;
                if (zero.x * zero.x + zero.y * zero.y + zero.z * zero.z <= num6 + 2.2f)
                {
                    planetFactory.RemoveVegeWithComponents(num7);
                    continue;
                }
                float num8 = data.QueryModifiedHeight(planetFactory.vegePool[num7].pos) - 0.03f;
                planetFactory.vegePool[num7].pos = planetFactory.vegePool[num7].pos.normalized * num8;
                GameMain.gpuiManager.AlterModel(planetFactory.vegePool[num7].modelIndex, planetFactory.vegePool[num7].modelId, num7, planetFactory.vegePool[num7].pos, planetFactory.vegePool[num7].rot, setBuffer: false);
            }
            float num9 = 50f;

            vegetablesInAreaNonAlloc = ((!veinBuried) ? nearColliderLogic.GetVeinsInOceanInAreaNonAlloc(center, areaRadius, planetFactory.tmp_ids) : nearColliderLogic.GetVeinsInAreaNonAlloc(center, areaRadius, planetFactory.tmp_ids));
            for (int j = 0; j < vegetablesInAreaNonAlloc; j++)
            {
                int num10 = planetFactory.tmp_ids[j];
                zero = planetFactory.veinPool[num10].pos;
                float   num11  = realRadius + 0.2f;
                Vector3 vector = zero.normalized * num11 - center;
                if (!(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z <= num6 + 2f))
                {
                    continue;
                }
                PlanetPhysics physics      = planetFactory.planet.physics;
                int           colliderId   = planetFactory.veinPool[num10].colliderId;
                ColliderData  colliderData = physics.GetColliderData(colliderId);
                if (veinBuried)
                {
                    num11 -= num9;
                }
                else
                {
                    Vector3 center2 = zero.normalized * num11;
                    int     entitiesInAreaWhenReformNonAlloc = nearColliderLogic.GetEntitiesInAreaWhenReformNonAlloc(center2, colliderData.radius, planetFactory.tmp_entity_ids);
                    if (entitiesInAreaWhenReformNonAlloc > 0)
                    {
                        num11 = zero.magnitude;
                    }
                }
                Vector3 pos   = colliderData.pos.normalized * num11;
                int     num12 = colliderId >> 20;
                colliderId &= 0xFFFFF;
                physics.colChunks[num12].colliderPool[colliderId].pos = pos;
                planetFactory.veinPool[num10].pos = zero.normalized * num11;
                physics.RefreshColliders();
                GameMain.gpuiManager.AlterModel(planetFactory.veinPool[num10].modelIndex, planetFactory.veinPool[num10].modelId, num10, planetFactory.veinPool[num10].pos, setBuffer: false);
            }
            planetFactory.tmp_levelChanges.Clear();
            Array.Clear(planetFactory.tmp_ids, 0, planetFactory.tmp_ids.Length);
            Array.Clear(planetFactory.tmp_ids, 0, planetFactory.tmp_entity_ids.Length);
            GameMain.gpuiManager.SyncAllGPUBuffer();
        }
예제 #10
0
        public void ProcessPacket(CreatePrebuildsRequest packet, NebulaConnection conn)
        {
            PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId);

            if (planet.factory == null)
            {
                // We only execute the code if the client has loaded the factory at least once.
                // Else it will get it once it goes to the planet for the first time.
                return;
            }

            PlayerAction_Build pab = GameMain.mainPlayer.controller?.actionBuild;

            if (pab != null)
            {
                FactoryManager.TargetPlanet = packet.PlanetId;

                //Make backup of values that are overwritten
                List <BuildPreview> tmpList             = pab.buildPreviews;
                bool tmpConfirm                         = pab.waitConfirm;
                UnityEngine.Vector3    tmpPos           = pab.previewPose.position;
                UnityEngine.Quaternion tmpRot           = pab.previewPose.rotation;
                PlanetFactory          tmpFactory       = (PlanetFactory)AccessTools.Field(typeof(PlayerAction_Build), "factory").GetValue(GameMain.mainPlayer.controller.actionBuild);
                PlanetPhysics          tmpPlanetPhysics = (PlanetPhysics)AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").GetValue(pab);

                //Create Prebuilds from incomming packet
                pab.buildPreviews = packet.GetBuildPreviews();
                pab.waitConfirm   = true;
                using (FactoryManager.EventFromServer.On())
                {
                    FactoryManager.EventFactory = planet.factory;
                    pab.previewPose.position    = new UnityEngine.Vector3(packet.PosePosition.x, packet.PosePosition.y, packet.PosePosition.z);
                    pab.previewPose.rotation    = new UnityEngine.Quaternion(packet.PoseRotation.x, packet.PoseRotation.y, packet.PoseRotation.z, packet.PoseRotation.w);
                    AccessTools.Field(typeof(PlayerAction_Build), "factory").SetValue(GameMain.mainPlayer.controller.actionBuild, planet.factory);

                    //Create temporary physics for spawning building's colliders
                    if (planet.physics == null || planet.physics.colChunks == null)
                    {
                        planet.physics = new PlanetPhysics(planet);
                        planet.physics.Init();
                    }

                    //Take item from the inventory if player is author of the build
                    if (packet.AuthorId == LocalPlayer.PlayerId)
                    {
                        foreach (BuildPreview buildPreview in pab.buildPreviews)
                        {
                            if (GameMain.mainPlayer.inhandItemId == buildPreview.item.ID && GameMain.mainPlayer.inhandItemCount > 0)
                            {
                                GameMain.mainPlayer.UseHandItems(1);
                            }
                            else
                            {
                                int num = 1;
                                GameMain.mainPlayer.package.TakeTailItems(ref buildPreview.item.ID, ref num, false);
                            }
                        }
                    }

                    AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").SetValue(GameMain.mainPlayer.controller.actionBuild, planet.physics);
                    pab.CreatePrebuilds();
                    FactoryManager.EventFactory = null;
                }

                //Author has to call this for the continuous belt building
                if (packet.AuthorId == LocalPlayer.PlayerId)
                {
                    pab.AfterPrebuild();
                }

                //Revert changes back
                AccessTools.Field(typeof(PlayerAction_Build), "planetPhysics").SetValue(GameMain.mainPlayer.controller.actionBuild, tmpPlanetPhysics);
                AccessTools.Field(typeof(PlayerAction_Build), "factory").SetValue(GameMain.mainPlayer.controller.actionBuild, tmpFactory);
                pab.buildPreviews        = tmpList;
                pab.waitConfirm          = tmpConfirm;
                pab.previewPose.position = tmpPos;
                pab.previewPose.rotation = tmpRot;

                FactoryManager.TargetPlanet = -2;
            }
        }
예제 #11
0
        public static void AlterSelection(PlayerAction_Build __instance)
        {
            bool removeMode = VFInput.control;

            if (referenceSelectionGizmo != null)
            {
                referenceSelectionGizmo.Close();
                referenceSelectionGizmo = null;
            }
            if (areaSelectionGizmo == null)
            {
                areaSelectionGizmo = CircleGizmo.Create(6, Vector3.zero, 10);

                areaSelectionGizmo.fadeOutScale = areaSelectionGizmo.fadeInScale = 1.8f;
                areaSelectionGizmo.fadeOutTime  = areaSelectionGizmo.fadeInTime = 0.15f;
                areaSelectionGizmo.autoRefresh  = true;
                areaSelectionGizmo.Open();
            }

            areaSelectionGizmo.color  = removeMode ? REMOVE_SELECTION_GIZMO_COLOR : ADD_SELECTION_GIZMO_COLOR;
            areaSelectionGizmo.radius = selectionRadius;

            if (__instance.groundTestPos != Vector3.zero)
            {
                areaSelectionGizmo.position = __instance.groundTestPos;
            }


            if (VFInput._buildConfirm.pressing)
            {
                areaSelectionGizmo.color = removeMode ? REMOVE_SELECTION_GIZMO_COLOR : ADD_SELECTION_GIZMO_COLOR;

                // target only buildings
                int mask  = 131072;
                int found = Physics.OverlapBoxNonAlloc(__instance.groundTestPos, new Vector3(selectionRadius, 100f, selectionRadius), _tmp_cols, Maths.SphericalRotation(__instance.groundTestPos, 0f), mask, QueryTriggerInteraction.Collide);

                PlanetPhysics planetPhysics = __instance.player.planetData.physics;

                for (int i = 0; i < found; i++)
                {
                    planetPhysics.GetColliderData(_tmp_cols[i], out ColliderData colliderData);
                    if (colliderData.objId > 0)
                    {
                        var entityId = colliderData.objId;
                        if (removeMode)
                        {
                            if (bpSelection.ContainsKey(entityId))
                            {
                                bpSelection[entityId].Close();
                                bpSelection.Remove(entityId);
                            }
                            if (entityId == referenceId)
                            {
                                referenceId = 0;
                            }
                        }
                        else if (!bpSelection.ContainsKey(entityId))
                        {
                            var       entityData = __instance.factory.entityPool[entityId];
                            ItemProto itemProto  = LDB.items.Select((int)entityData.protoId);
                            var       gizmo      = BoxGizmo.Create(entityData.pos, entityData.rot, itemProto.prefabDesc.selectCenter, itemProto.prefabDesc.selectSize);
                            gizmo.multiplier      = 1f;
                            gizmo.alphaMultiplier = itemProto.prefabDesc.selectAlpha;
                            gizmo.fadeInScale     = gizmo.fadeOutScale = 1.3f;
                            gizmo.fadeInTime      = gizmo.fadeOutTime = 0.05f;
                            gizmo.fadeInFalloff   = gizmo.fadeOutFalloff = 0.5f;
                            gizmo.color           = Color.white;

                            gizmo.Open();

                            bpSelection.Add(entityId, gizmo);
                        }
                    }
                }

                if (referenceId == 0)
                {
                    var belts     = new List <int>();
                    var buildings = new List <int>();

                    foreach (var entityId in bpSelection.Keys)
                    {
                        var entityData = __instance.factory.entityPool[entityId];

                        if (entityId != entityData.id)
                        {
                            continue;
                        }

                        ItemProto itemProto = LDB.items.Select((int)entityData.protoId);
                        if (itemProto.prefabDesc.isBelt)
                        {
                            belts.Add(entityId);
                        }
                        else if (!itemProto.prefabDesc.isInserter)
                        {
                            buildings.Add(entityId);
                        }
                    }

                    if (buildings.Count > 0)
                    {
                        referenceId = buildings.First();
                    }
                    else if (belts.Count > 0)
                    {
                        referenceId = belts.First();
                    }
                }
            }

            if (referenceId != 0 && bpSelection.TryGetValue(referenceId, out BoxGizmo reference))
            {
                if (referenceGizmo == null)
                {
                    referenceGizmo                 = BoxGizmo.Create(Vector3.zero, Quaternion.identity, Vector3.zero, new Vector3(0.5f, 100f, 0.5f));
                    referenceGizmo.multiplier      = 1f;
                    referenceGizmo.alphaMultiplier = 0.5f;
                    referenceGizmo.fadeInScale     = referenceGizmo.fadeOutScale = 1.3f;
                    referenceGizmo.fadeInTime      = referenceGizmo.fadeOutTime = 0.05f;
                    referenceGizmo.fadeInFalloff   = referenceGizmo.fadeOutFalloff = 0.5f;
                    referenceGizmo.color           = Color.green;

                    referenceGizmo.Open();
                }

                referenceGizmo.transform.position = reference.transform.position;
                referenceGizmo.transform.rotation = reference.transform.rotation;
                referenceGizmo.center             = reference.center;
            }
        }
예제 #12
0
        private static void CheckBelts(BuildTool_BlueprintPaste tool, BuildPreview preview)
        {
            if (preview.IsCollide())
            {
                if (preview.output == null)
                {
                    return;
                }

                if (!preview.output.IsCollide())
                {
                    return;
                }


                int overlapCount = Physics.OverlapSphereNonAlloc(preview.lpos, 0.28f, BuildTool._tmp_cols, 425984, QueryTriggerInteraction.Collide);

                PlanetPhysics physics = tool.player.planetData.physics;

                for (int m = 0; m < overlapCount; m++)
                {
                    bool found    = physics.GetColliderData(BuildTool._tmp_cols[m], out ColliderData collider);
                    int  objectId = 0;
                    if (found && collider.isForBuild)
                    {
                        if (collider.objType == EObjectType.Entity)
                        {
                            objectId = collider.objId;
                        }
                    }

                    if (objectId == 0)
                    {
                        continue;
                    }
                    ItemProto itemProto = tool.GetItemProto(objectId);
                    if (!itemProto.prefabDesc.isBelt)
                    {
                        continue;
                    }


                    tool.factory.ReadObjectConn(objectId, 0, out bool _, out int otherObjId, out int _);

                    //0 next
                    //1 prev

                    tool.factory.ReadObjectConn(objectId, 1, out bool _, out otherObjId, out int _);

                    if (preview.output.IsCollide())
                    {
                        if (otherObjId == 0)
                        {
                            preview.coverObjId           = objectId;
                            preview.willRemoveCover      = false;
                            preview.output.bpgpuiModelId = 0;
                            preview.output    = null;
                            preview.condition = EBuildCondition.Ok;
                            BlueprintTweaksPlugin.logger.LogInfo("Setting belt condition to OK");
                            break;
                        }
                    }
                }
            }
        }
예제 #13
0
        public static void CreatePrebuildsRequest(CreatePrebuildsRequest packet)
        {
            PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId);

            if (planet.factory == null)
            {
                if (FactoryManager.EventFromServer)
                {
                    // We only execute the code if the client has loaded the factory at least once.
                    // Else it will get it once it goes to the planet for the first time.
                    return;
                }
                Log.Warn($"planet.factory was null create new one");
                planet.factory = GameMain.data.GetOrCreateFactory(planet);
            }

            PlayerAction_Build pab = GameMain.mainPlayer.controller != null ? GameMain.mainPlayer.controller.actionBuild : null;

            BuildTool[] buildTools = pab.tools;
            BuildTool   buildTool  = null;

            for (int i = 0; i < buildTools.Length; i++)
            {
                if (buildTools[i].GetType().ToString() == packet.BuildToolType)
                {
                    buildTool = buildTools[i];
                    break;
                }
            }
            if (pab != null && buildTool != null)
            {
                FactoryManager.TargetPlanet = packet.PlanetId;
                FactoryManager.PacketAuthor = packet.AuthorId;

                PlanetFactory     tmpFactory       = null;
                NearColliderLogic tmpNearcdLogic   = null;
                PlanetPhysics     tmpPlanetPhysics = null;
                bool loadExternalPlanetData        = GameMain.localPlanet != planet;

                if (loadExternalPlanetData)
                {
                    //Make backup of values that are overwritten
                    tmpFactory       = buildTool.factory;
                    tmpNearcdLogic   = buildTool.actionBuild.nearcdLogic;
                    tmpPlanetPhysics = buildTool.actionBuild.planetPhysics;
                }

                //Create Prebuilds from incoming packet and prepare new position
                List <BuildPreview> tmpList = new List <BuildPreview>();
                tmpList.AddRange(buildTool.buildPreviews); buildTool.buildPreviews.Clear();
                buildTool.buildPreviews.AddRange(packet.GetBuildPreviews());
                FactoryManager.EventFactory = planet.factory;

                //Check if some mandatory variables are missing
                if (planet.physics == null || planet.physics.colChunks == null)
                {
                    planet.physics = new PlanetPhysics(planet);
                    planet.physics.Init();
                }
                if (planet.aux == null)
                {
                    planet.aux = new PlanetAuxData(planet);
                }

                //Set temporary Local Planet / Factory data that are needed for original methods CheckBuildConditions() and CreatePrebuilds()
                buildTool.factory    = planet.factory;
                pab.factory          = planet.factory;
                pab.noneTool.factory = planet.factory;
                if (FactoryManager.EventFromClient)
                {
                    // Only the server needs to set these
                    pab.planetPhysics = planet.physics;
                    pab.nearcdLogic   = planet.physics.nearColliderLogic;
                }

                //Check if prebuilds can be build (collision check, height check, etc)
                bool canBuild = false;
                if (FactoryManager.EventFromClient)
                {
                    GameMain.mainPlayer.mecha.buildArea = float.MaxValue;
                    canBuild = CheckBuildingConnections(buildTool.buildPreviews, planet.factory.entityPool, planet.factory.prebuildPool);
                }

                Debug.Log(buildTool.buildPreviews[0].condition);

                if (canBuild || FactoryManager.EventFromServer)
                {
                    if (FactoryManager.EventFromClient)
                    {
                        CheckAndFixConnections(buildTool, planet);
                    }

                    if (packet.BuildToolType == typeof(BuildTool_Click).ToString())
                    {
                        ((BuildTool_Click)buildTool).CreatePrebuilds();
                    }
                    else if (packet.BuildToolType == typeof(BuildTool_Path).ToString())
                    {
                        ((BuildTool_Path)buildTool).CreatePrebuilds();
                    }
                    else if (packet.BuildToolType == typeof(BuildTool_Inserter).ToString())
                    {
                        ((BuildTool_Inserter)buildTool).CreatePrebuilds();
                    }
                }

                //Revert changes back to the original planet
                if (loadExternalPlanetData)
                {
                    buildTool.factory    = tmpFactory;
                    pab.factory          = tmpFactory;
                    pab.noneTool.factory = tmpFactory;

                    if (FactoryManager.EventFromClient)
                    {
                        pab.planetPhysics = tmpPlanetPhysics;
                        pab.nearcdLogic   = tmpNearcdLogic;
                        planet.physics.Free();
                        planet.physics = null;
                    }
                }

                GameMain.mainPlayer.mecha.buildArea = Configs.freeMode.mechaBuildArea;
                FactoryManager.EventFactory         = null;

                buildTool.buildPreviews.Clear();
                buildTool.buildPreviews.AddRange(tmpList);

                FactoryManager.TargetPlanet = FactoryManager.PLANET_NONE;
                FactoryManager.PacketAuthor = -1;
            }
        }
예제 #14
0
        // collision with vegetation, landing sound effect
        private void UpdateExtraSoundEffects(PlayerAnimationUpdate packet)
        {
            if (localPlanetId < 0)
            {
                return;
            }

            if (localPlanetId > 0)
            {
                PlanetData    pData          = GameMain.galaxy.PlanetById(localPlanetId);
                PlanetPhysics pPhys          = (pData != null) ? pData.physics : null;
                PlanetFactory pFactory       = (pData != null) ? pData.factory : null;
                float         tmpMaxAltitude = rootTransform.localPosition.magnitude - pData.realRadius;
                if (tmpMaxAltitude > 1000f)
                {
                    tmpMaxAltitude = 1000f;
                }

                if (rootAnimation.RunSlow.enabled || rootAnimation.RunFast.enabled || rootAnimation.Drift.enabled || rootAnimation.DriftF.enabled || rootAnimation.DriftR.enabled || rootAnimation.DriftL.enabled)
                {
                    bool ground = IsGrounded();

                    if (DriftDetermineInWater(pData))
                    {
                        if (maxAltitude > 1f && pData.waterItemId > 0)
                        {
                            VFAudio audio = VFAudio.Create("landing-water", base.transform, Vector3.zero, false, 0);
                            audio.volumeMultiplier = Mathf.Clamp01(maxAltitude / 5f + 0.5f);
                            audio.Play();
                            PlayFootstepEffect(true, 0f, true);
                            PlayFootstepEffect(false, 0f, true);
                        }
                        maxAltitude = 0f;
                    }
                    if (ground && maxAltitude > 3f)
                    {
                        VFAudio audio = VFAudio.Create("landing", base.transform, Vector3.zero, false, 0);
                        audio.volumeMultiplier = Mathf.Clamp01(maxAltitude / 25f + 0.5f);
                        audio.Play();
                        maxAltitude = 0f;
                    }
                    if (!ground && tmpMaxAltitude > maxAltitude)
                    {
                        maxAltitude = tmpMaxAltitude;
                    }
                }
                else
                {
                    maxAltitude = 15f;
                }

                // NOTE: the pPhys can only be loaded if the player trying to load it has the planet actually loaded (meaning he is on the same planet or near it)
                if (pPhys != null && pFactory != null && packet.horzSpeed > 5f)
                {
                    int number = Physics.OverlapSphereNonAlloc(base.transform.localPosition, 1.8f, collider, 1024, QueryTriggerInteraction.Collide);
                    for (int i = 0; i < number; i++)
                    {
                        int          colId = pPhys.nearColliderLogic.FindColliderId(collider[i]);
                        ColliderData cData = pPhys.GetColliderData(colId);
                        if (cData.objType == EObjectType.Vegetable && cData.objId > 0)
                        {
                            VegeData  vData  = pFactory.vegePool[cData.objId];
                            VegeProto vProto = LDB.veges.Select((int)vData.protoId);
                            if (vProto != null && vProto.CollideAudio > 0 && vegeCollideColdTime <= 0)
                            {
                                VFAudio.Create(vProto.CollideAudio, base.transform, Vector3.zero, true, 0);
                                vegeCollideColdTime = UnityEngine.Random.value * 0.23f + 0.1f;
                            }
                        }
                    }
                }
            }

            if (vegeCollideColdTime > 0)
            {
                vegeCollideColdTime -= Time.deltaTime * 2;
            }
            else
            {
                vegeCollideColdTime = 0;
            }
        }
예제 #15
0
        public static void CreatePrebuildsRequest(CreatePrebuildsRequest packet)
        {
            PlanetData planet = GameMain.galaxy.PlanetById(packet.PlanetId);

            if (planet.factory == null)
            {
                if (FactoryManager.IsIncomingRequest)
                {
                    // We only execute the code if the client has loaded the factory at least once.
                    // Else it will get it once it goes to the planet for the first time.
                    return;
                }
                Log.Warn($"planet.factory was null create new one");
                planet.factory = GameMain.data.GetOrCreateFactory(planet);
            }

            PlayerAction_Build pab = GameMain.mainPlayer.controller != null ? GameMain.mainPlayer.controller.actionBuild : null;

            BuildTool[] buildTools = pab.tools;
            BuildTool   buildTool  = null;

            for (int i = 0; i < buildTools.Length; i++)
            {
                if (buildTools[i].GetType().ToString() == packet.BuildToolType)
                {
                    buildTool = buildTools[i];
                    break;
                }
            }

            if (pab != null && buildTool != null)
            {
                FactoryManager.TargetPlanet = packet.PlanetId;
                FactoryManager.PacketAuthor = packet.AuthorId;

                PlanetFactory     tmpFactory       = null;
                NearColliderLogic tmpNearcdLogic   = null;
                PlanetPhysics     tmpPlanetPhysics = null;
                bool loadExternalPlanetData        = GameMain.localPlanet?.id != planet.id;

                if (loadExternalPlanetData)
                {
                    //Make backup of values that are overwritten
                    tmpFactory       = buildTool.factory;
                    tmpNearcdLogic   = buildTool.actionBuild.nearcdLogic;
                    tmpPlanetPhysics = buildTool.actionBuild.planetPhysics;
                    FactoryManager.AddPlanetTimer(packet.PlanetId);
                }

                bool incomingBlueprintEvent = packet.BuildToolType == typeof(BuildTool_BlueprintPaste).ToString();

                //Create Prebuilds from incoming packet and prepare new position
                List <BuildPreview> tmpList = new List <BuildPreview>();
                if (!incomingBlueprintEvent)
                {
                    tmpList.AddRange(buildTool.buildPreviews);
                    buildTool.buildPreviews.Clear();
                    buildTool.buildPreviews.AddRange(packet.GetBuildPreviews());
                }

                FactoryManager.EventFactory = planet.factory;

                //Set temporary Local Planet / Factory data that are needed for original methods CheckBuildConditions() and CreatePrebuilds()
                buildTool.factory    = planet.factory;
                pab.factory          = planet.factory;
                pab.noneTool.factory = planet.factory;
                if (FactoryManager.IsIncomingRequest)
                {
                    // Only the server needs to set these
                    pab.planetPhysics = planet.physics;
                    pab.nearcdLogic   = planet.physics.nearColliderLogic;
                }

                //Check if prebuilds can be build (collision check, height check, etc)
                bool canBuild = false;
                if (FactoryManager.IsIncomingRequest)
                {
                    GameMain.mainPlayer.mecha.buildArea = float.MaxValue;
                    canBuild = CheckBuildingConnections(buildTool.buildPreviews, planet.factory.entityPool, planet.factory.prebuildPool);
                }

                if (canBuild || FactoryManager.IsIncomingRequest)
                {
                    if (FactoryManager.IsIncomingRequest)
                    {
                        CheckAndFixConnections(buildTool, planet);
                    }

                    if (packet.BuildToolType == typeof(BuildTool_Click).ToString())
                    {
                        ((BuildTool_Click)buildTool).CreatePrebuilds();
                    }
                    else if (packet.BuildToolType == typeof(BuildTool_Path).ToString())
                    {
                        ((BuildTool_Path)buildTool).CreatePrebuilds();
                    }
                    else if (packet.BuildToolType == typeof(BuildTool_Inserter).ToString())
                    {
                        ((BuildTool_Inserter)buildTool).CreatePrebuilds();
                    }
                    else if (incomingBlueprintEvent)
                    {
                        BuildTool_BlueprintPaste bpTool = buildTool as BuildTool_BlueprintPaste;

                        // Cache the current data before performing the requested CreatePrebuilds();
                        int            previousCursor = bpTool.bpCursor;
                        BuildPreview[] previousPool   = bpTool.bpPool;

                        // Perform the requested CreatePrebuilds();
                        List <BuildPreview> incomingPreviews = packet.GetBuildPreviews();
                        bpTool.bpCursor = incomingPreviews.Count;
                        bpTool.bpPool   = incomingPreviews.ToArray();
                        bpTool.CreatePrebuilds();

                        // Revert to previous data
                        bpTool.bpCursor = previousCursor;
                        bpTool.bpPool   = previousPool;
                    }
                }

                //Revert changes back to the original planet
                if (loadExternalPlanetData)
                {
                    buildTool.factory    = tmpFactory;
                    pab.factory          = tmpFactory;
                    pab.noneTool.factory = tmpFactory;
                    pab.planetPhysics    = tmpPlanetPhysics;
                    pab.nearcdLogic      = tmpNearcdLogic;
                }

                GameMain.mainPlayer.mecha.buildArea = Configs.freeMode.mechaBuildArea;
                FactoryManager.EventFactory         = null;

                if (!incomingBlueprintEvent)
                {
                    buildTool.buildPreviews.Clear();
                    buildTool.buildPreviews.AddRange(tmpList);
                }

                FactoryManager.TargetPlanet = FactoryManager.PLANET_NONE;
                FactoryManager.PacketAuthor = FactoryManager.AUTHOR_NONE;
            }
        }