Exemplo n.º 1
0
    public void FaceDataYNegative(CubeBlock block, Vector3 pos, bool dropItem = false)
    {
        float half_block_size = block.blockSize / 2.0f;

        this.AddVertex(new Vector3(pos.x - half_block_size, pos.y - half_block_size, pos.z - half_block_size));
        this.AddVertex(new Vector3(pos.x + half_block_size, pos.y - half_block_size, pos.z - half_block_size));
        this.AddVertex(new Vector3(pos.x + half_block_size, pos.y - half_block_size, pos.z + half_block_size));
        this.AddVertex(new Vector3(pos.x - half_block_size, pos.y - half_block_size, pos.z + half_block_size));

        // add normals
        Vector3 down = Vector3.down;

        this.normals.Add(down);
        this.normals.Add(down);
        this.normals.Add(down);
        this.normals.Add(down);

        // add triangles
        this.AddQuadTriangles();

        // add textures
        BlockTile blockTile = dropItem ? block.getDropBlockTile() : block.getBlockTile();
        Vector2   _00       = blockTile.bottom_00;
        Vector2   _10       = blockTile.bottom_10;
        Vector2   _01       = blockTile.bottom_01;
        Vector2   _11       = blockTile.bottom_11;

        this.uvs.Add(_11);
        this.uvs.Add(_01);
        this.uvs.Add(_00);
        this.uvs.Add(_10);
    }
Exemplo n.º 2
0
        private void LockAndShoot()
        {
            if (m_onCooldown || m_onGameCooldown)
            {
                Log.TraceLog("on cooldown");
                return;
            }

            if (!_shootCluster)
            {
                InitialTargetStatus initial = GetInitialTarget();
                if (initial != _initial || _initialTarget != m_weaponTarget.CurrentTarget)
                {
                    Log.TraceLog("Updating custom info");
                    _initial       = initial;
                    _initialTarget = m_weaponTarget.CurrentTarget;
                    CubeBlock.UpdateCustomInfo();
                }

                if (m_weaponTarget.CurrentTarget is NoTarget && !m_weaponTarget.FireWithoutLock)
                {
                    Log.TraceLog("Cannot fire, no target found", Logger.severity.TRACE);
                    return;
                }
            }

            Log.TraceLog("Shooting from terminal");
            _isShooting = true;
            ((MyUserControllableGun)CubeBlock).ShootFromTerminal(m_weaponTarget.Facing());
            Log.TraceLog("Back from shoot");
        }
Exemplo n.º 3
0
        public GuidedMissileLauncher(WeaponTargeting weapon)
        {
            m_weaponTarget      = weapon;
            m_relayPart         = RelayClient.GetOrCreateRelayPart(m_weaponTarget.CubeBlock);
            this._initialTarget = NoTarget.Instance;

            MyWeaponBlockDefinition defn = (MyWeaponBlockDefinition)CubeBlock.GetCubeBlockDefinition();

            Vector3[] points        = new Vector3[3];
            Vector3   forwardAdjust = Vector3.Forward * WeaponDescription.GetFor(CubeBlock).MissileSpawnForward;

            points[0] = CubeBlock.LocalAABB.Min + forwardAdjust;
            points[1] = CubeBlock.LocalAABB.Max + forwardAdjust;
            points[2] = CubeBlock.LocalAABB.Min + Vector3.Up * defn.Size.Y * CubeBlock.CubeGrid.GridSize + forwardAdjust;

            MissileSpawnBox = BoundingBox.CreateFromPoints(points);
            if (m_weaponTarget.myTurret != null)
            {
                Log.TraceLog("original box: " + MissileSpawnBox);
                MissileSpawnBox.Inflate(CubeBlock.CubeGrid.GridSize * 2f);
            }

            Log.TraceLog("MissileSpawnBox: " + MissileSpawnBox);

            myInventory = ((MyEntity)CubeBlock).GetInventoryBase(0);

            Registrar.Add(weapon.CubeBlock, this);
            m_weaponTarget.GuidedLauncher = true;

            m_gameCooldownTime = TimeSpan.FromSeconds(60d / MyDefinitionManager.Static.GetWeaponDefinition(defn.WeaponDefinitionId).WeaponAmmoDatas[(int)MyAmmoType.Missile].RateOfFire);
            Log.TraceLog("m_gameCooldownTime: " + m_gameCooldownTime);

            CubeBlock.AppendingCustomInfo += CubeBlock_AppendingCustomInfo;
        }
Exemplo n.º 4
0
    public void FaceDataZPositive(CubeBlock block, Vector3 pos, bool dropItem = false)
    {
        float half_block_size = block.blockSize / 2.0f;

        this.AddVertex(new Vector3(pos.x - half_block_size, pos.y - half_block_size, pos.z - half_block_size));
        this.AddVertex(new Vector3(pos.x - half_block_size, pos.y + half_block_size, pos.z - half_block_size));
        this.AddVertex(new Vector3(pos.x + half_block_size, pos.y + half_block_size, pos.z - half_block_size));
        this.AddVertex(new Vector3(pos.x + half_block_size, pos.y - half_block_size, pos.z - half_block_size));

        // add normals
        Vector3 front = Vector3.forward;

        this.normals.Add(front);
        this.normals.Add(front);
        this.normals.Add(front);
        this.normals.Add(front);

        // add triangles
        this.AddQuadTriangles();

        // add textures
        BlockTile blockTile = dropItem ? block.getDropBlockTile() : block.getBlockTile();
        Vector2   _00       = blockTile.front_00;
        Vector2   _10       = blockTile.front_10;
        Vector2   _01       = blockTile.front_01;
        Vector2   _11       = blockTile.front_11;

        this.uvs.Add(_10);
        this.uvs.Add(_11);
        this.uvs.Add(_01);
        this.uvs.Add(_00);
    }
Exemplo n.º 5
0
	public void FaceDataYNegative(CubeBlock block, Vector3 pos, bool dropItem = false){
		float half_block_size = block.blockSize / 2.0f;
		this.AddVertex(new Vector3(pos.x - half_block_size, pos.y - half_block_size, pos.z - half_block_size));
		this.AddVertex(new Vector3(pos.x + half_block_size, pos.y - half_block_size, pos.z - half_block_size));
		this.AddVertex(new Vector3(pos.x + half_block_size, pos.y - half_block_size, pos.z + half_block_size));
		this.AddVertex(new Vector3(pos.x - half_block_size, pos.y - half_block_size, pos.z + half_block_size));

		// add normals
		Vector3 down = Vector3.down;
		this.normals.Add (down);
		this.normals.Add (down);
		this.normals.Add (down);
		this.normals.Add (down);

		// add triangles
		this.AddQuadTriangles();

		// add textures
		BlockTile blockTile = dropItem ? block.getDropBlockTile() : block.getBlockTile();
		Vector2 _00 = blockTile.bottom_00;
		Vector2 _10 = blockTile.bottom_10;
		Vector2 _01 = blockTile.bottom_01;
		Vector2 _11 = blockTile.bottom_11;
		this.uvs.Add (_11);
		this.uvs.Add (_01);
		this.uvs.Add (_00);
		this.uvs.Add (_10);
	}
Exemplo n.º 6
0
    private static void BuildFace(CubeFace face, CubeBlock cube, BlockDirection direction, Vector3 localPos, MeshBuilder mesh)
    {
        int iFace = (int)face;

        mesh.AddFaceIndices(cube.GetAtlasID());
        mesh.AddVertices(vertices[iFace], localPos);
        mesh.AddNormals(normals[iFace]);
        mesh.AddTexCoords(cube.GetFaceUV(face, direction));
    }
Exemplo n.º 7
0
        /// <summary>
        /// Called before update loop begins
        /// </summary>
        public virtual void Start()
        {
            WeaponDefinition = CubeBlock.BlockDefinition.Id;

            State = new NetSync <WeaponState>(ControlLayer, TransferType.Both, WeaponState.None);
            State.ValueChanged += StateChanged;
            Reloading           = new NetSync <bool>(ControlLayer, TransferType.ServerToClient, false);
            DeviationIndex      = new NetSync <sbyte>(ControlLayer, TransferType.ServerToClient, (sbyte)MyRandom.Instance.Next(0, sbyte.MaxValue));
            InventoryComponent.GetOrAddComponent(CubeBlock.CubeGrid);
            Inventory = CubeBlock.GetInventory();
        }
Exemplo n.º 8
0
 public void Set(CubeBlock block)
 {
     workObject = block;
     workObject.SetWorksite(this);
     GameMaster.colonyController.SendWorkers(START_WORKERS_COUNT, this);
     if (!worksitesList.Contains(this))
     {
         worksitesList.Add(this);
     }
     if (!subscribedToUpdate)
     {
         GameMaster.realMaster.labourUpdateEvent += WorkUpdate;
         subscribedToUpdate = true;
     }
 }
Exemplo n.º 9
0
    public static MeshBuilder Build(CubeBlock cube)
    {
        MeshBuilder mesh = new MeshBuilder();

        for (int i = 0; i < vertices.Length; i++)
        {
            mesh.AddFaceIndices(0);
            mesh.AddVertices(vertices[i], Vector3.zero);
            mesh.AddNormals(normals[i]);

            Vector2[] texCoords = cube.GetFaceUV((CubeFace)i, BlockDirection.Z_PLUS);
            mesh.AddTexCoords(texCoords);
            //mesh.AddFaceColor( new Color(0,0,0,1) );
        }
        return(mesh);
    }
Exemplo n.º 10
0
    public void Set(CubeBlock block, bool work_is_dig)
    {
        workObject = block;
        workObject.SetWorksite(this);
        dig = work_is_dig;
        if (dig)
        {
            Block b = GameMaster.mainChunk.GetBlock(block.pos.x, block.pos.y + 1, block.pos.z);
            if (b != null && (b.type == BlockType.Surface & b.worksite == null))
            {
                CleanSite cs = b.gameObject.AddComponent <CleanSite>();
                TransferWorkers(this, cs);
                cs.Set(b as SurfaceBlock, true);
                if (showOnGUI)
                {
                    cs.ShowOnGUI();
                    showOnGUI = false;
                }
                StopWork();
                return;
            }
            sign = Instantiate(Resources.Load <GameObject> ("Prefs/DigSign")).GetComponent <WorksiteSign>();
        }
        else
        {
            sign = Instantiate(Resources.Load <GameObject>("Prefs/PourInSign")).GetComponent <WorksiteSign>();
        }
        sign.worksite           = this;
        sign.transform.position = workObject.transform.position + Vector3.up * Block.QUAD_SIZE;
        //FollowingCamera.main.cameraChangedEvent += SignCameraUpdate;

        mainResource = ResourceType.GetResourceTypeById(workObject.material_id);
        if (workersCount < START_WORKERS_COUNT)
        {
            GameMaster.colonyController.SendWorkers(START_WORKERS_COUNT, this);
        }
        if (!worksitesList.Contains(this))
        {
            worksitesList.Add(this);
        }
        if (!subscribedToUpdate)
        {
            GameMaster.realMaster.labourUpdateEvent += WorkUpdate;
            subscribedToUpdate = true;
        }
    }
Exemplo n.º 11
0
    override public void SetBasement(SurfaceBlock b, PixelPosByte pos)
    {
        if (b == null)
        {
            return;
        }
        SetBuildingData(b, pos);
        if (!subscribedToUpdate)
        {
            GameMaster.realMaster.labourUpdateEvent += LabourUpdate;
            subscribedToUpdate = true;
        }
        Block bb = basement.myChunk.GetBlock(basement.pos.x, basement.pos.y - 1, basement.pos.z);

        workObject        = bb as CubeBlock;
        lastWorkObjectPos = bb.pos;
    }
Exemplo n.º 12
0
        public void UpdateAfterSimulation100()
        {
            try
            {
                if (!myLaserAntenna.IsWorking)
                {
                    return;
                }

                //Showoff.doShowoff(CubeBlock, myLastSeen.Values.GetEnumerator(), myLastSeen.Count);

                // stage 5 is the final stage. It is possible for one to be in stage 5, while the other is not
                MyObjectBuilder_LaserAntenna builder = CubeBlock.getSlim().GetObjectBuilder() as MyObjectBuilder_LaserAntenna;
                if (builder.targetEntityId != null)
                {
                    foreach (LaserAntenna lAnt in value_registry)
                    {
                        if (lAnt.CubeBlock.EntityId == builder.targetEntityId)
                        {
                            if (builder.State == 5 && (lAnt.CubeBlock.getSlim().GetObjectBuilder() as MyObjectBuilder_LaserAntenna).State == 5)
                            {
                                //log("Laser " + CubeBlock.gridBlockName() + " connected to " + lAnt.CubeBlock.gridBlockName(), "UpdateAfterSimulation100()", Logger.severity.DEBUG);
                                foreach (LastSeen seen in myLastSeen.Values)
                                {
                                    lAnt.receive(seen);
                                }
                                foreach (Message mes in myMessages)
                                {
                                    lAnt.receive(mes);
                                }
                                break;
                            }
                        }
                    }
                }

                // send to attached receivers
                Receiver.sendToAttached(CubeBlock, myLastSeen);
                Receiver.sendToAttached(CubeBlock, myMessages);

                UpdateEnemyNear();
            }
            catch (Exception e)
            { myLogger.log("Exception: " + e, "UpdateAfterSimulation100()", Logger.severity.ERROR); }
        }
Exemplo n.º 13
0
	public void AddCube() {
		if (cubes.Count == maxHeight) {
			return;
		}
		CubeBlock newCubeBlock = Instantiate(cubeBlockPrefab) as CubeBlock;
		newCubeBlock.transform.parent = this.transform;
		newCubeBlock.transform.localRotation = Quaternion.identity;
		if (cubes.Count == 0) {
			newCubeBlock.transform.localPosition = new Vector3(0f, .55f, 0f);
		}
		else {
			newCubeBlock.transform.localPosition = cubes.Last.Value.transform.localPosition 
				+ new Vector3(0f, cubeLength, 0f);
			cubes.Last.Value.UnhighlightCube();
		}
		cubes.AddLast(newCubeBlock);
		cubes.Last.Value.HighlightCube();
	}
Exemplo n.º 14
0
 override public void StopWork()
 {
     if (destroyed)
     {
         return;
     }
     else
     {
         destroyed = true;
     }
     if (workersCount > 0)
     {
         GameMaster.colonyController.AddWorkers(workersCount);
         workersCount = 0;
     }
     if (sign != null)
     {
         Destroy(sign.gameObject);
     }
     if (worksitesList.Contains(this))
     {
         worksitesList.Remove(this);
     }
     if (subscribedToUpdate)
     {
         GameMaster.realMaster.labourUpdateEvent -= WorkUpdate;
         subscribedToUpdate = false;
     }
     if (workObject != null)
     {
         if (workObject.worksite == this)
         {
             workObject.ResetWorksite();
         }
         workObject = null;
     }
     if (showOnGUI)
     {
         observer.SelfShutOff();
         showOnGUI = false;
     }
     Destroy(this);
 }
Exemplo n.º 15
0
	public void generate3DMeshFromCubeBlock(CubeBlock block) {
		meshData = new MeshData ();
		block.generateMesh (meshData, Vector3.zero, null, false, true);

		MeshFilter filter = GetComponent<MeshFilter> (); // transform.gameObject.AddComponent< MeshFilter >() as MeshFilter;
		Mesh mesh = filter.mesh;
		mesh.Clear();

		mesh.vertices = meshData.vertices.ToArray();
		mesh.triangles = meshData.triangles.ToArray();

		// mesh.normals = meshData.normals.ToArray ();
		mesh.uv = meshData.uvs.ToArray();

		mesh.RecalculateBounds();
		mesh.Optimize();

		Material material = GetComponent<Renderer>().material as Material;
		material.mainTexture = GameObject.Find ("Chunk").GetComponent<Renderer> ().material.mainTexture; 
	}
Exemplo n.º 16
0
    public static void Build(Vector3i localPos, Vector3i worldPos, Map map, MeshBuilder mesh, bool onlyLight)
    {
        BlockData      block     = map.GetBlock(worldPos);
        CubeBlock      cube      = (CubeBlock)block.block;
        BlockDirection direction = block.GetDirection();

        for (int i = 0; i < 6; i++)
        {
            CubeFace face    = faces[i];
            Vector3i dir     = directions[i];
            Vector3i nearPos = worldPos + dir;
            if (IsFaceVisible(map, nearPos))
            {
                if (!onlyLight)
                {
                    BuildFace(face, cube, direction, localPos, mesh);
                }
                BuildFaceLight(face, map, worldPos, mesh);
            }
        }
    }
Exemplo n.º 17
0
        protected void UpdateEnemyNear()
        {
            Vector3D myPosition = CubeBlock.GetPosition();

            EnemyNear = false;
            foreach (LastSeen seen in myLastSeen.Values)
            {
                IMyCubeGrid seenAsGrid = seen.Entity as IMyCubeGrid;
                if (seenAsGrid != null)
                {
                    //myLogger.debugLog("testing grid: " + seenAsGrid.DisplayName + ", recent = " + seen.isRecent() + ", hostile = " + CubeBlock.canConsiderHostile(seenAsGrid) + ", distance squared = " + (seen.LastKnownPosition - myPosition).LengthSquared(), "UpdateEnemyNear()");
                    if (seen.isRecent() && CubeBlock.canConsiderHostile(seenAsGrid) && (seen.LastKnownPosition - myPosition).LengthSquared() < 9000000)                     // 3km, squared = 9Mm
                    {
                        //myLogger.debugLog("nearby enemy: " + seen.Entity.getBestName(), "UpdateEnemyNear()");
                        EnemyNear = true;
                        return;
                    }
                }
            }
            //myLogger.debugLog("no enemy nearby", "UpdateEnemyNear()");
        }
Exemplo n.º 18
0
    public void generate3DMeshFromCubeBlock(CubeBlock block)
    {
        meshData = new MeshData();
        block.generateMesh(meshData, Vector3.zero, null, false, true);

        MeshFilter filter = GetComponent <MeshFilter> ();        // transform.gameObject.AddComponent< MeshFilter >() as MeshFilter;
        Mesh       mesh   = filter.mesh;

        mesh.Clear();

        mesh.vertices  = meshData.vertices.ToArray();
        mesh.triangles = meshData.triangles.ToArray();

        // mesh.normals = meshData.normals.ToArray ();
        mesh.uv = meshData.uvs.ToArray();

        mesh.RecalculateBounds();
        mesh.Optimize();

        Material material = GetComponent <Renderer>().material as Material;

        material.mainTexture = GameObject.Find("Chunk").GetComponent <Renderer> ().material.mainTexture;
    }
Exemplo n.º 19
0
        public Turret(IMyCubeBlock block)
            : base(block)
        {
            // definition limits
            MyLargeTurretBaseDefinition definition = CubeBlock.GetCubeBlockDefinition() as MyLargeTurretBaseDefinition;

            if (definition == null)
            {
                throw new NullReferenceException("definition");
            }

            minElevation = Math.Max(MathHelper.ToRadians(definition.MinElevationDegrees), -0.6f);
            maxElevation = MathHelper.ToRadians(definition.MaxElevationDegrees);
            minAzimuth   = MathHelper.ToRadians(definition.MinAzimuthDegrees);
            maxAzimuth   = MathHelper.ToRadians(definition.MaxAzimuthDegrees);

            Can360 = Math.Abs(definition.MaxAzimuthDegrees - definition.MinAzimuthDegrees) >= 360;

            // speeds are in rads per ms (from S.E. source)
            speedElevation = definition.ElevationSpeed * 100f / 6f;
            speedAzimuth   = definition.RotationSpeed * 100f / 6f;

            setElevation = myTurret.Elevation;
            setAzimuth   = myTurret.Azimuth;

            // subparts for turrets form a chain
            var subparts = ((MyCubeBlock)CubeBlock).Subparts;

            while (subparts.Count != 0)
            {
                m_barrel = subparts.FirstPair().Value;
                subparts = m_barrel.Subparts;
            }

            //Log.DebugLog("definition limits = " + definition.MinElevationDegrees + ", " + definition.MaxElevationDegrees + ", " + definition.MinAzimuthDegrees + ", " + definition.MaxAzimuthDegrees, "Turret()");
            //Log.DebugLog("radian limits = " + minElevation + ", " + maxElevation + ", " + minAzimuth + ", " + maxAzimuth, "Turret()");
        }
Exemplo n.º 20
0
    override public void LevelUp(bool returnToUI)
    {
        Block b = basement.myChunk.GetBlock(lastWorkObjectPos.x, lastWorkObjectPos.y - 1, lastWorkObjectPos.z);

        if (b != null && b.type == BlockType.Cube)
        {
            if (!GameMaster.realMaster.weNeedNoResources)
            {
                ResourceContainer[] cost = GetUpgradeCost();
                if (cost != null && cost.Length != 0)
                {
                    if (!GameMaster.colonyController.storage.CheckBuildPossibilityAndCollectIfPossible(cost))
                    {
                        UIController.current.MakeAnnouncement(Localization.GetAnnouncementString(GameAnnouncements.NotEnoughResources));
                        return;
                    }
                }
            }
            workObject        = b as CubeBlock;
            lastWorkObjectPos = b.pos;
            workFinished      = false;
            UpgradeMine((byte)(level + 1));
        }
    }
Exemplo n.º 21
0
        /// <summary>
        /// Updates m_stage if guidance starts or stops.
        /// </summary>
        private void CheckGuidance()
        {
            switch (m_stage)
            {
            case Stage.Rail:
                double minDist = (MyEntity.WorldAABB.Max - MyEntity.WorldAABB.Min).AbsMax();
                minDist *= 2;

                if (CubeBlock.WorldAABB.DistanceSquared(MyEntity.GetPosition()) >= minDist * minDist)
                {
                    myGuidanceEnds = Globals.ElapsedTime.Add(TimeSpan.FromSeconds(myDescr.GuidanceSeconds));
                    m_rail         = null;
                    if (myDescr.SemiActiveLaser)
                    {
                        Log.DebugLog("past arming range, semi-active.", Logger.severity.INFO);
                        m_stage = Stage.SemiActive;
                        return;
                    }

                    if (CurrentTarget is GolisTarget)
                    {
                        Log.DebugLog("past arming range, golis active", Logger.severity.INFO);
                        m_stage = Stage.Golis;
                        return;
                    }

                    if (myAmmo.Description.BoostDistance > 1f)
                    {
                        Log.DebugLog("past arming range, starting boost stage", Logger.severity.INFO);
                        StartGravity();
                        m_stage = Stage.Boost;
                        if (m_gravData == null)
                        {
                            Log.DebugLog("no gravity, terminating", Logger.severity.WARNING);
                            m_stage = Stage.Terminated;
                        }
                    }
                    else
                    {
                        Log.DebugLog("past arming range, starting guidance.", Logger.severity.INFO);
                        m_stage = Stage.Guided;
                    }
                }
                return;

            case Stage.Boost:
                if (Vector3D.DistanceSquared(CubeBlock.GetPosition(), MyEntity.GetPosition()) >= myAmmo.Description.BoostDistance * myAmmo.Description.BoostDistance)
                {
                    Log.DebugLog("completed boost stage, starting mid course stage", Logger.severity.INFO);
                    m_stage = Stage.MidCourse;
                }
                return;

            case Stage.MidCourse:
                Target t = CurrentTarget;
                if (t.Entity == null)
                {
                    return;
                }

                double toTarget = Vector3D.Distance(MyEntity.GetPosition(), t.GetPosition());
                double toLaunch = Vector3D.Distance(MyEntity.GetPosition(), CubeBlock.GetPosition());

                if (toTarget < toLaunch)
                {
                    Log.DebugLog("closer to target(" + toTarget + ") than to launch(" + toLaunch + "), starting guidance", Logger.severity.INFO);
                    m_stage        = Stage.Guided;
                    myGuidanceEnds = Globals.ElapsedTime.Add(TimeSpan.FromSeconds(myDescr.GuidanceSeconds));
                    m_gravData     = null;
                }
                return;

            case Stage.SemiActive:
            case Stage.Golis:
            case Stage.Guided:
                if (Globals.ElapsedTime >= myGuidanceEnds)
                {
                    Log.DebugLog("finished guidance", Logger.severity.INFO);
                    m_stage = Stage.Ballistic;
                }
                return;
            }
        }
Exemplo n.º 22
0
        private void Update_OnThread()
        {
            try
            {
                m_nearbyEntities.Clear();
                m_nearbyRange = 0f;
                myLastSeen.Clear();
                detectedObjects_list.Clear();
                if (detectedObjects_hash != null)
                {
                    detectedObjects_hash.Clear();
                }

                if (!IsWorking)
                {
                    if (PowerLevel_Current > 0)
                    {
                        PowerLevel_Current += myDefinition.PowerDecrease;
                    }
                    ClearJamming();
                    return;
                }

                UpdatePowerLevel();

                if (IsJammer)
                {
                    JamRadar();
                }

                if (IsRadar)
                {
                    ActiveDetection();
                }

                if (myDefinition.PassiveDetect_Jamming > 0)
                {
                    PassiveDetection(false);
                }

                if (myDefinition.PassiveDetect_Radar > 0)
                {
                    PassiveDetection(true);
                }

                if (detectedObjects_list.Count > 0)
                {
                    detectedObjects_list.Sort();
                    int transmit = Math.Min(detectedObjects_list.Count, myDefinition.MaxTargets_Tracking);
                    for (int i = 0; i < transmit; i++)
                    {
                        DetectedInfo detFo = detectedObjects_list[i];
                        myLastSeen.Add(new LastSeen(detFo.Entity, detFo.Times, detFo.Info));
                        //Log.DebugLog("created last seen for: " + detFo.Entity.getBestName());
                    }
                    //Log.DebugLog("sending to storage: " + myLastSeen.Count);
                    m_node.Storage.Receive(myLastSeen);
                }
            }
            catch (Exception ex)
            {
                Log.AlwaysLog("Exception: " + ex, Logger.severity.ERROR);
                CubeBlock.EnableGameThread(false);
            }
            finally
            { myLock.ReleaseExclusive(); }
        }
Exemplo n.º 23
0
    void Load()
    {
        Dictionary <int, BlockData> blockData = new Dictionary <int, BlockData>();

        using (TextReader reader = AssetUtils.LoadText(Application.streamingAssetsPath + Path.DirectorySeparatorChar + blocksDataFile))
        {
            reader.ReadLine();
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                BlockData data = new BlockData(line);
                blockData[data.Index] = data;
            }
        }

        Dictionary <string, System.Type> definedBlocks = new Dictionary <string, System.Type>();

        foreach (System.Type t in System.Reflection.Assembly.GetAssembly(typeof(Block)).GetTypes())
        {
            if (t.IsSubclassOf(typeof(Block)))
            {
                definedBlocks.Add(t.Name, t);
            }
        }

        List <Block> b     = new List <Block>();
        int          i     = 0;
        int          count = blockData.Count;

        while (i < count)
        {
            if (blockData.ContainsKey(i))
            {
                Block block = (Block)System.Activator.CreateInstance(definedBlocks[blockData[i].BlockType]);
                InitializeBlock(block, blockData[i]);
                b.Add(block);
                i++;
            }
            else
            {
                Block block = new CubeBlock();
                InitializeBlock(block, blockData[0]);
                b.Add(block);
            }
        }

        Blocks = b.ToArray();

        StandardCubeBlocks = new IStandardCubeBlock[Blocks.Length];
        NormalBlocks       = new INormalBlock[Blocks.Length];
        IsTransparent      = new bool[Blocks.Length];
        for (int k = 0; k < Blocks.Length; k++)
        {
            var standard = Blocks[k] as IStandardCubeBlock;
            var normal   = Blocks[k] as INormalBlock;

            if (standard == null && normal == null)
            {
                Debug.LogErrorFormat("block {0} does not define GenerateTerrain", Blocks[k].GetType().Name);
            }

            StandardCubeBlocks[k] = standard;
            NormalBlocks[k]       = normal;
            IsTransparent[k]      = standard == null;
        }
    }
Exemplo n.º 24
0
    public void CalculateOutput(float production, CubeBlock workObject, Storage storage)
    {
        if (workObject == null)
        {
            return;
        }
        if (workObject.naturalFossils > 0)
        {
            float v = Random.value - GameMaster.LUCK_COEFFICIENT;
            float m = 0;
            switch (workObject.material_id)
            {
            case ResourceType.STONE_ID:
                if (metalK_abundance >= v)
                {
                    m = metalK_abundance * production * (Random.value + 1 + GameMaster.LUCK_COEFFICIENT);
                    storage.AddResource(ResourceType.metal_K_ore, m); production -= m;
                }
                if (metalM_abundance >= v)
                {
                    m = metalM_abundance * production * (Random.value + 1 + GameMaster.LUCK_COEFFICIENT);
                    storage.AddResource(ResourceType.metal_M_ore, m); production -= m;
                }
                if (metalE_abundance >= v)
                {
                    m = metalE_abundance * production * (Random.value + 1 + GameMaster.LUCK_COEFFICIENT);
                    storage.AddResource(ResourceType.metal_E_ore, m); production -= m;
                }
                if (metalN_abundance >= v)
                {
                    m = metalN_abundance * production * (Random.value + 1 + GameMaster.LUCK_COEFFICIENT);
                    storage.AddResource(ResourceType.metal_N_ore, m); production -= m;
                }
                if (metalP_abundance >= v)
                {
                    m = metalP_abundance * production * (Random.value + 1 + GameMaster.LUCK_COEFFICIENT);
                    storage.AddResource(ResourceType.metal_P_ore, m); production -= m;
                }
                if (metalS_abundance >= v)
                {
                    m = metalS_abundance * production * (Random.value + 1 + GameMaster.LUCK_COEFFICIENT);
                    storage.AddResource(ResourceType.metal_S_ore, m); production -= m;
                }
                if (mineralF_abundance >= v)
                {
                    m = mineralF_abundance * production * (Random.value + 1 + GameMaster.LUCK_COEFFICIENT);
                    storage.AddResource(ResourceType.mineral_F, m); production -= m;
                }
                if (mineralL_abundance >= v)
                {
                    m = mineralL_abundance * production * (Random.value + 1 + GameMaster.LUCK_COEFFICIENT);
                    storage.AddResource(ResourceType.mineral_L, m); production -= m;
                }
                if (production > 0)
                {
                    GameMaster.colonyController.storage.AddResource(ResourceType.Stone, production);
                }
                break;

            case ResourceType.DIRT_ID:
                if (metalK_abundance >= v)
                {
                    m = metalK_abundance / 2f * production * (Random.value + 1 + GameMaster.LUCK_COEFFICIENT);
                    GameMaster.colonyController.storage.AddResource(ResourceType.metal_K_ore, m); production -= m;
                }
                if (metalP_abundance >= v)
                {
                    m = metalP_abundance / 2f * production * (Random.value + 1 + GameMaster.LUCK_COEFFICIENT);
                    GameMaster.colonyController.storage.AddResource(ResourceType.metal_P, m); production -= m;
                }
                if (mineralL_abundance >= v)
                {
                    m = mineralL_abundance / 2f * production * (Random.value + 1 + GameMaster.LUCK_COEFFICIENT);
                    GameMaster.colonyController.storage.AddResource(ResourceType.mineral_L, m); production -= m;
                }
                if (production > 0)
                {
                    GameMaster.colonyController.storage.AddResource(ResourceType.Dirt, production);
                }
                break;

            default:
                GameMaster.colonyController.storage.AddResource(ResourceType.GetResourceTypeById(workObject.material_id), production);
                break;
            }
            workObject.naturalFossils -= production;
        }
        else           // no fossils
        {
            GameMaster.colonyController.storage.AddResource(ResourceType.GetResourceTypeById(workObject.material_id), production);
        }
    }
Exemplo n.º 25
0
    public void ChangeChosenObject(ChosenObjectType newChosenType)
    {
        if (hospitalPanel.activeSelf)
        {
            DeactivateHospitalPanel();
        }
        else
        {
            if (expeditionCorpusPanel.activeSelf)
            {
                DeactivateExpeditionCorpusPanel();
            }
            else
            {
                if (rollingShopPanel.activeSelf)
                {
                    DeactivateRollingShopPanel();
                }
            }
        }

        //отключение предыдущего observer
        if (workingObserver != null)
        {
            workingObserver.ShutOff();
            workingObserver = null;
        }
        bool disableCubeMenuButtons = true, changeFrameColor = true;

        if (newChosenType == ChosenObjectType.None)
        {
            rightPanel.SetActive(false);
            selectionFrame.gameObject.SetActive(false);
            chosenObjectType = ChosenObjectType.None;
            chosenWorksite   = null;
            chosenStructure  = null;
            chosenCube       = null;
            chosenSurface    = null;
            faceIndex        = 10;
            changeFrameColor = false;
        }
        else
        {
            chosenObjectType = newChosenType;
            rightPanel.transform.SetAsLastSibling();
            rightPanel.SetActive(true);
            disableCubeMenuButtons = true;
            selectionFrame.gameObject.SetActive(true);
            if (showMenuWindow)
            {
                MenuButton();
            }
        }

        Vector3 sframeColor = Vector3.one;

        switch (chosenObjectType)
        {
        case ChosenObjectType.Surface:
        {
            faceIndex = 10;         // вспомогательная дата для chosenCube
            selectionFrame.position   = chosenSurface.transform.position + Vector3.down * Block.QUAD_SIZE / 2f;
            selectionFrame.rotation   = Quaternion.identity;
            selectionFrame.localScale = new Vector3(SurfaceBlock.INNER_RESOLUTION, 1, SurfaceBlock.INNER_RESOLUTION);
            sframeColor = new Vector3(140f / 255f, 1, 1);

            workingObserver = chosenSurface.ShowOnGUI();
            FollowingCamera.main.SetLookPoint(chosenSurface.transform.position);
        }
        break;

        case ChosenObjectType.Cube:
        {
            selectionFrame.position = chosenCube.faces[faceIndex].transform.position;
            switch (faceIndex)
            {
            case 0: selectionFrame.transform.rotation = Quaternion.Euler(90, 0, 0); break;

            case 1: selectionFrame.transform.rotation = Quaternion.Euler(0, 0, -90); break;

            case 2: selectionFrame.transform.rotation = Quaternion.Euler(-90, 0, 0); break;

            case 3: selectionFrame.transform.rotation = Quaternion.Euler(0, 0, 90); break;

            case 4: selectionFrame.transform.rotation = Quaternion.identity; break;

            case 5: selectionFrame.transform.rotation = Quaternion.Euler(-180, 0, 0); break;
            }
            selectionFrame.localScale = new Vector3(SurfaceBlock.INNER_RESOLUTION, 1, SurfaceBlock.INNER_RESOLUTION);
            sframeColor = new Vector3(140f / 255f, 1, 0.9f);
            FollowingCamera.main.SetLookPoint(chosenCube.transform.position);

            Transform t = rightPanel.transform;
            t.GetChild(RPANEL_CUBE_DIG_BUTTON_INDEX).gameObject.SetActive(true);
            if (chosenCube.excavatingStatus != 0)
            {
                t.GetChild(RPANEL_CUBE_DIG_BUTTON_INDEX + 1).gameObject.SetActive(true);
            }
            else
            {
                t.GetChild(RPANEL_CUBE_DIG_BUTTON_INDEX + 1).gameObject.SetActive(false);
            }
            disableCubeMenuButtons = false;
        }
        break;

        case ChosenObjectType.Structure:
            faceIndex = 10;     // вспомогательная дата для chosenCube
            selectionFrame.position   = chosenStructure.transform.position;
            selectionFrame.rotation   = chosenStructure.transform.rotation;
            selectionFrame.localScale = new Vector3(chosenStructure.innerPosition.size, 1, chosenStructure.innerPosition.size);
            sframeColor     = new Vector3(1, 0, 1);
            workingObserver = chosenStructure.ShowOnGUI();
            FollowingCamera.main.SetLookPoint(chosenStructure.transform.position);
            break;

        case ChosenObjectType.Worksite:
            faceIndex = 10;     // вспомогательная дата для chosenCube
            selectionFrame.gameObject.SetActive(false);
            changeFrameColor = false;
            workingObserver  = chosenWorksite.ShowOnGUI();
            FollowingCamera.main.SetLookPoint(chosenWorksite.sign.transform.position);
            break;
        }
        if (disableCubeMenuButtons)
        {
            Transform t = rightPanel.transform;
            t.GetChild(RPANEL_CUBE_DIG_BUTTON_INDEX).gameObject.SetActive(false);
            t.GetChild(RPANEL_CUBE_DIG_BUTTON_INDEX + 1).gameObject.SetActive(false);
        }
        if (changeFrameColor)
        {
            selectionFrameMaterial.SetColor("_TintColor", Color.HSVToRGB(sframeColor.x, sframeColor.y, sframeColor.z));
            selectionFrame.gameObject.SetActive(true);
        }
    }
Exemplo n.º 26
0
    public void Raycasting()
    {
        if (GameMaster.colonyController == null || GameMaster.colonyController.hq == null)
        {
            return;
        }
        // кастует луч, проверяет, выделен ли уже этот объект, если нет - меняет режим через ChabgeChosenObject
        Vector2    mpos = Input.mousePosition;
        RaycastHit rh;

        if (Physics.Raycast(FollowingCamera.cam.ScreenPointToRay(Input.mousePosition), out rh))
        {
            GameObject collided = rh.collider.gameObject;

            switch (collided.tag)
            {
            case "Structure":
            {
                Structure s = collided.transform.parent.GetComponent <Structure>();
                if (s == null)
                {
                    ChangeChosenObject(ChosenObjectType.None);
                }
                else
                {
                    if (chosenStructure == s)
                    {
                        return;
                    }
                    else
                    {
                        chosenStructure = s;
                        chosenSurface   = s.basement;
                        chosenCube      = null;
                        chosenWorksite  = null;
                        ChangeChosenObject(ChosenObjectType.Structure);
                    }
                }
                break;
            }

            case "BlockCollider":
            {
                Block b = collided.transform.parent.GetComponent <Block>();
                if (b == null)
                {
                    b = collided.transform.parent.parent.GetComponent <Block>();                   // cave block
                }
                if (b == null)
                {
                    ChangeChosenObject(ChosenObjectType.None);
                }
                switch (b.type)
                {
                case BlockType.Cave:
                case BlockType.Surface:
                    SurfaceBlock sb = b as SurfaceBlock;
                    if (sb == chosenSurface)
                    {
                        return;
                    }
                    else
                    {
                        chosenSurface   = sb;
                        chosenStructure = null;
                        chosenCube      = null;
                        chosenWorksite  = sb.worksite;
                        ChangeChosenObject(ChosenObjectType.Surface);
                    }
                    break;

                case BlockType.Cube:
                    CubeBlock cb = b as CubeBlock;
                    if (cb == chosenCube)
                    {
                        return;
                    }
                    else
                    {
                        chosenCube      = cb;
                        chosenSurface   = null;
                        chosenStructure = null;
                        chosenWorksite  = cb.worksite;
                        faceIndex       = 10;
                        for (byte i = 0; i < 6; i++)
                        {
                            if (chosenCube.faces[i] == null)
                            {
                                continue;
                            }
                            if (chosenCube.faces[i].GetComponent <Collider>() == rh.collider)
                            {
                                faceIndex = i; break;
                            }
                        }
                        if (faceIndex < 6)
                        {
                            ChangeChosenObject(ChosenObjectType.Cube);
                        }
                        else
                        {
                            ChangeChosenObject(ChosenObjectType.None);
                        }
                    }
                    break;
                }
            }
            break;

            case "WorksiteSign":
            {
                WorksiteSign ws = collided.GetComponent <WorksiteSign>();
                if (ws != null)
                {
                    if (ws.worksite == chosenWorksite)
                    {
                        return;
                    }
                    else
                    {
                        chosenCube      = null;
                        chosenSurface   = null;
                        chosenStructure = null;
                        chosenWorksite  = ws.worksite;
                        ChangeChosenObject(ChosenObjectType.Worksite);
                    }
                }
                else
                {
                    ChangeChosenObject(ChosenObjectType.None);
                }
            }
            break;

            default:
                if (collided.transform.parent != null)
                {
                    if (collided.transform.parent.gameObject.GetInstanceID() == interceptingConstructPlaneID)
                    {
                        UISurfacePanelController.current.ConstructingPlaneTouch(rh.point);
                    }
                }
                break;
            }
        }
        else
        {
            SelectedObjectLost();
        }
    }
Exemplo n.º 27
0
        public void UpdateAfterSimulation100()
        {
            try
            {
                if (!myRadioAntenna.IsWorking)
                {
                    return;
                }

                //Showoff.doShowoff(CubeBlock, myLastSeen.Values.GetEnumerator(), myLastSeen.Count);

                float radiusSquared;
                MyObjectBuilder_RadioAntenna antBuilder = CubeBlock.GetObjectBuilderCubeBlock() as MyObjectBuilder_RadioAntenna;
                if (!antBuilder.EnableBroadcasting)
                {
                    radiusSquared = 0;
                }
                else
                {
                    radiusSquared = myRadioAntenna.Radius * myRadioAntenna.Radius;
                }

                // send antenna self to radio antennae
                LinkedList <RadioAntenna> canSeeMe = new LinkedList <RadioAntenna>();               // friend and foe alike
                foreach (RadioAntenna ant in RadioAntenna.registry)
                {
                    if (CubeBlock.canSendTo(ant.CubeBlock, false, radiusSquared, true))
                    {
                        canSeeMe.AddLast(ant);
                    }
                }

                LastSeen self = new LastSeen(CubeBlock.CubeGrid);
                foreach (RadioAntenna ant in canSeeMe)
                {
                    ant.receive(self);
                }

                // relay information to friendlies
                foreach (RadioAntenna ant in value_registry)
                {
                    if (CubeBlock.canSendTo(ant.CubeBlock, true, radiusSquared, true))
                    {
                        foreach (LastSeen seen in myLastSeen.Values)
                        {
                            ant.receive(seen);
                        }
                        foreach (Message mes in myMessages)
                        {
                            ant.receive(mes);
                        }
                    }
                }

                Receiver.sendToAttached(CubeBlock, myLastSeen);
                Receiver.sendToAttached(CubeBlock, myMessages);

                UpdateEnemyNear();
            }
            catch (Exception e)
            { myLogger.log("Exception: " + e, "UpdateAfterSimulation100()", Logger.severity.ERROR); }
        }
Exemplo n.º 28
0
	public void FaceDataZPositive(CubeBlock block, Vector3 pos, bool dropItem = false){
		float half_block_size = block.blockSize / 2.0f;
		this.AddVertex(new Vector3(pos.x - half_block_size, pos.y - half_block_size, pos.z - half_block_size));
		this.AddVertex(new Vector3(pos.x - half_block_size, pos.y + half_block_size, pos.z - half_block_size));
		this.AddVertex(new Vector3(pos.x + half_block_size, pos.y + half_block_size, pos.z - half_block_size));
		this.AddVertex(new Vector3(pos.x + half_block_size, pos.y - half_block_size, pos.z - half_block_size));

		// add normals
		Vector3 front = Vector3.forward;
		this.normals.Add (front);
		this.normals.Add (front);
		this.normals.Add (front);
		this.normals.Add (front);

		// add triangles
		this.AddQuadTriangles();

		// add textures
		BlockTile blockTile = dropItem ? block.getDropBlockTile() : block.getBlockTile();
		Vector2 _00 = blockTile.front_00;
		Vector2 _10 = blockTile.front_10;
		Vector2 _01 = blockTile.front_01;
		Vector2 _11 = blockTile.front_11;
		this.uvs.Add (_10);
		this.uvs.Add (_11);
		this.uvs.Add (_01);
		this.uvs.Add (_00);
	}
Exemplo n.º 29
0
        /// <summary>
        /// target priority
        /// missiles - not implementing due to keen
        /// suites, decoys
        /// closest terminal block
        /// meteor
        /// </summary>
        private MyEntity TargetAcquisition()
        {
            MyGridTargeting targetingSystem = Block.CubeGrid.Components.Get <MyGridTargeting>();

            if (targetingSystem == null)
            {
                return(null);
            }

            List <MyEntity> targetSet = targetingSystem.TargetRoots;

            double   likelyTargetDistanceSqrd = double.MaxValue;
            MyEntity likelyTarget             = null;

            foreach (MyEntity ent in targetSet)
            {
                if (ent.Physics == null || !ent.Physics.Enabled)
                {
                    continue;
                }

                if (IsValidCharacter(ent as IMyCharacter))
                {
                    Vector3D characterPosition = ent.PositionComp.WorldVolume.Center + (ent.WorldMatrix.Up * 0.5f);
                    double   rangeSqrd         = (CubeBlock.WorldMatrix.Translation - characterPosition).LengthSquared();
                    if (rangeSqrd < MaximumRangeSqrd && rangeSqrd < likelyTargetDistanceSqrd && // is closest
                        IsPositionInTurretArch(characterPosition) &&                            // is in arch
                        IsTargetVisible(ent, characterPosition))                                // is visible
                    {
                        likelyTarget             = ent;
                        likelyTargetDistanceSqrd = rangeSqrd;
                    }
                }

                if (likelyTarget is IMyCharacter)
                {
                    continue;
                }

                MyCubeGrid grid = ent as MyCubeGrid;
                if (grid != null)
                {
                    if (grid.GridSizeEnum == MyCubeSize.Large)
                    {
                        if (!TargetLargeShips || (grid.IsStatic && !TargetStations))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (!TargetSmallShips)
                        {
                            continue;
                        }
                    }

                    bool foundEnemyGrid = false;
                    if (grid.BigOwners.Count == 0 && TargetNeutrals)
                    {
                        foundEnemyGrid = true;
                    }

                    foreach (long owner in grid.BigOwners)
                    {
                        MyRelationsBetweenPlayerAndBlock relation = CubeBlock.GetUserRelationToOwner(owner);

                        if (relation == MyRelationsBetweenPlayerAndBlock.Enemies ||
                            TargetNeutrals && (relation == MyRelationsBetweenPlayerAndBlock.Neutral || relation == MyRelationsBetweenPlayerAndBlock.NoOwnership))
                        {
                            foundEnemyGrid = true;
                        }
                    }

                    if (!foundEnemyGrid)
                    {
                        continue;
                    }

                    foreach (MyCubeBlock block in grid.GetFatBlocks())
                    {
                        if (likelyTarget is IMyDecoy)
                        {
                            break;
                        }

                        if (likelyTarget != null && !(block is IMyDecoy))
                        {
                            continue;
                        }

                        MyRelationsBetweenPlayerAndBlock relation = block.GetUserRelationToOwner(CubeBlock.OwnerId);

                        if (relation == MyRelationsBetweenPlayerAndBlock.Enemies ||
                            TargetNeutrals && (relation == MyRelationsBetweenPlayerAndBlock.Neutral || relation == MyRelationsBetweenPlayerAndBlock.NoOwnership))
                        {
                            Vector3D blockPosition = block.WorldMatrix.Translation;
                            double   rangeSqrd     = (CubeBlock.WorldMatrix.Translation - blockPosition).LengthSquared();
                            if (rangeSqrd < MaximumRangeSqrd &&
                                (rangeSqrd < likelyTargetDistanceSqrd || (block is IMyDecoy && !(likelyTarget is IMyDecoy))) &&
                                IsPositionInTurretArch(blockPosition) &&
                                IsTargetVisible(block, blockPosition))
                            {
                                likelyTarget             = block;
                                likelyTargetDistanceSqrd = rangeSqrd;
                            }
                        }
                    }
                }

                if (likelyTarget is IMyCubeBlock)
                {
                    continue;
                }

                if (ent is MyMeteor)
                {
                    if (!TargetMeteors)
                    {
                        continue;
                    }

                    double rangeSqrd = (CubeBlock.WorldMatrix.Translation - ent.WorldMatrix.Translation).LengthSquared();
                    if (rangeSqrd < MaximumRangeSqrd && rangeSqrd < likelyTargetDistanceSqrd)
                    {
                        if (IsTargetVisible(ent, ent.WorldMatrix.Translation))
                        {
                            likelyTarget             = ent;
                            likelyTargetDistanceSqrd = rangeSqrd;
                        }
                    }
                }
            }

            return(likelyTarget);
        }
Exemplo n.º 30
0
        private InitialTargetStatus GetInitialTarget()
        {
            if (loadedAmmo == null || loadedAmmo.MissileDefinition == null)
            {
                Log.DebugLog("no ammo");
                return(InitialTargetStatus.NotReady);
            }

            if (m_weaponTarget.Options.TargetGolis.IsValid())
            {
                Log.TraceLog("golis: " + m_weaponTarget.Options.TargetGolis);
                m_weaponTarget.SetTarget(new GolisTarget(CubeBlock, m_weaponTarget.Options.TargetGolis));
                return(InitialTargetStatus.Golis);
            }

            if (m_weaponTarget.CurrentControl != WeaponTargeting.Control.Off && !(m_weaponTarget.CurrentTarget is NoTarget))
            {
                Log.TraceLog("from active weapon, control: " + m_weaponTarget.CurrentControl + ", target: " + m_weaponTarget.CurrentTarget);
                return(InitialTargetStatus.FromWeapon);
            }
            else
            {
                Log.TraceLog("clearing weapon target");
                m_weaponTarget.SetTarget(NoTarget.Instance);
            }

            RelayStorage storage = m_relayPart.GetStorage();

            if (storage == null)
            {
                Log.TraceLog("Failed to get storage for launcher");
                return(InitialTargetStatus.NoStorage);
            }
            else
            {
                ITerminalProperty <float> rangeProperty = CubeBlock.GetProperty("Range") as ITerminalProperty <float>;
                if (rangeProperty == null)
                {
                    Logger.AlwaysLog("rangeProperty == null", Logger.severity.FATAL);
                    return(InitialTargetStatus.NotReady);
                }
                float range = rangeProperty.GetValue(CubeBlock);
                if (range < 1f)
                {
                    range = loadedAmmo.MissileDefinition.MaxTrajectory;
                }
                m_weaponTarget.GetLastSeenTarget(storage, range);
                if (!(m_weaponTarget.CurrentTarget is NoTarget))
                {
                    Log.TraceLog("LastSeen: " + m_weaponTarget.CurrentTarget.Entity.nameWithId());
                    return(InitialTargetStatus.FromWeapon);
                }
                else if (m_weaponTarget.Options.TargetEntityId != 0)
                {
                    return(InitialTargetStatus.NotFoundId);
                }
                else
                {
                    return(InitialTargetStatus.NotFoundAny);
                }
            }
        }
Exemplo n.º 31
0
    public void Click()
    {
        if (FollowingCamera.touchscreen)
        {
            if (Input.touchCount != 1)
            {
                return;
            }
            else
            {
                Touch t = Input.GetTouch(0);
                if (t.phase != TouchPhase.Ended | t.deltaPosition != Vector2.zero)
                {
                    return;
                }
            }
        }
        RaycastHit rh;

        if (Physics.Raycast(FollowingCamera.cam.ScreenPointToRay(Input.mousePosition), out rh))
        {
            Transform collided = rh.transform;
            switch (currentAction)
            {
            case ClickAction.CreateBlock:
            {
                Block b = collided.parent.gameObject.GetComponent <Block>();
                if (b == null)
                {
                    b = collided.parent.parent.gameObject.GetComponent <Block>();
                }
                if (b != null)
                {
                    Vector3Int cpos = new Vector3Int(b.pos.x, b.pos.y, b.pos.z);
                    if (b.type == BlockType.Cube)
                    {
                        float coordsDelta = rh.point.z - b.transform.position.z;
                        if (Mathf.Abs(coordsDelta) >= Block.QUAD_SIZE / 2f)
                        {
                            if (coordsDelta > 0)
                            {
                                cpos.z += 1;
                                if (cpos.z >= Chunk.CHUNK_SIZE)
                                {
                                    return;
                                }
                            }
                            else
                            {
                                cpos.z -= 1;
                                if (cpos.z < 0)
                                {
                                    return;
                                }
                            }
                        }
                        coordsDelta = rh.point.x - b.transform.position.x;
                        if (Mathf.Abs(coordsDelta) >= Block.QUAD_SIZE / 2f)
                        {
                            if (coordsDelta > 0)
                            {
                                cpos.x += 1;
                                if (cpos.x >= Chunk.CHUNK_SIZE)
                                {
                                    return;
                                }
                            }
                            else
                            {
                                cpos.x -= 1;
                                if (cpos.x < 0)
                                {
                                    return;
                                }
                            }
                        }
                        coordsDelta = rh.point.y - b.transform.position.y;
                        if (Mathf.Abs(coordsDelta) >= Block.QUAD_SIZE / 2f)
                        {
                            if (coordsDelta > 0)
                            {
                                cpos.y += 1;
                                if (cpos.y >= Chunk.CHUNK_SIZE)
                                {
                                    return;
                                }
                            }
                            else
                            {
                                cpos.y -= 1;
                                if (cpos.y < 0)
                                {
                                    return;
                                }
                            }
                        }
                        GameMaster.mainChunk.AddBlock(new ChunkPos(cpos.x, cpos.y, cpos.z), BlockType.Cube, chosenMaterialId, true);
                    }
                    else         // surface block
                    {
                        GameMaster.mainChunk.ReplaceBlock(b.pos, BlockType.Cube, chosenMaterialId, true);
                    }
                }
                break;
            }

            case ClickAction.DeleteBlock:
            {
                Block b = collided.parent.gameObject.GetComponent <Block>();
                if (b == null)
                {
                    b = collided.parent.parent.gameObject.GetComponent <Block>();
                }
                if (b != null)
                {
                    Vector3Int cpos = new Vector3Int(b.pos.x, b.pos.y, b.pos.z);
                    if (b.type == BlockType.Surface | b.type == BlockType.Cave)
                    {
                        GameMaster.mainChunk.DeleteBlock(new ChunkPos(cpos.x, cpos.y - 1, cpos.z));
                    }
                    GameMaster.mainChunk.DeleteBlock(new ChunkPos(cpos.x, cpos.y, cpos.z));
                }
                break;
            }

            case ClickAction.AddGrassland:
            {
                Block b = collided.parent.gameObject.GetComponent <Block>();
                if (b == null)
                {
                    b = collided.parent.parent.gameObject.GetComponent <Block>();
                }
                if (b != null)
                {
                    SurfaceBlock sb = b as SurfaceBlock;
                    if (sb == null & b.pos.y < Chunk.CHUNK_SIZE - 1)
                    {
                        sb = b.myChunk.AddBlock(new ChunkPos(b.pos.x, b.pos.y + 1, b.pos.z), BlockType.Surface, ResourceType.DIRT_ID, true) as SurfaceBlock;
                    }
                    if (sb != null && sb.grassland == null)
                    {
                        Grassland.CreateOn(sb);
                        sb.grassland.AddLifepowerAndCalculate(LIFEPOWER_PORTION);
                    }
                }
                break;
            }

            case ClickAction.DeleteGrassland:
            {
                Block b = collided.parent.gameObject.GetComponent <Block>();
                if (b == null)
                {
                    b = collided.parent.parent.gameObject.GetComponent <Block>();
                }
                if (b != null)
                {
                    SurfaceBlock sb = b as SurfaceBlock;
                    if (sb != null && sb.grassland != null)
                    {
                        sb.grassland.Annihilation(true);
                    }
                }
                break;
            }

            case ClickAction.MakeSurface:
            {
                Block b = collided.parent.gameObject.GetComponent <Block>();
                if (b == null)
                {
                    b = collided.parent.parent.gameObject.GetComponent <Block>();
                }
                if (b != null)
                {
                    if (b.type != BlockType.Surface)
                    {
                        if (b.pos.y < Chunk.CHUNK_SIZE - 1)
                        {
                            b.myChunk.AddBlock(new ChunkPos(b.pos.x, b.pos.y + 1, b.pos.z), BlockType.Surface, chosenMaterialId, true);
                        }
                    }
                    else
                    {
                        b.ReplaceMaterial(chosenMaterialId);
                    }
                }
                break;
            }

            case ClickAction.MakeCave:
            {
                CubeBlock cb = collided.parent.gameObject.GetComponent <CubeBlock>();
                if (cb != null)
                {
                    float x = cb.myChunk.CalculateSupportPoints(cb.pos.x, cb.pos.y, cb.pos.z);
                    if (x > 0.5f)
                    {
                        cb.myChunk.ReplaceBlock(cb.pos, BlockType.Cave, cb.material_id, true);
                    }
                }
                break;
            }

            case ClickAction.AddLifepower:
            {
                Block b = collided.parent.gameObject.GetComponent <Block>();
                if (b == null)
                {
                    b = collided.parent.parent.gameObject.GetComponent <Block>();
                }
                if (b != null)
                {
                    SurfaceBlock sb = b as SurfaceBlock;
                    if (sb != null && sb.grassland != null)
                    {
                        sb.grassland.AddLifepowerAndCalculate(LIFEPOWER_PORTION);
                    }
                }
                break;
            }

            case ClickAction.TakeLifepower:
            {
                Block b = collided.parent.gameObject.GetComponent <Block>();
                if (b == null)
                {
                    b = collided.parent.parent.gameObject.GetComponent <Block>();
                }
                if (b != null)
                {
                    SurfaceBlock sb = b as SurfaceBlock;
                    if (sb != null && sb.grassland != null)
                    {
                        sb.grassland.TakeLifepowerAndCalculate(LIFEPOWER_PORTION);
                    }
                }
                break;
            }
            }
        }
    }