Exemple #1
0
    /// <summary> Interprets the datastructure of the conversation </summary>
    /// <param name="structure"></param>
    /// <returns>
    ///		A dictionnary unsigned short -> message array.
    ///		Every key-valuepair in the dictionnary represents one
    ///		stage of the conversation.
    ///	</returns>
    private Dictionary <ushort, Message[]> InterpretDS(DataStructure structure)
    {
        Dictionary <ushort, Message[]> res = new Dictionary <ushort, Message[]>();

        foreach (DataStructure child in structure.AllChildren)
        {
            Message[] msgs = new Message[child.children.Count];
            int       i    = 0;
            foreach (DataStructure childchild in child.AllChildren)
            {
                if (Message.string2message_types.ContainsKey(childchild.Name))
                {
                    msgs [i++] = new Message(childchild, Message.string2message_types [childchild.Name])
                    {
                        parent_conv = this,
                    };
                }
                else
                {
                    DeveloppmentTools.Log(childchild.Name + "Not a command");
                }
            }
            res.Add(child.Get <ushort>("num"), msgs);
        }
        return(res);
    }
Exemple #2
0
 public void Change(string func, KeyBinding newbinding)
 {
     foreach (DataStructure child in keydata.AllChildren)
     {
         if (child.Contains <ushort>(func))
         {
             if (newbinding.act_code.Length == 1)
             {
                 child.Set(func, newbinding.keyids [0]);
             }
             else
             {
                 child.short_integers_arr.Remove(func);
                 child.short_integers.Add(func, newbinding.keyids [0]);
             }
             return;
         }
         if (child.Contains <ushort []>(func))
         {
             if (newbinding.act_code.Length == 1)
             {
                 child.short_integers.Remove(func);
                 child.short_integers_arr.Add(func, newbinding.keyids);
             }
             else
             {
                 child.Set(func, newbinding.keyids);
             }
             return;
         }
     }
     DeveloppmentTools.LogFormat("Keybinding \"{0}\" not found", func);
 }
Exemple #3
0
    /// <summary> Displays text as an error </summary>
    public void LogError(string message)
    {
        string act_text = string.Format("**ERROR**: {0} ", message);

        DeveloppmentTools.Log(act_text);
        console.WriteLine(act_text);
    }
Exemple #4
0
    public void Spawn(string type, string name)
    {
        switch (type)
        {
        case "squadron":
            if (!squadrons_dict.ContainsKey(name))
            {
                ThrowError("No such squadron: " + name);
                DeveloppmentTools.Log("no such squadron: " + name);
                return;
            }
            SpawnSquadron(squadrons_dict [name]);
            break;

        case "single target":
            if (!single_targets_dict.ContainsKey(name))
            {
                ThrowError("No such single target: " + name);
                DeveloppmentTools.Log("no such single target: " + name);
                return;
            }
            SpawnSingleTarget(single_targets_dict [name]);
            break;
        }
    }
Exemple #5
0
    /// <summary>
    ///		Should be called every frame.
    ///		Continiues execution, depending on what the previous message returned
    ///	</summary>
    public void Update()
    {
        if (!Running)
        {
            return;
        }
        if (!messages.ContainsKey(CurrentState))
        {
            DeveloppmentTools.Log(string.Format("State {0} not an option", CurrentState));
            return;
        }
        if (messages[CurrentState].Length <= messgecycle)
        {
            DeveloppmentTools.Log(string.Format("MessageID {0} not an option", messgecycle));
            return;
        }
        Message curr_message = messages[CurrentState][messgecycle];

        Message.Result res = curr_message.Execute(console.HasInput ? console.ReadLine() : null);
        switch (res)
        {
        default:
        case Message.Result.error:
        case Message.Result.finished:
            if (++messgecycle >= messages [CurrentState].Length)
            {
                if (nextstate == ushort.MaxValue)
                {
                    LogError("State not set");
                }
                CurrentState = nextstate;
                messgecycle  = 0;
                // To be recognized as the error-source
                nextstate = ushort.MaxValue;
            }
            break;

        case Message.Result.running:
            break;

        case Message.Result.break_:
            CurrentState = nextstate;
            break;

        case Message.Result.notimplemented:
            LogError("Function not implemented yet");
            goto case Message.Result.error;

        case Message.Result.exit:
            Exit();
            break;
        }
        return;
    }
Exemple #6
0
 /// <summary>
 ///		Returns the current binding of a certain funtion
 /// </summary>
 public KeyBinding GetByFunction(string function)
 {
     foreach (KeyBinding binding in AllBindings)
     {
         if (binding.function == function)
         {
             return(binding);
         }
     }
     DeveloppmentTools.LogFormat("No such key function exists: \"{0}\"", function);
     return(KeyBinding.None);
 }
Exemple #7
0
 public void PlayMusic(string title)
 {
     if (Globals.loaded_data.music_dict.ContainsKey(title))
     {
         _audio.clip = Globals.loaded_data.music_dict[title][(int)Mathf.Floor(Random.Range(0, Globals.loaded_data.music_dict[title].Length - .001f))];
         _audio.Play();
     }
     else
     {
         Debug.LogFormat("Title does not exist: {0};\n {1}", title, DeveloppmentTools.LogIterable(Globals.loaded_data.music_dict.Keys));
     }
 }
    /// <summary> Lets show the explosion </summary>
    /// <param name="position"> The position, where the explosion takes place </param>
    public void Boom(Vector3 position)
    {
        float radius = Mathf.Pow(explosion_force / 10, .33f);

        explosion_obj = Object.Instantiate(template_obj, position, Quaternion.identity);

        particles = explosion_obj.GetComponent <ParticleSystem>();
        if (particles == null)
        {
            DeveloppmentTools.Log("There is no particlesystem on the explosion object");
            return;
        }

        ParticleSystem.EmissionModule ps_emission = particles.emission;
        ParticleSystem.MainModule     ps_main     = particles.main;
        ps_emission.rateOverTime = Mathf.Pow(explosion_force, .33f) * 100;
        ps_main.startSpeed       = Mathf.Pow(explosion_force, .33f) / 2;
        ps_main.startSize        = Mathf.Pow(explosion_force, .33f);

        // Detect nearby ships
        List <Ship> nearby_ships = new List <Ship>();

        foreach (Ship ship in SceneGlobals.ship_collection)
        {
            float threshhold = radius + ship.radius;
            if ((ship.Position - position).sqrMagnitude <= threshhold * threshhold)
            {
                nearby_ships.Add(ship);
            }
        }

        float dammage_1m = explosion_force * 5;

        foreach (Ship ship in nearby_ships)
        {
            foreach (ShipPart component in ship.Parts.AllParts)
            {
                if (component.Exists)
                {
                    float dammage = dammage_1m / Mathf.Max(.5f, (component.OwnObject.transform.position - position).sqrMagnitude);
                    float bef_hp  = component.HP;
                    component.HP -= dammage;
                }
            }
        }

        foreach (DestroyableTarget obj in SceneGlobals.destroyables)
        {
            float dammage = dammage_1m / Mathf.Max(.5f, (obj.Position - position).sqrMagnitude);
            float bef_hp  = obj.HP;
            obj.HP -= dammage;
        }
    }
Exemple #9
0
    public void LoadSave(string path)
    {
        if (!System.IO.File.Exists(DataStructure.GeneralPath + path + ".cfgt"))
        {
            DeveloppmentTools.Log(path + " does not exist");
            return;
        }

        SceneGlobals.is_save = true;
        SceneManager.LoadScene(sceneName: "battlefield");
        saved_path_loaded = path;
    }
Exemple #10
0
    /// <summary> Checks if certain items of certain types are in the data </summary>
    /// <param name="item_array"></param>
    /// <returns> True if all items are contained </returns>
    public bool Check4Items(System.Type[] types, string[] names)
    {
        bool present = true;

        for (int i = 0; i < Mathf.Min(types.Length, names.Length); i++)
        {
            if (!data.Contains(names[i], types[i]))
            {
                DeveloppmentTools.LogFormat("\"{0}\" not found", names [i]);
                present = false;
            }
        }
        return(present);
    }
Exemple #11
0
    public virtual void PhysicsUpdate(float p_deltatime)
    {
        deltatime = p_deltatime;

        Velocity += Acceleration * deltatime;
        Position += SceneGlobals.ReferenceSystem.RelativeVelocity(Velocity) * deltatime;

        AngularVelocity += AngularAcceleration * deltatime;
        try {
            Orientation *= Quaternion.Euler(AngularVelocity * deltatime);
        } catch (System.Exception) {
            DeveloppmentTools.Log("Angular Velocity: " + AngularVelocity);
        }
    }
Exemple #12
0
 public ArmorGeometryData(Vector3[] pkeypos, float[] pradii, float[] pthicknesses, int presolution)
 {
     size       = pkeypos.Length;
     resolution = presolution;
     if (pradii.Length != size || pthicknesses.Length != size)
     {
         DeveloppmentTools.Log("The arrays for armor hav to have the following length pattern: length(key positions) = length(radii) = length(thickness)");
         keypos = new Vector3 [0];
         radii  = thicknesses = new float [0];
         return;
     }
     keypos      = pkeypos;
     radii       = pradii;
     thicknesses = pthicknesses;
 }
Exemple #13
0
    private void Awake()
    {
        NotLoadingRelated();
        if (!SceneGlobals.is_save)
        {
            PreLoading();
            loader.attack_data = new AttackData(Vector3.forward, new Vector3(0, 100, -200));
            loader.LoadEssentials();
            loader.LoadObjects();
            NextCommand();
        }
        PostLoading();

        Debug.Log(DeveloppmentTools.LogIterable(SceneObject.TotObjectList));
    }
Exemple #14
0
 /// <summary> Finishes a conversation </summary>
 private void Exit()
 {
     DeveloppmentTools.Log("Exit coversation");
     if (console != null)
     {
         console.current_conversation = Null;
     }
     if (SceneGlobals.general != null && SceneGlobals.general.gameObject)
     {
         SceneGlobals.general.NextCommand();
     }
     else if (CampagneManager.active != null && CampagneManager.active.gameObject)
     {
         CampagneManager.active.ExitConversation();
     }
 }
Exemple #15
0
    public override void PhysicsUpdate(float p_deltatime)
    {
        deltatime = p_deltatime;

        Velocity           += Acceleration;
        Transform.position += Velocity * deltatime;

        AngularVelocity += AngularAcceleration;
        try {
            Transform.position += Orientation * offset;
            Orientation        *= Quaternion.Euler(AngularVelocity * deltatime);
            Transform.position -= Orientation * offset;
        } catch (System.Exception) {
            DeveloppmentTools.Log("Angular Velocity: " + AngularVelocity);
        }
    }
Exemple #16
0
    private void Awake()
    {
        // Make this persistent
        if (GameObject.FindGameObjectsWithTag("Persistent").Length > 1)
        {
            Destroy(gameObject);
            return;
        }
        DontDestroyOnLoad(gameObject);
        Globals.persistend = this;

        var sound_coll = new SoundCollection("sounds");

        SetCursor();
        UpdateOnMenu();

        Volumes.Initialize(Globals.settings.GetChild("sound volume"));
        DeveloppmentTools.Testing();
    }
    public void LoadShipParts()
    {
        // Find all assemblies
        string path = Globals.plugin_path + "/ShipParts";

        string[] dll_file_names = null;
        if (Directory.Exists(path))
        {
            dll_file_names = Directory.GetFiles(path, "*.dll");
        }
        else
        {
            DeveloppmentTools.Log("No such path: " + path);
        }

        // load assemblies
        foreach (string dllname in dll_file_names)
        {
            AssemblyName an       = AssemblyName.GetAssemblyName(dllname);
            Assembly     assembly = Assembly.Load(an);

            if (assembly != null)
            {
                foreach (Type type in assembly.GetTypes())
                {
                    if (type.IsInterface || type.IsAbstract)
                    {
                        goto CONTINUE_;
                    }
                    if (type.BaseType == typeof(ShipPart))
                    {
                        ship_parts.Add(type);
                    }
                }
            }
            CONTINUE_ :;
        }
    }
Exemple #18
0
    /// <summary> Loads a battle </summary>
    public void LoadBattle(string battle_name)
    {
        TerminateScene();
        if (!Globals.battle_list.ContainsChild(battle_name))
        {
            return;
        }
        DataStructure battle_inforamtion = Globals.battle_list.GetChild(battle_name);
        string        battle_file        = battle_inforamtion.Get <string>("path");

        DataStructure battle_data = DataStructure.Load(battle_file, "battle_data", is_general: true);

        if (battle_data == null)
        {
            DeveloppmentTools.Log(battle_file + " does not exist");
        }

        SceneGlobals.is_save = false;
        SceneManager.LoadScene(sceneName: "battlefield");
        loader = new Loader(battle_data)
        {
            path = battle_file
        };
    }
Exemple #19
0
    public static void Load(string path)
    {
        DataStructure saved = DataStructure.Load(path);
        DataStructure general_information = saved.GetChild("GeneralInformation");
        DataStructure original_file       = DataStructure.Load(general_information.Get <string>("original_path"), is_general: true);

        FileReader.FileLog("Begin Loading", FileLogType.loader);
        GameObject       placeholder = GameObject.Find("Placeholder");
        GeneralExecution general     = placeholder.GetComponent <GeneralExecution>();

        general.battle_path = path;

        // Initiate Operating system
        general.os = new NMS.OS.OperatingSystem(Object.FindObjectOfType <ConsoleBehaviour>(), null);

        // Initiate mission core
        Loader partial_loader = new Loader(original_file);

        general.mission_core = new MissionCore(general.console, partial_loader);

        general.mission_core.in_level_progress = (short)general_information.Get <int>("in level progress");
        general.mission_core.in_stage_progress = (short)general_information.Get <int>("in stage progress");
        DeveloppmentTools.Log("start loading");
        partial_loader.LoadEssentials();

        DataStructure objects = saved.GetChild("ObjectStates");

        Debug.Log(objects);
        foreach (DataStructure child in objects.AllChildren)
        {
            int id = child.Get <ushort>("type", 1000, quiet: true);
            switch (id)
            {
            case 0:
                // Ship
                Dictionary <string, Turret[]> weapon_arrays = new Dictionary <string, Turret[]>();

                string     config_path  = child.Get <string>("config path");
                bool       is_friendly  = child.Get <bool>("friendly");
                bool       is_player    = child.Get <bool>("player");
                int        given_id     = child.Get <int>("id");
                GameObject ship_chassis = Loader.SpawnShip(config_path, is_friendly, is_player, false, pre_id: given_id);

                //LowLevelAI ai = Loader.EnsureComponent<LowLevelAI>(ship_chassis);
                //ai.HasHigherAI = !is_player;

                ShipControl ship_control = ship_chassis.GetComponent <ShipControl>();
                Ship        ship         = ship_control.myship;
                //ship.control_script.ai_low = ai;
                //ship.low_ai = ai;

                int netID = child.Get("parent network", is_friendly ? 1 : 2);
                if (SceneObject.TotObjectList.ContainsKey(netID) && SceneObject.TotObjectList [netID] is Network)
                {
                    ship.high_ai.Net = SceneObject.TotObjectList [netID] as Network;
                }

                ship.Position        = child.Get <Vector3>("position");
                ship.Orientation     = child.Get <Quaternion>("orientation");
                ship.Velocity        = child.Get <Vector3>("velocity");
                ship.AngularVelocity = child.Get <Vector3>("angular velocity");

                foreach (DataStructure child01 in child.AllChildren)
                {
                    switch (child01.Get <ushort>("type", 9, quiet:true))
                    {
                    case 1:                     // weapon
                        Weapon.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 3:                     // fuel tank
                        FuelTank.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 4:                     // engine
                        Engine.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 10:                     // ammo box
                        AmmoBox.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 11:                     // missile launcher
                        MissileLauncher.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 12:                     // armor
                        Armor.GetFromDS(child01, ship);
                        break;

                    default:
                        if (child01.Name.StartsWith("turr-"))
                        {
                            var tg = TurretGroup.Load(child01, ship);
                            weapon_arrays [child01.Name.Substring(5)] = tg.TurretArray;
                            ship_control.turretgroup_list.Add(new TurretGroup(Target.None, tg.TurretArray, tg.name)
                            {
                                own_ship = ship
                            });
                        }
                        break;
                    }
                }


                // Initializes parts
                foreach (BulletCollisionDetection part in ship_chassis.GetComponentsInChildren <BulletCollisionDetection>())
                {
                    part.Initialize();
                }
                ship_control.turrets = weapon_arrays;

                ship.os.cpu.Execute(child.Get <ulong []>("code"));

                if (is_player)
                {
                    SceneGlobals.Player = ship;
                    SceneGlobals.ui_script.Start_();
                }

                break;

            case 1:             // Missile
                Missile.SpawnFlying(child);
                break;

            case 2:             // Bullet
                Bullet.Spawn(
                    Globals.ammunition_insts [child.Get <string>("ammunition")],
                    child.Get <Vector3>("position"),
                    Quaternion.FromToRotation(Vector3.forward, child.Get <Vector3>("velocity")),
                    child.Get <Vector3>("velocity"),
                    child.Get <bool>("is_friend")
                    );
                break;

            case 3:             // Destroyable target
                DestroyableTarget.Load(child);
                break;

            case 4:             // Explosion

                break;
            }
        }

        general.os.Attached = SceneGlobals.Player;

        ReferenceSystem ref_sys;

        if (general_information.Contains <Vector3>("RS position"))
        {
            ref_sys = new ReferenceSystem(general_information.Get <Vector3>("RS position"));
        }
        else
        {
            int parent_id = general_information.Get <int>("RS parent");
            if (SceneObject.TotObjectList.ContainsKey(parent_id))
            {
                ref_sys = new ReferenceSystem(SceneObject.TotObjectList [parent_id]);
            }
            else
            {
                ref_sys = new ReferenceSystem(Vector3.zero);
            }
            ref_sys.Offset = general_information.Get <Vector3>("RS offset");
        }
        SceneGlobals.ReferenceSystem = ref_sys;
    }
 /// <summary> Throws an error </summary>
 /// <param name="message"> The error in question </param>
 public static void Throw(string message)
 {
     DeveloppmentTools.Log(message);
 }
Exemple #21
0
 public override string ToString()
 {
     return(DeveloppmentTools.LogIterable(AllParts));
 }
Exemple #22
0
        /// <summary> Takes an input and processes it like a CPU </summary>
        /// <param name="arguments"> The input as a ulong form bytes. For further information see the remarque </param>
        /// <remarks>
        ///		Content of command |	pointers?			\
        ///		[-------------]	 [-----] X V V V			|		X -> float flag : indicates, wheter operations are float operations
        ///		0 0 0 0 0 0 0 0  0 0 0 0 0 0 0 0			|
        ///						 Importance					|
        ///		Content of a								|
        ///		[------------------------------]			|
        ///		0 0 0 0 0 0 0 0  0 0 0 0 0 0 0 0			|
        ///													 >- 64-bit integer (ulong)
        ///		Content of b								|
        ///		[------------------------------]			|
        ///		0 0 0 0 0 0 0 0  0 0 0 0 0 0 0 0			|
        ///													|
        ///		Content of c								|
        ///		[------------------------------]			|
        ///		0 0 0 0 0 0 0 0  0 0 0 0 0 0 0 0			/
        /// </remarks>
        public void Execute(ulong [] code)
        {
            bool running = true;
            var  t0      = DateTime.Now;

            for (int i = 0; running& i < code.Length; i++)
            {
                ulong  arguments = code [i];
                ushort arg3      = (arguments >> 0x30) % 2 == 1 ? ram[(int)((arguments >> 0x00) % 0x10000)] : (ushort)((arguments >> 0x00) % 0x10000);
                ushort arg2      = (arguments >> 0x31) % 2 == 1 ? ram[(int)((arguments >> 0x10) % 0x10000)] : (ushort)((arguments >> 0x10) % 0x10000);
                ushort arg1      = (arguments >> 0x32) % 2 == 1 ? ram[(int)((arguments >> 0x20) % 0x10000)] : (ushort)((arguments >> 0x20) % 0x10000);
                ushort arg0      = (ushort)(arguments >> 0x38);
                //UnityEngine.Debug.LogFormat("{0} -> {1:x}", (OS.AssemblyCommands) arg0, arguments);

                float importance = ((arguments >> 0x34) % 16) / 15f;
                bool  is_float   = (arguments >> 0x33) % 2 == 1;
                switch (arg0)
                {
                // 0x00 - 0x0f: Simple operations
                case 0x00:
                    // NULL - NUL
                    goto ENDCOMMAND;

                case 0x01:
                    // Assign a -> &b || SET
                    ram [arg2] = arg1;
                    goto ENDCOMMAND;

                case 0x02:
                    // End the programm; No arguments || END
                    running = false;
                    goto ENDCOMMAND;

                case 0x03:
                    // Float &a to Integer || F2I
                    ram [arg1] = (ushort)RAM.Short2Float(arg1);
                    goto ENDCOMMAND;

                case 0x04:
                    // Integer &a to float || I2F
                    ram [arg1] = RAM.Float2Short((float)arg1);
                    goto ENDCOMMAND;

                // 0x10 - 0x1f: Simple logic
                case 0x10:
                    // go to line a || JMP
                    i = arg1 - 1;
                    goto ENDCOMMAND;

                case 0x11:
                    // if a == b: go to line c || JEQ
                    if (arg1 == arg2)
                    {
                        i = arg3 - 1;
                    }
                    goto ENDCOMMAND;

                case 0x12:
                    // if a > b: go to line c || JGT
                    if (is_float)
                    {
                        if (arg1 > arg2)
                        {
                            i = arg3 - 1;
                        }
                    }
                    else
                    {
                        if (RAM.Short2Float(arg1) > RAM.Short2Float(arg2))
                        {
                            i = arg3 - 1;
                        }
                    }
                    goto ENDCOMMAND;

                case 0x13:
                    // if a >= b: go to line c || JGE
                    if (is_float)
                    {
                        if (arg1 >= arg2)
                        {
                            i = arg3 - 1;
                        }
                    }
                    else
                    {
                        if (RAM.Short2Float(arg1) >= RAM.Short2Float(arg2))
                        {
                            i = arg3 - 1;
                        }
                    }
                    goto ENDCOMMAND;

                // 0x20 - 0x2f: Mathematical operations
                case 0x20:
                    // Addition a + b -> &c || ADD
                    ram [arg3] = is_float ? RAM.Float2Short(RAM.Short2Float(arg1) + RAM.Short2Float(arg2)) : (ushort)(arg1 + arg2);
                    //UnityEngine.Debug.LogFormat("{0} + {1} = {2}", arg1, arg2, is_float ? RAM.Float2Short(RAM.Short2Float(arg1) + RAM.Short2Float(arg2)) : (ushort) (arg1 + arg2));
                    goto ENDCOMMAND;

                case 0x21:
                    // Substraction a - b -> &c || SUB
                    ram [arg3] = is_float ? RAM.Float2Short(RAM.Short2Float(arg1) - RAM.Short2Float(arg2)) : (ushort)(arg1 - arg2);
                    goto ENDCOMMAND;

                case 0x22:
                    // Multiplication a * b -> &c || MUL
                    ram [arg3] = is_float ? RAM.Float2Short(RAM.Short2Float(arg1) * RAM.Short2Float(arg2)) : (ushort)(arg1 * arg2);
                    goto ENDCOMMAND;

                case 0x23:
                    // Integer Division a / b -> &c || DIV
                    ram [arg3] = is_float ? RAM.Float2Short(RAM.Short2Float(arg1) / RAM.Short2Float(arg2)) : (ushort)(arg1 / arg2);
                    goto ENDCOMMAND;

                // 0x40 - 0x4f: console functions
                case 0x40:
                    // Print from &a, length b on console || PRT
                    if (arg1 + arg2 > ram.size)
                    {
                        Error("Buffer overflow", i);
                    }

                    char[] characters = new char[arg2 * 2];
                    for (uint j = 0u; j < arg2; j++)
                    {
                        ushort nums = ram[arg1 + j];
                        characters [2 * j]     = (char)(nums >> 8);
                        characters [2 * j + 1] = (char)(nums % 0x100);
                    }
                    string word = new string(characters);
                    Output += word;
                    goto ENDCOMMAND;

                case 0x41:
                    // Save Input, beginning from a || INP
                    string word_ = Input;
                    if (arg1 + word_.Length / 2 > ram.size)
                    {
                        Error("Buffer overflow", i);
                    }

                    for (uint j = 0u; j < word_.Length; j += 2)
                    {
                        ram [arg0 + j / 2] = (ushort)(word_ [(int)j] + word_ [(int)j] << 8);
                    }
                    goto ENDCOMMAND;

                case 0x42:
                    // ClearScreen; No arguments || CLS
                    Output = string.Empty;
                    goto ENDCOMMAND;

                // 0x80 - 0x8f : Movement Control
                case 0x80:
                    // Turn with RCS: euler angles: (a / 100, b / 100, c / 100)
                    AI.ApplyTurn(new UnityEngine.Vector3(RAM.Short2Float(arg1), RAM.Short2Float(arg2), RAM.Short2Float(arg3)), importance);
                    goto ENDCOMMAND;

                case 0x81:
                    // Thrust with RCS: Δv-vector: (a / 100, b / 100, c / 100)
                    AI.RCSThrust(new UnityEngine.Vector3(RAM.Short2Float(arg1), RAM.Short2Float(arg2), RAM.Short2Float(arg3)));
                    goto ENDCOMMAND;

                case 0x82:
                    // Engine Acceleration: Δv-vector: (a / 100, b / 100, c / 100)
                    AI.Thrust(new UnityEngine.Vector3(RAM.Short2Float(arg1), RAM.Short2Float(arg2), RAM.Short2Float(arg3)));
                    goto ENDCOMMAND;

                case 0x83:
                    // Hold Orientation: time: a / 10 seconds
                    AI.movement_quack.PushBack(AIMouvementCommand.HoldOrientation(RAM.Short2Float(arg1), ship));
                    goto ENDCOMMAND;

                case 0x84:
                    // Lock target: time: a / 10
                    AI.movement_quack.PushBack(AIMouvementCommand.HoldOrientation(RAM.Short2Float(arg1), ship));
                    goto ENDCOMMAND;

                // 0x90 - 0x9f : Ship actions
                case 0x90:
                    // Shoot turretgroup number a at aim
                    AI.action_list.Add(AIActionCommand.ShootTG(ship.TurretGroups[arg1], ship.TurretAim));
                    goto ENDCOMMAND;

                case 0x91:
                    // Shoot fixed weapon number a at euler_angle rotation (b, c, 0)
                    AI.action_list.Add(AIActionCommand.FireMain(ship.TurretAim));
                    goto ENDCOMMAND;

                case 0x92:
                    // Shoot missile at target_id a
                    goto ENDCOMMAND;

                // 0xa0 - 0x9f : Complex/Ship related general commands
                case 0xa0:
                    // Wait for a / 10 seconds
                    AI.movement_quack.PushBack(AIMouvementCommand.Wait(RAM.Short2Float(arg1)));
                    goto ENDCOMMAND;
                }
ENDCOMMAND:
                if ((DateTime.Now - t0).Seconds > 3)
                {
                    DeveloppmentTools.Log("Simulated CPU processor jumpout");
                    return;
                }
            }
        }
Exemple #23
0
    public static void Save()
    {
        GeneralExecution general = SceneGlobals.general;

        System.DateTime t0 = System.DateTime.Now;
        DataStructure   save_datastructure = new DataStructure();

        DataStructure general_information = new DataStructure("GeneralInformation", save_datastructure);

        general_information.Set("original_path", general.battle_path);
        general_information.Set("in level progress", (int)general.mission_core.in_level_progress);
        general_information.Set("in stage progress", (int)general.mission_core.in_stage_progress);

        ReferenceSystem ref_sys = SceneGlobals.ReferenceSystem;

        if (ref_sys.HasParent)
        {
            general_information.Set("RS offset", ref_sys.Offset);
            general_information.Set("RS parent", ref_sys.ref_obj.ID);
        }
        else
        {
            general_information.Set("RS position", ref_sys.Position);
        }

        SceneObject[]       scene_array     = new SceneObject[SceneObject.TotObjectList.Count];
        Explosion[]         explosion_array = new Explosion[SceneGlobals.explosion_collection.Count];
        Bullet[]            bullet_array    = new Bullet[SceneGlobals.bullet_collection.Count];
        DestroyableTarget[] target_array    = new DestroyableTarget[SceneGlobals.destroyables.Count];

        SceneObject.TotObjectList.Values.CopyTo(scene_array, 0);
        SceneGlobals.bullet_collection.CopyTo(bullet_array);
        SceneGlobals.destroyables.CopyTo(target_array);

        scene_array = System.Array.FindAll(scene_array,
                                           x =>
                                           !(x is Missile && !(x as Missile).Released) &&
                                           !(x is Network && (x as Network).Name == "\"friendly rogue\"-Network" | (x as Network).Name == "\"hostile rogue\"-Network") &&
                                           !(x is Target)
                                           );

        ISavable[] savable_objects = new ISavable[scene_array.Length +
                                                  explosion_array.Length +
                                                  bullet_array.Length +
                                                  target_array.Length];

        int indx = 0;

        System.Array.ConvertAll(scene_array, x => x as ISavable).CopyTo(savable_objects, indx);
        indx += scene_array.Length;
        System.Array.ConvertAll(explosion_array, x => x as ISavable).CopyTo(savable_objects, indx);
        indx += explosion_array.Length;
        System.Array.ConvertAll(bullet_array, x => x as ISavable).CopyTo(savable_objects, indx);
        indx += bullet_array.Length;
        System.Array.ConvertAll(target_array, x => x as ISavable).CopyTo(savable_objects, indx);

        DataStructure object_states = new DataStructure("ObjectStates", save_datastructure);

        foreach (ISavable obj in savable_objects)
        {
            if (obj != null)
            {
                DataStructure ds = new DataStructure(obj.Name, object_states);
                obj.Save(ds);
            }
        }

        //save_datastructure.Save("saved/Saves/" + System.DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss"));
        save_datastructure.Save("saved/Saves/def_save");
        DeveloppmentTools.LogFormat("Saved: {0} ms", (System.DateTime.Now - t0).Milliseconds.ToString());
    }
Exemple #24
0
    /// <summary> Generates the mesh </summary>
    /// <remarks> Needs 0.028ms per edge (inner and outer) at resolution = 32 </remarks>
    private void GetMesh()
    {
        Vector3 [] key_pos     = geometry.keypos;
        float []   radii       = geometry.radii;
        float []   thicknesses = geometry.thicknesses;
        int        resolution  = geometry.resolution;
        int        size        = geometry.size;

        if (key_pos.Length != radii.Length || key_pos.Length != thicknesses.Length)
        {
            DeveloppmentTools.Log("The arrays for armor hav to have the following length pattern: length(key positions) = length(radii) = length(thickness)");
        }

        Main = new Mesh();
        outer_collider_mesh = new Mesh();
        inner_collider_mesh = new Mesh();

        Vector3[] mesh_vertecies     = new Vector3[resolution * 2 * size];
        Vector2[] uv1                = new Vector2[resolution * 2 * size];
        int[]     outer_triangles    = new int[resolution * 6 * (size - 1)];
        int[]     inner_triangles    = new int[resolution * 6 * (size + 1)];
        Vector3[] outerCol_vertecies = new Vector3[resolution * size];
        Vector3[] innerCol_vertecies = new Vector3[resolution * size];
        Vector2[] col_uv             = new Vector2[resolution * size];
        int[]     col_triangles      = new int[(resolution + 2) * 6 * (size - 1) - 6];

        int   collider_tri_index = 0, main_tri_index = 0;
        float max_rad = 0;

        for (int i = 0; i < size; i++)
        {
            if (radii [i] > max_rad)
            {
                max_rad = radii [i];
            }
        }

        // For uv2 mapping
        float x_step = 1f / size;
        float y_step = 1f / resolution;

        //Vector3 normal;
        int   vert1, vert2, vert3, vert4;
        float inclination_ratio = 0;
        int   curr_x            = 0;

        for (int i = 0; i < size; i++)
        {
            if (i != size - 1)
            {
                // Calculate volume
                float outer_rad1 = radii[i];
                float outer_rad2 = radii[i + 1];
                float inner_rad1 = radii[i] - thicknesses[i];
                float inner_rad2 = radii[i + 1] - thicknesses[i + 1];
                float V          = .3333f * Vector3.Distance(key_pos[i], key_pos[i + 1]) * (outer_rad1 * outer_rad1 + outer_rad2 * outer_rad2 - outer_rad1 * outer_rad2
                                                                                            - inner_rad1 * inner_rad1 - inner_rad2 * inner_rad2 + inner_rad1 * inner_rad2);
                Volume           += V;
                inclination_ratio = (radii[i] - radii[i + 1]) / (Vector3.Distance(key_pos[i], key_pos[i + 1]) * (key_pos[i].z < key_pos[i + 1].z ? 1 : -1));
            }

            if (i != 0)
            {
                // Subdivisions
                float ideal_dist = (radii[i - 1] + radii[i]) * Mathf.PI / resolution;
                float whole_d    = Vector3.Distance(key_pos[i - 1], key_pos[i]);
                curr_x += (int)Mathf.Round(whole_d / ideal_dist);
            }

            // Calculate vertex positions
            Vector3[] circle_inner = GetPointsInCircle(resolution, radii[i] - thicknesses[i], Vector3.forward);
            Vector3[] circle_outer = GetPointsInCircle(resolution, radii[i], Vector3.forward);
            Vector2[] uv_tot       = new Vector2[resolution * 2];

            Vector3 pos = key_pos[i] - offset;

            int init_vert_indx     = i * 2 * resolution;
            int col_init_vert_indx = i * resolution;
            for (int j = 0; j < resolution; j++)
            {
                // UV Mapping
                uv_tot [j] = new Vector2(i * x_step, j * y_step);

                // Adjust vertex positions
                circle_inner [j] += pos;
                circle_outer [j] += pos;

                // Calculate triangles
                bool j_end = j == resolution - 1;
                if (i != size - 1)
                {
                    // Colliders
                    vert1 = col_init_vert_indx + j;
                    vert2 = col_init_vert_indx + resolution + j;
                    vert3 = col_init_vert_indx + (j_end ? 0 : j + 1);
                    vert4 = col_init_vert_indx + resolution + (j_end ? 0 : j + 1);
                    col_triangles [collider_tri_index++] = vert1;
                    col_triangles [collider_tri_index++] = vert2;
                    col_triangles [collider_tri_index++] = vert3;
                    col_triangles [collider_tri_index++] = vert3;
                    col_triangles [collider_tri_index++] = vert2;
                    col_triangles [collider_tri_index++] = vert4;

                    // Inner
                    vert1 = init_vert_indx + j;
                    vert2 = init_vert_indx + resolution * 2 + j;
                    vert3 = init_vert_indx + (j_end ? 0 : j + 1);
                    vert4 = init_vert_indx + resolution * 2 + (j_end ? 0 : j + 1);
                    inner_triangles [main_tri_index++] = vert2;
                    inner_triangles [main_tri_index++] = vert1;
                    inner_triangles [main_tri_index++] = vert3;
                    inner_triangles [main_tri_index++] = vert2;
                    inner_triangles [main_tri_index++] = vert3;
                    inner_triangles [main_tri_index++] = vert4;

                    // Outer
                    vert1 = init_vert_indx + resolution + j;
                    vert2 = init_vert_indx + resolution * 3 + j;
                    vert3 = init_vert_indx + resolution + (j_end ? 0 : j + 1);
                    vert4 = init_vert_indx + resolution * 3 + (j_end ? 0 : j + 1);
                    outer_triangles [main_tri_index - 6] = vert1;
                    outer_triangles [main_tri_index - 5] = vert2;
                    outer_triangles [main_tri_index - 4] = vert3;
                    outer_triangles [main_tri_index - 3] = vert3;
                    outer_triangles [main_tri_index - 2] = vert2;
                    outer_triangles [main_tri_index - 1] = vert4;
                }
            }

            // Copy vertex positions
            System.Array.Copy(circle_inner, 0, mesh_vertecies, resolution * 2 * i, resolution);
            System.Array.Copy(circle_outer, 0, mesh_vertecies, resolution * (2 * i + 1), resolution);
            System.Array.Copy(circle_inner, 0, innerCol_vertecies, resolution * i, resolution);
            System.Array.Copy(circle_outer, 0, outerCol_vertecies, resolution * i, resolution);
            System.Array.Copy(uv_tot, 0, uv1, resolution * 2 * i, resolution);
            System.Array.Copy(uv_tot, 0, uv1, resolution * (2 * i + 1), resolution);
            System.Array.Copy(uv_tot, 0, col_uv, resolution * i, resolution);
        }

        int vert_indx = 2 * resolution * (size - 1);

        for (int j = 0; j < resolution; j++)
        {
            // Calculate triangles
            bool j_end = j == resolution - 1;
            vert1 = j;
            vert2 = resolution + j;
            vert3 = (j_end ? 0 : j + 1);
            vert4 = resolution + (j_end ? 0 : j + 1);
            inner_triangles [main_tri_index++] = vert1;
            inner_triangles [main_tri_index++] = vert2;
            inner_triangles [main_tri_index++] = vert3;
            inner_triangles [main_tri_index++] = vert3;
            inner_triangles [main_tri_index++] = vert2;
            inner_triangles [main_tri_index++] = vert4;

            vert1 = vert_indx + j;
            vert2 = vert_indx + resolution + j;
            vert3 = vert_indx + (j_end ? 0 : j + 1);
            vert4 = vert_indx + resolution + (j_end ? 0 : j + 1);
            inner_triangles [main_tri_index++] = vert1;
            inner_triangles [main_tri_index++] = vert2;
            inner_triangles [main_tri_index++] = vert3;
            inner_triangles [main_tri_index++] = vert3;
            inner_triangles [main_tri_index++] = vert2;
            inner_triangles [main_tri_index++] = vert4;

            // Calculate collider ends
            if (j != 0 && j != resolution - 1)
            {
                col_triangles [collider_tri_index++] = 0;
                col_triangles [collider_tri_index++] = j;
                col_triangles [collider_tri_index++] = j + 1;

                col_triangles [collider_tri_index++] = resolution * (size - 1);
                col_triangles [collider_tri_index++] = resolution * (size - 1) + j + 1;
                col_triangles [collider_tri_index++] = resolution * (size - 1) + j;
            }
        }

        Main.name         = "armor_mesh";
        Main.subMeshCount = 2;
        Main.vertices     = mesh_vertecies;
        Main.SetTriangles(outer_triangles, 0);
        Main.SetTriangles(inner_triangles, 1);
        Main.uv = uv1;
        Main.RecalculateNormals();

        inner_collider_mesh.name      = "inner collider mesh";
        inner_collider_mesh.vertices  = innerCol_vertecies;
        inner_collider_mesh.triangles = col_triangles;
        inner_collider_mesh.uv        = col_uv;
        inner_collider_mesh.RecalculateNormals();

        outer_collider_mesh.name     = "outer collider mesh";
        outer_collider_mesh.vertices = outerCol_vertecies;

        for (int i = 0; i < outer_collider_mesh.normals.Length; i++)
        {
            Debug.DrawRay(outer_collider_mesh.vertices [i] + offset, outer_collider_mesh.normals [i], Color.cyan, float.PositiveInfinity);
        }

        outer_collider_mesh.triangles = col_triangles;
        outer_collider_mesh.uv        = col_uv;
    }
    /// <summary>
    ///		Executes an event in the level once
    /// </summary>
    /// <param name="data"> The Datastructure containing the information about the event </param>
    private void StoryCommand(DataStructure data)
    {
        switch (data.Name)
        {
        case "get conversation":
            FileReader.FileLog("Begin Conversation", FileLogType.story);
            ushort id = data.Get <ushort>("ID");
            new Conversation(conversations [id - 1], console)
            {
                Running = true
            };
            console.ConsolePos = ConsolePosition.shown;
            break;

        case "spawn":
            string[] types = data.Get <string[]>("types");
            string[] names = data.Get <string[]>("names");
            if (types.Length != names.Length)
            {
                DeveloppmentTools.Log("length of \"types\" array must be the same as length of \"names\" array");
            }
            for (int i = 0; i < types.Length; i++)
            {
                loader.Spawn(types[i], names[i]);
            }
            NextCommand();
            break;

        case "objective":
            // Todo: Check compleateness
            Objectives obj_type; Target [] obj_targets;
            string []  objective_specs = data.Get <string>("objective type").Split(' ');
            // What to do with the target?
            switch (objective_specs [0])
            {
            case "kill":
                obj_type = Objectives.destroy;
                break;

            case "escort":
                obj_type = Objectives.escort;
                break;

            case "hack":
                obj_type = Objectives.hack;
                break;

            default:
                obj_type = Objectives.none;
                break;
            }
            string obj_name = data.Get <string>("target name");
            // Which target is it?
            switch (objective_specs [1])
            {
            case "squadron":
                if (!squads.ContainsKey(obj_name))
                {
                    DeveloppmentTools.Log("LOADER - no such sqadron in the scene" + obj_name);
                }
                obj_targets = System.Array.ConvertAll(squads [obj_name], s => s.Associated);
                break;

            case "target":
                if (!single_targets.ContainsKey(obj_name))
                {
                    DeveloppmentTools.Log("LOADER - no such target in the scene: " + obj_name);
                }
                Target selected_target = single_targets[obj_name].Associated;
                obj_targets = new Target [1] {
                    selected_target
                };
                break;

            default:
                obj_targets = new Target[0];
                break;
            }
            Objective objective = new Objective()
            {
                objective_type = obj_type, targets = obj_targets
            };
            tracker.NewObjective(objective);
            return;

        case "goto":
            FileReader.FileLog("Go to story num " + data.Get <ushort>("stage").ToString(), FileLogType.story);
            in_level_progress = (short)(data.Get <ushort>("stage"));
            in_stage_progress = -1;
            NextCommand();
            return;

        case "finish mission":
            bool won = data.Get <bool>("won");
            SceneGlobals.general.EndBattle(won);
            return;
        }
    }
    public void SelectorClicked(SelectorButton button)
    {
        SubSelector concerned = button.parent as SubSelector;

        if (concerned == null)
        {
            return;
        }
        byte option = button.num;

        bool multiple = concerned.targets.Length > 1;

        for (int i = 0; i < concerned.targets.Length; i++)
        {
            // Check Flags
            if (i != 0 && (button.flags >> 1) % 2 == 0)
            {
                // single vessel only
                goto LOOPEND;
            }
            if (i == 0 && button.flags % 2 == 1)
            {
                // use pinlabel
                Debug.Log(DeveloppmentTools.LogIterable(concerned.targets));
                concerned_objects = concerned.targets;
                lasting_command   = button.function;
            }

            IMarkerParentObject parentObject = concerned.targets[i];
            var ship = parentObject as Ship;

            SelectorOptions options = concerned.options;

            switch (button.function)
            {
//  +-----------------------------------------------------------------------------------------------------------------------+
//	|									Reference																			|
//  +-----------------------------------------------------------------------------------------------------------------------+
            case 0x0c:
// Set Camera ---------------------------------------------------------------------------------------------------------------
                SceneGlobals.ReferenceSystem.Offset += parentObject.Position - SceneGlobals.ReferenceSystem.Position;
                goto LOOPEND;

            case 0x0d:
// Set Reference ------------------------------------------------------------------------------------------------------------
                SceneGlobals.map_core.CurrentSystem = new ReferenceSystem(parentObject.Position);
                goto LOOPEND;

            case 0x0e:
// Lock Reference -----------------------------------------------------------------------------------------------------------
                Vector3     offset    = Vector3.zero;
                SceneObject scene_obj = parentObject as SceneObject;
                if (parentObject is SceneObject)
                {
                    offset = SceneGlobals.ReferenceSystem.Position - scene_obj.Position;
                    SceneGlobals.ReferenceSystem = new ReferenceSystem(scene_obj);
                }
                else if (parentObject is ITargetable)
                {
                    offset = SceneGlobals.ReferenceSystem.Position - parentObject.Position;
                    Target tgt = (parentObject as ITargetable).Associated;
                    SceneGlobals.ReferenceSystem = new ReferenceSystem(tgt);
                }

                SceneGlobals.ReferenceSystem.Offset = offset;
                goto LOOPEND;

            case 0x0f:
// Lock & Set ---------------------------------------------------------------------------------------------------------------
                if (parentObject is SceneObject)
                {
                    SceneGlobals.ReferenceSystem = new ReferenceSystem(parentObject as SceneObject);
                }
                else if (parentObject is ITargetable)
                {
                    SceneGlobals.ReferenceSystem = new ReferenceSystem((parentObject as ITargetable).Associated);
                }
                goto LOOPEND;

            case 0x19:
// Match Velocity Closest ---------------------------------------------------------------------------------------------------
                if (parentObject is ITargetable)
                {
                    foreach (IMarkerParentObject impo in MapCore.Active.selection)
                    {
                        Ship ship01 = impo as Ship;
                        if (ship01 != null && ship01.Friendly)
                        {
                            ship01.low_ai.MatchVelocityNearTarget((parentObject as ITargetable).Associated);
                        }
                    }
                }
                goto LOOPEND;

            case 0x1a:
// Match Velocity -----------------------------------------------------------------------------------------------------------
                if (parentObject is IPhysicsObject)
                {
                    foreach (IMarkerParentObject impo in MapCore.Active.selection)
                    {
                        Ship ship01 = impo as Ship;
                        if (ship01 != null && ship01.Friendly)
                        {
                            ship01.low_ai.MatchVelocity((parentObject as ITargetable).Associated);
                        }
                    }
                }
                goto LOOPEND;

            case 0x1b:
// Attack -------------------------------------------------------------------------------------------------------------------
                if (parentObject is ITargetable)
                {
                    Target self_tgt = (parentObject as ITargetable).Associated;
                    foreach (IMarkerParentObject impo in MapCore.Active.selection)
                    {
                        Ship ship01 = impo as Ship;
                        if (ship01 != null && ship01.Friendly)
                        {
                            ship01.low_ai.Attack(self_tgt);
                        }
                    }
                }
                goto LOOPEND;

            case 0x1c:
// TurretAttack -------------------------------------------------------------------------------------------------------------
                if (parentObject is ITargetable)
                {
                    Target self_tgt = (parentObject as ITargetable).Associated;
                    foreach (IMarkerParentObject impo in MapCore.Active.selection)
                    {
                        Ship ship01 = impo as Ship;
                        if (ship01 != null && ship01.Friendly)
                        {
                            ship01.low_ai.TurretAttack(self_tgt);
                        }
                    }
                }
                goto LOOPEND;

            case 0x1d:
// Aim Here -----------------------------------------------------------------------------------------------------------------
                SceneGlobals.Player.TurretAim = parentObject;
                goto LOOPEND;

            case 0x1e:
// Target Part --------------------------------------------------------------------------------------------------------------

                goto LOOPEND;

            case 0x1f:
// Set Target ---------------------------------------------------------------------------------------------------------------
                if (parentObject is ITargetable)
                {
                    Target tgt = (parentObject as ITargetable).Associated;
                    SceneGlobals.Player.Target = tgt;
                }
                goto LOOPEND;

//  +-----------------------------------------------------------------------------------------------------------------------+
//  |										Info																			|
//  +-----------------------------------------------------------------------------------------------------------------------+
            case 0x2e:
// Ship Information ---------------------------------------------------------------------------------------------------------
                if (i != 0)
                {
                    goto LOOPEND;
                }
                concerned.SpawnChild("Ship Information", new string [] {
                    ship.Mass.ToString("Mass: 0.0 t"),
                    string.Format("HP: {0:0.0} / {1:0.0}", ship.HP, ship.tot_hp),
                });
                goto LOOPEND;

            case 0x2f:
// OS -----------------------------------------------------------------------------------------------------------------------
                goto LOOPEND;
//  +-----------------------------------------------------------------------------------------------------------------------+
//  |									Command																				|
//  +-----------------------------------------------------------------------------------------------------------------------+

// Match Velocity Closest ---------------------------------------------------------------------------------------------------
            case 0x29:

                goto LOOPEND;

// Match Velocity -----------------------------------------------------------------------------------------------------------
            case 0x3a:

                goto LOOPEND;

            case 0x3b:
// Flee ---------------------------------------------------------------------------------------------------------------------
                ship.low_ai.Flee();
                goto LOOPEND;

            case 0x3c:
// Idle ---------------------------------------------------------------------------------------------------------------------
                ship.low_ai.Idle();
                goto LOOPEND;

            case 0x3d:
// Attack -------------------------------------------------------------------------------------------------------------------

                goto LOOPEND;

            case 0x3e:
// TurretAttack -------------------------------------------------------------------------------------------------------------

                goto LOOPEND;

            case 0x3f:
// Control ------------------------------------------------------------------------------------------------------------------
                if (parentObject is Ship)
                {
                    SceneGlobals.Player = parentObject as Ship;
                }
                goto LOOPEND;

            default: goto LOOPEND;
            }
            LOOPEND :;
        }
    }