Beispiel #1
0
		/// <summary>
		/// 初始化一个新 <see cref="WhereBuilder" /> 实例。
		/// </summary>
		/// <param name="db">数据库实例</param>
		/// <param name="args">参数</param>
		/// <param name="withTableName">指定是否包含表名</param>
		public WhereBuilder(Database db, List<object> args = null, bool withTableName = true)
		{
			__sql = new STR();
			__db = db;
			__wtn = withTableName;
			this.Params = args ?? new List<object>();
		}
Beispiel #2
0
        internal static unsafe string PtrToStringUTF8(STR* buf) {
            byte* walk = (byte *)buf;
            // byte* buf2 = stackalloc byte[4000];

            // find the end of the string
            while (*walk != 0) {
                walk++;
            }
            int length = (int)(walk - (byte *)buf);

            string data;
            byte[] strbuf = new byte[length];  // should not be null terminated
            if (length > 0) {
                Marshal.Copy((IntPtr)buf, strbuf, 0, length);
                data = Encoding.UTF8.GetString(strbuf);
            } else {
                data = "";
            }            

            return data;                       
        }
Beispiel #3
0
        public VMAvatar(GameObject obj)
            : base(obj)
        {
            PlatformState = new VMTSOAvatarState(); //todo: ts1 switch
            BodyStrings   = Object.Resource.Get <STR>(Object.OBJ.BodyStringID);

            SetAvatarType(BodyStrings);
            SkinTone = AppearanceType.Light;

            if (UseWorld)
            {
                WorldUI = new AvatarComponent();
                var avatarc = (AvatarComponent)WorldUI;
                avatarc.Avatar = Avatar;
            }


            MotiveDecay = new VMAvatarMotiveDecay();
            for (int i = 0; i < 16; i++)
            {
                MotiveChanges[i]        = new VMMotiveChange();
                MotiveChanges[i].Motive = (VMMotive)i;
            }
        }
        public bool Read(MemoryStream s)
        {
            uint Magic = Tools.ReadUInt(s);

            if (Magic != 0xD78B40EB)
            {
                return(false);
            }

            Tools.ReadInt(s);
            int DataOffset = Tools.ReadInt(s);

            Tools.ReadInt(s);
            Tools.ReadInt(s);
            Tools.ReadInt(s);

            int Data1Count  = Tools.ReadInt(s);
            int Data1Offset = Tools.ReadInt(s);
            int Data2Count  = Tools.ReadInt(s);
            int Data2Offset = Tools.ReadInt(s);
            int Data3Count  = Tools.ReadInt(s);
            int Data3Offset = Tools.ReadInt(s);
            int Data4Count  = Tools.ReadInt(s);
            int Data4Offset = Tools.ReadInt(s);

            if (Data4Count > 0)
            {
                int Data5Count  = Tools.ReadInt(s);
                int Data5Offset = Tools.ReadInt(s);
            }

            s.Seek(Data1Offset, SeekOrigin.Begin);
            List <int> Data1 = new List <int>();

            for (int i = 0; i < Data1Count; i++)
            {
                Data1.Add(Tools.ReadInt(s));
            }

            s.Seek(Data2Offset, SeekOrigin.Begin);
            List <uint> StringIDs  = new List <uint>();
            List <int>  StringData = new List <int>();

            for (int i = 0; i < Data2Count; i++)
            {
                StringIDs.Add(Tools.ReadUInt(s));
                StringData.Add(Tools.ReadInt(s));
            }

            s.Seek(DataOffset, SeekOrigin.Begin);
            List <uint> Data = new List <uint>();

            while (s.Position < s.Length)
            {
                Data.Add(Tools.ReadUInt(s));
            }

            Strings = new List <STR>();
            for (int i = 0; i < StringIDs.Count; i++)
            {
                STR ValueString = new STR();
                ValueString.ID    = StringIDs[i];
                ValueString.Value = "";

                int Index = StringData[i] >> 5;
                int Shift = StringData[i] & 0x1F;

                while (true)
                {
                    int e = (Data1.Count / 2) - 1;
                    while (e > 0)
                    {
                        int offset = (int)((Data[Index] >> Shift) & 1);
                        e = Data1[(e * 2) + offset];

                        Shift++;
                        Index += (Shift >> 5);
                        Shift %= 32;
                    }

                    ushort c = (ushort)(0xFFFF - e);
                    if (c == 0)
                    {
                        break;
                    }

                    ValueString.Value += (char)c;
                }

                Strings.Add(ValueString);
            }

            return(true);
        }
 public void ReadHead(STR bodyStrings)
 {
     TS1AppearanceID = ToApr(bodyStrings.GetString(2));
     TS1TextureID    = ToTex(bodyStrings.GetString(2));
 }
Beispiel #6
0
        public static string ParseDialogString(VMStackFrame context, string input, STR source, int depth)
        {
            if (depth > 10)
            {
                return(input);
            }
            int           state   = 0;
            StringBuilder command = new StringBuilder();
            StringBuilder output  = new StringBuilder();

            if (input == null)
            {
                return("Missing String!!!");
            }

            for (int i = 0; i < input.Length; i++)
            {
                if (state == 0)
                {
                    if (input[i] == '$')
                    {
                        state = 1; //start parsing string
                        command.Clear();
                    }
                    else
                    {
                        output.Append(input[i]);
                    }
                }
                else
                {
                    command.Append(input[i]);
                    if (i == input.Length - 1 || !CommandSubstrValid(command.ToString()))
                    {
                        if (i != input.Length - 1 || char.IsDigit(input[i]))
                        {
                            command.Remove(command.Length - 1, 1);
                            i--;
                        }

                        var     cmdString = command.ToString();
                        short[] values    = new short[3];
                        if (cmdString.Length > 1 && cmdString[cmdString.Length - 1] == ':')
                        {
                            try
                            {
                                if (cmdString == "DynamicStringLocal:" || cmdString == "TimeLocal:" || cmdString == "JobOffer:" || cmdString == "Job:" || cmdString == "JobDesc:" || cmdString == "DateLocal:")
                                {
                                    values[1] = -1;
                                    values[2] = -1;
                                    for (int j = 0; j < 3; j++)
                                    {
                                        char   next = input[++i];
                                        string num  = "";
                                        while (char.IsDigit(next))
                                        {
                                            num += next;
                                            next = (++i == input.Length) ? '!': input[i];
                                        }
                                        if (num == "")
                                        {
                                            values[j] = -1;
                                            if (j == 1)
                                            {
                                                values[2] = -1;
                                            }
                                            break;
                                        }
                                        values[j] = short.Parse(num);
                                        if (i == input.Length || next != ':')
                                        {
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    char   next = input[++i];
                                    string num  = "";
                                    while (char.IsDigit(next))
                                    {
                                        num += next;
                                        next = (++i == input.Length) ? '!' : input[i];
                                    }
                                    values[0] = short.Parse(num);
                                }
                                i--;
                            }
                            catch (FormatException)
                            {
                            }
                        }
                        try
                        {
                            switch (cmdString)
                            {
                            case "Object":
                            case "DynamicObjectName":
                                //hack: if stack object doesn't exist and should contain owner's id,
                                //try output the callee's owner id instead for tip jar.
                                //special id for this is -1.
                                if (context.StackObjectID == -1 && !context.VM.TS1)
                                {
                                    //StackObjectOwnerID call sets the id to -1 if no owner found. (null is usually 0)
                                    output.Append(context.VM.TSOState.Names.GetNameForID(
                                                      context.VM,
                                                      (context.Callee.TSOState as VMTSOObjectState)?.OwnerID ?? 0
                                                      ));
                                }
                                else
                                {
                                    output.Append(context.StackObject.ToString());
                                }
                                break;

                            case "Me":
                                output.Append(context.Caller.ToString()); break;

                            case "TempXL:":
                                output.Append(VMMemory.GetBigVariable(context, Scopes.VMVariableScope.TempXL, values[0]).ToString()); break;

                            case "MoneyXL:":
                                output.Append("$" + VMMemory.GetBigVariable(context, Scopes.VMVariableScope.TempXL, values[0]).ToString("##,#0")); break;

                            case "Temp:":
                                output.Append(VMMemory.GetBigVariable(context, Scopes.VMVariableScope.Temps, values[0]).ToString()); break;

                            case "$":
                                output.Append("$"); i--; break;

                            case "Attribute:":
                                output.Append(VMMemory.GetBigVariable(context, Scopes.VMVariableScope.MyObjectAttributes, values[0]).ToString()); break;

                            case "DynamicStringLocal:":
                                STR res = null;
                                if (values[2] != -1 && values[1] != -1)
                                {
                                    VMEntity obj = context.VM.GetObjectById((short)context.Locals[values[2]]);
                                    if (obj == null)
                                    {
                                        break;
                                    }
                                    ushort tableID = (ushort)context.Locals[values[1]];

                                    {    //local
                                        if (obj.SemiGlobal != null)
                                        {
                                            res = obj.SemiGlobal.Get <STR>(tableID);
                                        }
                                        if (res == null)
                                        {
                                            res = obj.Object.Resource.Get <STR>(tableID);
                                        }
                                        if (res == null)
                                        {
                                            res = context.Global.Resource.Get <STR>(tableID);
                                        }
                                    }
                                }
                                else if (values[1] != -1)
                                {
                                    //global table
                                    ushort tableID = (ushort)context.Locals[values[1]];
                                    res = context.Global.Resource.Get <STR>(tableID);
                                }
                                else
                                {
                                    res = source;
                                }

                                ushort index = (ushort)context.Locals[values[0]];
                                if (res != null)
                                {
                                    var str = res.GetString(index);
                                    output.Append(ParseDialogString(context, str, res, depth++));     // recursive command parsing!
                                    // this is needed for the crafting table.
                                    // though it is also, completely insane?
                                }
                                break;

                            case "Local:":
                                output.Append(VMMemory.GetBigVariable(context, Scopes.VMVariableScope.Local, values[0]).ToString()); break;

                            case "FixedLocal:":
                                output.Append((VMMemory.GetBigVariable(context, Scopes.VMVariableScope.Local, values[0]) / 100f).ToString("F2")); break;

                            case "TimeLocal:":
                                var hours  = VMMemory.GetBigVariable(context, Scopes.VMVariableScope.Local, values[0]);
                                var mins   = (values[1] == -1)?0:VMMemory.GetBigVariable(context, Scopes.VMVariableScope.Local, values[1]);
                                var suffix = (hours > 11) ? "pm" : "am";
                                if (hours > 12)
                                {
                                    hours -= 12;
                                }
                                output.Append(hours.ToString());
                                output.Append(":");
                                output.Append(mins.ToString().PadLeft(2, '0'));
                                output.Append(suffix);
                                break;

                            case "JobOffer:":
                                output.Append(Content.Content.Get().Jobs.JobOffer(
                                                  (short)VMMemory.GetBigVariable(context, Scopes.VMVariableScope.Local, values[0]),
                                                  VMMemory.GetBigVariable(context, Scopes.VMVariableScope.Local, values[1])));
                                break;

                            case "Job:":
                            case "JobDesc:":
                                var level  = VMMemory.GetBigVariable(context, Scopes.VMVariableScope.Local, values[1]);
                                var jobStr = Content.Content.Get().Jobs.JobStrings(
                                    (short)VMMemory.GetBigVariable(context, Scopes.VMVariableScope.Local, values[0]));
                                if (jobStr != null)
                                {
                                    output.Append(jobStr.GetString(level * 3 + ((cmdString == "JobDesc:")?3:4)));
                                }
                                break;

                            case "Param:":
                                output.Append(VMMemory.GetBigVariable(context, Scopes.VMVariableScope.Parameters, values[0]).ToString()); break;

                            case "NameLocal:":
                                output.Append(context.VM.GetObjectById(VMMemory.GetVariable(context, Scopes.VMVariableScope.Local, values[0])).ToString()); break;

                            case "Neighbor":
                                //neighbour in stack object id
                                if (!context.VM.TS1)
                                {
                                    break;
                                }
                                var guid = Content.Content.Get().Neighborhood.GetNeighborByID(context.StackObjectID)?.GUID ?? 0;
                                var gobj = Content.Content.Get().WorldObjects.Get(guid);
                                if (gobj == null)
                                {
                                    output.Append("Unknown");
                                }
                                else
                                {
                                    output.Append(gobj.Resource.Get <FSO.Files.Formats.IFF.Chunks.CTSS>(gobj.OBJ.CatalogStringsID)?.GetString(0) ?? "Unknown");
                                }
                                break;

                            case "ListObject":
                                output.Append(new string(context.StackObject.MyList.Select(x => (char)x).ToArray()));
                                break;

                            case "CatalogLocal:":
                                var catObj = context.VM.GetObjectById(VMMemory.GetVariable(context, Scopes.VMVariableScope.Local, values[0]));
                                var cat    = catObj.Object.Resource.Get <CTSS>(catObj.Object.OBJ.CatalogStringsID)?.GetString(1);
                                output.Append(cat ?? "");
                                break;

                            case "DateLocal:":
                                var date = new DateTime(context.Locals[values[2]], context.Locals[values[1]], context.Locals[values[0]]);
                                output.Append(date.ToLongDateString());
                                break;

                            case "\\n":
                                output.Append("\n");
                                break;

                            default:
                                output.Append(cmdString);
                                break;
                            }
                        } catch (Exception)
                        {
                            //something went wrong. just skip command
                        }
                        state = 0;
                    }
                }
            }
            output.Replace("\r\n", "\r\n\r\n");
            return(output.ToString());
        }
        public void SetAvatarBodyStrings(STR data, VMContext context)
        {
            if (data == null)
            {
                return;
            }

            var body     = data.GetString(1);
            var randBody = data.GetString(10);

            var gender = data.GetString(12);
            var genVar = (int)VMPersonDataVariable.Gender;

            try
            {
                if (randBody != "")
                {
                    var bodySpl = randBody.Split(';');
                    DefaultSuits.Daywear = Convert.ToUInt64(bodySpl[context.NextRandom((ulong)bodySpl.Length - 1)], 16);
                }
                else if (body != "")
                {
                    DefaultSuits.Daywear = Convert.ToUInt64(body, 16);
                }

                BodyOutfit = DefaultSuits.Daywear;

                var head     = data.GetString(2);
                var randHead = data.GetString(9);

                if (randHead != "")
                {
                    var headSpl = randHead.Split(';');
                    HeadOutfit = Convert.ToUInt64(headSpl[context.NextRandom((ulong)headSpl.Length - 1)], 16);
                }
                else if (head != "")
                {
                    HeadOutfit = Convert.ToUInt64(head, 16);
                }
            }
            catch
            {
                //head or body invalid, resort to default.
                HeadOutfit = SetAvatarRandomOutfit(1);
                BodyOutfit = SetAvatarRandomOutfit(0);
            }


            if (gender.Equals("male", StringComparison.InvariantCultureIgnoreCase))
            {
                PersonData[genVar] = 0;
            }
            else if (gender.Equals("female", StringComparison.InvariantCultureIgnoreCase))
            {
                PersonData[genVar] = 1;
            }
            else if (gender.Equals("dogmale", StringComparison.InvariantCultureIgnoreCase))
            {
                PersonData[genVar] = 8;
            }
            else if (gender.Equals("dogfemale", StringComparison.InvariantCultureIgnoreCase))
            {
                PersonData[genVar] = 9;
            }
            else if (gender.Equals("catmale", StringComparison.InvariantCultureIgnoreCase))
            {
                PersonData[genVar] = 16;
            }
            else if (gender.Equals("catfemale", StringComparison.InvariantCultureIgnoreCase))
            {
                PersonData[genVar] = 17;
            }

            var names = data.GetString(11);

            if (names != "")
            {
                var nameSpl = names.Split(';');
                Name = nameSpl[context.NextRandom((ulong)nameSpl.Length)];
            }

            PersonData[(int)VMPersonDataVariable.PersonsAge] = Convert.ToInt16(data.GetString(13));

            var skinTone = data.GetString(14);

            if (skinTone.Equals("lgt", StringComparison.InvariantCultureIgnoreCase))
            {
                SkinTone = AppearanceType.Light;
            }
            else if (skinTone.Equals("med", StringComparison.InvariantCultureIgnoreCase))
            {
                SkinTone = AppearanceType.Medium;
            }
            else if (skinTone.Equals("drk", StringComparison.InvariantCultureIgnoreCase))
            {
                SkinTone = AppearanceType.Dark;
            }
        }
Beispiel #8
0
        public static VMPrimitiveExitCode ExecuteGeneric(VMStackFrame context, VMPrimitiveOperand args, STR table)
        {
            var operand   = (VMDialogOperand)args;
            var curDialog = (VMDialogResult)context.Thread.BlockingState;

            if (curDialog == null)
            {
                //in ts1, it's possible for a lot of blocking dialogs to come in one frame. due to the way our engine works,
                //we cannot pause the rest of the tick as soon as we hit a blocking dialog, and we cannot show more than one blocking dialog.
                //so additional blocking dialogs must wait.
                if (context.VM.TS1 && context.VM.GlobalBlockingDialog != null)
                {
                    return(VMPrimitiveExitCode.CONTINUE_NEXT_TICK);
                }
                VMDialogHandler.ShowDialog(context, operand, table);

                if ((operand.Flags & VMDialogFlags.Continue) == 0)
                {
                    context.Thread.BlockingState = new VMDialogResult
                    {
                        Type         = operand.Type,
                        HasDisplayed = true
                    };
                    if (context.VM.TS1)
                    {
                        context.VM.GlobalBlockingDialog = context.Caller;
                        context.VM.LastSpeedMultiplier  = context.VM.SpeedMultiplier;
                        context.VM.SpeedMultiplier      = 0;
                    }
                    return(VMPrimitiveExitCode.CONTINUE_NEXT_TICK);
                }
                else
                {
                    return(VMPrimitiveExitCode.GOTO_TRUE);
                }
            }
            else
            {
                if (curDialog.Responded || curDialog.WaitTime > DIALOG_MAX_WAITTIME)
                {
                    context.Thread.BlockingState = null;
                    context.VM.SignalDialog(null);
                    switch (curDialog.Type)
                    {
                    default:
                    case VMDialogType.Message:
                        return(VMPrimitiveExitCode.GOTO_TRUE);

                    case VMDialogType.YesNo:
                        return((curDialog.ResponseCode == 0) ? VMPrimitiveExitCode.GOTO_TRUE : VMPrimitiveExitCode.GOTO_FALSE);

                    case VMDialogType.YesNoCancel:
                        if (curDialog.ResponseCode > 1)
                        {
                            context.Thread.TempRegisters[((operand.Flags & VMDialogFlags.UseTemp1) > 0) ? 1 : 0] = (short)((curDialog.ResponseCode - 1) % 2);
                            return(VMPrimitiveExitCode.GOTO_FALSE);
                        }
                        else
                        {
                            return(VMPrimitiveExitCode.GOTO_TRUE);
                        }

                    case VMDialogType.TextEntry:
                        //todo: filter profanity, limit name length
                        //also verify behaviour.
                        if ((curDialog.ResponseText ?? "") != "")
                        {
                            ((VMAvatar)context.StackObject).Name = curDialog.ResponseText;
                        }
                        return(VMPrimitiveExitCode.GOTO_TRUE);

                    case VMDialogType.NumericEntry:     //also downtown
                    case VMDialogType.TS1Vacation:
                    case VMDialogType.TS1Neighborhood:
                    case VMDialogType.TS1StudioTown:
                    case VMDialogType.TS1Magictown:
                        int number;
                        if (!int.TryParse(curDialog.ResponseText, out number))
                        {
                            return(VMPrimitiveExitCode.GOTO_FALSE);
                        }

                        var tempNumber = ((operand.Flags & VMDialogFlags.UseTemp1) > 0) ? 1 : 0;

                        if ((operand.Flags & VMDialogFlags.UseTempXL) > 0)
                        {
                            context.Thread.TempXL[tempNumber] = number;
                        }
                        else
                        {
                            context.Thread.TempRegisters[tempNumber] = (short)number;
                        }
                        return(VMPrimitiveExitCode.GOTO_TRUE);

                    case VMDialogType.FSOColor:
                        int number2;
                        if (curDialog.ResponseCode == 1)
                        {
                            return(VMPrimitiveExitCode.GOTO_FALSE);
                        }
                        if (!int.TryParse(curDialog.ResponseText, out number2))
                        {
                            return(VMPrimitiveExitCode.GOTO_FALSE);
                        }
                        context.Thread.TempRegisters[0] = (byte)(number2 >> 16);
                        context.Thread.TempRegisters[1] = (byte)(number2 >> 8);
                        context.Thread.TempRegisters[2] = (byte)(number2);
                        return(VMPrimitiveExitCode.GOTO_TRUE);
                    }
                }
                else
                {
                    if (!curDialog.HasDisplayed)
                    {
                        VMDialogHandler.ShowDialog(context, operand, table);
                        curDialog.HasDisplayed = true;
                    }
                    return(VMPrimitiveExitCode.CONTINUE_NEXT_TICK);
                }
            }
        }
Beispiel #9
0
    static void Main()
    {
        var n  = int.Parse(Console.ReadLine());
        var a  = Read();
        var qc = int.Parse(Console.ReadLine());
        var qs = Array.ConvertAll(new bool[qc], _ => Read3());

        var d   = a.GroupBy(x => x).ToDictionary(g => g.Key, g => g.LongCount());
        var sum = d.Values.Sum(c => c * (c - 1) / 2);

        void Add(int x, int count)
        {
            var c = d.GetValueOrDefault(x);

            sum -= c * (c - 1) / 2;
            c   += count;
            sum += c * (c - 1) / 2;
            d[x] = c;
        }

        var ruq = new STR <int>(n, (x, y) => x == -1 ? y : x, -1);
        var rs  = new int[n];

        for (var(l, r) = (0, 1); r <= n; r++)
        {
            if (r == n || a[r] != a[r - 1])
            {
                ruq.Set(l, r, l);
                rs[l] = r;
                l     = r;
            }
        }

        Console.SetOut(new System.IO.StreamWriter(Console.OpenStandardOutput())
        {
            AutoFlush = false
        });
        foreach (var q in qs)
        {
            var(L, R, X) = q;
            L--;

            var ll = ruq.Get(L);
            var rl = ruq.Get(R - 1);
            var rr = rs[rl];
            var lx = a[ll];
            var rx = a[rl];

            // 関連する区間を全て除きます。
            for (int l = ll; l < rr; l = rs[l])
            {
                Add(a[l], -(rs[l] - l));
            }

            Add(lx, L - ll);
            Add(X, R - L);
            Add(rx, rr - R);

            rs[ll] = L;

            a[L] = X;
            ruq.Set(L, R, L);
            rs[L] = R;

            if (R < rr)
            {
                a[R] = rx;
                ruq.Set(R, rr, R);
                rs[R] = rr;
            }

            Console.WriteLine(sum);
        }
        Console.Out.Flush();
    }
Beispiel #10
0
 /// <summary>
 ///  初始化一个新 <see cref="GroupByBuilder" /> 实例。
 /// </summary>
 /// <param name="context">构建器上下文</param>
 public GroupByBuilder(BuilderContext context)
 {
     __sql              = new STR();
     this.context       = context;
     this.withTableName = true;
 }
Beispiel #11
0
 public void SetActiveResource(IffChunk chunk,GameIffResource res)
 {
     ActiveSLOT      = (SLOT)chunk;
     ActiveSLOTLabel = res.Get <STR>(257);
     UpdateStrings();
 }
Beispiel #12
0
 private void strRollButton_Click(object sender, EventArgs e)
 {
     STR           = rng.Next(1, 21);
     strValue.Text = STR.ToString();
 }
 public IEnumerable <DataField> GetFields(IEnumerable <string> fields)
 {
     return(Fields.Where(FLD => fields.Any(STR => STR.Equals(FLD.FieldName, StringComparison.OrdinalIgnoreCase))));
 }
Beispiel #14
0
 /// <summary>
 /// 初始化一个新 <see cref="UpdateBuilder&lt;T&gt;" /> 实例。
 /// </summary>
 /// <param name="db">数据库实例</param>
 /// <param name="args">参数</param>
 public UpdateBuilder(Database db, List <object> args = null)
 {
     __sql       = new STR();
     __db        = db;
     this.Params = args ?? new List <object>();
 }
Beispiel #15
0
        public static STR Load(MemoryStreamReader data, string path)
        {
            var header = data.ReadBinaryString(4);

            if (!header.Equals(STR.Header))
            {
                throw new Exception("EffectLoader.Load: Header (" + header + ") is not \"STRM\"");
            }

            var version = data.ReadUInt();

            if (version != 0x94)
            {
                throw new Exception("EffectLoader.Load: Unsupported STR version (v" + version + ")");
            }

            STR str = new STR();

            str.version = version;
            str.fps     = data.ReadUInt();
            str.maxKey  = data.ReadUInt();
            var layerCount = data.ReadUInt();

            data.Seek(16, System.IO.SeekOrigin.Current);


            //read layers
            str.layers = new STR.Layer[layerCount];
            for (uint i = 0; i < layerCount; i++)
            {
                STR.Layer layer = str.layers[i] = new STR.Layer();

                //read texture filenames
                var textureCount = data.ReadInt();
                layer.textures    = new Texture2D[textureCount];
                layer.texturesIds = new List <int>();
                for (int j = 0; j < textureCount; j++)
                {
                    var tex     = data.ReadBinaryString(128);
                    var texture = FileManager.Load(path + "/" + tex) as Texture2D;
                    layer.textures[j] = texture;

                    if (!textureNames.Contains(tex))
                    {
                        layer.texturesIds.Add(textureNames.Count);
                        textureIdLookup.Add(tex, textureNames.Count);
                        textureNames.Add(tex);
                        textures.Add(texture);
                    }
                    else
                    {
                        layer.texturesIds.Add(textureIdLookup[tex]);
                    }
                }

                //read animations
                var animCount = data.ReadInt();
                layer.animations = new STR.Animation[animCount];
                for (int j = 0; j < animCount; j++)
                {
                    var entry = new STR.Animation()
                    {
                        frame    = data.ReadInt(),
                        type     = data.ReadUInt(),
                        position = new Vector2(data.ReadFloat(), data.ReadFloat())
                    };

                    var uv = new float[] {
                        data.ReadFloat(), data.ReadFloat(), data.ReadFloat(), data.ReadFloat(),
                        data.ReadFloat(), data.ReadFloat(), data.ReadFloat(), data.ReadFloat()
                    };
                    var xy = new float[] {
                        data.ReadFloat(), data.ReadFloat(), data.ReadFloat(), data.ReadFloat(),
                        data.ReadFloat(), data.ReadFloat(), data.ReadFloat(), data.ReadFloat()
                    };

                    entry.uv    = new Vector2[4];
                    entry.uv[0] = new Vector2(0, 0);
                    entry.uv[1] = new Vector2(1, 0);
                    entry.uv[2] = new Vector2(0, 1);
                    entry.uv[3] = new Vector2(1, 1);

                    entry.xy    = new Vector2[4];
                    entry.xy[0] = new Vector2(xy[0], -xy[4]);
                    entry.xy[1] = new Vector2(xy[1], -xy[5]);
                    entry.xy[2] = new Vector2(xy[3], -xy[7]);
                    entry.xy[3] = new Vector2(xy[2], -xy[6]);

                    entry.animFrame = data.ReadFloat();
                    entry.animType  = data.ReadUInt();
                    entry.delay     = data.ReadFloat();
                    entry.angle     = data.ReadFloat() / (1024f / 360f);
                    entry.color     = new Color(data.ReadFloat() / 255, data.ReadFloat() / 255, data.ReadFloat() / 255, data.ReadFloat() / 255);
                    entry.srcAlpha  = data.ReadUInt();
                    entry.destAlpha = data.ReadUInt();
                    entry.mtPreset  = data.ReadUInt();

                    layer.animations[j] = entry;
                }
            }

            return(MakeAtlas(str, path));
        }
Beispiel #16
0
 /// <summary>
 /// 初始化一个新 <see cref="WhereBuilder" /> 实例。
 /// </summary>
 /// <param name="context">构建器上下文</param>
 /// <param name="withTableName">指定是否包含表名</param>
 public WhereBuilder(BuilderContext context, bool withTableName = true)
 {
     __sql = new STR();
     this.withTableName = withTableName;
     this.context       = context;
 }
Beispiel #17
0
        public static void SaveOBJ(string destPath, STR locations)
        {
            var exportedFlr = new HashSet <ushort>();
            var gd          = GameFacade.GraphicsDevice;
            var mtlBuilder  = new StringBuilder();

            Directory.CreateDirectory(destPath);

            //var mtlMem = new MemoryStream();
            //var mtlIO = new StreamWriter(mtlMem);
            var mtlIO = new StreamWriter(new FileStream(Path.Combine(destPath, "neighbourhood.mtl"), FileMode.Create, FileAccess.Write, FileShare.None));

            var path     = Path.Combine(destPath, "neighbourhood.obj");
            var filename = Path.GetFileNameWithoutExtension(path);

            using (var io = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)))
            {
                io.WriteLine("# Generated by the Simitone Neighbourhood Exporter.");
                io.WriteLine("# The purpose is to allow users to mesh neighbourhood surroundings using");
                io.WriteLine("# the projected physical positions and terrain profiles of lots as a starting point.");

                io.WriteLine("mtllib neighbourhood.mtl");
                io.WriteLine("s 1");

                int indCount = 1;
                for (int i = 0; i < locations.Length; i++)
                {
                    var loc   = locations.GetString(i).Split(',');
                    var num   = int.Parse(loc[0].TrimStart());
                    var pos2d = new Vector2(int.Parse(loc[1].TrimStart()), int.Parse(loc[2].TrimStart()));

                    var house = Content.Get().Neighborhood.GetHouse(num);

                    World world = new FSO.LotView.World(GameFacade.GraphicsDevice);

                    world.Opacity = 1;
                    GameFacade.Scenes.Add(world);

                    var globalLink = new VMTS1GlobalLinkStub();
                    var driver     = new VMServerDriver(globalLink);

                    var vm = new VM(new VMContext(world), driver, new UIHeadlineRendererProvider());
                    vm.ListenBHAVChanges();
                    vm.Init();

                    vm.SetGlobalValue(11, (short)num);

                    var activator = new VMTS1Activator(vm, vm.Context.World, (short)num);
                    var blueprint = activator.LoadFromIff(house);

                    var floorVerts = blueprint.Terrain.GetVertices(gd);
                    blueprint.FloorGeom.FullReset(gd, false);
                    var groundfloor = blueprint.FloorGeom.Floors[0];

                    //we need to calculate the
                    var minHeight = int.MaxValue;
                    var heights   = vm.Context.Architecture.Terrain.Heights;
                    for (int j = 0; j < heights.Length; j++)
                    {
                        if ((j % blueprint.Width) == 0 || (j % blueprint.Width) == blueprint.Width - 1 || j < blueprint.Width || j >= (blueprint.Height - 1) * blueprint.Width)
                        {
                            continue;
                        }
                        var h = heights[j];
                        if (h != 0 && h < minHeight)
                        {
                            minHeight = h;
                        }
                    }
                    if (minHeight == int.MaxValue)
                    {
                        minHeight = 0;
                    }
                    var scale = (locations.Length > 30 ? 1f : 2f) * 1.4142135623730950488016887242097f;
                    var baseV = new Vector3(pos2d.X + pos2d.Y * 2, 0, pos2d.Y * 2 - pos2d.X) / scale;
                    baseV.Y -= (minHeight * 3 / 160f) * 3;

                    var ctr = blueprint.GetFineBounds().Location.ToVector2() + blueprint.GetFineBounds().Size.ToVector2() / 2;

                    var voff = baseV + new Vector3(ctr.X, 0, ctr.Y) * 3f / -1;

                    voff.X = (int)(voff.X / 3) * 3;
                    voff.Z = (int)(voff.Z / 3) * 3;

                    SetOutsideTime(GameFacade.GraphicsDevice, vm, world, 0.5f, false);
                    world.State.PrepareLighting();
                    var facade = new LotFacadeGenerator();
                    facade.FLOOR_TILES        = blueprint.Width;
                    facade.GROUND_SUBDIV      = blueprint.Width;
                    facade.FLOOR_RES_PER_TILE = 4;
                    facade.LotName            = "p" + num.ToString();
                    facade.Generate(GameFacade.GraphicsDevice, world, blueprint);
                    facade.AppendOBJ(io, filename, indCount, voff / 3);
                    facade.AppendMTL(mtlIO, Path.GetDirectoryName(path));
                    indCount = facade.LastIndex;

                    /*
                     * foreach (var group in groundfloor.GroupForTileType)
                     * {
                     *  if (!exportedFlr.Contains(group.Key) && group.Key != 0 && group.Key < 65000)
                     *  {
                     *      //get and export this floor's texture. add it as a material as well.
                     *      var floor = Content.Get().WorldFloors.Get(group.Key).Near.Frames[0].GetTexture(gd);
                     *      using (var flrStream = new FileStream(Path.Combine(destPath, "flr_" + group.Key + ".png"), FileMode.Create, FileAccess.Write, FileShare.None))
                     *          floor.SaveAsPng(flrStream, floor.Width, floor.Height);
                     *
                     *      //add as material
                     *      GenerateMTL("flr_" + group.Key, mtlBuilder);
                     *  }
                     *  //write out verts and indices.
                     *
                     *
                     *  var indices = group.Value.BuildIndexData();
                     *  var done = new Dictionary<int, int>(); //index remap
                     *
                     *  if (group.Key == 0)
                     *  {
                     *      //grass... export as grass colour
                     *      io.WriteLine("usemtl " + "grass");
                     *      io.WriteLine("o " + "lot_" + num + "_grass");
                     *
                     *  }
                     *  else
                     *  {
                     *      //export with floor textured material
                     *      io.WriteLine("usemtl " + "flr_" + group.Key);
                     *      io.WriteLine("o " + "lot_" + num + "_" + group.Key);
                     *  }
                     *
                     *  var indexStr = new StringBuilder();
                     *  indexStr.Append("f ");
                     *
                     *  for (int j = 0; j < indices.Length; j++)
                     *  {
                     *      var index = indices[j];
                     *      int remapped = index;
                     *      if (!done.TryGetValue(index, out remapped))
                     *      {
                     *          remapped = indCount;
                     *          done.Add(index, indCount++);
                     *          //append a vertex
                     *          var vert = floorVerts[index];
                     *          vert.Position += voff;
                     *          io.Write("v " + vert.Position.X.ToString(CultureInfo.InvariantCulture) + " " + vert.Position.Y.ToString(CultureInfo.InvariantCulture) + " " + vert.Position.Z.ToString(CultureInfo.InvariantCulture));
                     *          io.WriteLine((group.Key == 0) ? " " + vert.Color.X.ToString(CultureInfo.InvariantCulture) + " " + vert.Color.Y.ToString(CultureInfo.InvariantCulture) + " " + vert.Color.Z.ToString(CultureInfo.InvariantCulture) : "");
                     *          io.WriteLine("vt " + vert.GrassInfo.Y.ToString(CultureInfo.InvariantCulture) + " " + (1 - vert.GrassInfo.Z).ToString(CultureInfo.InvariantCulture));
                     *      }
                     *      indexStr.Append(remapped + "/" + remapped);
                     *      if (j % 3 == 2)
                     *      {
                     *          indexStr.AppendLine();
                     *          if (j != indices.Length - 1) indexStr.Append("f ");
                     *      }
                     *      else indexStr.Append(" ");
                     *  }
                     *
                     *  io.WriteLine(indexStr);
                     * }
                     */

                    GameFacade.Scenes.Remove(world);
                    world.Dispose();
                }
            }

            mtlIO.Close();
        }
Beispiel #18
0
    private static object DoLoad(string file, string ext)
    {
        //string fileWOExt = file.Replace("." + ext, "");

        switch (ext)
        {
        case "grf":
            return(File.OpenRead(file));

        // Regular images files
        case "jpg":
        case "jpeg":
        case "png":
            using (var br = ReadSync(file)) {
                return(new RawImage()
                {
                    data = br.ToArray()
                });
            }

        case "bmp":
            using (var br = ReadSync(file))
                return(loader.LoadBMP(br));

        case "tga":
            using (var br = ReadSync(file))
                return(TGALoader.LoadTGA(br));

        // Texts
        case "txt":
        case "xml":
        case "lua":
            using (var br = ReadSync(file)) {
                if (br != null)
                {
                    return(Encoding.UTF8.GetString(br.ToArray()));
                }
                else
                {
                    return(null);
                }
            }

        case "spr":
            using (var br = ReadSync(file)) {
                if (br != null)
                {
                    SPR spr = SpriteLoader.Load(br);
                    spr.SwitchToRGBA();
                    spr.Compile();
                    spr.filename = file;
                    return(spr);
                }
                else
                {
                    return(null);
                }
            }

        case "str":
            using (var br = ReadSync(file)) {
                if (br != null)
                {
                    STR str = EffectLoader.Load(br);
                    return(str);
                }
                else
                {
                    return(null);
                }
            }

        // Binary
        case "gat":
            using (var br = ReadSync(file))
                return(new Altitude(br));

        case "rsw":
            using (var br = ReadSync(file))
                return(WorldLoader.Load(br));

        case "gnd":
            using (var br = ReadSync(file))
                return(GroundLoader.Load(br));

        case "rsm":
            using (var br = ReadSync(file))
                return(ModelLoader.Load(br));

        // Audio
        case "wav":
            using (var br = ReadSync(file)) {
                WAVLoader.WAVFile wav  = WAVLoader.OpenWAV(br.ToArray());
                AudioClip         clip = AudioClip.Create(file, wav.samples, wav.channels, wav.sampleRate, false);
                clip.SetData(wav.leftChannel, 0);
                return(clip);
            }

        case "mp3":
        case "ogg":

        case "act":
            //return new Action(ReadSync(file)).compile();
            Debug.LogWarning("Can't read " + file + "\nLoader for " + ext + " is not implemented");
            break;

        default:
            throw new System.Exception("Unknown file format: " + file);
        }
        return(null);
    }
Beispiel #19
0
 unsafe CSFILELOAD thunk_delegate;  // we have to hold onto the delegate to make sure the pinned thunk sticks around
 private unsafe NEOERR* csFileLoad(void* ctx, HDF* raw_hdf, STR* pFilename, STR** contents) {
     // Console.WriteLine("csFileLoad delegate called");
     IntPtr buf = IntPtr.Zero;
     try {
         Hdf hdf = new Hdf(raw_hdf);
         string filename = Marshal.PtrToStringAnsi((IntPtr)pFilename);
         byte[] data = cur_delegate(hdf, filename);
         byte[] end_null = new byte[] { 0 };               
         buf = NeoUtil.neo_malloc(data.Length + 1); // +1 so we can null terminate
         Marshal.Copy(data, 0, buf, data.Length);
         Marshal.Copy(end_null, 0, (IntPtr)((uint)buf + data.Length), 1); // write the end_null
         *contents = (STR*)buf;
     } catch (Exception e) {
         // Console.WriteLine("csFileLoad Thunk Exception + " + e);
         // should return a neo error
         if (buf != IntPtr.Zero) {
             NeoUtil.neo_free(buf);                   
         }
         return NeoErr.nERR(e.ToString());
     } 
     return (NEOERR*) IntPtr.Zero;
 }
        public static string ParseDialogString(VMStackFrame context, string input, STR source)
        {
            int           state   = 0;
            StringBuilder command = new StringBuilder();
            StringBuilder output  = new StringBuilder();

            if (input == null)
            {
                return("Missing String!!!");
            }

            for (int i = 0; i < input.Length; i++)
            {
                if (state == 0)
                {
                    if (input[i] == '$')
                    {
                        state = 1; //start parsing string
                        command.Clear();
                    }
                    else
                    {
                        output.Append(input[i]);
                    }
                }
                else
                {
                    command.Append(input[i]);
                    if (i == input.Length - 1 || !CommandSubstrValid(command.ToString()))
                    {
                        if (i != input.Length - 1 || char.IsDigit(input[i]))
                        {
                            command.Remove(command.Length - 1, 1);
                            i--;
                        }

                        var     cmdString = command.ToString();
                        short[] values    = new short[3];
                        if (cmdString.Length > 1 && cmdString[cmdString.Length - 1] == ':')
                        {
                            try
                            {
                                if (cmdString == "DynamicStringLocal:")
                                {
                                    values[1] = -1;
                                    values[2] = -1;
                                    for (int j = 0; j < 3; j++)
                                    {
                                        char   next = input[++i];
                                        string num  = "";
                                        while (char.IsDigit(next))
                                        {
                                            num += next;
                                            next = (++i == input.Length) ? '!': input[i];
                                        }
                                        if (num == "")
                                        {
                                            values[j] = -1;
                                            if (j == 1)
                                            {
                                                values[2] = -1;
                                            }
                                            break;
                                        }
                                        values[j] = short.Parse(num);
                                        if (i == input.Length || next != ':')
                                        {
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    char   next = input[++i];
                                    string num  = "";
                                    while (char.IsDigit(next))
                                    {
                                        num += next;
                                        next = (++i == input.Length) ? '!' : input[i];
                                    }
                                    values[0] = short.Parse(num);
                                }
                                i--;
                            }
                            catch (FormatException)
                            {
                            }
                        }
                        try
                        {
                            switch (cmdString)
                            {
                            case "Object":
                            case "DynamicObjectName":
                                output.Append(context.StackObject.ToString()); break;

                            case "Me":
                                output.Append(context.Caller.ToString()); break;

                            case "TempXL:":
                                output.Append(VMMemory.GetBigVariable(context, Scopes.VMVariableScope.TempXL, values[0]).ToString()); break;

                            case "MoneyXL:":
                                output.Append("$" + VMMemory.GetBigVariable(context, Scopes.VMVariableScope.TempXL, values[0]).ToString("##,#0")); break;

                            case "Temp:":
                                output.Append(VMMemory.GetBigVariable(context, Scopes.VMVariableScope.Temps, values[0]).ToString()); break;

                            case "$":
                                output.Append("$"); i--; break;

                            case "Attribute:":
                                output.Append(VMMemory.GetBigVariable(context, Scopes.VMVariableScope.MyObjectAttributes, values[0]).ToString()); break;

                            case "DynamicStringLocal:":
                                STR res = null;
                                if (values[2] != -1 && values[1] != -1)
                                {
                                    VMEntity obj = context.VM.GetObjectById((short)context.Locals[values[2]]);
                                    if (obj == null)
                                    {
                                        break;
                                    }
                                    ushort tableID = (ushort)context.Locals[values[1]];

                                    {    //local
                                        if (obj.SemiGlobal != null)
                                        {
                                            res = obj.SemiGlobal.Get <STR>(tableID);
                                        }
                                        if (res == null)
                                        {
                                            res = obj.Object.Resource.Get <STR>(tableID);
                                        }
                                        if (res == null)
                                        {
                                            res = context.Global.Resource.Get <STR>(tableID);
                                        }
                                    }
                                }
                                else if (values[1] != -1)
                                {
                                    //global table
                                    ushort tableID = (ushort)context.Locals[values[1]];
                                    res = context.Global.Resource.Get <STR>(tableID);
                                }
                                else
                                {
                                    res = source;
                                }

                                ushort index = (ushort)context.Locals[values[0]];
                                if (res != null)
                                {
                                    var str = res.GetString(index);
                                    output.Append(ParseDialogString(context, str, res));     // recursive command parsing!
                                    // this is needed for the crafting table.
                                    // though it is also, completely insane?
                                }
                                break;

                            case "Local:":
                                output.Append(VMMemory.GetBigVariable(context, Scopes.VMVariableScope.Local, values[0]).ToString()); break;

                            case "Param:":
                                output.Append(VMMemory.GetBigVariable(context, Scopes.VMVariableScope.Parameters, values[0]).ToString()); break;

                            case "NameLocal:":
                                output.Append("(NameLocal)"); break;

                            default:
                                output.Append(cmdString);
                                break;
                            }
                        } catch (Exception)
                        {
                            //something went wrong. just skip command
                        }
                        state = 0;
                    }
                }
            }
            output.Replace("\r\n", "\r\n\r\n");
            return(output.ToString());
        }
Beispiel #21
0
 extern static unsafe NEOERR *cs_parse_string (CSPARSE *parse,       
                  STR* buffer, 
                  int buf_len);
        public static VMPrimitiveExitCode ExecuteGeneric(VMStackFrame context, VMPrimitiveOperand args, STR table)
        {
            var operand   = (VMDialogOperand)args;
            var curDialog = (VMDialogResult)context.Thread.BlockingState;

            if (curDialog == null)
            {
                VMDialogHandler.ShowDialog(context, operand, table);

                if ((operand.Flags & VMDialogFlags.Continue) == 0)
                {
                    context.Thread.BlockingState = new VMDialogResult
                    {
                        Type         = operand.Type,
                        HasDisplayed = true
                    };
                    return(VMPrimitiveExitCode.CONTINUE_NEXT_TICK);
                }
                else
                {
                    return(VMPrimitiveExitCode.GOTO_TRUE);
                }
            }
            else
            {
                if (curDialog.Responded || curDialog.WaitTime > DIALOG_MAX_WAITTIME)
                {
                    context.Thread.BlockingState = null;
                    context.VM.SignalDialog(null);
                    switch (curDialog.Type)
                    {
                    default:
                    case VMDialogType.Message:
                        return(VMPrimitiveExitCode.GOTO_TRUE);

                    case VMDialogType.YesNo:
                        return((curDialog.ResponseCode == 0) ? VMPrimitiveExitCode.GOTO_TRUE : VMPrimitiveExitCode.GOTO_FALSE);

                    case VMDialogType.YesNoCancel:
                        if (curDialog.ResponseCode > 1)
                        {
                            context.Thread.TempRegisters[((operand.Flags & VMDialogFlags.UseTemp1) > 0) ? 1 : 0] = (short)((curDialog.ResponseCode - 1) % 2);
                            return(VMPrimitiveExitCode.GOTO_FALSE);
                        }
                        else
                        {
                            return(VMPrimitiveExitCode.GOTO_TRUE);
                        }

                    case VMDialogType.TextEntry:
                        //todo: filter profanity, limit name length
                        //also verify behaviour.
                        if ((curDialog.ResponseText ?? "") != "")
                        {
                            ((VMAvatar)context.StackObject).Name = curDialog.ResponseText;
                        }
                        return(VMPrimitiveExitCode.GOTO_TRUE);

                    case VMDialogType.NumericEntry:
                        int number;
                        if (!int.TryParse(curDialog.ResponseText, out number))
                        {
                            return(VMPrimitiveExitCode.GOTO_FALSE);
                        }

                        var tempNumber = ((operand.Flags & VMDialogFlags.UseTemp1) > 0) ? 1 : 0;

                        if ((operand.Flags & VMDialogFlags.UseTempXL) > 0)
                        {
                            context.Thread.TempXL[tempNumber] = number;
                        }
                        else
                        {
                            context.Thread.TempRegisters[tempNumber] = (short)number;
                        }
                        return(VMPrimitiveExitCode.GOTO_TRUE);
                    }
                }
                else
                {
                    if (!curDialog.HasDisplayed)
                    {
                        VMDialogHandler.ShowDialog(context, operand, table);
                        curDialog.HasDisplayed = true;
                    }
                    return(VMPrimitiveExitCode.CONTINUE_NEXT_TICK);
                }
            }
        }
Beispiel #23
0
 public unsafe NEOERR* handleOutput(void* ctx, STR* more_bytes) {                     
     string data = NeoUtil.PtrToStringUTF8(more_bytes);
     output += data;           
     return null;
 }
Beispiel #24
0
        public Coupling GetCoupling(AnalogChannel channel)
        {
            STR dc = channel == AnalogChannel.ChA ? STR.CHA_DCCOUPLING : STR.CHB_DCCOUPLING;

            return(StrobeMemory[dc].GetBool() ? Coupling.DC : Coupling.AC);
        }
 internal bool GetStrobe(STR s)
 {
     if (!SmartScope.AcquisitionStrobes.Contains(s))
         throw new Exception("Strobe  " + s.ToString("G") + " not part of header");
     int offset = SmartScope.AcquisitionRegisters.Length + SmartScope.DumpRegisters.Length;
     offset += Array.IndexOf(SmartScope.AcquisitionStrobes, s) / 8;
     return Utils.IsBitSet(raw[offset], (int)Array.IndexOf(SmartScope.AcquisitionStrobes, s) % 8);
 }
Beispiel #26
0
 public BoolRegister this[STR r]
 {
     get { return(this[(uint)r]); }
 }
Beispiel #27
0
        /// <summary>
        /// 获取所有字段
        /// </summary>
        /// <returns>查询构建器</returns>
        public GetBuilder <T> SelectAll()
        {
            __select = "*";

            return(this);
        }
Beispiel #28
0
        private void OKButton_Click(object sender, EventArgs e)
        {
            var  name  = ChunkLabelEntry.Text;
            var  guidT = GUIDEntry.Text;
            uint guid;
            var  objProvider = Content.Content.Get().WorldObjects;

            if (name == "")
            {
                MessageBox.Show("Name cannot be empty!", "Invalid Object Name");
            }
            else if (guidT == "")
            {
                MessageBox.Show("GUID cannot be empty!", "Invalid GUID");
            }
            else if (!uint.TryParse(guidT, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out guid))
            {
                MessageBox.Show("GUID is invalid! Make sure it is a hex string of size 8. (eg. 6789ABCD)", "Invalid GUID");
            }
            else
            {
                lock (objProvider.Entries)
                {
                    if (objProvider.Entries.ContainsKey(guid))
                    {
                        MessageBox.Show("This GUID is already being used!", "GUID is Taken!");
                        return;
                    }

                    //OK, it's valid. Now to add it to the objects system...
                    //This is a little tricky because we want to add an object that does not exist yet.
                    //There's a special function just for this! But first, we need an OBJD...

                    var obj = new OBJD()
                    {
                        GUID             = guid,
                        ObjectType       = OBJDType.Normal,
                        ChunkLabel       = name,
                        ChunkID          = 1,
                        ChunkProcessed   = true,
                        ChunkType        = "OBJD",
                        ChunkParent      = TargetIff,
                        AnimationTableID = 128,
                        AddedByPatch     = true
                    };

                    Content.Content.Get().Changes.BlockingResMod(new ResAction(() =>
                    {
                        //find a free space to place the object
                        ushort id = 16807; //todo: why???
                        var list  = TargetIff.List <OBJD>();
                        if (list != null)
                        {
                            foreach (var chk in list.OrderBy(x => x.ChunkID))
                            {
                                if (chk.ChunkID == id)
                                {
                                    id++;
                                }
                            }
                        }
                        obj.ChunkID = id;
                        //add it to the iff file
                        TargetIff.AddChunk(obj);
                    }, obj));

                    if (IsNew)
                    {
                        //add a default animation table, for quality of life reasons

                        var anim = new STR()
                        {
                            ChunkLabel     = name,
                            ChunkID        = 128,
                            ChunkProcessed = true,
                            ChunkType      = "STR#",
                            ChunkParent    = TargetIff,
                        };

                        anim.InsertString(0, new STRItem {
                            Value = "", Comment = ""
                        });
                        TargetIff.AddChunk(anim);

                        var filename = TargetIff.RuntimeInfo.Path;
                        Directory.CreateDirectory(Path.GetDirectoryName(filename));
                        using (var stream = new FileStream(filename, FileMode.Create))
                            TargetIff.Write(stream);
                    }

                    //add it to the provider
                    objProvider.AddObject(TargetIff, obj);

                    DialogResult = DialogResult.OK;
                    ResultGUID   = guid;
                    Close();
                }
            }
        }
Beispiel #29
0
 /// <summary>将驼峰格式转换成以指定字符分隔</summary>
 /// <param name="str">要转换的字符串</param>
 /// <param name="separator">分隔符</param>
 /// <returns>返回转换后的字符串</returns>
 public static string ToSeparate_(this string str, string separator = "-")
 {
     if(str.IsNullOrEmpty_()) return string.Empty;
     char[] _cs = str.ToCharArray();
     int _len = _cs.Length;
     char _c;
     STR _str = new STR((int)Math.Ceiling(_len * 1.5));
     _str += _cs[0];
     for(int i = 1; i < _len; i++)
     {
         _c = _cs[i];
         if(char.IsUpper(_c))
             _str += separator + char.ToLowerInvariant(_c);
         else
             _str += _c;
     }
     return _str.ToString();
 }
Beispiel #30
0
 public static string ParseDialogString(VMStackFrame context, string input, STR source)
 {
     return(ParseDialogString(context, input, source, 0));
 }
Beispiel #31
0
        public override VMPrimitiveExitCode Execute(VMStackFrame context, VMPrimitiveOperand args)
        {
            var operand = (VMRunTreeByNameOperand)args;

            if (context.StackObject == null)
            {
                return(VMPrimitiveExitCode.GOTO_FALSE);
            }

            string name;
            STR    res = null;

            if (operand.StringScope == 1)
            {//global
                res = context.Global.Resource.Get <STR>(operand.StringTable);
            }
            else
            {//local
                if (context.Routine.ID >= 8192 && context.ScopeResource.SemiGlobal != null)
                {
                    res = context.ScopeResource.SemiGlobal.Get <STR>(operand.StringTable);
                }
                if (res == null)
                {
                    res = context.ScopeResource.Get <STR>(operand.StringTable);
                }
            }
            if (res == null)
            {
                return(VMPrimitiveExitCode.GOTO_FALSE);
            }
            name = res.GetString(operand.StringID - 1);

            if (context.StackObject.TreeByName == null)
            {
                return(VMPrimitiveExitCode.GOTO_FALSE);
            }
            if (context.StackObject.TreeByName.ContainsKey(name))
            {
                var tree = context.StackObject.TreeByName[name];

                if (operand.Destination == 2)
                {
                    context.Thread.ExecuteSubRoutine(context, tree.bhav, context.StackObject.Object, new VMSubRoutineOperand(context.Thread.TempRegisters));
                    return(VMPrimitiveExitCode.CONTINUE);
                    //push onto my stack - acts like a subroutine.
                }
                else if (operand.Destination == 0)
                {
                    var result = context.Thread.RunInMyStack(tree.bhav, context.StackObject.Object, context.Thread.TempRegisters, context.StackObject)
                        ? VMPrimitiveExitCode.GOTO_TRUE : VMPrimitiveExitCode.GOTO_FALSE;
                    return((context.VM.Aborting) ? VMPrimitiveExitCode.ERROR : result);
                    //run in my stack
                }
                else
                {
                    var result = context.StackObject.Thread.RunInMyStack(tree.bhav, context.StackObject.Object, context.Thread.TempRegisters, context.StackObject)
                        ? VMPrimitiveExitCode.GOTO_TRUE : VMPrimitiveExitCode.GOTO_FALSE;
                    return((context.VM.Aborting) ? VMPrimitiveExitCode.ERROR : result);
                    //run in stack obj's stack
                }
                //found it! now lets call the tree ;)
            }
            else
            {
                return(VMPrimitiveExitCode.GOTO_FALSE);
            }
        }
 public BoolRegister this[STR r]
 {
     get { return this[(uint)r]; }
 }
Beispiel #33
0
 public UpdateBuilder(BuilderContext context)
 {
     __sql        = new STR();
     this.context = context;
 }
Beispiel #34
0
 public void SetActiveResource(IffChunk chunk, GameIffResource res)
 {
     ActiveString = (STR)chunk;
     UpdateStrings();
 }
Beispiel #35
0
 public OpStaticNamedPropertyProvider(STR strRes) : this(strRes, 0)
 {
 }
Beispiel #36
0
        private static string ToRMB_(decimal num, string digits, string units, string err)
        {
            string _str = num.ToString("F2");
            STR _s = new STR();
            if(_str[0] == '-')
            {
                _s += units[15];
                _str = _str.TrimStart('-');
            }

            string[] _parts = _str.Split('.');

            int _intLen = _parts[0].Length;
            if(_intLen > 12)
                return err;
            bool _int0 = _parts[0] == "0";
            bool _dec0 = _parts[1] == "00";

            int i, j, x, n = 0;
            bool _0 = false, _j0 = false;

            if(_int0 && _dec0)
            {
                _s += digits[0];
                _s += units[1];
            }
            else if(!_int0)
            {
                // 处理整数部分
                for(i = 0; i < _intLen; i++)
                {
                    n = Convert.ToInt32(_parts[0][i]) - 48;
                    x = _intLen - i;
                    // j = 0 时为段尾
                    j = (x - 1) & 0x3;

                    // 处理 0
                    if(n == 0)
                    {
                        _0 = true;
                        // 处理为段尾的 0
                        if(j == 0)
                        {
                            if(_intLen == 1 && _dec0)
                                _s += digits[0];
                            if(_j0 || x == 1)
                                _s += units[x];
                            _j0 = false;
                        }
                    }
                    // 处理非 0
                    else
                    {
                        if(_0)
                        {
                            _s += digits[0];
                            _0 = false;
                        }
                        _s += digits[n];
                        _s += units[x];

                        // 如果是段尾,设置非 0 标志
                        _j0 = j == 0 ? false : true;
                    }
                }
            }

            // 处理小数部分
            // 如果没有小数,添加"整"字符
            if(_dec0)
            {
                _s += units[0];
            }
            else
            {
                int g = n;

                // 角
                n = Convert.ToInt32(_parts[1][0]) - 48;
                if(n != 0)
                {
                    _s += digits[n];
                    _s += units[13];
                }
                else if(_intLen != 1 || g != 0)
                    _s += digits[0];

                // 分
                n = Convert.ToInt32(_parts[1][1]) - 48;
                if(n != 0)
                {
                    _s += digits[n];
                    _s += units[14];
                }
                else
                    _s += units[0];
            }

            return _s.ToString();
        }
Beispiel #37
0
    public static STR Load(BinaryReader data)
    {
        var header = data.ReadBinaryString(4);

        if (!header.Equals(STR.Header))
        {
            throw new Exception("EffectLoader.Load: Header (" + header + ") is not \"STRM\"");
        }

        var version = data.ReadULong();

        if (version != 0x94)
        {
            throw new Exception("EffectLoader.Load: Unsupported STR version (v" + version + ")");
        }

        STR str = new STR();

        str.version = version;
        str.fps     = data.ReadULong();
        str.maxKey  = data.ReadULong();
        var layerCount = data.ReadULong();

        data.Seek(16, System.IO.SeekOrigin.Current);


        //read layers
        str.layers = new STR.Layer[layerCount];
        for (uint i = 0; i < layerCount; i++)
        {
            STR.Layer layer = str.layers[i] = new STR.Layer();

            //read texture filenames
            var textureCount = data.ReadLong();
            layer.textures = new string[textureCount];
            for (int j = 0; j < textureCount; j++)
            {
                layer.textures[j] = "data/texture/effect/" + data.ReadBinaryString(128);
            }

            //read animations
            var animCount = data.ReadLong();
            layer.animations = new STR.Animation[animCount];
            for (int j = 0; j < animCount; j++)
            {
                layer.animations[j] = new STR.Animation()
                {
                    frame    = data.ReadLong(),
                    type     = data.ReadULong(),
                    position = new Vector2(data.ReadFloat(), data.ReadFloat()),
                    uv       = new float[] {
                        data.ReadFloat(), data.ReadFloat(), data.ReadFloat(), data.ReadFloat(),
                                          data.ReadFloat(), data.ReadFloat(), data.ReadFloat(), data.ReadFloat()
                    },
                    xy = new float[] {
                        data.ReadFloat(), data.ReadFloat(), data.ReadFloat(), data.ReadFloat(),
                                          data.ReadFloat(), data.ReadFloat(), data.ReadFloat(), data.ReadFloat()
                    },
                    animFrame = data.ReadFloat(),
                    animType  = data.ReadULong(),
                    delay     = data.ReadFloat(),
                    angle     = data.ReadFloat() / (1024 / 360),
                    color     = new Color(
                        data.ReadFloat() / 255, data.ReadFloat() / 255,
                        data.ReadFloat() / 255, data.ReadFloat() / 255),
                    srcAlpha  = data.ReadULong(),
                    destAlpha = data.ReadULong(),
                    mtPreset  = data.ReadULong()
                };
            }
        }

        return(str);
    }
Beispiel #38
0
        public static object GetSuit(VMStackFrame context, VMSuitScope scope, ushort id)
        {
            STR suitTable = null;

            var avatar = (VMAvatar)context.Caller;

            switch (scope)
            {
            case VMSuitScope.Object:
                suitTable = context.CodeOwner.Resource.Get <STR>(304);
                break;

            case VMSuitScope.Global:
                suitTable = context.Global.Resource.Get <STR>(304);
                break;

            case VMSuitScope.Person:
                //get outfit from person
                if (context.VM.TS1)
                {
                    return(GetPersonSuitTS1((VMAvatar)context.Caller, id));
                }

                var  type = (VMPersonSuits)id;
                bool male = (avatar.GetPersonData(VMPersonDataVariable.Gender) == 0);
                switch (type)
                {
                //todo: (tail etc), cockroach head

                case VMPersonSuits.DefaultDaywear:
                    return(avatar.DefaultSuits.Daywear.ID);

                case VMPersonSuits.Naked:
                    return((ulong)(male ? 0x24E0000000D : 0x10000000D));

                case VMPersonSuits.DefaultSwimwear:
                    return(avatar.DefaultSuits.Swimwear.ID);

                case VMPersonSuits.JobOutfit:
                    if (context.VM.TS1)
                    {
                        return(null);
                    }
                    var job = avatar.GetPersonData(VMPersonDataVariable.OnlineJobID);
                    if (job < 1 || job > 5)
                    {
                        return(null);
                    }
                    var level = Math.Max(0, Math.Min(3, (avatar.GetPersonData(VMPersonDataVariable.OnlineJobGrade) - 1) / 4));
                    return((ulong)(JobOutfits[male?0:1][job - 1][level]));

                case VMPersonSuits.DefaultSleepwear:
                    return(avatar.DefaultSuits.Sleepwear.ID);

                case VMPersonSuits.SkeletonPlus:
                    return((ulong)(0x5750000000D));

                case VMPersonSuits.SkeletonMinus:
                    return((ulong)(0x5740000000D));

                case VMPersonSuits.TeleporterMishap:
                    return((ulong)(male ? 0x2900000000D : 0x4A0000000D));


                case VMPersonSuits.DynamicDaywear:
                    return(avatar.DynamicSuits.Daywear);

                case VMPersonSuits.DynamicSleepwear:
                    return(avatar.DynamicSuits.Sleepwear);

                case VMPersonSuits.DynamicSwimwear:
                    return(avatar.DynamicSuits.Swimwear);

                case VMPersonSuits.DynamicCostume:
                    return(avatar.DynamicSuits.Costume);

                case VMPersonSuits.DecorationHead:
                    return(avatar.Decoration.Head);

                case VMPersonSuits.DecorationBack:
                    return(avatar.Decoration.Back);

                case VMPersonSuits.DecorationShoes:
                    return(avatar.Decoration.Shoes);

                case VMPersonSuits.DecorationTail:
                    return(avatar.Decoration.Tail);
                }

                return(null);
            }

            if (suitTable != null)
            {
                var suitFile = suitTable.GetString(id) + ".apr";

                return(suitFile);
                //var apr = FSO.Content.Content.Get().AvatarAppearances.Get(suitFile);
                //return apr;
            }
            return(null);
        }
Beispiel #39
0
        public static string INSERTANDUPDATEBANKDETAILS(string BankID, string BankName, string ZoneName, string BranchName, string City, string Empanelmentdate, string Validupto, string ContactPerson, string CPHNumber, string BankEmailAddress, string BPHNumber, string Address, string Active, string Ranges, string OTSRanges)
        {
            try
            {
                string[] NormalRange = Ranges.Split(';');
                string[] OTSRange    = OTSRanges.Split(';');

                DataTable NORMALDT = new DataTable();
                NORMALDT.Columns.Add("ID", typeof(int));
                NORMALDT.Columns.Add("RANGE_START", typeof(decimal));
                NORMALDT.Columns.Add("RANGE_END", typeof(decimal));
                NORMALDT.Columns.Add("PERCENTAGE", typeof(decimal));
                foreach (string STR in NormalRange)
                {
                    DataRow NORMALDT_NEWROW = NORMALDT.NewRow();
                    if (STR.Split(',')[0] != string.Empty)
                    {
                        NORMALDT_NEWROW["ID"] = STR.Split(',')[0];
                    }
                    else
                    {
                        return("Please Enter Valid Normal Range.");
                    }

                    if (STR.Split(',')[1] != string.Empty)
                    {
                        NORMALDT_NEWROW["RANGE_START"] = STR.Split(',')[1];
                    }
                    else
                    {
                        return("Please Enter Valid Normal Range Of Start Range.");
                    }

                    if (STR.Split(',')[2] != string.Empty)
                    {
                        NORMALDT_NEWROW["RANGE_END"] = STR.Split(',')[2];
                    }
                    else
                    {
                        return("Please Enter Valid Normal Range Of End Range.");
                    }

                    if (STR.Split(',')[3] != string.Empty)
                    {
                        NORMALDT_NEWROW["PERCENTAGE"] = STR.Split(',')[3];
                    }
                    else
                    {
                        return("Please Enter Valid Normal Range Of Percentage.");
                    }
                    NORMALDT.Rows.Add(NORMALDT_NEWROW);
                }

                DataTable OTSDT = new DataTable();
                OTSDT.Columns.Add("ID", typeof(int));
                OTSDT.Columns.Add("RANGE_START", typeof(decimal));
                OTSDT.Columns.Add("RANGE_END", typeof(decimal));
                OTSDT.Columns.Add("PERCENTAGE", typeof(decimal));


                foreach (string STR in OTSRange)
                {
                    DataRow OTSDT_NEWROW = OTSDT.NewRow();
                    if (STR.Split(',')[0] != string.Empty)
                    {
                        OTSDT_NEWROW["ID"] = STR.Split(',')[0];
                    }
                    else
                    {
                        return("Please Enter Valid OTS Range.");
                    }

                    if (STR.Split(',')[1] != string.Empty)
                    {
                        OTSDT_NEWROW["RANGE_START"] = STR.Split(',')[1];
                    }
                    else
                    {
                        return("Please Enter Valid OTS Range Of Start Range.");
                    }

                    if (STR.Split(',')[2] != string.Empty)
                    {
                        OTSDT_NEWROW["RANGE_END"] = STR.Split(',')[2];
                    }
                    else
                    {
                        return("Please Enter Valid OTS Range End Range.");
                    }

                    if (STR.Split(',')[3] != string.Empty)
                    {
                        OTSDT_NEWROW["PERCENTAGE"] = STR.Split(',')[3];
                    }
                    else
                    {
                        return("Please Enter Valid OTS Range Of Percentage.");
                    }
                    OTSDT.Rows.Add(OTSDT_NEWROW);
                }

                //Ranges = Ranges.Replace(',', '/');
                //Ranges = Ranges.Replace('.', '?');

                //OTSRanges = OTSRanges.Replace(',', '/');
                //OTSRanges = OTSRanges.Replace('.', '?');
                DataSet DT = CRBusinessLogicLayer.BANK_DETAILS_INSERT_UPDATE(BankID, BankName, ZoneName, BranchName, City, Empanelmentdate, Validupto, ContactPerson, CPHNumber, BankEmailAddress, BPHNumber, Address, Active, NORMALDT, OTSDT);
                if (DT.Tables.Count > 0)
                {
                    return(DT.Tables[0].Rows[0][0].ToString());
                }
                else
                {
                    return("");
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }