Пример #1
0
 public static void Eq(Arguments args, VM vm, SourceInfo info)
 {
     Check(args, 2, info);
     ValueInt integer1 = (ValueInt)args[0];
     ValueInt integer2 = (ValueInt)args[1];
     vm.Push((integer1.Value == integer2.Value).ToValueBool());
 }
Пример #2
0
 public static void Klasses(Arguments args, VM vm, SourceInfo info)
 {
     IList<IValue> list = args[0].KlassList.Select(
         (elem) => (IValue)elem
     ).ToList();
     vm.Push(new ValueArray(list));
 }
Пример #3
0
        public override bool Execute(VM vm)
        {
            var type = State.GetType();
            //if ID is 0, there is no thread to unblock, and we just have to do the extra functionality below.
            if (ID != 0)
            {
                VMEntity obj = vm.GetObjectById(ID);
                //we can only update an object's blocking state if it exists and is of the same type exactly.
                if (obj == null || obj.Thread.BlockingState == null || obj.Thread.BlockingState.GetType() != type) return false;
                obj.Thread.BlockingState = State;
            }

            if (type == typeof(VMTransferFundsState))
            {
                //special handling. update visual budgets of involved elements.
                //note: if we are the server and the reference budget IS the visual, do not update.
                if (vm.GlobalLink == null || !(vm.GlobalLink is VMTSOGlobalLinkStub))
                {
                    var state = (VMTransferFundsState)State;
                    var obj1 = vm.GetObjectByPersist(state.UID1);
                    if (obj1 != null) obj1.TSOState.Budget.Value = state.Budget1;
                    var obj2 = vm.GetObjectByPersist(state.UID2);
                    if (obj2 != null) obj2.TSOState.Budget.Value = state.Budget2;
                }
            }

            return true;
        }
Пример #4
0
        public void Connect(uint UID, VMEntity invoker, VMEntity obj, VMAvatar avatar, bool joinable, VM vm)
        {
            if (InvokerToEOD.ContainsKey(invoker.ObjectID)) return; //uh, what?

            VMEODServer server = null;
            if (avatar != null && AvatarToEOD.ContainsKey(avatar.PersistID))
            {
                //avatar already using an EOD... quickly abort this attempt with the stub EOD.
                joinable = false;
                UID = 0;
                avatar = null;
            }

            if (joinable)
            {
                if (!JoinableEODs.TryGetValue(obj.ObjectID, out server))
                {
                    server = new VMEODServer(UID, obj, joinable, vm);
                    JoinableEODs[obj.ObjectID] = server;
                    Servers.Add(server);
                }
            }
            else
            {
                server = new VMEODServer(UID, obj, joinable, vm);
                Servers.Add(server);
            }

            if (avatar != null) RegisterAvatar(avatar, server);
            RegisterInvoker(invoker, server);
            server.Connect(new VMEODClient(invoker, avatar, vm, UID));
        }
Пример #5
0
        protected void InternalTick(VM vm, VMNetTick tick)
        {
            if (!tick.ImmediateMode && (tick.Commands.Count == 0 || !(tick.Commands[0].Command is VMStateSyncCmd)) && vm.Context.RandomSeed != tick.RandomSeed)
            {
                if (DesyncCooldown == 0)
                {
                    System.Console.WriteLine("DESYNC - Requested state from host");
                    vm.SendCommand(new VMRequestResyncCmd());
                    DesyncCooldown = 30 * 3;
                } else
                {
                    System.Console.WriteLine("WARN - DESYNC - Too soon to try again!");
                }
                ExceptionOnDesync = true;
            }
            vm.Context.RandomSeed = tick.RandomSeed;
            bool doTick = !tick.ImmediateMode;
            foreach(var cmd in tick.Commands)
            {
                if (cmd.Command is VMStateSyncCmd) doTick = false;

                var caller = vm.GetObjectByPersist(cmd.Command.ActorUID);
                if (!(caller is VMAvatar)) caller = null;
                cmd.Command.Execute(vm, (VMAvatar)caller);
            }
            if (doTick && vm.Context.Ready)
            {
                vm.InternalTick();
                if (DesyncCooldown > 0) DesyncCooldown--;
            }
        }
Пример #6
0
 public static void MakeInstance(Arguments args, VM vm, SourceInfo info)
 {
     ValueArray array = args[0] as ValueArray;
     ValueHash hash = args[1] as ValueHash;
     if (array == null ||
         array.Value.Any((elem) => !(elem is ValueSymbol)))
     {
         throw new RheaException(
             string.Format("array(symbol) required, but got {0}", args[0]), info
         );
     }
     if (hash == null ||
         hash.Value.Any((kvp) => !(kvp.Key is ValueSymbol) || !(kvp.Value is IValueFunc)))
     {
         throw new RheaException(
             string.Format("hash(symbol, function) required, but got {0}", args[1]), info
         );
     }
     IList<ValueSymbol> klasses = array.Value.Select(
         (elem) => (ValueSymbol)elem
     ).ToList();
     IDictionary<ValueSymbol, IValueFunc> slots = hash.Value.ToDictionary(
         (kvp) => (ValueSymbol)kvp.Key,
         (kvp) => (IValueFunc)kvp.Value
     );
     vm.Push(new ValueInstance(klasses, slots));
 }
Пример #7
0
        public override bool Execute(VM vm)
        {
            var sim = vm.Entities.FirstOrDefault(x => x is VMAvatar && x.PersistID == SimID);

            if (sim != null) sim.Delete(true, vm.Context);
            return true;
        }
Пример #8
0
        public override bool Execute(VM vm)
        {
            Name = Name.Substring(0, Math.Min(Name.Length, 64));
            var sim = vm.Context.CreateObjectInstance(VMAvatar.TEMPLATE_PERSON, LotTilePos.OUT_OF_WORLD, Direction.NORTH).Objects[0];
            var mailbox = vm.Entities.FirstOrDefault(x => (x.Object.OBJ.GUID == 0xEF121974 || x.Object.OBJ.GUID == 0x1D95C9B0));

            if (VM.UseWorld) FSO.HIT.HITVM.Get().PlaySoundEvent("lot_enter");
            if (mailbox != null) VMFindLocationFor.FindLocationFor(sim, mailbox, vm.Context);
            sim.PersistID = ActorUID;

            VMAvatar avatar = (VMAvatar)sim;
            avatar.SkinTone = (Vitaboy.AppearanceType)SkinTone;
            avatar.SetPersonData(VMPersonDataVariable.Gender, (short)((Gender) ? 1 : 0));
            avatar.DefaultSuits = new VMAvatarDefaultSuits(Gender);
            avatar.DefaultSuits.Daywear = BodyID;
            avatar.BodyOutfit = BodyID;
            avatar.HeadOutfit = HeadID;
            avatar.Name = Name;
            ((VMTSOAvatarState)avatar.TSOState).Permissions = Permissions;

            if (ActorUID == uint.MaxValue - 1)
            {
                avatar.SetValue(VMStackObjectVariable.Hidden, 1);
                avatar.SetPosition(LotTilePos.OUT_OF_WORLD, Direction.NORTH, vm.Context);
                avatar.SetFlag(VMEntityFlags.HasZeroExtent, true);
                avatar.SetPersonData(VMPersonDataVariable.IsGhost, 1); //oooooOOooooOo
            }

            if (RequesterID == vm.MyUID) vm.MyUID = ActorUID; //we're this sim! try send commands as them.
            vm.SignalChatEvent(new VMChatEvent(avatar.PersistID, VMChatEventType.Join, avatar.Name));

            return true;
        }
Пример #9
0
 public override bool Execute(VM vm)
 {
     VMEntity obj = vm.GetObjectById(ObjectID);
     if (obj == null || (obj is VMAvatar)) return false;
     obj.Delete(CleanupAll, vm.Context);
     return true;
 }
Пример #10
0
 private ConsoleColor ConvertColor(VM.Color zColor)
 {
     switch (zColor)
     {
         case Color.Black:
             return ConsoleColor.Black;
         case Color.Red:
             return ConsoleColor.Red;
         case Color.Green:
             return ConsoleColor.Green;
         case Color.Yellow:
             return ConsoleColor.Yellow;
         case Color.Blue:
             return ConsoleColor.Blue;
         case Color.Magenta:
             return ConsoleColor.Magenta;
         case Color.Cyan:
             return ConsoleColor.Cyan;
         case Color.White:
             return ConsoleColor.White;
         case Color.DarkishGray:
             return ConsoleColor.DarkGray;
         default:
             return ConsoleColor.Black;
     }
 }
Пример #11
0
        public override bool Execute(VM vm, VMAvatar caller)
        {
            var catalog = Content.Content.Get().WorldCatalog;
            var item = catalog.GetItemByGUID(GUID);
            if (Blacklist.Contains(GUID) || caller == null) return false;

            //careful here! if the object can't be placed, we have to give the user their money back.
            if (TryPlace(vm, caller)) return true;
            else if (vm.GlobalLink != null && item != null)
            {
                vm.GlobalLink.PerformTransaction(vm, false, uint.MaxValue, caller.PersistID, (int)item.Price,
                (bool success, int transferAmount, uint uid1, uint budget1, uint uid2, uint budget2) =>
                {
                    vm.SendCommand(new VMNetAsyncResponseCmd(0, new VMTransferFundsState
                    { //update budgets on clients. id of 0 means there is no target thread.
                        Responded = true,
                        Success = success,
                        TransferAmount = transferAmount,
                        UID1 = uid1,
                        Budget1 = budget1,
                        UID2 = uid2,
                        Budget2 = budget2
                    }));
                });
            }
            return false;
        }
        public void Test_WPFBrowserNavigator_Simple()
        {
            var vm = new VM();
            TestNavigation((wpfnav, WindowTest)
                =>
                {
                    wpfnav.Should().NotBeNull();
                    _INavigationBuilder.Register<VM>("Navigation data\\index.html");
                    wpfnav.UseINavigable = true;

                    var mre = new ManualResetEvent(false);
                    DateTime? nav = null;
                    DateTime? Opened = null;
                    DisplayEvent de = null;

                    wpfnav.OnDisplay += (o, e) => { Opened = DateTime.Now; de = e; };

                    WindowTest.RunOnUIThread(
                   () =>
                   {
                       wpfnav.NavigateAsync(vm).ContinueWith
                      (
                          t =>
                          {
                              vm.Navigation.Should().Be(wpfnav);
                              nav = DateTime.Now;
                              mre.Set();
                          });
                   });

                    mre.WaitOne();
                    mre = new ManualResetEvent(false);
                    Thread.Sleep(4500);

                    de.Should().NotBeNull();
                    de.DisplayedViewModel.Should().Be(vm);
                    Opened.HasValue.Should().BeTrue();
                    Opened.Value.Subtract(nav.Value).Should().BeGreaterThan(TimeSpan.FromSeconds(2)).
                        And.BeLessOrEqualTo(TimeSpan.FromSeconds(3));

                    WindowTest.RunOnUIThread(
                 () =>
                 {
                     wpfnav.NavigateAsync(vm).ContinueWith
                    (
                        t =>
                        {
                           
                            mre.Set();
                        });
                 });

                    mre.WaitOne();
                    Thread.Sleep(500); 
                    vm.Navigation.Should().Be(wpfnav);
                });


        }
        public override bool Execute(VM vm)
        {
            var sim = vm.Context.CreateObjectInstance(VMAvatar.TEMPLATE_PERSON, LotTilePos.OUT_OF_WORLD, Direction.NORTH).Objects[0];
            var mailbox = vm.Entities.First(x => (x.Object.OBJ.GUID == 0xEF121974 || x.Object.OBJ.GUID == 0x1D95C9B0));

            VMFindLocationFor.FindLocationFor(sim, mailbox, vm.Context);
            return true;
        }
Пример #14
0
 public override bool Verify(VM vm, VMAvatar caller)
 {
     if (Verified == true) return true; //temporary... forward messages through tick broadcast
     //only run by server. Forward message to this avatar's connected EOD.
     if (caller == null) return false;
     vm.EODHost.Deliver(this, caller);
     return false;
 }
Пример #15
0
 public override bool Execute(VM vm)
 {
     VMEntity caller = vm.GetObjectById(CallerID);
     //TODO: check if net user owns caller!
     if (caller == null || caller is VMGameObject) return false;
     ((VMAvatar)caller).Message = Message;
     return true;
 }
Пример #16
0
 public static void SetItem(Arguments args, VM vm, SourceInfo info)
 {
     Check(args, 1, info);
     ValueHash hash = (ValueHash)args[0];
     IValue key = args[1];
     IValue value = args[2];
     vm.Push(hash.Value[key] = value);
 }
Пример #17
0
        public override bool Execute(VM vm)
        {
            VMEntity caller = vm.Entities.FirstOrDefault(x => x.PersistID == ActorUID);
            if (caller == null) return false;

            caller.Thread.CancelAction(ActionUID);

            return true;
        }
Пример #18
0
        public override bool Execute(VM vm)
        {
            VMEntity callee = vm.GetObjectById(CalleeID);
            VMEntity caller = vm.Entities.FirstOrDefault(x => x.PersistID == ActorUID);
            if (callee == null || caller == null) return false;
            callee.PushUserInteraction(Interaction, caller, vm.Context, new short[] { Param0, 0, 0, 0 });

            return true;
        }
        public static SerializedRuntimeState FromRuntimeState(VM.RuntimeState state)
        {
            SerializedRuntimeState serState = new SerializedRuntimeState();
            serState.IP = state.IP;
            serState.LSLState = state.LSLState;
            serState.Globals = SerializedLSLPrimitive.FromPrimitiveList(state.Globals);
            serState.Operands = SerializedLSLPrimitive.FromPrimitiveStack(state.Operands);



            serState.Calls = new SerializedStackFrame[state.Calls.Count];
            int i = 0;
            foreach (VM.StackFrame frame in state.Calls)
            {
                serState.Calls[i] = SerializedStackFrame.FromStackFrame(frame);
                i++;
            }

            serState.TopFrame = SerializedStackFrame.FromStackFrame(state.TopFrame);
            serState.MemInfo = state.MemInfo;

            serState.EventQueue = new SerializedPostedEvent[state.EventQueue.Count];
            i = 0;
            foreach (VM.PostedEvent evt in state.EventQueue)
            {
                serState.EventQueue[i] = SerializedPostedEvent.FromPostedEvent(evt);
                i++;
            }

            serState.RunState = state.RunState;
            serState.Enabled = state.GeneralEnable;

            UInt64 tickCountNow = Util.Clock.GetLongTickCount();
            serState.StateCapturedOn = DateTime.Now;

            //if the next wakeup is in the past, just filter it to be now equal to the state capture time
            //this prevents strange values from getting into the tickcounttodatetime calculation
            serState.NextWakeup = state.NextWakeup < tickCountNow ? serState.StateCapturedOn : Util.Clock.TickCountToDateTime(state.NextWakeup, tickCountNow);
            serState.TimerLastScheduledOn = Util.Clock.TickCountToDateTime(state.TimerLastScheduledOn, tickCountNow);

            serState.TimerInterval = state.TimerInterval;
            serState.RunningEvent = SerializedPostedEvent.FromPostedEvent(state.RunningEvent);
            serState.ActiveListens = new Dictionary<int, VM.ActiveListen>(state.ActiveListens);
            serState.StartParameter = state.StartParameter;

            serState.MiscAttributes = new Dictionary<int, SerializedLSLPrimitive[]>();
            foreach (KeyValuePair<int, object[]> kvp in state.MiscAttributes)
            {
                serState.MiscAttributes[kvp.Key] = SerializedLSLPrimitive.FromPrimitiveList(kvp.Value);
            }
        
            //calculate total runtime
            serState.TotalRuntime = state.TotalRuntime;

            return serState;
        }
        public override bool Execute(VM vm)
        {
            VMEntity callee = vm.GetObjectById(CalleeID);
            VMEntity caller = vm.GetObjectById(CallerID);
            //TODO: check if net user owns caller!
            if (callee == null || caller == null) return false;
            callee.PushUserInteraction(Interaction, caller, vm.Context);

            return true;
        }
Пример #21
0
        public void LoadPluginPersist(VM vm, uint objectPID, uint pluginID, VMAsyncPluginLoadCallback callback)
        {
            var dat = Database.LoadPluginPersist(objectPID, pluginID);

            new System.Threading.Thread(() =>
            {
                System.Threading.Thread.Sleep(100);
                callback(dat);
            }).Start();
        }
Пример #22
0
 public static void Add(Arguments args, VM vm, SourceInfo info)
 {
     Check(args, 2, info);
     ValueInt integer1 = (ValueInt)args[0];
     ValueInt integer2 = (ValueInt)args[1];
     ValueInt newInteger = new ValueInt(
         integer1.Value + integer2.Value
     );
     vm.Push(newInteger);
 }
Пример #23
0
 public override bool Execute(VM vm)
 {
     VMEntity caller = vm.GetObjectById(CallerID);
     //TODO: check if net user owns caller!
     if (caller == null || caller is VMGameObject || caller.Thread.BlockingDialog == null) return false;
     caller.Thread.BlockingDialog.Responded = true;
     caller.Thread.BlockingDialog.ResponseCode = ResponseCode;
     caller.Thread.BlockingDialog.ResponseText = ResponseText;
     return true;
 }
 public ConfigurationForm(string watchToken, VM vm, bool isLocal)
 {
     _isLocal = isLocal;
     InitializeComponent();
     if (_isLocal)
         _watchToken = watchToken;
     _vm = vm;
     readConfiguration();
     Text = _isLocal ? "Solution Configuration" : "Global Template Configuration";
 }
Пример #25
0
        public override bool Execute(VM vm)
        {
            VMEntity callee = vm.Context.CreateObjectInstance(GOTO_GUID, new LotTilePos(x, y, level), Direction.NORTH).Objects[0];
            VMEntity caller = vm.GetObjectById(CallerID);
            //TODO: check if net user owns caller!
            if (callee == null || callee.Position == LotTilePos.OUT_OF_WORLD || caller == null) return false;
            callee.PushUserInteraction(Interaction, caller, vm.Context);

            return true;
        }
Пример #26
0
 //type 1: interaction callback
 public VMActionCallback(VM vm, byte interactionNumber, VMEntity target, VMEntity stackObj, VMEntity caller, bool paramAsObjectID)
 {
     this.type = 1;
     this.Target = target;
     this.Interaction = interactionNumber;
     this.SetParam = paramAsObjectID;
     this.StackObject = stackObj;
     this.vm = vm;
     this.Caller = caller;
 }
Пример #27
0
 public override bool Execute(VM vm)
 {
     vm.SignalDialog(new SimAntics.Model.VMDialogInfo
     {
         Title = Title,
         Message = Message,
         Block = false,
     });
     return true;
 }
Пример #28
0
        public override bool Execute(VM vm, VMAvatar caller)
        {
            //only run by client. send to their UI handler.
            //TODO: DO NOT BROADCAST VIA SYNC COMMAND INTERFACE TO ALL. ONLY TO TARGET!
            if (caller != null && caller.PersistID == vm.MyUID)
            {
                vm.SignalEODMessage(this);
            }

            return true;
        }
Пример #29
0
 public void LeaveLot(VM vm, VMAvatar avatar)
 {
     //TODO: in the global server, this will save the avatar (and possibly lot) states and send back to server.
     if (avatar.PersistID == vm.MyUID)
     {
         //stub has some functionality here. if we have left lot, disconnect.
         vm.CloseNet(VMCloseNetReason.LeaveLot);
     }
     avatar.Delete(true, vm.Context);
     vm.Context.VM.SignalChatEvent(new VMChatEvent(avatar.PersistID, VMChatEventType.Leave, avatar.Name));
 }
Пример #30
0
        public void AssertSteps(string hexBytes, string expected, int numberOfSteps = 1)
        {
            var vm = new VM();
            var program = new Program(hexBytes.HexToByteArray());
            for (var i = 0; i < numberOfSteps; i++)
            {
                vm.Step(program);
            }
 
            Assert.Equal(expected, program.Stack.Peek().ToHex().ToUpper());
        }
Пример #31
0
        public static void RestoreRoad(VM vm, byte roads)
        {
            //lo bits: road flags
            //hi bits: road corners flags
            var arch = vm.Context.Architecture;

            //road starts: bit 1 = citymapRight = topLeft
            //bit 2 = citymapBottom = topRight (and so on in clockwise order)

            if ((roads & 8) > 0)
            {
                RepeatTilemap(arch, TopLeftRoadTile, 1, 1, 1, 1, (arch.Height + 3) / 4);
                StampTilemap(arch, TopLeftRoadCrossing, 1, 3, 1);
                StampTilemap(arch, TopLeftRoadCrossing, 1, (short)(arch.Height - 9), 1);
            }
            if ((roads & 4) > 0)
            {
                RepeatTilemap(arch, TopRightRoadTile, 1, 1, 1, (arch.Width + 3) / 4, 1);
                StampTilemap(arch, TopRightRoadCrossing, 3, 1, 1);
                StampTilemap(arch, TopRightRoadCrossing, (short)(arch.Width - 9), 1, 1);
            }
            if ((roads & 2) > 0)
            {
                RepeatTilemap(arch, BottomRightRoadTile, (short)(arch.Width - 7), 1, 1, 1, (arch.Height + 3) / 4);
                StampTilemap(arch, BottomRightRoadCrossing, (short)(arch.Width - 7), 3, 1);
                FillTiles(arch, 9, (short)(arch.Width - 2), 1, 1, 1, 2);
                StampTilemap(arch, BottomRightRoadCrossing, (short)(arch.Width - 7), (short)(arch.Height - 9), 1);
                FillTiles(arch, 9, (short)(arch.Width - 2), (short)(arch.Height - 4), 1, 1, 3);
            }
            if ((roads & 1) > 0)
            {
                RepeatTilemap(arch, BottomLeftRoadTile, 1, (short)(arch.Height - 7), 1, (arch.Width + 3) / 4, 1);
                StampTilemap(arch, BottomLeftRoadCrossing, 3, (short)(arch.Height - 7), 1);
                FillTiles(arch, 9, 1, (short)(arch.Height - 2), 1, 2, 1);
                StampTilemap(arch, BottomLeftRoadCrossing, (short)(arch.Width - 9), (short)(arch.Height - 7), 1);
                FillTiles(arch, 9, (short)(arch.Width - 4), (short)(arch.Height - 2), 1, 3, 1);
            }

            if ((roads & 12) == 12)
            {
                StampTilemap(arch, TopRoadInnerCorner, 1, 1, 1, true);
            }
            if ((roads & 6) == 6)
            {
                StampTilemap(arch, RightRoadInnerCorner, (short)(arch.Width - 9), 1, 1, true);
            }
            if ((roads & 3) == 3)
            {
                StampTilemap(arch, BottomRoadInnerCorner, (short)(arch.Width - 9), (short)(arch.Height - 9), 1, true);
            }
            if ((roads & 9) == 9)
            {
                StampTilemap(arch, LeftRoadInnerCorner, 1, (short)(arch.Height - 9), 1, true);
            }


            //corners start bit 1 = citymapTopRight = left,
            //bit2 = citymapBottomRight = top (and so on in clockwise order)

            var corners = (roads >> 4);

            if ((corners & 1) > 0)
            {
                StampTilemap(arch, LeftRoadCorner, 1, (short)(arch.Height - 7), 1);
            }
            if ((corners & 2) > 0)
            {
                StampTilemap(arch, BottomRoadCorner, (short)(arch.Width - 7), (short)(arch.Height - 7), 1);
            }
            if ((corners & 4) > 0)
            {
                StampTilemap(arch, RightRoadCorner, (short)(arch.Width - 7), 1, 1);
            }
            if ((corners & 8) > 0)
            {
                StampTilemap(arch, TopRoadCorner, 1, 1, 1);
            }
        }
Пример #32
0
 protected override Host GetHost(VM vm)
 {
     return(_host);
 }
Пример #33
0
        public static void RestoreSurroundings(VM vm, byte[][] hollowAdj)
        {
            var myArch   = vm.Context.Architecture;
            var terrain  = vm.TSOState.Terrain;
            var size     = myArch.Width;
            var lotsMode = WorldConfig.Current.SurroundingLots;

            foreach (var world in vm.Context.Blueprint.SubWorlds)
            {
                world.Dispose();
            }
            vm.Context.Blueprint.SubWorlds.Clear();

            var baseHeight = GetBaseLevel(vm, terrain, 1, 1);

            //vm.Context.Blueprint.BaseAlt = 0;// 128;
            //vm.Context.World.State.BaseHeight = 0;// (128 * 3) / 16f;

            if (lotsMode == 0)
            {
                return;
            }
            for (int y = 0; y < 3; y++)
            {
                for (int x = 0; x < 3; x++)
                {
                    if (x == 1 & y == 1)
                    {
                        continue;                  //that's us...
                    }
                    var gd       = vm.Context.World.State.Device;
                    var subworld = vm.Context.World.MakeSubWorld(gd);
                    subworld.Initialize(gd);
                    var tempVM = new VM(new VMContext(subworld), new VMServerDriver(new VMTSOGlobalLinkStub()), new VMNullHeadlineProvider());
                    tempVM.Init();

                    var state = (hollowAdj == null)? null : hollowAdj[y * 3 + x];
                    if (lotsMode == 1)
                    {
                        state = null;
                    }

                    float           height = 0;
                    VMHollowMarshal hollow = null;
                    if (state != null)
                    {
                        try
                        {
                            hollow = new VMHollowMarshal();
                            using (var reader = new BinaryReader(new MemoryStream(state))) {
                                hollow.Deserialize(reader);
                            }
                            tempVM.HollowLoad(hollow);
                            RestoreTerrain(tempVM, terrain.BlendN[x, y], terrain.Roads[x, y], RestoreLotType.Normal);
                            if (hollow.Version < 19)
                            {
                                height = RestoreHeight(tempVM, terrain, x, y);
                            }
                            else
                            {
                                height = GetBaseLevel(tempVM, terrain, x, y);
                            }
                            tempVM.Context.Blueprint.BaseAlt = (int)((baseHeight - height));
                            foreach (var obj in tempVM.Entities)
                            {
                                obj.Position = obj.Position;
                            }

                            tempVM.Tick();
                            subworld.CalculateFloorsUsed();
                        } catch (Exception)
                        {
                            hollow = null;
                            hollowAdj[y * 3 + x] = null;
                            subworld.Dispose();
                            x--;
                            continue; //try this surrounding lot again, but as an empty one.
                        }
                    }

                    if (hollow == null)
                    {
                        var blueprint = new Blueprint(size, size);
                        tempVM.Context.Blueprint = blueprint;
                        subworld.InitBlueprint(blueprint);
                        tempVM.Context.Architecture = new VMArchitecture(size, size, blueprint, tempVM.Context);

                        tempVM.Context.Architecture.EmptyRoomMap();
                        tempVM.Context.RegeneratePortalInfo();

                        var terrainC = new TerrainComponent(new Rectangle(0, 0, size, size), blueprint);
                        terrainC.Initialize(subworld.State.Device, subworld.State);
                        blueprint.Terrain = terrainC;

                        tempVM.Context.Architecture.Terrain.LowQualityGrassState = true;
                        RestoreTerrain(tempVM, terrain.BlendN[x, y], terrain.Roads[x, y], RestoreLotType.Blank);
                        height = RestoreHeight(tempVM, terrain, x, y);
                        tempVM.Context.Blueprint.BaseAlt = (int)((baseHeight - height));

                        PopulateBlankTerrain(tempVM);
                        tempVM.Context.Architecture.ClearDirty();
                        tempVM.Context.Architecture.RegenRoomMap();
                        tempVM.Context.RegeneratePortalInfo();
                        tempVM.Context.RefreshAllLighting();
                        tempVM.Tick();
                    }

                    subworld.State.Level = 5;

                    subworld.GlobalPosition = new Vector2((1 - y) * (size - 2), (x - 1) * (size - 2));

                    vm.Context.Blueprint.SubWorlds.Add(subworld);
                }
            }
            vm.Context.World.InitSubWorlds();
        }
Пример #34
0
        public void Apply(VM vm)
        {
            var wallMap  = BuildDict(WallNamesByID, Content.Content.Get().WorldWalls.DynamicWallFromID, vm.LoadErrors, VMLoadErrorCode.MISSING_WALL);
            var floorMap = BuildDict(FloorNamesByID, Content.Content.Get().WorldFloors.DynamicFloorFromID, vm.LoadErrors, VMLoadErrorCode.MISSING_FLOOR);

            var arch = vm.Context.Architecture;

            foreach (var floors in arch.Floors)
            {
                for (int i = 0; i < floors.Length; i++)
                {
                    var floor = floors[i];
                    if (floor.Pattern != 0)
                    {
                        ushort newID;
                        if (floorMap.TryGetValue(floor.Pattern, out newID))
                        {
                            floors[i].Pattern = newID;
                        }
                    }
                }
            }

            foreach (var walls in arch.Walls)
            {
                for (int i = 0; i < walls.Length; i++)
                {
                    var    wall = walls[i];
                    ushort newID;
                    if (wall.BottomLeftPattern != 0)
                    {
                        if (wallMap.TryGetValue(wall.BottomLeftPattern, out newID))
                        {
                            walls[i].BottomLeftPattern = newID;
                        }
                    }
                    if (wall.BottomRightPattern != 0)
                    {
                        if (wallMap.TryGetValue(wall.BottomRightPattern, out newID))
                        {
                            walls[i].BottomRightPattern = newID;
                        }
                    }
                    if ((wall.Segments & WallSegments.AnyDiag) > 0)
                    {
                        //diagonally split floors
                        if (wall.TopLeftPattern != 0)
                        {
                            if (floorMap.TryGetValue(wall.TopLeftPattern, out newID))
                            {
                                walls[i].TopLeftPattern = newID;
                            }
                        }
                        if (wall.TopLeftStyle != 0)
                        {
                            if (floorMap.TryGetValue(wall.TopLeftStyle, out newID))
                            {
                                walls[i].TopLeftStyle = newID;
                            }
                        }
                    }
                    else
                    {
                        if (wall.TopLeftPattern != 0)
                        {
                            if (wallMap.TryGetValue(wall.TopLeftPattern, out newID))
                            {
                                walls[i].TopLeftPattern = newID;
                            }
                        }
                        if (wall.TopRightPattern != 0)
                        {
                            if (wallMap.TryGetValue(wall.TopRightPattern, out newID))
                            {
                                walls[i].TopRightPattern = newID;
                            }
                        }
                    }
                }
            }

            arch.RoofStyle = (uint)Content.Content.Get().WorldRoofs.NameToID(Roof);
            if (arch.RoofStyle == int.MaxValue)
            {
                vm.LoadErrors.Add(new VMLoadError(VMLoadErrorCode.MISSING_ROOF, Roof));
                arch.RoofStyle = 0;
            }
            arch.SignalAllDirty();
        }
Пример #35
0
        public static DataSet Create(string uuid, IXenObject xo, bool show, string settype)
        {
            var dataSet = new DataSet(uuid, xo, show, settype);

            if (settype == "xapi_open_fds" || settype == "pool_task_count" || settype == "pool_session_count")
            {
                dataSet.NeverShow = true;
            }
            if (settype.StartsWith("latency") || settype.EndsWith("latency"))
            {
                if (settype.StartsWith("latency"))
                {
                    //if it's storage latency xapi units are in milliseconds
                    dataSet.MultiplyingFactor = 1000000;
                }
                else if (settype.StartsWith("vbd"))
                {
                    //if it's vbd latency xapi units are in microseconds
                    dataSet.MultiplyingFactor = 1000;
                }
                else
                {
                    //otherwise they are in seconds
                    dataSet.MultiplyingFactor = 1000000000;
                }

                dataSet.CustomYRange = new DataRange(1, 0, 1, Unit.NanoSeconds, RangeScaleMode.Auto);
                dataSet.Type         = DataType.Latency;
            }
            else if (settype.StartsWith("vif") || settype.StartsWith("pif"))
            {
                //xapi units are in bytes/sec or errors/sec
                Unit unit = settype.EndsWith("errors") ? Unit.CountsPerSecond : Unit.BytesPerSecond;

                dataSet.CustomYRange = new DataRange(1, 0, 1, unit, RangeScaleMode.Auto);
                dataSet.Type         = DataType.Network;
            }
            else if (settype.StartsWith("vbd"))
            {
                if (settype.Contains("iops"))
                {
                    dataSet.CustomYRange = new DataRange(1, 0, 1, Unit.CountsPerSecond, RangeScaleMode.Auto);
                }
                else if (settype.Contains("io_throughput"))
                {
                    dataSet.CustomYRange      = new DataRange(1, 0, 1, Unit.BytesPerSecond, RangeScaleMode.Auto);
                    dataSet.MultiplyingFactor = (int)Util.BINARY_MEGA; //xapi units are in mebibytes/sec
                }
                else if (settype.EndsWith("iowait"))
                {
                    dataSet.CustomYRange      = new DataRange(100, 0, 10, Unit.Percentage, RangeScaleMode.Auto);
                    dataSet.MultiplyingFactor = 100;
                }
                else if (settype.EndsWith("inflight") || settype.EndsWith("avgqu_sz"))
                {
                    dataSet.CustomYRange = new DataRange(1, 0, 1, Unit.None, RangeScaleMode.Auto);
                }
                else
                {
                    dataSet.CustomYRange = new DataRange(1, 0, 1, Unit.BytesPerSecond, RangeScaleMode.Auto);
                }

                dataSet.Type = DataType.Disk;
            }
            else if ((settype.Contains("memory") || settype.Contains("allocation")) && !settype.Contains("utilisation"))
            {
                dataSet.Type = settype.Contains("gpu") ? DataType.Gpu : DataType.Memory;

                dataSet.MultiplyingFactor = settype.Contains("kib") || settype == "memory_internal_free"
                                                ? (int)Util.BINARY_KILO
                                                : 1;

                if (settype == "memory" || settype == "memory_total_kib")
                {
                    dataSet.NeverShow = true;
                }
                else if (settype == "memory_free_kib" && xo is Host)
                {
                    dataSet.Name = Helpers.GetFriendlyDataSourceName("memory_used_kib", dataSet.XenObject);
                    Host         host    = (Host)xo;
                    Host_metrics metrics = host.Connection.Resolve(host.metrics);
                    long         max     = metrics != null ? metrics.memory_total : 100;
                    dataSet.CustomYRange = new DataRange(max, 0, max / 10d, Unit.Bytes, RangeScaleMode.Delegate)
                    {
                        UpdateMax        = dataSet.GetMemoryMax,
                        UpdateResolution = dataSet.GetMemoryResolution
                    };
                }
                else if (settype == "memory_internal_free" && xo is VM)
                {
                    dataSet.Name = Helpers.GetFriendlyDataSourceName("memory_internal_used", dataSet.XenObject);
                    VM         vm      = (VM)xo;
                    VM_metrics metrics = vm.Connection.Resolve(vm.metrics);
                    long       max     = metrics != null ? metrics.memory_actual : (long)vm.memory_dynamic_max;
                    dataSet.CustomYRange = new DataRange(max, 0, max / 10d, Unit.Bytes, RangeScaleMode.Delegate)
                    {
                        UpdateMax        = dataSet.GetMemoryMax,
                        UpdateResolution = dataSet.GetMemoryResolution
                    };
                }
                else
                {
                    dataSet.CustomYRange = new DataRange(1, 0, 1, Unit.Bytes, RangeScaleMode.Auto);
                }
            }
            else if (settype.StartsWith("loadavg"))
            {
                dataSet.CustomYRange      = new DataRange(100, 0, 10, Unit.Percentage, RangeScaleMode.Auto);
                dataSet.MultiplyingFactor = 100;
                dataSet.Type = DataType.LoadAverage;
            }
            else if (settype.StartsWith("cpu") || settype == "avg_cpu" || settype.StartsWith("runstate"))
            {
                dataSet.CustomYRange      = new DataRange(100, 0, 10, Unit.Percentage, RangeScaleMode.Fixed);
                dataSet.MultiplyingFactor = 100;
                dataSet.Type = DataType.Cpu;
            }
            else if (settype.StartsWith("io_throughput"))
            {
                dataSet.CustomYRange      = new DataRange(1, 0, 1, Unit.BytesPerSecond, RangeScaleMode.Auto);
                dataSet.MultiplyingFactor = (int)Util.BINARY_MEGA; //xapi units are in mebibytes/sec
                dataSet.Type = DataType.Storage;
            }
            else if (settype.StartsWith("sr"))
            {
                dataSet.Type = DataType.Storage;

                if (settype.EndsWith("cache_size"))
                {
                    dataSet.CustomYRange = new DataRange(1, 0, 1, Unit.Bytes, RangeScaleMode.Auto);
                }
                else if (settype.EndsWith("cache_hits") || settype.EndsWith("cache_misses"))
                {
                    dataSet.CustomYRange = new DataRange(1, 0, 1, Unit.CountsPerSecond, RangeScaleMode.Auto);
                }
            }
            else if (settype.StartsWith("iops"))
            {
                //xapi units are in requests/sec
                dataSet.CustomYRange = new DataRange(1, 0, 1, Unit.CountsPerSecond, RangeScaleMode.Auto);
                dataSet.Type         = DataType.Storage;
            }
            else if (settype.StartsWith("iowait"))
            {
                dataSet.CustomYRange      = new DataRange(100, 0, 10, Unit.Percentage, RangeScaleMode.Auto);
                dataSet.MultiplyingFactor = 100;
                dataSet.Type = DataType.Storage;
            }
            else if (settype.StartsWith("inflight") || settype.StartsWith("avgqu_sz"))
            {
                //xapi units are in requests
                dataSet.CustomYRange = new DataRange(1, 0, 1, Unit.None, RangeScaleMode.Auto);
                dataSet.Type         = DataType.Storage;
            }
            else if (settype.StartsWith("gpu"))
            {
                if (settype.Contains("power_usage"))
                {
                    //xapi units are in mW
                    dataSet.CustomYRange = new DataRange(1, 0, 1, Unit.MilliWatt, RangeScaleMode.Auto);
                }
                else if (settype.Contains("temperature"))
                {
                    //xapi units are in Centigrade
                    dataSet.CustomYRange = new DataRange(1, 0, 1, Unit.Centigrade, RangeScaleMode.Auto);
                }
                else if (settype.Contains("utilisation"))
                {
                    dataSet.CustomYRange      = new DataRange(100, 0, 10, Unit.Percentage, RangeScaleMode.Fixed);
                    dataSet.MultiplyingFactor = 100;
                }
                dataSet.Type = DataType.Gpu;
            }
            else
            {
                dataSet.CustomYRange = new DataRange(1, 0, 1, Unit.None, RangeScaleMode.Auto);
                dataSet.Type         = DataType.Custom;
            }

            return(dataSet);
        }
Пример #36
0
        /// <summary>
        /// Positions the Landmark objects depending on the lot direction. (npc/car portals, bin, mailbox, phone)
        /// </summary>
        /// <param name="vm">The VM.</param>
        public static void PositionLandmarkObjects(VM vm, RestoreLotType type)
        {
            var arch      = vm.Context.Architecture;
            var lotSInfo  = vm.TSOState.Size;
            var lotSize   = lotSInfo & 255;
            var lotFloors = ((lotSInfo >> 8) & 255) + 2;
            var lotDir    = (lotSInfo >> 16);

            var dim = VMBuildableAreaInfo.BuildableSizes[lotSize];

            //need to rotate the lot dir towards the road. bit weird cos we're rotating a rectangle

            var w = arch.Width;
            var h = arch.Height;
            //little bit different from the array in VMContext. Want the tile positions outside buildable area
            //so min x and y are 5 instead of 6.
            var corners = new Vector2[]
            {
                new Vector2(5, 5),         // top, default orientation
                new Vector2(w - 7, 5),     // right
                new Vector2(w - 7, h - 7), // bottom
                new Vector2(5, h - 7)      // left
            };
            var perpIncrease = new Vector2[]
            {
                new Vector2(0, -1), //bottom left road side
                new Vector2(1, 0),
                new Vector2(0, 1),
                new Vector2(-1, 0)
            };

            //rotation 0: move perp from closer point to top bottom -> left (90 degree ccw of perp)
            //rotation 1: choose closer pt to top left->top (90 degree ccw of perp)
            //rotation 2: choose closer pt to top top->right (90 degree cw of perp)

            var pt1 = corners[(lotDir + 2) % 4];
            var pt2 = corners[(lotDir + 3) % 4];

            var ctr = (pt1 + pt2) / 2; //ok.

            var xperp = perpIncrease[(lotDir + 1) % 4];
            var yperp = perpIncrease[(lotDir + 2) % 4];

            //move relative position objs
            foreach (var pos in MovePositions)
            {
                var rpos = ctr + (pos.X * xperp) + (pos.Y * yperp);
                var ent  = EntityByGUID(vm, pos.GUID);
                if (type != RestoreLotType.Blank && ent == null && (pos.Type == type || pos.Type == RestoreLotType.Generic))
                {
                    ent = vm.Context.CreateObjectInstance(pos.GUID, LotTilePos.OUT_OF_WORLD, Direction.NORTH).BaseObject;
                }
                if (ent != null)
                {
                    var result = ent.MultitileGroup.BaseObject.SetPosition(LotTilePos.FromBigTile((short)rpos.X, (short)rpos.Y, 1), (Direction)(1 << ((lotDir * 2 + pos.DirOff) % 8)), vm.Context, VMPlaceRequestFlags.AllowIntersection);
                    if (result.Status != VMPlacementError.Success)
                    {
                        // if we can't place the object, put it oow.
                        ent.MultitileGroup.BaseObject.SetPosition(LotTilePos.OUT_OF_WORLD, (Direction)(1 << ((lotDir * 2 + pos.DirOff) % 8)), vm.Context);
                    }
                }
            }

            // finally, must position npc portals. These are on the sidewalk, but at the far edge of the lot.
            // ped, npc1, npc2 (0x81E6BEF9, 0x23BC2034, 0x4E57C380)
            // if there is water on the space we can't intersect it :(

            // for now just choose pavement corners. These are safe from being in water.
            var npc1 = EntityByGUID(vm, 0x23BC2034);

            if (npc1 != null)
            {
                npc1.SetPosition(LotTilePos.FromBigTile((short)pt1.X, (short)pt1.Y, 1), (Direction)(1 << ((lotDir * 2 + 0) % 8)), vm.Context);
            }
            var npc2 = EntityByGUID(vm, 0x4E57C380);

            if (npc2 != null)
            {
                npc2.SetPosition(LotTilePos.FromBigTile((short)pt2.X, (short)pt2.Y, 1), (Direction)(1 << ((lotDir * 2 + 0) % 8)), vm.Context);
            }
            var ped = EntityByGUID(vm, 0x81E6BEF9);

            if (ped != null)
            {
                ped.SetPosition(LotTilePos.FromBigTile((short)ctr.X, (short)ctr.Y, 1), (Direction)(1 << ((lotDir * 2 + 0) % 8)), vm.Context);
            }

            var rPos = ctr + (-13 * xperp) + (2 * yperp);

            if (ped != null)
            {
                StampTerrainmap(arch, CarDirtRoad, (short)rPos.X, (short)rPos.Y, xperp, yperp);
            }
        }
Пример #37
0
 public void SetVm(VM vm)
 {
     m_vm = vm;
 }
Пример #38
0
        // Work out what values to put in the device position combobox
        public void UpdateDevicePositions(Session session)
        {
            Program.AssertOffEventThread();

            List <String> devices = new List <String>();

            // Make the list of possible userdevice positions: the union of the spare get_allowed_VBD_devices...
            devices.AddRange(VM.get_allowed_VBD_devices(session, vm.opaque_ref));

            // Never allow the DVD drive device number to be used, unless it's already in use (it will be added below)
            devices.Remove("3");

            // ...with the userdevice values already in use
            foreach (VBD vbd in vm.Connection.ResolveAll(vm.VBDs))
            {
                if (devices.Contains(vbd.userdevice))
                {
                    continue;
                }

                devices.Add(vbd.userdevice);
            }

            // Put the userdevices values into the combobox
            devices.Sort(StringUtility.NaturalCompare);

            Program.Invoke(Program.MainWindow, delegate()
            {
                devicePositionComboBox.BeginUpdate();

                try
                {
                    devicePositionComboBox.Items.Clear();

                    var comboBoxItems = vm.Connection.ResolveAll(vm.VBDs).Select(d => new DevicePositionComboBoxItem(d.userdevice, d));

                    foreach (var devicePosition in devices)
                    {
                        var comboBoxItemWithVdi = comboBoxItems.FirstOrDefault(ci => ci.VBD.userdevice == devicePosition);
                        if (comboBoxItemWithVdi != null)
                        {
                            devicePositionComboBox.Items.Add(comboBoxItemWithVdi);

                            if (vbd != null && comboBoxItemWithVdi.VBD.userdevice == vbd.userdevice)
                            {
                                devicePositionComboBox.SelectedItem = comboBoxItemWithVdi;
                            }
                        }
                        else
                        {
                            devicePositionComboBox.Items.Add(new DevicePositionComboBoxItem(devicePosition));
                        }
                    }
                }
                finally
                {
                    devicePositionComboBox.EndUpdate();
                    devicePositionComboBox.Enabled = true;
                }
            });
        }
Пример #39
0
 private static VMEntity EntityByGUID(VM vm, uint GUID)
 {
     return(vm.Entities.FindAll(x => (x.MasterDefinition?.GUID ?? 0) == GUID || x.Object.GUID == GUID).FirstOrDefault());
 }
Пример #40
0
 public VMResetVDICommand(IMainWindow mainWindow, VM vm)
     : base(mainWindow, vm)
 {
 }
Пример #41
0
        protected virtual async void OnCreate(object sender, EventArgs e)
        {
            await VM.Add(Item);

            await Navigation.PopAsync();
        }
Пример #42
0
        private bool TryPlace(VM vm, VMAvatar caller)
        {
            var internalMode = caller == null;

            if (Mode != PurchaseMode.Donate && !vm.PlatformState.CanPlaceNewUserObject(vm))
            {
                return(false);
            }
            if (Mode == PurchaseMode.Donate && !vm.PlatformState.CanPlaceNewDonatedObject(vm))
            {
                return(false);
            }

            VMStandaloneObjectMarshal state;

            var catalog = Content.Content.Get().WorldCatalog;
            var item    = catalog.GetItemByGUID(Info.GUID);

            if (caller != null && (item?.DisableLevel ?? 0) > 2)
            {
                //object cannot be placed (disable level 3)
                return(false);
            }

            if ((Info.Data?.Length ?? 0) == 0)
            {
                state = null;
            }
            else
            {
                state = new VMStandaloneObjectMarshal();
                try
                {
                    using (var reader = new BinaryReader(new MemoryStream(Info.Data)))
                    {
                        state.Deserialize(reader);
                    }
                    foreach (var e in state.Entities)
                    {
                        // Undisable the object, and remove any non-persist relationships.
                        ((VMGameObjectMarshal)e).Disabled = 0;
                        e.MeToObject = new VMEntityRelationshipMarshal[0];
                    }
                }
                catch (Exception)
                {
                    //failed to restore state
                    state = null;
                }
            }

            if (state != null)
            {
                CreatedGroup = state.CreateInstance(vm, false);
                CreatedGroup.ChangePosition(new LotTilePos(x, y, level), dir, vm.Context, VMPlaceRequestFlags.UserPlacement);

                CreatedGroup.ExecuteEntryPoint(11, vm.Context); //User Placement
                if (CreatedGroup.Objects.Count == 0)
                {
                    return(false);
                }
                if (CreatedGroup.BaseObject.Position == LotTilePos.OUT_OF_WORLD && !internalMode)
                {
                    return(false);
                }
            }
            else
            {
                CreatedGroup = vm.Context.CreateObjectInstance(Info.GUID, LotTilePos.OUT_OF_WORLD, dir);
                if (CreatedGroup == null)
                {
                    return(false);
                }
                CreatedGroup.ChangePosition(new LotTilePos(x, y, level), dir, vm.Context, VMPlaceRequestFlags.UserPlacement);

                CreatedGroup.ExecuteEntryPoint(11, vm.Context); //User Placement
                if (CreatedGroup.Objects.Count == 0)
                {
                    return(false);
                }

                if (CreatedGroup.BaseObject.Position == LotTilePos.OUT_OF_WORLD && !internalMode)
                {
                    return(false);
                }
            }

            foreach (var obj in CreatedGroup.Objects)
            {
                var tsostate = (obj.PlatformState as VMTSOObjectState);
                if (tsostate != null)
                {
                    if (caller != null)
                    {
                        tsostate.OwnerID = caller.PersistID;
                    }
                    bool reinitRequired = false;
                    if (Info.UpgradeLevel > tsostate.UpgradeLevel)
                    {
                        tsostate.UpgradeLevel = Info.UpgradeLevel;
                        reinitRequired        = true;
                    }
                    obj.UpdateTuning(vm);
                    if (reinitRequired)
                    {
                        VMNetUpgradeCmd.TryReinit(obj, vm, tsostate.UpgradeLevel);
                    }
                }
                obj.PersistID = ObjectPID;
                ((VMGameObject)obj).DisableIfTSOCategoryWrong(vm.Context);
            }
            vm.Context.ObjectQueries.RegisterMultitilePersist(CreatedGroup, ObjectPID);

            //is this my sim's object? try remove it from our local inventory representaton
            if (((VMTSOObjectState)CreatedGroup.BaseObject.TSOState).OwnerID == vm.MyUID && Info.RestoreType != VMInventoryRestoreType.CopyOOW)
            {
                var index = vm.MyInventory.FindIndex(x => x.ObjectPID == ObjectPID);
                if (index != -1)
                {
                    vm.MyInventory.RemoveAt(index);
                }
            }

            if (Mode == PurchaseMode.Donate)
            {
                //this object should be donated.
                (CreatedGroup.BaseObject.TSOState as VMTSOObjectState).Donate(vm, CreatedGroup.BaseObject);
            }

            if (caller != null)
            {
                vm.SignalChatEvent(new VMChatEvent(caller, VMChatEventType.Arch,
                                                   caller.Name,
                                                   vm.GetUserIP(caller.PersistID),
                                                   "placed (from inventory) " + CreatedGroup.BaseObject.ToString() + " at (" + x / 16f + ", " + y / 16f + ", " + level + ")"
                                                   ));
            }
            return(true);
        }
Пример #43
0
 protected override bool CanExecute(VM vm)
 {
     return(vm != null && _recommendation.CanExecuteByVM.ContainsKey(vm) && _recommendation.CanExecuteByVM[vm]);
 }
Пример #44
0
        public static void RestoreTerrain(VM vm, TerrainBlend blend, byte roads, RestoreLotType type)
        {
            var arch = vm.Context.Architecture;

            arch.DisableClip = true;

            var baseB = blend.Base;

            arch.Terrain.LightType = (baseB == TerrainType.WATER) ? TerrainType.SAND : blend.Base;
            arch.Terrain.DarkType  = (blend.Blend == TerrainType.WATER) ? blend.Base : blend.Blend;
            arch.Terrain.GenerateGrassStates();

            //clear all previous roads/sea
            VMArchitectureTools.FloorPatternRect(arch, new Rectangle(0, 0, arch.Width, 5), 0, 0, 1);
            VMArchitectureTools.FloorPatternRect(arch, new Rectangle(arch.Width - 7, 0, 7, arch.Height), 0, 0, 1);
            VMArchitectureTools.FloorPatternRect(arch, new Rectangle(0, arch.Height - 7, arch.Width, 7), 0, 0, 1);
            VMArchitectureTools.FloorPatternRect(arch, new Rectangle(0, 0, 5, arch.Height), 0, 0, 1);

            if (baseB == TerrainType.WATER)
            {
                //...
                VMArchitectureTools.FloorPatternRect(arch, new Rectangle(1, 1, arch.Width - 3, arch.Height - 3), 0, 65534, 1);
            }

            //blend flags start at top left, then go clockwise. (top right, bottom right..)

            if ((blend.WaterFlags & 1) > 0)
            {
                FillTileLine(arch, W, 0, 0, 1, WaterLineSegments, false);
            }
            if ((blend.WaterFlags & 4) > 0)
            {
                FillTileLine(arch, W, 0, 0, 1, WaterLineSegments, true);
            }
            if ((blend.WaterFlags & 16) > 0)
            {
                FillTileLine(arch, W, (short)(arch.Width - 1), 0, 1, WaterLineSegments, false);
            }
            if ((blend.WaterFlags & 64) > 0)
            {
                FillTileLine(arch, W, 0, (short)(arch.Height - 1), 1, WaterLineSegments, true);
            }

            if ((blend.WaterFlags & 2) > 0)
            {
                FillTiles(arch, W, 1, 1, 1, 1, 1);
            }
            if ((blend.WaterFlags & 8) > 0)
            {
                FillTiles(arch, W, (short)(arch.Width - 2), 1, 1, 1, 1);
            }
            if ((blend.WaterFlags & 32) > 0)
            {
                FillTiles(arch, W, (short)(arch.Width - 2), (short)(arch.Height - 2), 1, 1, 1);
            }
            if ((blend.WaterFlags & 128) > 0)
            {
                FillTiles(arch, W, 1, (short)(arch.Height - 2), 1, 1, 1);
            }

            if ((blend.WaterFlags & 5) == 5)
            {
                StampTilemap(arch, TopWaterCorner, 1, 1, 1);
            }
            if ((blend.WaterFlags & 20) == 20)
            {
                StampTilemap(arch, RightWaterCorner, (short)(arch.Width - 7), 1, 1);
            }
            if ((blend.WaterFlags & 80) == 80)
            {
                StampTilemap(arch, BottomWaterCorner, (short)(arch.Width - 7), (short)(arch.Height - 7), 1);
            }
            if ((blend.WaterFlags & 65) == 65)
            {
                StampTilemap(arch, LeftWaterCorner, 1, (short)(arch.Height - 7), 1);
            }

            /*
             *
             * if ((blend.WaterFlags & 1) > 0) VMArchitectureTools.FloorPatternRect(arch, new Rectangle(1, 1, 4, arch.Height - 2), 0, 65534, 1);
             * if ((blend.WaterFlags & 2) > 0) VMArchitectureTools.FloorPatternRect(arch, new Rectangle(1, 1, arch.Width-2, 4), 0, 65534, 1);
             * if ((blend.WaterFlags & 4) > 0) VMArchitectureTools.FloorPatternRect(arch, new Rectangle(arch.Width-5, 1, 4, arch.Height - 2), 0, 65534, 1);
             * if ((blend.WaterFlags & 8) > 0) VMArchitectureTools.FloorPatternRect(arch, new Rectangle(1, arch.Height-5, arch.Width-2, 4), 0, 65534, 1);
             *
             */

            //hard blends into the next terrain type

            FillTerrainRect(arch, new Rectangle(0, 0, 1, arch.Height - 1), (byte)(((blend.AdjFlags & 1) > 0) ? 255 : 0));
            FillTerrainRect(arch, new Rectangle(0, 0, arch.Width - 1, 1), (byte)(((blend.AdjFlags & 4) > 0) ? 255 : 0));
            FillTerrainRect(arch, new Rectangle(arch.Width - 2, 0, 1, arch.Height - 1), (byte)(((blend.AdjFlags & 16) > 0) ? 255 : 0));
            FillTerrainRect(arch, new Rectangle(0, arch.Height - 2, arch.Width - 1, 1), (byte)(((blend.AdjFlags & 64) > 0) ? 255 : 0));

            /*
             * FillTerrainRect(arch, new Rectangle(0, 0, 1, 1), (byte)(((blend.AdjFlags & 2) > 0) ? 255 : 0));
             * FillTerrainRect(arch, new Rectangle(arch.Width - 2, 0, 1, 1), (byte)(((blend.AdjFlags & 8) > 0) ? 255 : 0));
             * FillTerrainRect(arch, new Rectangle(arch.Width - 2, arch.Height - 2, 1, 1), (byte)(((blend.AdjFlags & 32) > 0) ? 255 : 0));
             * FillTerrainRect(arch, new Rectangle(0, arch.Height - 2, 1, 1), (byte)(((blend.AdjFlags & 128) > 0) ? 255 : 0));
             */

            //smooth blends into the next terrain type

            ApplyTerrainBlend(arch, RotateByte(blend.AdjFlags, 0), new Rectangle(0, 0, arch.Width - 1, 24), 255, 0, -11,
                              new Point[] { new Point(0, 0), new Point(arch.Width - 1, 0) },
                              new float[] { (135f / 180f) * (float)Math.PI, (225f / 180f) * (float)Math.PI },
                              new float[] { (15f / 180f) * (float)Math.PI, (-15f / 180f) * (float)Math.PI });

            ApplyTerrainBlend(arch, RotateByte(blend.AdjFlags, 6), new Rectangle(arch.Width - 25, 0, 24, arch.Height - 1), 0, 11, 0,
                              new Point[] { new Point(arch.Width - 1, 0), new Point(arch.Width - 1, arch.Height - 1) },
                              new float[] { (225f / 180f) * (float)Math.PI, (315f / 180f) * (float)Math.PI },
                              new float[] { (15f / 180f) * (float)Math.PI, (-15f / 180f) * (float)Math.PI });

            ApplyTerrainBlend(arch, RotateByte(blend.AdjFlags, 4), new Rectangle(0, arch.Height - 25, arch.Width - 1, 24), 0, 0, 11,
                              new Point[] { new Point(arch.Width - 1, arch.Height - 1), new Point(0, arch.Height - 1) },
                              new float[] { (315f / 180f) * (float)Math.PI, (45f / 180f) * (float)Math.PI },
                              new float[] { (15f / 180f) * (float)Math.PI, (-15f / 180f) * (float)Math.PI });

            ApplyTerrainBlend(arch, RotateByte(blend.AdjFlags, 2), new Rectangle(0, 0, 24, arch.Height - 1), 255, -11, 0,
                              new Point[] { new Point(0, arch.Height - 1), new Point(0, 0) },
                              new float[] { (45f / 180f) * (float)Math.PI, (135f / 180f) * (float)Math.PI },
                              new float[] { (15f / 180f) * (float)Math.PI, (-15f / 180f) * (float)Math.PI });

            RestoreRoad(vm, roads);
            if (vm.GetGlobalValue(11) == -1)
            {
                //set road dir. should only really do this FIRST EVER time, then road dir changes after are manual and rotate the contents of the lot.
                vm.TSOState.Size &= 0xFFFF;
                vm.TSOState.Size |= PickRoadDir(roads) << 16;
            }

            PositionLandmarkObjects(vm, type);

            arch.SignalTerrainRedraw();
            arch.DisableClip = false;
        }
Пример #45
0
 void SearchHelp() => messageBoxService.Show(VM.GetSearchHelpText(), ownerWindow: Window.GetWindow(control));
Пример #46
0
 public ExistingVmProblem(Check check, VM vm)
     : base(check, vm)
 {
 }
Пример #47
0
Файл: HALT.cs Проект: sam159/SVM
 public override void Exec(VM vm, byte[] vars)
 {
     Debug.Assert(vars.Length == 0);
     vm.RUN = false;
     vm.Ports[0].Write(Encoding.ASCII.GetBytes("\r\nSYSTEM HALTED"));
 }
Пример #48
0
        public static int RestoreHeight(VM vm, VMTSOSurroundingTerrain terrain, int x, int y)
        {
            var sr = new float[4, 4];

            for (int oy = 0; oy < 4; oy++)
            {
                var srcY = Math.Min(3, Math.Max(0, oy + y - 1));
                for (int ox = 0; ox < 4; ox++)
                {
                    var srcX = Math.Min(3, Math.Max(0, ox + x - 1));
                    sr[3 - oy, ox] = terrain.Height[srcX, srcY];
                }
            }

            var baseLevel = (int)(((sr[1, 1] + sr[1, 2] + sr[2, 2] + sr[2, 1]) / 4) * 100);

            var target = vm.Context.Architecture.Terrain;
            var xn     = VMArchitectureTerrain.TerrainXNoise;
            var yn     = VMArchitectureTerrain.TerrainYNoise;

            for (int oy = 1; oy < target.Height; oy++)
            {
                for (int ox = 1; ox < target.Width; ox++)
                {
                    int index = (target.Height - oy) * target.Width + (target.Height - ox);

                    float fracy = (oy - 1f) / (target.Height - 2f);
                    fracy -= (yn[index] - 0.5f) / 5f;
                    float y1    = Cubic(sr[0, 0], sr[0, 1], sr[0, 2], sr[0, 3], fracy);
                    float y2    = Cubic(sr[1, 0], sr[1, 1], sr[1, 2], sr[1, 3], fracy);
                    float y3    = Cubic(sr[2, 0], sr[2, 1], sr[2, 2], sr[2, 3], fracy);
                    float y4    = Cubic(sr[3, 0], sr[3, 1], sr[3, 2], sr[3, 3], fracy);
                    float fracx = (ox - 1f) / (target.Width - 2f);
                    fracx -= (xn[index] - 0.5f) / 5f;

                    var h = Cubic(y1, y2, y3, y4, fracx);
                    target.Heights[index] = (short)(((h * 100f) - baseLevel));
                }
            }

            var lotSInfo = vm.TSOState.Size;

            if (vm.TSOState.OwnerID == 0)
            {
                lotSInfo = 10;
            }
            var ret = vm.Context.GetTSOBuildableArea(lotSInfo);

            var mailbox = vm.Entities.FirstOrDefault(m => (m.Object.OBJ.GUID == 0xEF121974 || m.Object.OBJ.GUID == 0x1D95C9B0));

            if (mailbox != null && mailbox.Position != LotTilePos.OUT_OF_WORLD)
            {
                var mailheight = target.Heights[mailbox.Position.TileY * target.Width + mailbox.Position.TileX];

                ret.Inflate(-1, -1);
                vm.Context.Architecture.DisableClip = true;
                VMArchitectureTools.RaiseTerrain(vm.Context.Architecture, ret, mailheight, false);
                vm.Context.Architecture.DisableClip = false;

                ret.Width--; ret.Height--;
                for (int oy = ret.Top; oy < ret.Bottom; oy++)
                {
                    for (int ox = ret.Left; ox < ret.Right; ox++)
                    {
                        int index = (oy) * target.Width + (ox);
                        target.GrassState[index] = 0;
                    }
                }
            }

            target.RegenerateCenters();
            if (VM.UseWorld)
            {
                vm.Context.Blueprint.Altitude        = target.Heights;
                vm.Context.Blueprint.AltitudeCenters = target.Centers;
            }

            foreach (var obj in vm.Entities)
            {
                obj.Position = obj.Position;
            }
            return(baseLevel);
        }
Пример #49
0
        protected override AsyncAction CreateAction(out bool cancelled)
        {
            Program.AssertOnEventThread();

            DialogResult dialogResult;

            using (var dlg = new ThreeButtonDialog(
                       new ThreeButtonDialog.Details(SystemIcons.Warning, String.Format(Messages.CONFIRM_DELETE_VM, VM.Name(), VM.Connection.Name), Messages.ACTION_SHUTDOWN_AND_DESTROY_VM_TITLE),
                       ThreeButtonDialog.ButtonYes,
                       ThreeButtonDialog.ButtonNo))
            {
                dialogResult = dlg.ShowDialog();
            }
            if (dialogResult == DialogResult.Yes)
            {
                cancelled = false;
                List <VM> vms = new List <VM> {
                    VM
                };
                return(new ShutdownAndDestroyVMsAction(VM.Connection, vms));
            }

            cancelled = true;
            return(null);
        }
Пример #50
0
        public override bool FailureFoundFor(IXenObject itemToFilterOn)
        {
            Pool        targetPool;
            List <Host> targets = CollateHosts(itemToFilterOn, out targetPool);

            foreach (VM vm in preSelectedVMs)
            {
                log.InfoFormat("Asserting can migrate VM {0} to {1}...", vm.Name(), itemToFilterOn);
                bool vmIsMigratable = false;
                foreach (Host host in targets)
                {
                    if (canceled)
                    {
                        return(false);
                    }

                    // obtain the cache data for a vm
                    IDictionary <string, string> vmCache;
                    lock (cacheLock)
                    {
                        if (!cache.ContainsKey(vm.opaque_ref))
                        {
                            cache.Add(vm.opaque_ref, new Dictionary <string, string>());
                        }
                        vmCache = cache[vm.opaque_ref];
                    }

                    try
                    {
                        //CA-220218: for intra-pool motion of halted VMs we do a move, so no need to assert we can migrate
                        Pool vmPool = Helpers.GetPoolOfOne(vm.Connection);
                        if (_wizardMode == WizardMode.Move && vmPool != null && targetPool != null && vmPool.opaque_ref == targetPool.opaque_ref)
                        {
                            vmIsMigratable = true;
                            break;
                        }
                        //Skip the resident host as there's a filter for it and
                        //if not then you could exclude intrapool migration
                        //CA-205799: do not offer the host the VM is currently on
                        //CA-205799: do not offer the host the VM is currently on
                        Host homeHost = vm.Home();
                        if (homeHost != null && homeHost.opaque_ref == host.opaque_ref)
                        {
                            continue;
                        }

                        if (vmCache.ContainsKey(host.opaque_ref))
                        {
                            disableReason = vmCache[host.opaque_ref];
                            if (string.IsNullOrEmpty(disableReason))
                            {
                                // vm is migratable to at least one host in the pool, no need to itearate through all the pool members
                                vmIsMigratable = true;
                                break;
                            }
                            continue;
                        }

                        //if pool_migrate can be done, then we will allow it in the wizard, even if storage migration is not allowed (i.e. users can use the wizard to live-migrate a VM inside the pool)
                        if (_wizardMode == WizardMode.Migrate && vmPool != null && targetPool != null && vmPool.opaque_ref == targetPool.opaque_ref)
                        {
                            var reason = VMOperationHostCommand.GetVmCannotBootOnHostReason(vm, host, vm.Connection.Session, vm_operations.pool_migrate);
                            if (string.IsNullOrEmpty(reason))
                            {
                                lock (cacheLock)
                                {
                                    vmCache[host.opaque_ref] = reason;
                                }
                                // vm is migratable to at least one host in the pool, no need to itearate through all the pool members
                                vmIsMigratable = true;
                                break;
                            }
                        }

                        //check if the destination host is older than the source host
                        var destinationVersion = Helpers.HostPlatformVersion(host);
                        var sourceVersion      = Helpers.HostPlatformVersion(vm.Home() ?? Helpers.GetMaster(vmPool));
                        if (Helpers.productVersionCompare(destinationVersion, sourceVersion) < 0)
                        {
                            throw new Failure(Messages.OLDER_THAN_CURRENT_SERVER);
                        }

                        PIF            managementPif     = host.Connection.Cache.PIFs.First(p => p.management);
                        XenAPI.Network managementNetwork = host.Connection.Cache.Resolve(managementPif.network);

                        Session session = host.Connection.DuplicateSession();
                        Dictionary <string, string> receiveMapping = Host.migrate_receive(session, host.opaque_ref, managementNetwork.opaque_ref, new Dictionary <string, string>());

                        var targetSrs     = host.Connection.Cache.SRs.Where(sr => sr.SupportsStorageMigration()).ToList();
                        var targetNetwork = GetANetwork(host);

                        Dictionary <string, string> options = new Dictionary <string, string>();
                        if (force)
                        {
                            options.Add("force", "true");
                        }
                        VM.assert_can_migrate(vm.Connection.Session,
                                              vm.opaque_ref,
                                              receiveMapping,
                                              true,
                                              GetVdiMap(vm, targetSrs),
                                              vm.Connection == host.Connection ? new Dictionary <XenRef <VIF>, XenRef <XenAPI.Network> >() : GetVifMap(vm, targetNetwork),
                                              options);
                        lock (cacheLock)
                        {
                            vmCache[host.opaque_ref] = string.Empty;
                        }
                        // vm is migratable to at least one host in the pool, no need to itearate through all the pool members
                        vmIsMigratable = true;
                        break;
                    }
                    catch (Failure failure)
                    {
                        if (failure.ErrorDescription.Count > 0 && failure.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED)
                        {
                            disableReason = failure.Message.Split('\n')[0].TrimEnd('\r');     // we want the first line only
                        }
                        else
                        {
                            disableReason = failure.Message;
                        }

                        lock (cacheLock)
                        {
                            vmCache[host.opaque_ref] = disableReason.Clone().ToString();
                        }

                        log.InfoFormat("VM {0} cannot be migrated to {1}. Reason: {2};", vm.Name(), host.Name(), failure.Message);

                        vmIsMigratable = false;
                    }
                    catch (Exception e)
                    {
                        log.Error($"There was an error while asserting the VM {vm.Name()} can be migrated to {itemToFilterOn.Name()}:", e);
                        disableReason  = Messages.HOST_MENU_UNKNOWN_ERROR;
                        vmIsMigratable = false;
                    }
                }

                // if at least one VM is not migratable to the target pool, then there is no point checking the remaining VMs
                if (!vmIsMigratable)
                {
                    return(true);
                }
            }
            return(false);
        }
Пример #51
0
        public override bool Execute(VM vm, VMAvatar caller)
        {
            if (ObjectPID == 0) //only has value when this is an inventory move.
            {
                VMEntity obj = vm.GetObjectById(ObjectID);
                if (obj == null || (!vm.TS1 && caller == null))
                {
                    return(false);
                }
                obj.Delete(CleanupAll, vm.Context);

                // If we're the server, tell the global link to give their money back.
                if (vm.GlobalLink != null)
                {
                    vm.GlobalLink.PerformTransaction(vm, false, uint.MaxValue, caller?.PersistID ?? uint.MaxValue, (obj.PersistID != 0)?obj.MultitileGroup.Price:0,
                                                     (bool success, int transferAmount, uint uid1, uint budget1, uint uid2, uint budget2) =>
                    {
                    });
                }
                vm.SignalChatEvent(new VMChatEvent(caller, VMChatEventType.Arch,
                                                   caller?.Name ?? "Unknown",
                                                   vm.GetUserIP(caller?.PersistID ?? 0),
                                                   "deleted " + obj.ToString()
                                                   ));
            }
            else
            {
                //inventory move. Just delete the object.
                VMEntity obj = vm.GetObjectByPersist(ObjectPID);
                if (obj == null)
                {
                    return(false);
                }

                if (Success)
                {
                    if (((VMTSOObjectState)obj.TSOState).OwnerID == vm.MyUID)
                    {
                        //if the owner is here, tell them this object is now in their inventory.
                        //if they're elsewhere, they'll see it the next time their inventory updates.
                        //Inventory accesses are not by index, but PID, and straight to DB... so this won't cause any race conditions.
                        vm.MyInventory.Add(new VMInventoryItem()
                        {
                            ObjectPID = ObjectPID,
                            GUID      = (obj.MasterDefinition?.GUID) ?? obj.Object.OBJ.GUID,
                            Name      = obj.MultitileGroup.Name,
                            Value     = (uint)obj.MultitileGroup.Price,
                            Graphic   = (ushort)obj.GetValue(VMStackObjectVariable.Graphic),
                            DynFlags1 = obj.DynamicSpriteFlags,
                            DynFlags2 = obj.DynamicSpriteFlags2,
                        });
                    }
                    vm.Context.ObjectQueries.RemoveMultitilePersist(vm, obj.PersistID);
                    foreach (var o in obj.MultitileGroup.Objects)
                    {
                        o.PersistID = 0;                                           //no longer representative of the object in db.
                    }
                    obj.Delete(CleanupAll, vm.Context);

                    vm.SignalChatEvent(new VMChatEvent(caller, VMChatEventType.Arch,
                                                       caller?.Name ?? "disconnected user",
                                                       vm.GetUserIP(caller.PersistID),
                                                       "sent " + obj.ToString() + " back to the inventory of its owner."
                                                       ));
                }
                else
                {
                    //something bad happened. just unlock the object.
                    foreach (var o in obj.MultitileGroup.Objects)
                    {
                        ((VMGameObject)o).Disabled &= VMGameObjectDisableFlags.TransactionIncomplete;
                    }
                }
            }

            return(true);
        }
Пример #52
0
        /// <summary>
        /// Generate a resource ID map from the specified lot.
        /// </summary>
        /// <param name="vm">The target lot VM.</param>
        public VMResourceIDMarshal(VM vm)
        {
            var arch     = vm.Context.Architecture;
            var content  = Content.Content.Get();
            var floorids = new HashSet <ushort>();

            foreach (var level in arch.Floors)
            {
                foreach (var floor in level)
                {
                    floorids.Add(floor.Pattern);
                }
            }
            var wallids = new HashSet <ushort>();

            foreach (var level in arch.Walls)
            {
                foreach (var wall in level)
                {
                    //this can get stupid. diagonal walls can also contain floors, obviously.
                    //styles don't need remapping since they are limited to the base game ones, and custom temp wall styles are restored from objects.

                    if ((wall.Segments & LotView.Model.WallSegments.AnyDiag) > 0)
                    {
                        if (wall.TopLeftPattern != 0)
                        {
                            floorids.Add(wall.TopLeftPattern);
                        }
                        if (wall.TopLeftStyle != 0)
                        {
                            floorids.Add(wall.TopLeftStyle);
                        }

                        if (wall.BottomLeftPattern != 0)
                        {
                            wallids.Add(wall.BottomLeftPattern);
                        }
                        if (wall.BottomRightPattern != 0)
                        {
                            wallids.Add(wall.BottomRightPattern);
                        }
                    }
                    else if ((wall.Segments & LotView.Model.WallSegments.AnyAdj) > 0)
                    {
                        if (wall.BottomLeftPattern != 0)
                        {
                            wallids.Add(wall.BottomLeftPattern);
                        }
                        if (wall.BottomRightPattern != 0)
                        {
                            wallids.Add(wall.BottomRightPattern);
                        }
                        if (wall.TopLeftPattern != 0)
                        {
                            wallids.Add(wall.TopLeftPattern);
                        }
                        if (wall.TopRightPattern != 0)
                        {
                            wallids.Add(wall.TopRightPattern);
                        }
                    }
                }
            }

            foreach (var x in floorids)
            {
                FloorReference fref;
                if (content.WorldFloors.Entries.TryGetValue(x, out fref) && fref.FileName != "global")
                {
                    FloorNamesByID.Add(x, new string(fref.FileName.ToLowerInvariant().TakeWhile(y => y != '.').ToArray()));
                }
            }

            foreach (var x in wallids)
            {
                WallReference wref;
                if (content.WorldWalls.Entries.TryGetValue(x, out wref) && wref.FileName != "global")
                {
                    WallNamesByID.Add(x, new string(wref.FileName.ToLowerInvariant().TakeWhile(y => y != '.').ToArray()));
                }
            }

            Roof = content.WorldRoofs.IDToName((int)arch.RoofStyle);
        }
Пример #53
0
 public void SetXenObjects(IXenObject orig, IXenObject clone)
 {
     vm = clone as VM;
     Repopulate();
 }
Пример #54
0
 public static void RestoreTerrain(VM vm)
 {
     //take center of lotstate
     RestoreTerrain(vm, vm.TSOState.Terrain.BlendN[1, 1], vm.TSOState.Terrain.Roads[1, 1]);
 }
Пример #55
0
        public void InitializeLot(string lotName, bool external)
        {
            if (lotName == "")
            {
                return;
            }
            var recording = lotName.ToLowerInvariant().EndsWith(".fsor");

            CleanupLastWorld();

            if (FSOEnvironment.Enable3D)
            {
                var rc = new LotView.RC.WorldRC(GameFacade.GraphicsDevice);
                World = rc;
            }
            else
            {
                World = new World(GameFacade.GraphicsDevice);
            }
            World.Opacity = 1;
            GameFacade.Scenes.Add(World);

            var settings = GlobalSettings.Default;
            var myState  = new VMNetAvatarPersistState()
            {
                Name         = settings.LastUser,
                DefaultSuits = new VMAvatarDefaultSuits(settings.DebugGender),
                BodyOutfit   = settings.DebugBody,
                HeadOutfit   = settings.DebugHead,
                PersistID    = (uint)(new Random()).Next(),
                SkinTone     = (byte)settings.DebugSkin,
                Gender       = (short)(settings.DebugGender ? 0 : 1),
                Permissions  = SimAntics.Model.TSOPlatform.VMTSOAvatarPermissions.Admin,
                Budget       = 1000000,
            };

            if (recording)
            {
                var stream = new FileStream(lotName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                var rd     = new VMFSORDriver(stream);
                Driver = rd;
            }
            else if (external)
            {
                var cd = new VMClientDriver(ClientStateChange);
                SandCli             = new FSOSandboxClient();
                cd.OnClientCommand += (msg) => { SandCli.Write(new VMNetMessage(VMNetMessageType.Command, msg)); };
                cd.OnShutdown      += (reason) => SandCli.Disconnect();
                SandCli.OnMessage  += cd.ServerMessage;
                SandCli.Connect(lotName);
                Driver = cd;

                var dat = new MemoryStream();
                var str = new BinaryWriter(dat);
                myState.SerializeInto(str);
                var ava = new VMNetMessage(VMNetMessageType.AvatarData, dat.ToArray());
                dat.Close();
                SandCli.OnConnectComplete += () =>
                {
                    SandCli.Write(ava);
                };
            }
            else
            {
                var globalLink = new VMTSOGlobalLinkStub();
                globalLink.Database = new SimAntics.Engine.TSOGlobalLink.VMTSOStandaloneDatabase();
                var sd = new VMServerDriver(globalLink);
                SandServer = new FSOSandboxServer();

                Driver                   = sd;
                sd.OnDropClient         += SandServer.ForceDisconnect;
                sd.OnTickBroadcast      += SandServer.Broadcast;
                sd.OnDirectMessage      += SandServer.SendMessage;
                SandServer.OnConnect    += sd.ConnectClient;
                SandServer.OnDisconnect += sd.DisconnectClient;
                SandServer.OnMessage    += sd.HandleMessage;

                SandServer.Start((ushort)37564);
            }

            //Driver.OnClientCommand += VMSendCommand;
            //Driver.OnShutdown += VMShutdown;

            vm = new VM(new VMContext(World), Driver, new UIHeadlineRendererProvider());
            vm.ListenBHAVChanges();
            vm.Init();

            LotControl = new UILotControl(vm, World);
            this.AddAt(0, LotControl);

            var time    = DateTime.UtcNow;
            var tsoTime = TSOTime.FromUTC(time);

            vm.Context.Clock.Hours   = tsoTime.Item1;
            vm.Context.Clock.Minutes = tsoTime.Item2;
            if (m_ZoomLevel > 3)
            {
                World.Visible      = false;
                LotControl.Visible = false;
            }

            if (IDEHook.IDE != null)
            {
                IDEHook.IDE.StartIDE(vm);
            }

            vm.OnFullRefresh      += VMRefreshed;
            vm.OnChatEvent        += Vm_OnChatEvent;
            vm.OnEODMessage       += LotControl.EODs.OnEODMessage;
            vm.OnRequestLotSwitch += VMLotSwitch;
            vm.OnGenericVMEvent   += Vm_OnGenericVMEvent;

            if (!external && !recording)
            {
                if (!Downtown && ActiveFamily != null)
                {
                    ActiveFamily.SelectWholeFamily();
                    vm.TS1State.ActivateFamily(vm, ActiveFamily);
                }
                BlueprintReset(lotName);

                var experimentalTuning = new Common.Model.DynamicTuning(new List <Common.Model.DynTuningEntry> {
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "overfill", tuning_table = 255, tuning_index = 15, value = 200
                    },
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "overfill", tuning_table = 255, tuning_index = 5, value = 200
                    },
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "overfill", tuning_table = 255, tuning_index = 6, value = 200
                    },
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "overfill", tuning_table = 255, tuning_index = 7, value = 200
                    },
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "overfill", tuning_table = 255, tuning_index = 8, value = 200
                    },
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "overfill", tuning_table = 255, tuning_index = 9, value = 200
                    },
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "feature", tuning_table = 0, tuning_index = 0, value = 1
                    },                                                                                                            //ts1/tso engine animation timings (1.2x faster)
                });
                vm.ForwardCommand(new VMNetTuningCmd {
                    Tuning = experimentalTuning
                });

                vm.TSOState.PropertyCategory = 255;
                vm.Context.Clock.Hours       = 0;
                vm.TSOState.Size             = (10) | (3 << 8);
                vm.Context.UpdateTSOBuildableArea();
                var myClient = new VMNetClient
                {
                    PersistID   = myState.PersistID,
                    RemoteIP    = "local",
                    AvatarState = myState
                };

                var server = (VMServerDriver)Driver;
                server.ConnectClient(myClient);

                GameFacade.Cursor.SetCursor(CursorType.Normal);
                ZoomLevel = 1;
            }
            vm.MyUID  = myState.PersistID;
            ZoomLevel = 1;
        }
Пример #56
0
 protected override AsyncAction BuildAction(VM vm)
 {
     return(new VMHardReboot(vm));
 }
Пример #57
0
 private static bool ShowOnMainToolBarInternal(VM vm)
 {
     return(!vm.allowed_operations.Contains(XenAPI.vm_operations.clean_reboot));
 }
Пример #58
0
 public InvalidVCPUConfiguration(Check check, VM vm)
     : base(check, vm)
 {
 }
Пример #59
0
 private bool MatchesSearchText(VM vm)
 {
     return(m_searchTextBox.Matches(vm.Name));
 }
Пример #60
0
 public ForceVMRebootCommand(IMainWindow mainWindow, VM vm, Control parent)
     : base(mainWindow, vm, parent)
 {
 }