private void ShowCreationQueue() 
	{
		DestroyUnitCreationButtons();
		
		if (currentResource != null || currentBarrack != null ) {

			UnitTypes[] creationUnitQueue = null;

			if (currentResource != null) {
				creationUnitQueue = new UnitTypes[currentResource.getNumberElements()];
				creationUnitQueue = currentResource.getCreationQueue().ToArray();
			} else if (currentBarrack != null) {
				creationUnitQueue = new UnitTypes[currentBarrack.getNumberElements()];
				creationUnitQueue = currentBarrack.getCreationQueue().ToArray();
			}

			for (int i = 0; i < creationUnitQueue.Length; i++) {
				UnitTypes type = creationUnitQueue[i];
				Vector2 buttonCenter = new Vector2();
				buttonCenter.x = creationQueueInitialPoint.x + unitCreationPanel.x / 2f + (creationQueueButtonSize.x * i) + creationQueueButtonSize.x / 2f;
				buttonCenter.y = creationQueueInitialPoint.y - unitCreationPanel.y;
				GameObject button = CreateCreationUnitButton(buttonCenter, type, i);
				creationQueueButtons.Add(button);
			}
		}
	}
Beispiel #2
0
        public UnitBase(GameServer _server, Player player)
            : base(_server, player)
        {
            EntityType = Entity.EntityType.Unit;
            UnitType = UnitTypes.Default;

            EntityToAttack = null;

            Speed = .01f;
            Range = 50;
            AttackDelay = 100;
            AttackRechargeTime = 1000;
            SupplyUsage = 1;
            RangedUnit = false;

            StandardAttackDamage = 1;
            StandardAttackElement = Entity.DamageElement.Normal;

            State = UnitState.Agro;
            allowMovement = false;
            _moveXCompleted = false;
            _moveYCompleted = false;

            attackTimer = new Stopwatch();
            attackTimer.Reset();
            attackTimer.Stop();

            rechargeTimer = new Stopwatch();
            rechargeTimer.Restart();

            updatedMovePositionTimer = new Stopwatch();
            updatedMovePositionTimer.Start();
        }
	/**
	 * The constructor function for the units select canvas
	 */
	public void construct () {
		// Initialize the script
		unitTypesScript = UnitTypes.S;
		Unit unitScript = null;

		// Get the initial allowed population
		allowedPopulation = gameController.populationSettings.populationAtStart;

		// Set the initial population on the text
		pointsText = pointsObject.GetComponent<Text> ();
		pointsText.text = string.Format ("{0}", allowedPopulation);

		// Set the initial unit count on the text
		unitsText = unitsObject.GetComponent<Text> ();
		unitsText.text = string.Format ("{0}", queueSize);

		// Loop through all unit types
		foreach (KeyValuePair<string, GameObject> type in unitTypesScript.types) {
			unitScript = type.Value.GetComponent<Unit> ();

			// Limit the new panels to only the units that can be created
			if (unitScript.generalInformation.canCreate) {
				// Create the new panel
				GameObject newPanel = Instantiate (unitSelectPanelPrefab, Vector3.zero, Quaternion.identity) as GameObject;
				newPanel.transform.SetParent (unitsSelectContent.transform);
				newPanel.transform.localScale = new Vector3 (1, 1, 1);
				panels.Add (newPanel);

				// Call the contruction function for the new panel
				UnitPanelController tmpScript = newPanel.GetComponent<UnitPanelController> ();
				tmpScript.construct (playerController.factionName, type.Key);
			}
		} 
	}
 public void SpawnUnit(Vector2 position, int faction, UnitTypes type)
 {
     Unit u = UnitFactory.SpawnUnit(this, type, position, faction, world);
     u.Enable();
     attackables.Add(u);
     controllers.Add(new UnitController(u, this));
 }
Beispiel #5
0
        public UnitBase()
        {
            UnitType = UnitTypes.Default;

            drawPosition = new Vector2f();
            _moveXCompleted = false;
            _moveYCompleted = false;

            EntityToAttack = null;
            allowMovement = false;

            Speed = 0;
            State = UnitState.Agro;
            Range = 1000;
            AttackDelay = 2000;
            attackTimer = new Stopwatch();
            attackTimer.Restart();

            StandardAttackDamage = 1;
            StandardAttackElement = Entity.DamageElement.Normal;

            Sprites = new Dictionary<AnimationTypes, AnimatedSprite>();

            const byte AnimationTypeCount = 8;
            for (int i = 0; i < AnimationTypeCount; i++)
            {
                Sprites.Add((AnimationTypes)i, new AnimatedSprite(100));
            }

            CurrentAnimation = AnimationTypes.Idle;
            SpriteFolder = "";
        }
Beispiel #6
0
	public Dictionary<string, GameObject> types = null; //!< The associative array of unit types

	/**
	 * Called when the script is loaded, before the game starts
	 */
	void Awake() {
		S = this;

		types = new Dictionary<string, GameObject> ();
		foreach (GameObject type in unitTypes) {
			types.Add (type.name, type);
		}
	}
 public static Unit SpawnUnit(GameplayManager gm, UnitTypes type, Vector2 position, int faction, World world) {
     switch (type)
     {
         case UnitTypes.Ranged:
             return CreateRangedUnit(gm, position, faction, world);
         case UnitTypes.Melee:
             return CreateMeleeUnit(gm, position, faction, world);
         default:
             return CreateRangedUnit(gm, position, faction, world);
     }
 }
	private GameObject CreateCreationUnitButton(Vector2 center, UnitTypes type, int position) 
	{
		GameObject canvasObject = new GameObject("UnitCreationButtonCanvas");
		Canvas canvas = canvasObject.AddComponent<Canvas>();
		canvas.tag = "UnitCreationButton";
		canvasObject.AddComponent<GraphicRaycaster>();
		canvas.renderMode = RenderMode.ScreenSpaceOverlay;

		GameObject buttonObject = new GameObject("CreationUnitImage");
		Image image = buttonObject.AddComponent<Image>();
		image.transform.parent = canvas.transform;
		image.rectTransform.sizeDelta = creationQueueButtonSize * 0.9f;
		image.rectTransform.position = center;
		Sprite buttonImage = GetImageForType(type);
		if (buttonImage != null)
		{
			image.sprite = buttonImage;
		}
		else
		{
			image.color = new Color(1f, 1f, 1f, 1f);
		}

		Button button = buttonObject.AddComponent<Button>();
		button.targetGraphic = image;
		button.onClick.AddListener(() =>
		{
			if (position == 0) {
				if (currentResource != null) {
					currentResource.cancelUnitQueue();
				} else if (currentBarrack != null) {
					currentBarrack.cancelUnitQueue();
				}
				
				ShowCreationQueue();
			}
		});


		GameObject shadowObject = new GameObject("UnitCreationShadow");
		Image shadow = shadowObject.AddComponent<Image>();
		shadow.transform.parent = canvas.transform;
		shadow.rectTransform.sizeDelta = creationQueueButtonSize * 0.9f;
		shadow.rectTransform.position = center;
		shadow.type = Image.Type.Filled;
		shadow.fillMethod = Image.FillMethod.Radial360;
		shadow.transform.Rotate(180,0,0);
		Texture2D shadowTexture = (Texture2D)Resources.Load ("creationUnitShadow");
		if (shadowTexture) {
			shadow.sprite = Sprite.Create (shadowTexture, new Rect (0, 0, shadowTexture.width, shadowTexture.height), new Vector2 (0.5f, 0.5f));
		}
		return canvasObject;
	}
Beispiel #9
0
 public IUnit CreateUnit(Vector3 position, UnitTypes type, UnitData data, bool isDefender) {
     IUnit unit;
     if (type == UnitTypes.HERO) {
         unit = new HeroModel();
     } else {
         unit = new UnitModel();
     }
     InjectionBinder.injector.Inject(unit);
     unit.Spawn(position, data, type, isDefender);
     unit.InitializeStates();
     unit.StartAct();
     return unit;
 }
	/**
	 * Runs at load time
	 */
	void Start () {
		gameController = GameController.S;
		mapsController = MapsController.S;
		movementController = MovementController.S;
		playerController = PlayerController.S;
		remoteCamera = RemoteCamera.S;

		unitTypesCollection = UnitTypes.S;

		playerUnitCounts = new Dictionary<string, int>[4];

		// Copy the settings from the parent unit types to the faction units
		propagateOptions ();
	}
        public void From_XML(System.Xml.Linq.XElement xml)
        {
            Reset();
            var element = xml.Element("memory");
            if (element == null)
            {
                if (xml.Name == "memory") element = xml;
                else element = null;
            }
            if (element != null)
            {
                Int64 i = 0;
                Int64.TryParse(element.Value, out i);
                if (i < 128) i = 128;
                var attr = element.Attribute("unit");
                if (attr != null)
                {
                    var b = UnitTypes.MiB;
                    Enum.TryParse(attr.Value, true, out b);
                    memory_unit = b;
                }
                else memory_unit = UnitTypes.KiB;//default
                memory = i;
            }
            element = xml.Element("currentMemory");
            if (element != null)
            {
                Int64 i = 0;
                Int64.TryParse(element.Value, out i);
                if (i < 128) i = 128;
                var attr = element.Attribute("unit");
                if (attr != null)
                {
                    var b = UnitTypes.MiB;
                    Enum.TryParse(attr.Value, true, out b);
                    currentMemory_unit = b;
                }
                else memory_unit = UnitTypes.KiB;//default
                currentMemory = i;

            }
            else
            {// if not present, uses same as memory
                currentMemory = memory;
                currentMemory_unit = memory_unit;
            }
        }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="u"></param>
    /// <param name="type"></param>
    public void CreateUnit(Unit u, UnitTypes type)
    {
        if (Board.Instance.SelectedBase.QueueUnit == null) {

        /* Make the unit, but disable it until the spawntime! */
        Unit unit = Board.Instance.MakeUnit (0, 0, type, Board.Instance.SelectedBase.RaceType);
        unit.gameObject.SetActive (false);
        unit.InQueue = true;

        //Board.Instance.SelectedBase.MovementRange = 3;

        BaseCreatePanel.Instance.ToggleCreatingView(unit);
        Board.Instance.SelectedBase.QueueUnit = unit;
        Board.Instance.SelectedBase.TurnOffRangeIndicator();
        Board.Instance.SelectedBase.TurnOver = true;

        }

        GameController.Instance.IsDone ();
    }
Beispiel #13
0
        public Unit(string name, UnitTypes unitType, Faction side, IMovementBehavior movementBehavior, IAttackBehavior attackBehavior, ITargetBehavior targetBehavior)
        {
            _name = name;
            _experience = 50;
            _resources = 50;

            _side = side;

            _unitType = unitType;

            _movementBehavior = movementBehavior;
            _movementBehavior.Owner = this;

            _attackBehavior = attackBehavior;
            _attackBehavior.Owner = this;

            _targetBehavior = targetBehavior;
            _targetBehavior.Owner = this;

            _unitView = new UnitView(this, unitType);
        }
Beispiel #14
0
        //Constructors
        public Unit(UnitTypes type, RaceTypes race,
            int initialHealthLevel, int initialAttackLevel,
            int level, bool isAlive, Point currentPosition, bool isSelected)
        {
            this.Type = type;
            this.Race = race;

            //Current health level, initial health level and max health level are the same int the initialization
            this.HealthLevel = initialHealthLevel;
            this.InitialHealthLevel = initialHealthLevel;
            this.MaxHealthLevel = initialHealthLevel;
            
            //Current attack level, initial attack level and max attack level are the same int the initialization
            this.AttackLevel = initialAttackLevel;
            this.InitialAttackLevel = initialAttackLevel;
            this.MaxAttackLevel = initialAttackLevel;
            this.CounterAttackLevel = initialAttackLevel / 2;

            this.Level = level;
            this.IsAlive = isAlive;
            this.CurrentPosition = currentPosition;
            this.IsSelected = isSelected;
        }
 public ThermodynamicParameter(UnitTypes type, double value, UnitSystems unitsys)
     : this(0, type, 0, unitsys)
 {
 }
 private void Reset()
 {
     memory = currentMemory=128;
     currentMemory_unit = memory_unit = UnitTypes.MiB;
 }
 protected override void OnValueChanged(object sender, EventArgs e)
 {
     UnitTypes.MoveCurrentTo(GetValue().GridUnitType);
     NotifyPropertyChanged("Units");
     base.OnValueChanged(sender, e);
 }
    void showUnitSummary()
    {
        statScroll = GUILayout.BeginScrollView(statScroll, false, false);

        GUILayout.BeginHorizontal();
        unitDataList.unitList[toggledIndex].uName = EditorGUILayout.TextField("Unit Name", unitDataList.unitList[toggledIndex].uName);
        unitDataList.unitList[toggledIndex].uType = (UnitTypes)EditorGUILayout.EnumPopup("Unit Type", unitDataList.unitList[toggledIndex].uType);
        if (unitDataList.unitList[toggledIndex].uType != filterType)
            filterType = unitDataList.unitList[toggledIndex].uType;
        GUILayout.EndHorizontal();

        GUILayout.Space(5);

        unitDataList.unitList[toggledIndex].isHero = EditorGUILayout.Toggle("Hero", unitDataList.unitList[toggledIndex].isHero, GUILayout.ExpandWidth(false));
        GUILayout.Space(10);

        EditorGUILayout.LabelField("Stats");
        unitDataList.unitList[toggledIndex].maxHp = EditorGUILayout.IntField("HP", unitDataList.unitList[toggledIndex].maxHp, GUILayout.ExpandWidth(false));
        unitDataList.unitList[toggledIndex].maxSpeed = EditorGUILayout.Slider("Speed", unitDataList.unitList[toggledIndex].maxSpeed, 5, 20, GUILayout.ExpandWidth(false));

        if (unitDataList.unitList[toggledIndex].isHero)
        {
            unitDataList.unitList[toggledIndex].impulse = EditorGUILayout.IntSlider("Impulse", unitDataList.unitList[toggledIndex].impulse, 3, 6, GUILayout.ExpandWidth(false));
            unitDataList.unitList[toggledIndex].memory = EditorGUILayout.IntSlider("Memory", unitDataList.unitList[toggledIndex].memory, 0, 5, GUILayout.ExpandWidth(false));
        }

        /*****************************************/
        //Atk/Def Factors
        /*****************************************/
        EditorGUILayout.Space();

        
        GUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Attack Factors");
        EditorGUILayout.LabelField("Defence Factors");
        GUILayout.EndHorizontal();
        for (int i = 0; i < (int)DamageType.TOTAL; i++)
        {
            GUILayout.BeginHorizontal();
            unitDataList.unitList[toggledIndex].typeAtk[i] = EditorGUILayout.Slider(Enum.GetName(typeof(DamageType), i), unitDataList.unitList[toggledIndex].typeAtk[i], 0.5f, 2.0f);
            unitDataList.unitList[toggledIndex].typeDef[i] = EditorGUILayout.Slider(Enum.GetName(typeof(DamageType), i), unitDataList.unitList[toggledIndex].typeDef[i], 0.5f, 2.0f);
            GUILayout.EndHorizontal();
        }
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("Reset Attack Factors"))
            for (int i = 0; i < (int)DamageType.TOTAL; i++)
            {
                unitDataList.unitList[toggledIndex].typeAtk[i] = 1.0f;
            }
        if (GUILayout.Button("Reset Defence Factors"))
            for (int i = 0; i < (int)DamageType.TOTAL; i++)
            {
                unitDataList.unitList[toggledIndex].typeDef[i] = 1.0f;
            }
        GUILayout.EndHorizontal();

        

        GUILayout.EndScrollView();
    }
 public bool DoTrainUnit(UnitTypes unitType) {
     return this.bwapiObject.train(new SWIG.BWAPI.UnitType((int)unitType));
 }
Beispiel #20
0
 /// <summary>
 /// Get image url for a unit
 /// </summary>
 public string GetUnitImageUrl(UnitTypes type)
 {
     return string.Format(UnitGraphicsUrlFormat, type.ToString().ToLowerInvariant());
 }
Beispiel #21
0
        /// <summary>
        /// Create unit of specific type at specific location.
        /// All other parameters (hitpoints, etc.) are set from UnitManager.
        /// </summary>
        /// <param name="setType">Set type</param>
        /// <param name="setPosition">Set position</param>
        /// <param name="setMovementPattern">Movement pattern</param>
        public Unit(UnitTypes setType, Vector2 setPosition,
			MovementPattern setMovementPattern)
        {
            unitType =
                setType;
                //(Unit.UnitTypes)RandomHelper.GetRandomInt(5);
            position = setPosition;
            movementPattern = setMovementPattern;
            // Don't allow swing left/right for asteroid
            if (unitType == UnitTypes.Asteroid)
                movementPattern = MovementPattern.StraightDown;

            // Recalculate our unit values and reset hitpoints to 100%.
            maxHitpoints = hitpoints = DefaultUnitHitpoints[(int)unitType];
            cooldownTime = DefaultCooldownTime[(int)unitType];
            damage = DefaultUnitDamage[(int)unitType];
            explosionDamage = DefaultExplosionDamage[(int)unitType];
            maxSpeed = DefaultMaxSpeed[(int)unitType];
            shootTime = 0;
            lifeTimeMs = 0;
        }
Beispiel #22
0
 /// <summary>
 /// Перевести величину в другой тип измерения.
 /// </summary>
 /// <param name="destinationType">Тип измерения, в который необходимо перевести.</param>
 /// <returns>Сконвертированная величина.</returns>
 public Unit Convert(UnitTypes destinationType)
 {
     return(Convert(destinationType, GetTypeValue));
 }
Beispiel #23
0
 /// <summary>
 /// Создать величину типа <see cref="UnitTypes.Absolute"/> или <see cref="UnitTypes.Percent"/>.
 /// </summary>
 /// <param name="value">Значение.</param>
 /// <param name="type">Единица измерения.</param>
 public Unit(decimal value, UnitTypes type)
     : this(value, type, null)
 {
 }
Beispiel #24
0
        public override bool DetermineAction(Agent agent, Point2D target)
        {
            if (agent.Unit.UnitType != UnitTypes.INFESTOR)
            {
                return(false);
            }

            if (Tyr.Bot.Frame != CleanFungalTargetsFrame)
            {
                CleanFungalTargetsFrame = Tyr.Bot.Frame;

                List <ulong> clearTags = new List <ulong>();
                foreach (FungalTarget fungal in FungalTargets.Values)
                {
                    if (Tyr.Bot.Frame - fungal.Frame >= 22.4 * 3)
                    {
                        clearTags.Add(fungal.InfestorTag);
                    }
                }

                foreach (ulong tag in clearTags)
                {
                    FungalTargets.Remove(tag);
                }
            }


            if (NeuralFrame.ContainsKey(agent.Unit.Tag) && Tyr.Bot.Frame - NeuralFrame[agent.Unit.Tag] < 22)
            {
                return(true);
            }

            if (Fungal(agent))
            {
                return(true);
            }

            if (NeuralParasite(agent))
            {
                return(true);
            }

            Unit  closestEnemy = null;
            float distance     = agent.Unit.Energy < 70 ? 12 * 12 : 9 * 9;

            foreach (Unit unit in Tyr.Bot.Enemies())
            {
                if (!UnitTypes.CanAttackGround(unit.UnitType))
                {
                    continue;
                }
                float newDist = agent.DistanceSq(unit);
                if (newDist >= distance)
                {
                    continue;
                }

                distance     = newDist;
                closestEnemy = unit;
            }

            if (closestEnemy == null)
            {
                agent.Order(Abilities.MOVE, target);
                return(true);
            }

            agent.Order(Abilities.MOVE, agent.From(closestEnemy, 4));
            return(true);
        }
Beispiel #25
0
 // Sets unitType
 public void SetUnit(UnitTypes value)
 {
     unit = value;
 }
Beispiel #26
0
 public void SetUnitType(UnitTypes type)
 {
     LocalType         = type;
     Stats.MaxStrength = (int)type;
     SetStrength(Stats.CurStrength);
 }
Beispiel #27
0
 /// <summary>
 /// Cast the value to another type.
 /// </summary>
 /// <param name="unit">Source unit.</param>
 /// <param name="destinationType">Destination value type.</param>
 /// <param name="security">Information about the instrument. Required when using <see cref="UnitTypes.Point"/> и <see cref="UnitTypes.Step"/>.</param>
 /// <returns>Converted value.</returns>
 public static Unit Convert(this Unit unit, UnitTypes destinationType, Security security)
 {
     return(unit.Convert(destinationType, type => GetTypeValue(security, type)));
 }
Beispiel #28
0
            public Unit(double value, UnitTypes type)
            {
                this._value = value;

                this._type = type;
            }
Beispiel #29
0
 public BulletTypes GetBulletType(UnitTypes uniType) {
     return bullets[uniType];
 }
Beispiel #30
0
        public virtual int MoveAllJoint(MovementsTypes nMovementType, UnitTypes nUnit, SpeedTypes nSpeedUsed, WaitTypes nWaitType,
                                        double dbJ1Value, double dbJ2Value, double dbJ3Value, double dbJ4Value, double dbJ5Value, double dbJ6Value, double dbAcc, double dbDec, double dbSpeed)
        {
            int nRetResult = 0;

            lock (thisLock)
            {
                bool bRetSend = false;

                //先記錄目前各關節位置
                double dbJ1 = 0, dbJ2 = 0, dbJ3 = 0, dbJ4 = 0, dbJ5 = 0, dbJ6 = 0;

                //1.單位選擇
                switch (nUnit)
                {
                case UnitTypes.Degree:
                    dbJ1 = dbJ1Value * 3.1415926 / 180.0;;
                    dbJ2 = dbJ2Value * 3.1415926 / 180.0;;
                    dbJ3 = dbJ3Value * 3.1415926 / 180.0;;
                    dbJ4 = dbJ4Value * 3.1415926 / 180.0;;
                    dbJ5 = dbJ5Value * 3.1415926 / 180.0;;
                    dbJ6 = dbJ6Value * 3.1415926 / 180.0;;
                    break;

                case UnitTypes.Radian:
                    dbJ1 = dbJ1Value;
                    dbJ2 = dbJ2Value;
                    dbJ3 = dbJ3Value;
                    dbJ4 = dbJ4Value;
                    dbJ5 = dbJ5Value;
                    dbJ6 = dbJ6Value;
                    break;
                }

                //2.移動量模式選擇
                switch (nMovementType)
                {
                case MovementsTypes.Abs:
                    break;

                case MovementsTypes.Rel:
                    dbJ1 = URClient.m_jointRadianInfo.dbBasePosRadian + dbJ1;
                    dbJ2 = URClient.m_jointRadianInfo.dbShoulderPosRadian + dbJ2;
                    dbJ3 = URClient.m_jointRadianInfo.dbElbowPosRadian + dbJ3;
                    dbJ4 = URClient.m_jointRadianInfo.dbWrist1PosRadian + dbJ4;
                    dbJ5 = URClient.m_jointRadianInfo.dbWrist2PosRadian + dbJ5;
                    dbJ6 = URClient.m_jointRadianInfo.dbWrist3PosRadian + dbJ6;
                    break;
                }

                //4.速度型態選擇
                switch (nSpeedUsed)
                {
                case SpeedTypes.Use:
                    string strCmd1 = string.Format("(25,{0},{1},{2},{3},{4},{5},{6},{7},{8},{9})",
                                                   dbJ1, dbJ2, dbJ3, dbJ4, dbJ5, dbJ6, dbAcc, dbSpeed, 0, 0);
                    bRetSend = URServer.SendData(strCmd1);

                    break;

                case SpeedTypes.NoUse:
                    string strCmd2 = string.Format("(20,{0},{1},{2},{3},{4},{5})",
                                                   dbJ1, dbJ2, dbJ3, dbJ4, dbJ5, dbJ6);
                    bRetSend = URServer.SendData(strCmd2);
                    break;
                }

                if (bRetSend == true)
                {
                    //5.等待型態選擇
                    if (nWaitType == WaitTypes.Wait)
                    {
                        byte[] byteRecv;
                        byteRecv = new byte[32];

                        while (true)
                        {
                            Thread.Sleep(30);

                            int nLen = URServer.Receive(byteRecv);
                            if (nLen > 0)    // 讀取到資料
                            {
                                string result      = System.Text.Encoding.UTF8.GetString(byteRecv);
                                int    nRetCompare = string.Compare(result, "MoveJ Done");
                                if (nRetCompare == 0)
                                {
                                    nRetResult = 1;
                                }
                                else
                                {
                                    nRetResult = 0;
                                }

                                break;
                            }
                            else    //沒有讀取到資料
                            {
                                nRetResult = 0;
                                //if (nLen == SOCKET_ERROR)
                                //{
                                //   int nErr = WSAGetLastError();
                                //   if (nErr != WSAEWOULDBLOCK)
                                //   {
                                //       bRet = FALSE;
                                //       break;
                                //   }
                                // }

                                break;
                            }
                        }
                    }
                    else
                    {
                        nRetResult = 1;
                    }
                }
                else
                {
                    nRetResult = 0;
                }
            }

            return(nRetResult);
        }
Beispiel #31
0
		private static decimal? GetTypeValue(Security security, UnitTypes type)
		{
			switch (type)
			{
				case UnitTypes.Point:
					if (security == null)
						throw new ArgumentNullException(nameof(security));

					return security.StepPrice;
				case UnitTypes.Step:
					if (security == null)
						throw new ArgumentNullException(nameof(security));

					return security.PriceStep;
				default:
					throw new ArgumentOutOfRangeException(nameof(type), type, LocalizedStrings.Str1291);
			}
		}
Beispiel #32
0
 public void ReduceRegisterLessUnits(UnitTypes UT)
 {
     ReduceRegisterLessUnits(UT, 1);
 }
Beispiel #33
0
 public Unit To(UnitTypes unitType)
 {
     return(new Unit((this.Value * this.GetPixelPer(this.Type)) / this.GetPixelPer(unitType), unitType));
 }
Beispiel #34
0
        public override bool DetermineAction(Agent agent, Point2D target)
        {
            if (agent.Unit.UnitType != UnitTypes.REAPER)
            {
                return(false);
            }

            if (agent.Unit.Health <= 15)
            {
                RegeneratingReapers.Add(agent.Unit.Tag);
            }

            if (agent.Unit.Health >= agent.Unit.HealthMax)
            {
                RegeneratingReapers.Remove(agent.Unit.Tag);
            }

            if (RegeneratingReapers.Contains(agent.Unit.Tag))
            {
                agent.Order(Abilities.MOVE, SC2Util.To2D(Bot.Main.MapAnalyzer.StartLocation));
                return(true);
            }
            foreach (Unit unit in Bot.Main.Enemies())
            {
                if (unit.UnitType != UnitTypes.BUNKER &&
                    unit.UnitType != UnitTypes.MARAUDER &&
                    unit.UnitType != UnitTypes.QUEEN &&
                    unit.UnitType != UnitTypes.SPINE_CRAWLER &&
                    unit.UnitType != UnitTypes.ZERGLING &&
                    unit.UnitType != UnitTypes.PHOTON_CANNON &&
                    unit.UnitType != UnitTypes.STALKER &&
                    unit.UnitType != UnitTypes.ZEALOT)
                {
                    continue;
                }
                int dist;
                if (unit.UnitType == UnitTypes.BUNKER || unit.UnitType == UnitTypes.SPINE_CRAWLER || unit.UnitType == UnitTypes.PHOTON_CANNON)
                {
                    dist = 12 * 12;
                }
                else if (unit.UnitType == UnitTypes.ZERGLING || unit.UnitType == UnitTypes.ZEALOT)
                {
                    dist = 5 * 5;
                }
                else
                {
                    dist = 10 * 10;
                }
                if (agent.DistanceSq(unit) < dist)
                {
                    if (unit.UnitType == UnitTypes.ZERGLING && agent.Unit.WeaponCooldown == 0)
                    {
                        return(false);
                    }

                    agent.Order(Abilities.MOVE, SC2Util.To2D(Bot.Main.MapAnalyzer.StartLocation));
                    return(true);
                }
            }

            if (agent.Unit.WeaponCooldown == 0)
            {
                return(false);
            }

            float distance   = 12 * 12;
            Unit  killTarget = null;

            foreach (Unit unit in Bot.Main.Enemies())
            {
                if (!UnitTypes.WorkerTypes.Contains(unit.UnitType))
                {
                    continue;
                }
                float newDist = agent.DistanceSq(unit);
                if (newDist >= distance)
                {
                    continue;
                }
                distance   = newDist;
                killTarget = unit;
            }

            if (killTarget != null)
            {
                if (distance >= 3 * 3)
                {
                    agent.Order(Abilities.MOVE, SC2Util.To2D(killTarget.Pos));
                }
                else
                {
                    agent.Order(Abilities.MOVE, agent.From(killTarget, 4));
                }
                return(true);
            }

            foreach (Unit unit in Bot.Main.Enemies())
            {
                if (UnitTypes.CanAttackGround(unit.UnitType) &&
                    agent.DistanceSq(unit) <= 5 * 5)
                {
                    return(false);
                }
            }


            foreach (Unit unit in Bot.Main.Enemies())
            {
                if (!UnitTypes.ResourceCenters.Contains(unit.UnitType))
                {
                    continue;
                }
                if (SC2Util.DistanceSq(unit.Pos, Bot.Main.MapAnalyzer.StartLocation) > 4)
                {
                    continue;
                }

                PotentialHelper potential = new PotentialHelper(unit.Pos);
                potential.Magnitude = 4;
                potential.From(Bot.Main.MapAnalyzer.StartLocation);
                Point2D targetLoc = potential.Get();

                if (agent.DistanceSq(targetLoc) < 4 * 4)
                {
                    return(false);
                }

                agent.Order(Abilities.MOVE, targetLoc);
                return(true);
            }

            return(false);
        }
 public RaceAlliance(UnitTypes type, int initialHealthLevel, int initialAttackLevel,
     int level, bool isAlive, Point currentPosition, bool isSelected) : base(type, RaceTypes.Alliance, initialHealthLevel, initialAttackLevel,
     level, isAlive, currentPosition, isSelected)
 {
     
 }
Beispiel #36
0
 public Entity(string name, UnitTypes unitType, int playerNumber)
 {
     Name         = name;
     UnitType     = unitType;
     PlayerNumber = playerNumber;
 }
    void OnGUI()
    {
        /***********************************/
        //Header
        /***********************************/

        if (atkDataList == null)
        {
            string objectPath = EditorPrefs.GetString("AttackDatabasePath");
            atkDataList = AssetDatabase.LoadAssetAtPath(objectPath, typeof(AttackDataList)) as AttackDataList;

        }
        if (unitDataList == null)
        {
            string objectPath = EditorPrefs.GetString("UnitDataPath");
            unitPDataList = AssetDatabase.LoadAssetAtPath(objectPath, typeof(UnitDataList)) as UnitDataList;
        }

        if(cardDataBase == null)
        {
            cardDataBase = (CardDatabase)EditorWindow.GetWindow(typeof(CardDatabase));
        }

        GUILayout.Label("Unit Data Editor", EditorStyles.boldLabel);
        if (unitDataList.unitList.Count == 0)
        {
            EditorGUILayout.LabelField("No Unit database available, error.");
        }
        else
        {
            if (buttonToggled == null || buttonToggled.Count < unitDataList.unitList.Count)
            {
                buttonToggled = new List<bool>();
                toggledIndex = 0;
                for (int i = 0; i < unitDataList.unitList.Count; i++)
                    buttonToggled.Add(false);
            }

            if (toggledIndex > unitDataList.unitList.Count)
            {
                Debug.Log("Index was out of bounds");
                toggledIndex = unitDataList.unitList.Count - 1;
            }

            /************************************************************/

            /******************************************/
            //Display things
            /******************************************/
            if (unitDataList != null)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Space(10);
                EditorGUILayout.LabelField("Unit List Data", EditorStyles.boldLabel);
                filterType = (UnitTypes)EditorGUILayout.EnumPopup(filterType);

                if (GUILayout.Button("Sort", GUILayout.ExpandWidth(false)))
                {
                    sortByName();
                }

                GUILayout.EndHorizontal();
                if (unitDataList.unitList == null)
                {
                    Debug.Log("Mistakes were made - You should never reach this");
                }

                /****************************************/
                //How the list will look
                /***************************************/

                if (unitDataList.unitList.Count > 0)
                {
                    if (unitDataList.unitList[toggledIndex].uType != filterType)
                    {
                        toggledIndex = 0;
                        findNext();
                    }

                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.BeginVertical();
                    //----------Show all the buttons-----------
                    showScrollButtons();
                    //-----------------------------------------
                    EditorGUILayout.EndVertical();
                    GUILayout.Space(5);


                    EditorGUILayout.BeginVertical();
                    //---------Current selection info-----------

                    //SHOW UNIT SUMMARY
                    showUnitSummary();

                    /*************************************/
                    //UnitAttack WindowSpawn
                    /************************************/
                    GUILayout.Space(10);
                    EditorGUILayout.LabelField("Unit Attacks");

                    atkScroll = EditorGUILayout.BeginScrollView(atkScroll, GUILayout.Height(120));
                    foreach (string x in unitDataList.unitList[toggledIndex].attacksData.ToList<String>())
                    {
                        AttackData knownAtk = atkDataList.findByID(x);
                        if (knownAtk != null)
                        {
                            EditorGUILayout.BeginHorizontal();
                            EditorGUILayout.TextField(knownAtk.aName, knownAtk.pattern.ToString());
                            EditorGUILayout.TextField("Damage: " + knownAtk.expectedMin + " - " + knownAtk.expectedMax);
                            EditorGUILayout.TextField("Range: " + knownAtk.range.ToString());
                            EditorGUILayout.EndHorizontal();
                        }
                    }
                    EditorGUILayout.EndScrollView();
                    

                    if (GUILayout.Button("Link this unit"))
                    {
                        cardDataBase.assignElement(unitDataList.unitList[toggledIndex].uniqueId);
                        cardDataBase.Repaint();
                    }
                    EditorGUILayout.EndVertical();
                    GUILayout.EndHorizontal();
                }
                else
                {
                    GUILayout.Label("This Unit List is Empty.");
                }

                if (GUI.changed)
                {
                    EditorUtility.SetDirty(unitDataList);
                }
            }
        }
    }
Beispiel #38
0
 public Unit(double value, UnitTypes type)
 {
     Value    = value;
     UnitType = type;
 }
Beispiel #39
0
        private static bool confirmCompatibleTypes(UnitDouble left, UnitDouble right, out UnitConverter convert, out UnitTypes unittype, out Enum unit)
        {
            if (right != null && left.Converter != right.Converter && right.UnitType != UnitTypes.None && left.UnitType != UnitTypes.None)
            {
                convert  = null;
                unittype = UnitTypes.None;
                unit     = null;
                return(false);
            }

            convert  = (left.UnitType == UnitTypes.None && right != null ? right.Converter : left.Converter);
            unittype = (left.UnitType == UnitTypes.None && right != null ? right.UnitType : left.UnitType);
            unit     = (left.UnitType == UnitTypes.None && right != null ? right.Unit : left.Unit);

            return(true);
        }
Beispiel #40
0
 public void ChangeUnitType(UnitTypes unitType)
 {
     Unit = unitType;
 }
Beispiel #41
0
 public OutputAttribute(string name, string description, string group, UnitTypes units = UnitTypes.Undefined) :
     base(name, description, group, units)
 {
 }
Beispiel #42
0
 public UnitType(UnitTypes type, string displayTitle, SystemOfMeasurement system)
     : this(type, displayTitle)
 {
     this.System = system;
 }
Beispiel #43
0
        protected override void ParseUpdate(MemoryStream memoryStream)
        {
            var reader = new BinaryReader(memoryStream);

            UnitType = (UnitTypes) reader.ReadByte();

            bool hasEntToUse = reader.ReadBoolean();
            if (hasEntToUse)
            {
                ushort id = reader.ReadUInt16();
                if (WorldEntities.ContainsKey(id))
                {
                    EntityToUse = WorldEntities[id];
                }
            }

            RangedUnit = reader.ReadBoolean();
            Health = reader.ReadSingle();
            MaxHealth = reader.ReadSingle();
            State = (UnitState) reader.ReadByte();
            Position = new Vector2f(reader.ReadSingle(), reader.ReadSingle());
            Speed = reader.ReadSingle();
            Energy = reader.ReadUInt16();
            Range = reader.ReadSingle();
            allowMovement = reader.ReadBoolean();

            rallyPoints.Clear();
            ParseRallyPoints(memoryStream);

            StandardAttackDamage = reader.ReadSingle();
            HotkeyString = reader.ReadString();

            drawPosition = Position;
        }
Beispiel #44
0
 public UnitType(UnitTypes type, string displayTitle)
 {
     this.Type         = type;
     this.DisplayTitle = displayTitle;
 }
        public ThermodynamicParameter(double wm, UnitTypes utp, double value, UnitSystems unitsys, List<ThermodynamicParameter> List)
        {
            this.MolecularWeight = wm;
            this.UnitType = utp;
            this.Value = value;
            try
            {
                //利用映射
                string[] temp = (string[])(typeof(UnitConversion).GetField(UnitType.ToString()).GetValue(null));
                this.Unit = temp[(int)unitsys];
            }
            catch
            {
                RefpropErrorHandler.ErrorHandler(this, "Unknown unit", 1000);
            }

            this.UnitSystem = unitsys;
            List.Add(this);
        }
Beispiel #46
0
        /// <summary>
        /// Initializes a new instance of the Unit class.
        /// </summary>
        public Unit()
        {
            SetDeathState(DeathStates.Alive);
            this.unitFlags = UnitFlags.None;

            this.respawnLocation = new GridLocation();

            ObjectType = ObjectTypes.Unit;
            this.unitType = UnitTypes.Unit;
            this.unitSide = UnitSides.Evil;

            this.effectList = new EffectCollection(this);

            this.collidingUnits = new List<Unit>();

            BaseSpeed = 1.0d;
            SpeedRate = BaseSpeed;

            this.respawnTimer = 3000;

            this.effectList.EffectApplied += new EffectCollection.EffectHandler(OnEffectApplied);
            this.effectList.EffectRemoved += new EffectCollection.EffectHandler(OnEffectRemoved);
        }
Beispiel #47
0
		/// <summary>
		/// Cast the value to another type.
		/// </summary>
		/// <param name="unit">Source unit.</param>
		/// <param name="destinationType">Destination value type.</param>
		/// <param name="security">Information about the instrument. Required when using <see cref="UnitTypes.Point"/> и <see cref="UnitTypes.Step"/>.</param>
		/// <returns>Converted value.</returns>
		public static Unit Convert(this Unit unit, UnitTypes destinationType, Security security)
		{
			return unit.Convert(destinationType, type => GetTypeValue(security, type));
		}
Beispiel #48
0
 /// <summary>
 /// initiate the ofject
 /// </summary>
 /// <param name="name">Input, item description</param>
 /// <param name="amount">Input, item amount or quanitity</param>
 /// <param name="unit">Input, unit type</param>
 public ShoppingItem(string name, double amount, UnitTypes unit)
 {
     this.description = name;
     this.amount      = amount;
     this.unit        = unit;
 }
Beispiel #49
0
 /// <summary>
 /// copy constructor, creates an object with values from different object by making a complete copy of the internal reference
 /// </summary>
 /// <param name="theOtherShoppingItem"></param>
 public ShoppingItem(ShoppingItem theOtherShoppingItem)
 {
     description = theOtherShoppingItem.description;
     amount      = theOtherShoppingItem.amount;
     unit        = theOtherShoppingItem.unit;
 }
    void OnGUI()
    {
        /***********************************/
        //Header
        /***********************************/

        GUILayout.Label("Unit Data Editor", EditorStyles.boldLabel);
        if (unitDataList == null)
        {
            EditorGUILayout.LabelField("No Attack database available, error.");
        }

        /******************************************/
        //Sanity Checks and setups
        /******************************************/

        GUILayout.Space(20);

        if (unitDataList.unitList == null)
        {
            Debug.Log("New List was made");
            unitDataList.unitList = new List<UnitData>();
            toggledIndex = 0;
        }

        if (buttonToggled == null || buttonToggled.Count < unitDataList.unitList.Count)
        {
            buttonToggled = new List<bool>();
            toggledIndex = 0;
            for (int i = 0; i < unitDataList.unitList.Count; i++)
                buttonToggled.Add(false);
        }

        if (toggledIndex > unitDataList.unitList.Count)
        {
            Debug.Log("Index was out of bounds");
            toggledIndex = unitDataList.unitList.Count - 1;
        }

        /************************************************************/

        /******************************************/
        //Display things
        /******************************************/
        if (unitDataList != null)
        {
            GUILayout.BeginHorizontal();
            GUILayout.Space(10);

            if (GUILayout.Button("Prev", GUILayout.ExpandWidth(false)))
            {
                findPrev();
            }
            GUILayout.Space(5);
            if (GUILayout.Button("Next", GUILayout.ExpandWidth(false)))
            {
                findNext();
            }

            GUILayout.Space(60);

            if (GUILayout.Button("Add Item", GUILayout.ExpandWidth(false)))
            {
                AddUnit();
                unitDataList.unitList[toggledIndex].uType = filterType;

            }
            if (GUILayout.Button("Delete Item", GUILayout.ExpandWidth(false)))
            {
                DeleteUnit(toggledIndex);
            }

            filterType = (UnitTypes)EditorGUILayout.EnumPopup(filterType);

            if (GUILayout.Button("Sort", GUILayout.ExpandWidth(false)))
            {
                sortByName();
            }

            GUILayout.EndHorizontal();
            if (unitDataList.unitList == null)
            {
                Debug.Log("Mistakes were made - You should never reach this");
            }  

            /****************************************/
            //How the list will look
            /***************************************/
            
            if (unitDataList.unitList.Count > 0)
            {
                if (unitDataList.unitList[toggledIndex].uType != filterType)
                {
                    toggledIndex = 0;
                    findNext();
                }

                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.BeginVertical();
                //----------Show all the buttons-----------
                showScrollButtons();
                //-----------------------------------------
                EditorGUILayout.EndVertical();
                GUILayout.Space(5);


                EditorGUILayout.BeginVertical();
                //---------Current selection info-----------
                statScroll = GUILayout.BeginScrollView(statScroll,false, false);

                GUILayout.BeginHorizontal();
                unitDataList.unitList[toggledIndex].uName = EditorGUILayout.TextField("Unit Name", unitDataList.unitList[toggledIndex].uName);
                unitDataList.unitList[toggledIndex].uType = (UnitTypes)EditorGUILayout.EnumPopup("Unit Type", unitDataList.unitList[toggledIndex].uType);
                if (unitDataList.unitList[toggledIndex].uType != filterType)
                    filterType = unitDataList.unitList[toggledIndex].uType;
                GUILayout.EndHorizontal();

                GUILayout.Space(5);

                unitDataList.unitList[toggledIndex].isHero = EditorGUILayout.Toggle("Hero", unitDataList.unitList[toggledIndex].isHero, GUILayout.ExpandWidth(false));
                GUILayout.Space(10);

                EditorGUILayout.LabelField("Stats", EditorStyles.boldLabel);
                unitDataList.unitList[toggledIndex].maxHp = EditorGUILayout.IntField("HP", unitDataList.unitList[toggledIndex].maxHp, GUILayout.ExpandWidth(false));
                unitDataList.unitList[toggledIndex].maxSpeed = EditorGUILayout.Slider("Speed", unitDataList.unitList[toggledIndex].maxSpeed, 5, 20, GUILayout.ExpandWidth(false));
                
                if (unitDataList.unitList[toggledIndex].isHero)
                {
                    unitDataList.unitList[toggledIndex].impulse = EditorGUILayout.IntSlider("Impulse", unitDataList.unitList[toggledIndex].impulse, 3, 6, GUILayout.ExpandWidth(false));
                    unitDataList.unitList[toggledIndex].memory = EditorGUILayout.IntSlider("Memory", unitDataList.unitList[toggledIndex].memory, 0, 5, GUILayout.ExpandWidth(false));
                }
                
                /*****************************************/
                //Atk/Def Factors
                /*****************************************/
                EditorGUILayout.Space();
                
                showFactors = EditorGUILayout.Foldout(showFactors, "Type Factors");
                
                if (showFactors)
                {
                    GUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField("Attack Factors");
                    EditorGUILayout.LabelField("Defence Factors");
                    GUILayout.EndHorizontal();
                    for (int i = 0; i < (int)DamageType.TOTAL; i++)
                    {
                        GUILayout.BeginHorizontal();
                        unitDataList.unitList[toggledIndex].typeAtk[i] = EditorGUILayout.Slider(Enum.GetName(typeof(DamageType), i), unitDataList.unitList[toggledIndex].typeAtk[i], 0.5f, 2.0f);
                        unitDataList.unitList[toggledIndex].typeDef[i] = EditorGUILayout.Slider(Enum.GetName(typeof(DamageType), i), unitDataList.unitList[toggledIndex].typeDef[i], 0.5f, 2.0f);
                        GUILayout.EndHorizontal();
                    }
                    GUILayout.BeginHorizontal();
                    if (GUILayout.Button("Reset Attack Factors"))
                        for (int i = 0; i < (int)DamageType.TOTAL; i++)
                        {
                            unitDataList.unitList[toggledIndex].typeAtk[i] = 1.0f;
                        }
                    if (GUILayout.Button("Reset Defence Factors"))
                        for (int i = 0; i < (int)DamageType.TOTAL; i++)
                        {
                            unitDataList.unitList[toggledIndex].typeDef[i] = 1.0f;
                        }
                    GUILayout.EndHorizontal();
                    
                }

                GUILayout.EndScrollView();


                /*************************************/
                //UnitAttack WindowSpawn
                /************************************/
                GUILayout.Space(10);
                EditorGUILayout.LabelField("Unit Attacks", EditorStyles.boldLabel);

                atkScroll = EditorGUILayout.BeginScrollView(atkScroll, GUILayout.Height(120));
                foreach(string x in unitDataList.unitList[toggledIndex].attacksData.ToList<String>())
                {
                    AttackData knownAtk = atkDataList.findByID(x);
                    if(knownAtk != null)
                    {
                        EditorGUILayout.BeginHorizontal();
                        //EditorGUILayout.PrefixLabel(knownAtk.aName);
                        showAttackSummary(knownAtk);
                        if (GUILayout.Button("Remove", GUILayout.Width(120f)))
                            RemoveAttack((toggledIndex), x);
                        EditorGUILayout.EndHorizontal();
                    }       
                }
                EditorGUILayout.EndScrollView();

                EditorGUILayout.BeginHorizontal();
                if (GUILayout.Button("Attack List"))
                {
                    AttackListWindow.CardEdit(false);
                    atkWindow = (AttackListWindow)EditorWindow.GetWindow(typeof(AttackListWindow));
                }


                if (GUILayout.Button("Clear Residual Data"))
                    refreshUnitsAttackLists();
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.EndVertical();
                GUILayout.EndHorizontal();

            }
            else
            {
                GUILayout.Label("This Unit List is Empty.");
            }

            if (GUI.changed)
            {
                EditorUtility.SetDirty(unitDataList);
            }
        }
    }
Beispiel #51
0
        /// <summary>
        /// Reads a UnitObject from the internal serialised byte array.
        /// </summary>
        private void _ReadUnit()
        {
            //// start of header
            // unit object versions
            _version = _bitBuffer.ReadInt16();
            _context = (ObjectContext)_bitBuffer.ReadByte();
            if (_version != 0x00BF && _version != 0x00CD && _version != 0x00CF) throw new Exceptions.NotSupportedVersionException("0x00BF or 0x00CD or 0x00CF", "0x" + _version.ToString("X4"));
            if (_context != ObjectContext.Save && _context != ObjectContext.CharSelect &&
                _context != ObjectContext.CharStats && _context != ObjectContext.ItemDrop)
            {
                throw new Exceptions.NotSupportedVersionException("0x00 or 0x02 or 0x03 or 0x04", "0x" + _context.ToString("X2"));
            }
            if (_debugOutputLoadingProgress)
            {
                Debug.WriteLine(String.Format("Version = {0} (0x{0:X4}), Context = {1} (0x{2:X2})", _version, _context, (int)_context));
            }

            // content bit fields
            _bitFieldCount = _bitBuffer.ReadBits(8);
            if (_bitFieldCount == 1) _bitField = _bitBuffer.ReadUInt32();
            if (_bitFieldCount == 2) _bitField = _bitBuffer.ReadUInt64();
            if (_debugOutputLoadingProgress)
            {
                Debug.WriteLine(String.Format("BitField = {0} (0x{1:X16})", _DebugBinaryFormat(_bitField), _bitField));
            }

            // total bit count
            if (_TestBit(Bits.Bit1DBitCountEof))
            {
                _bitCount = _bitBuffer.ReadBits(32);
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("Total BitCount = {0}", _bitCount));
                }
            }

            // begin data magic word
            if (_TestBit(Bits.Bit00FlagAlignment))
            {
                _beginFlag = (uint)_bitBuffer.ReadBits(32);
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("BeginFlag = 0x{0}", _beginFlag.ToString("X8")));
                }
                if (_beginFlag != ObjectMagicWord && _beginFlag != ItemMagicWord) throw new Exceptions.UnexpectedTokenException(ObjectMagicWord, _beginFlag);
            }

            // dunno what these are exactly
            if (_TestBit(Bits.Bit1CTimeStamps))
            {
                _timeStamp1 = _bitBuffer.ReadBits(32);
                _timeStamp2 = _bitBuffer.ReadBits(32);
                _timeStamp3 = _bitBuffer.ReadBits(32);
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("TimeStamp1 = {0}, TimeStamp2 = {1}, TimeStamp3 = {2}", _timeStamp1, _timeStamp2, _timeStamp3));
                }
            }

            // last station visited save/respawn location
            if (_TestBit(Bits.Bit1FSaveLocations))
            {
                int saveLocationsCount = _bitBuffer.ReadBitsShift(4);
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("SaveLocationsCount = {0}", saveLocationsCount));
                }

                for (int i = 0; i < saveLocationsCount; i++)
                {
                    ushort levelCode = _bitBuffer.ReadUInt16(); // table 0x6D (LEVEL)
                    ushort difficultyCode = _bitBuffer.ReadUInt16();  // table 0xB2 (DIFFICULTY)

                    SaveLocation saveLocation = new SaveLocation
                    {
                        Level = (LevelRow)FileManager.GetRowFromCode(Xls.TableCodes.LEVEL, (short)levelCode),
                        Difficulty = (DifficultyRow)FileManager.GetRowFromCode(Xls.TableCodes.DIFFICULTY, (short)difficultyCode)
                    };
                    SaveLocations.Add(saveLocation);

                    if ((SaveLocations[i].Level == null && SaveLocations[i].Difficulty != null) || (SaveLocations[i].Level != null && SaveLocations[i].Difficulty == null))
                    {
                        throw new Exceptions.UnitObjectException(String.Format("Invalid SaveLocation encountered. Level = {0:X4}, Difficulty = {1:X4}", levelCode, difficultyCode));
                    }

                    if (!_debugOutputLoadingProgress) continue;
                    if (SaveLocations[i].Level == null || SaveLocations[i].Difficulty == null)
                    {
                        Debug.WriteLine(String.Format("SaveLocations[{0}].LevelCode = {1} (0x{1:X4}), SaveLocations[{0}].DifficultyCode = {2} (0x{2:X4})",
                                                      i, levelCode, difficultyCode));
                    }
                    else
                    {
                        Debug.WriteLine(String.Format("SaveLocations[{0}].Level = {1}, SaveLocations[{0}].Difficulty = {2}",
                                                      i, SaveLocations[i].Level.levelName, SaveLocations[i].Difficulty.name));
                    }
                }
            }

            // character flags
            if (_TestBit(Bits.Bit20States1))
            {
                int statCount = _bitBuffer.ReadBits(8);
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("StateCode1Count = {0}", statCount));
                }

                for (int i = 0; i < statCount; i++)
                {
                    int state = _bitBuffer.ReadInt16();
                    AddState1(state); // table 0x4B (STATES)
                    if (_debugOutputLoadingProgress)
                    {
                        Debug.WriteLine(String.Format("StateCodes1[{0}] = {1}({2:X})", i, StateCodes1[i], (short)(StateCodes1[i])));
                    }
                }
            }
            //// end of header

            // bit offsets to bookmarks (only 1 bookmark though - "hotkeys")
            if (_TestBit(Bits.Bit1BBookmarks))
            {
                BookmarkCount = _bitBuffer.ReadBits(5);
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("BookmarkCount = {0}", BookmarkCount));
                }
                if (BookmarkCount > 1)
                {
                    throw new Exceptions.UnitObjectNotImplementedException("Unexpected BookmarkCount (> 1)!\nNot-Implemented cases. Please report this error and supply the offending file.");
                }

                for (int i = 0; i < BookmarkCount; i++)
                {
                    Bookmark bookmark = new Bookmark
                    {
                        Code = _bitBuffer.ReadUInt16(),
                        Offset = _bitBuffer.ReadInt32()
                    };
                    if (_debugOutputLoadingProgress)
                    {
                        Debug.WriteLine(String.Format("Bookmarks[{0}].Code = {1} (0x{1:X4}), Bookmarks[{0}].Offset = {2}", i, bookmark.Code, bookmark.Offset));
                    }

                    Bookmarks.Add(bookmark);
                }
            }

            // dunno...
            if (_TestBit(Bits.Bit05Unknown))
            {
                UnitObjectId = _bitBuffer.ReadInt32();
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("UnitObjectId = {0} (0x{0:X4})", UnitObjectId));
                }
            }

            // unit type/code
            // if unit type == 1, table = 0x91 (PLAYERS)
            //                 2, table = 0x77 (MONSTERS)
            //                 3? (table = 0x72; MISSILES at a guess. For memory, MISSILES doesn't use code values - probably why not seen in ASM)
            //                 4, table = 0x67 (ITEMS)
            //                 5, table = 0x7B (OBJECTS)
            UnitType = (UnitTypes)_bitBuffer.ReadBits(4);
            if (_debugOutputLoadingProgress)
            {
                Debug.WriteLine(String.Format("UnitType = {0}", UnitType));
            }
            UnitCode = _bitBuffer.ReadUInt16();
            if (_debugOutputLoadingProgress)
            {
                Debug.Write(String.Format("UnitCode = {0} (0x{0:X4}), ", UnitCode));
            }
            Xls.TableCodes tableCode = Xls.TableCodes.Null;
            switch (UnitType)
            {
                case UnitTypes.Player:  tableCode = Xls.TableCodes.PLAYERS;  break;
                case UnitTypes.Monster: tableCode = Xls.TableCodes.MONSTERS; break;
                case UnitTypes.Missile: tableCode = Xls.TableCodes.MISSILES; break;
                case UnitTypes.Item:    tableCode = Xls.TableCodes.ITEMS;    break;
                case UnitTypes.Object:  tableCode = Xls.TableCodes.OBJECTS;  break;
            }
            if (tableCode == Xls.TableCodes.Null) throw new Exceptions.UnitObjectException("The unit object data has an unknown UnitType.");
            UnitData = FileManager.GetUnitDataRowFromCode(tableCode, (short)UnitCode);
            if (UnitData == null) Debug.WriteLine(String.Format("Warning: UnitCode {0} (0x{0:X4}) not found!", UnitCode));
            if (_debugOutputLoadingProgress && UnitData != null)
            {
                ExcelFile unitDataTable = FileManager.GetExcelTableFromCode(tableCode);
                String rowName = unitDataTable.ReadStringTable(UnitData.name);
                Debug.WriteLine(String.Format("UnitDataName = " + rowName));
            }

            // unit object id
            if (_TestBit(Bits.Bit17ObjectId))
            {
                if (_version > 0xB2)
                {
                    ObjectId = _bitBuffer.ReadUInt64();
                    if (_debugOutputLoadingProgress)
                    {
                        Debug.WriteLine(String.Format("ObjectId = {0} (0x{0:X16})", ObjectId));
                    }

                    if (ObjectId == 0)
                    {
                        throw new Exceptions.UnitObjectNotImplementedException("if (ObjectId == 0)");
                    }
                }
            }

            // item positioning stuff
            if (_TestBit(Bits.Bit01Unknown) || _TestBit(Bits.Bit03Unknown))
            {
                IsInventory = _bitBuffer.ReadBool();
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("IsInventory = {0}, Bits.Bit01Unknown = {1}, Bits.Bit03Unknown = {2}", IsInventory, _TestBit(Bits.Bit01Unknown), _TestBit(Bits.Bit03Unknown)));
                }

                if (IsInventory) // item is in inventory
                {
                    if (_TestBit(Bits.Bit02Unknown))
                    {
                        Unknown02 = _bitBuffer.ReadBits(32);
                        if (_debugOutputLoadingProgress)
                        {
                            Debug.WriteLine(String.Format("Unknown02 = {0}", Unknown02));
                        }
                    }

                    InventoryLocationIndex = _bitBuffer.ReadBits(12);
                    InventoryPositionX = _bitBuffer.ReadBits(12);
                    InventoryPositionY = _bitBuffer.ReadBits(12);
                    Unknown04 = _bitBuffer.ReadBits(4);
                    if (_debugOutputLoadingProgress)
                    {
                        Debug.WriteLine(String.Format("InventoryLocationIndex = {0}, InventoryPositionX = {1}, InventoryPositionY = {2}, Unknown04 = {3}",
                            InventoryLocationIndex, InventoryPositionX, InventoryPositionY, Unknown04));
                    }

                    Unknown0103Int64 = _bitBuffer.ReadNonStandardFunc();
                    if (_debugOutputLoadingProgress)
                    {
                        Debug.WriteLine(String.Format("Unknown0103Int64 = {0} (0x{0:X16})", Unknown0103Int64));
                    }
                }
                else // item is a "world drop"
                {
                    RoomId = _bitBuffer.ReadInt32();

                    Position.X = _bitBuffer.ReadFloat();
                    Position.Y = _bitBuffer.ReadFloat();
                    Position.Z = _bitBuffer.ReadFloat();

                    Unknown0103Float21 = _bitBuffer.ReadFloat();
                    Unknown0103Float22 = _bitBuffer.ReadFloat();
                    Unknown0103Float23 = _bitBuffer.ReadFloat();

                    Normal.X = _bitBuffer.ReadFloat();
                    Normal.Y = _bitBuffer.ReadFloat();
                    Normal.Z = _bitBuffer.ReadFloat();

                    Unknown0103Int2 = _bitBuffer.ReadBits(10);

                    Unknown0103Float4 = _bitBuffer.ReadFloat();

                    Unknown0103Float5 = _bitBuffer.ReadFloat();

                    if (_debugOutputLoadingProgress)
                    {
                        Debug.WriteLine(String.Format("RoomId = {0}", RoomId));
                        Debug.WriteLine(String.Format("Position.X = {0}, Position.Y = {1}, Position.Z = {2}", Position.X, Position.Y, Position.Z));
                        Debug.WriteLine(String.Format("Unknown0103Float21 = {0}, Unknown0103Float22 = {1}, Unknown0103Float23 = {2}", Unknown0103Float21, Unknown0103Float22, Unknown0103Float23));
                        Debug.WriteLine(String.Format("NormalX = {0}, NormalY = {1}, NormalZ = {2}", Normal.X, Normal.Y, Normal.Z));
                        Debug.WriteLine(String.Format("Unknown0103Int2 = {0}", Unknown0103Int2));
                        Debug.WriteLine(String.Format("Unknown0103Float4 = {0}", Unknown0103Float4));
                        Debug.WriteLine(String.Format("Unknown0103Float5 = {0}", Unknown0103Float5));
                    }
                }
            }

            // I think this has something to do with the Monsters table +46Ch, bit 0x55 = 4 bits or bit 0x47 = 2 bits. Or Objects table +46Ch, bit 0x55 = 2 bits... Something like that
            if (_TestBit(Bits.Bit06Unknown))
            {
                UnknownBool06 = _bitBuffer.ReadBool();
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("UnknownBool06 = {0}", UnknownBool06));
                }
                if (!UnknownBool06)
                {
                    throw new Exceptions.UnitObjectNotImplementedException("if (UnknownBool06 != 1)");
                }
            }

            if (_TestBit(Bits.Bit09ItemLookGroup))
            {
                ItemLookGroupCode = _bitBuffer.ReadBits(8);
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("ItemLookGroupCode = {0} (0x{0:X2})", ItemLookGroupCode));
                }
            }

            // on character only
            if (_TestBit(Bits.Bit07CharacterShape))
            {
                CharacterHeight = _bitBuffer.ReadByte();
                CharacterBulk = _bitBuffer.ReadByte();
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("CharacterHeight = {0}, CharacterBulk = {1}", CharacterHeight, CharacterBulk));
                }
            }

            // object id for older versions - they moved it?
            if (_TestBit(Bits.Bit17ObjectId))
            {
                if (_version <= 0xB2)
                {
                    throw new Exceptions.UnitObjectNotImplementedException("if (_TestBit(0x17) && Version <= 0xB2)");
                }
            }

            // on character only
            if (_TestBit(Bits.Bit08CharacterName))
            {
                int unicodeCharCount = _bitBuffer.ReadBits(8);
                if (unicodeCharCount > 0)
                {
                    int byteCount = unicodeCharCount * 2; // is Unicode string without \0
                    _charNameBytes = new byte[byteCount];
                    for (int i = 0; i < byteCount; i++)
                    {
                        _charNameBytes[i] = _bitBuffer.ReadByte();
                    }
                    Name = Encoding.Unicode.GetString(_charNameBytes, 0, byteCount);
                    if (_debugOutputLoadingProgress)
                    {
                        Debug.WriteLine(String.Format("Name = {0}", Name));
                    }
                }
            }

            // on both character and items - appears to be always zero for items
            if (_TestBit(Bits.Bit0AStates2))
            {
                int stateCount = _bitBuffer.ReadBits(8);
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("StateCode2Count = {0}", stateCount));
                }

                for (int i = 0; i < stateCount; i++)
                {
                    int state = _bitBuffer.ReadInt16();
                    AddState2(state);
                    if (_debugOutputLoadingProgress)
                    {
                        Debug.WriteLine(String.Format("StateCodes2[{0}] = {1}({2:X})", i, StateCodes2[i], (short)(StateCodes2[i])));
                    }

                    // this section looks like it has more reading if Bit14 is flagged (CharSelectStats)
                }
            }

            if (_context > ObjectContext.CharSelect && (_context <= ObjectContext.Unknown6 || _context != ObjectContext.Unknown7)) // so if == 0, 1, 2, 7, then *don't* do this
            {
                ContextBool = _bitBuffer.ReadBool();
                if (ContextBool)
                {
                    ContextBoolValue = _bitBuffer.ReadBits(4); // invlocidx??
                }

                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("UsageBool = {0}, UsageBoolValue = {1}", ContextBool, ContextBoolValue));
                }
            }

            // <unknown bitfield 0x11th bit> - only seen as false anyways

            IsDead = _bitBuffer.ReadBool();
            if (_debugOutputLoadingProgress)
            {
                Debug.WriteLine(String.Format("IsDead = {0}", IsDead));
            }

            // unit stats
            if (_TestBit(Bits.Bit0DStats))
            {
                Stats.ReadStats(_bitBuffer, true);
            }
            else if (_TestBit(Bits.Bit14CharSelectStats))
            {
                int characterLevel = _bitBuffer.ReadByte(); // stats row 0x000 (level)
                Stats.SetStat("level", characterLevel);

                int characterPvpRankRowIndex = _bitBuffer.ReadByte(); // stats row 0x347 (player_rank)
                Stats.SetStat("player_rank", characterPvpRankRowIndex);

                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("LevelRowIndex = {0}, PlayerRankRowIndex = {1}", characterLevel, characterPvpRankRowIndex));
                }

                if (_TestBit(Bits.Bit1ECharSelectStatsMaxDifficulty))
                {
                    int maxDifficultyRowIndex = _bitBuffer.ReadBits(3); // stats row 0x347 (difficulty_max)
                    Stats.SetStat("difficulty_max", maxDifficultyRowIndex);

                    if (_debugOutputLoadingProgress)
                    {
                        Debug.WriteLine(String.Format("MaxDifficultyRowIndex = {0}, ", maxDifficultyRowIndex));
                    }
                }
            }

            HasAppearanceDetails = _bitBuffer.ReadBool();
            if (_debugOutputLoadingProgress)
            {
                Debug.WriteLine(String.Format("HasAppearanceDetails = {0}", HasAppearanceDetails));
            }
            if (HasAppearanceDetails)
            {
                _ReadAppearance();
            }

            if (_TestBit(Bits.Bit12Items))
            {
                ItemEndBitOffset = _bitBuffer.ReadInt32();
                ItemCount = _bitBuffer.ReadBits(10);
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("ItemEndBitOffset = {0}, ItemCount = {1}", ItemEndBitOffset, ItemCount));
                }

                for (int i = 0; i < ItemCount; i++)
                {
                    UnitObject item = new UnitObject(_bitBuffer, _debugOutputLoadingProgress);
                    item._ReadUnit();
                    Items.Add(item);
                }
            }

            if (_TestBit(Bits.Bit1AHotkeys))
            {
                HotkeyFlag = _bitBuffer.ReadUInt32();
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("HotkeyFlag = {0} (0x{0:X8})", HotkeyFlag));
                }
                if (HotkeyFlag != HotkeysMagicWord)
                {
                    throw new Exceptions.UnexpectedTokenException(HotkeysMagicWord, HotkeyFlag);
                }

                EndFlagBitOffset = _bitBuffer.ReadBits(32);     // to end flag
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("EndFlagBitOffset = {0}", EndFlagBitOffset));
                }

                HotkeyCount = _bitBuffer.ReadBits(6);
                if (_debugOutputLoadingProgress)
                {
                    Debug.WriteLine(String.Format("HotkeyCount = {0}", HotkeyCount));
                }
                for (int i = 0; i < HotkeyCount; i++)
                {
                    Hotkey hotkey = new Hotkey
                    {
                        Code = _bitBuffer.ReadUInt16(), // code from TAG table
                    };
                    Hotkeys.Add(hotkey);
                    if (_debugOutputLoadingProgress)
                    {
                        Debug.WriteLine(String.Format("hotkey.Code = 0x{0:X4}", hotkey.Code));
                    }

                    hotkey.UnknownCount = _bitBuffer.ReadBits(4);
                    if (_debugOutputLoadingProgress)
                    {
                        Debug.WriteLine(String.Format("hotkey.UnknownCount = " + hotkey.UnknownCount));
                    }
                    if (hotkey.UnknownCount > 0x02)
                    {
                        throw new Exceptions.UnitObjectNotImplementedException("if (hotkey.UnknownCount > 0x02)");
                    }

                    hotkey.UnknownExists = new bool[hotkey.UnknownCount];
                    hotkey.UnknownValues = new int[hotkey.UnknownCount];
                    for (int j = 0; j < hotkey.UnknownCount; j++)
                    {
                        hotkey.UnknownExists[j] = _bitBuffer.ReadBool();
                        if (hotkey.UnknownExists[j])
                        {
                            hotkey.UnknownValues[j] = _bitBuffer.ReadBits(32); // under some condition this will be ReadFromOtherFunc thingy
                        }
                        if (_debugOutputLoadingProgress)
                        {
                            Debug.WriteLine(String.Format("hotkey.UnknownExists[{0}] = {1}, hotkey.UnknownValues[{0}] = 0x{2:X8}", j, hotkey.UnknownExists[j], hotkey.UnknownValues[j]));
                        }
                    }

                    hotkey.SkillCount = _bitBuffer.ReadBits(4);
                    hotkey.SkillExists = new bool[hotkey.SkillCount];
                    hotkey.SkillCode = new int[hotkey.SkillCount];
                    for (int j = 0; j < hotkey.SkillCount; j++)
                    {
                        hotkey.SkillExists[j] = _bitBuffer.ReadBool();
                        if (hotkey.SkillExists[j])
                        {
                            hotkey.SkillCode[j] = _bitBuffer.ReadBits(32); // code from SKILLS table
                        }
                        if (_debugOutputLoadingProgress)
                        {
                            Debug.WriteLine(String.Format("hotkey.SkillExists[{0}] = {1}, hotkey.SkillCode[{0}] = 0x{2:X8}", j, hotkey.SkillExists[j], hotkey.SkillCode[j]));
                        }
                    }

                    hotkey.UnitTypeCode = _bitBuffer.ReadBits(32); // code from UNITTYPES table
                    if (_debugOutputLoadingProgress)
                    {
                        Debug.WriteLine(String.Format("hotkey.UnitTypeCode = 0x{0:X8}", hotkey.UnitTypeCode));
                    }
                }
            }

            // end flag
            EndFlag = _bitBuffer.ReadBits(32);
            if (_debugOutputLoadingProgress)
            {
                Debug.WriteLine(String.Format("EndFlag = {0} (0x{0:X8})", EndFlag));
            }

            if (EndFlag != _beginFlag && EndFlag != ItemMagicWord)
            {
                int bitOffset = _bitCount - _bitBuffer.BitOffset;
                int byteOffset = (_bitBuffer.Length - _bitBuffer.Offset) - (_bitBuffer.BytesUsed);
                throw new Exceptions.InvalidFileException("Flags not aligned!\nBit Offset: " + _bitBuffer.BitOffset + "\nExpected: " + _bitCount + " (+" + bitOffset +
                                                          ")\nBytes Used: " + (_bitBuffer.BytesUsed) + "\nExpected: " + (_bitBuffer.Length - _bitBuffer.Offset) + " (+" + byteOffset + ")");
            }

            if (_TestBit(Bits.Bit1DBitCountEof)) // no reading is done in here
            {
                // todo: do check that we're at the EoF bit count etc
            }
        }
Beispiel #52
0
 public OutputAttribute(string name, UnitTypes units = UnitTypes.Undefined) : base(name, "", "Outputs", units)
 {
 }
Beispiel #53
0
 public Distance(UnitTypes unit, double originalValue)
 {
     Unit          = unit;
     OriginalValue = originalValue;
 }
Beispiel #54
0
 //set and get functions for unit type
 public virtual void SetUnitType(UnitTypes uT)
 {
     unitType = uT;
 }