示例#1
0
        public void ResetVM()
        {
            VMNetDriver driver;

            driver = new VMServerDriver(Port, NetClosed);

            var vm = new VM(new VMContext(null), driver, new VMNullHeadlineProvider());

            state = vm;
            vm.Init();
            vm.OnChatEvent += Vm_OnChatEvent;

            var    path     = Settings.Default.GamePath + "housedata/blueprints/" + Settings.Default.DebugLot;
            string filename = Path.GetFileName(path);

            try
            {
                //try to load from FSOV first.
                LoadState(vm, "Content/LocalHouse/" + filename.Substring(0, filename.Length - 4) + ".fsov");
            }
            catch (Exception)
            {
                try
                {
                    Console.WriteLine("Failed FSOV load... Trying Backup");
                    LoadState(vm, "Content/LocalHouse/" + filename.Substring(0, filename.Length - 4) + "_backup.fsov");
                }
                catch (Exception)
                {
                    Console.WriteLine("CRITICAL::: Failed FSOV load... Trying Blueprint (first run or something went wrong)");
                    short jobLevel = -1;

                    //quick hack to find the job level from the chosen blueprint
                    //the final server will know this from the fact that it wants to create a job lot in the first place...

                    try
                    {
                        if (filename.StartsWith("nightclub") || filename.StartsWith("restaurant") || filename.StartsWith("robotfactory"))
                        {
                            jobLevel = Convert.ToInt16(filename.Substring(filename.Length - 9, 2));
                        }
                    }
                    catch (Exception) { }

                    vm.SendCommand(new VMBlueprintRestoreCmd
                    {
                        JobLevel = jobLevel,
                        XMLData  = File.ReadAllBytes(path)
                    });

                    vm.Context.Clock.Hours = 10;
                }
            }
            vm.MyUID = uint.MaxValue - 1;
            vm.SendCommand(new VMNetSimJoinCmd
            {
                ActorUID = uint.MaxValue - 1,
                Name     = "server"
            });
        }
示例#2
0
        public static FSOF RenderFSOF(byte[] fsov, GraphicsDevice gd)
        {
            var marshal = new VMMarshal();

            using (var mem = new MemoryStream(fsov))
            {
                marshal.Deserialize(new BinaryReader(mem));
            }

            var world = new FSO.LotView.RC.WorldRC(gd);

            world.Opacity = 1;
            Layer.Add(world);

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

            var vm = new VM(new VMContext(world), driver, new VMNullHeadlineProvider());

            vm.Init();

            vm.Load(marshal);

            SetOutsideTime(gd, vm, world, 0.5f, false);
            world.State.PrepareLighting();
            var facade = new LotFacadeGenerator();

            facade.FLOOR_TILES        = 64;
            facade.GROUND_SUBDIV      = 5;
            facade.FLOOR_RES_PER_TILE = 2;

            SetAllLights(vm, world, 0.5f, 0);

            var result = facade.GetFSOF(gd, world, vm.Context.Blueprint, () => { SetAllLights(vm, world, 0.0f, 100); }, true);

            Layer.Remove(world);
            world.Dispose();
            vm.Context.Ambience.Kill();
            foreach (var ent in vm.Entities)
            { //stop object sounds
                var threads = ent.SoundThreads;
                for (int i = 0; i < threads.Count; i++)
                {
                    threads[i].Sound.RemoveOwner(ent.ObjectID);
                }
                threads.Clear();
            }

            return(result);
        }
示例#3
0
        public CVMInstance(int port)
        {
            VM.UseWorld = false;
            VMNetDriver driver;
            driver = new VMServerDriver(port);

            var vm = new VM(new VMContext(null), driver);
            vm.Init();

            vm.SendCommand(new VMBlueprintRestoreCmd
            {
                XMLData = File.ReadAllBytes(Path.Combine(Settings.Default.GamePath+"housedata/blueprints/"+Settings.Default.DebugLot))
            });
            vm.Context.Clock.Hours = 10;

            state = vm;
        }
示例#4
0
        public CVMInstance(int port)
        {
            VM.UseWorld = false;
            VMNetDriver driver;

            driver = new VMServerDriver(port);

            var vm = new VM(new VMContext(null), driver);

            vm.Init();

            vm.SendCommand(new VMBlueprintRestoreCmd
            {
                XMLData = File.ReadAllBytes(Path.Combine(Settings.Default.GamePath + "housedata/blueprints/" + Settings.Default.DebugLot))
            });
            vm.Context.Clock.Hours = 10;

            state = vm;
        }
示例#5
0
        public FSOF RenderFSOF(byte[] fsov)
        {
            var marshal = new VMMarshal();

            using (var mem = new MemoryStream(fsov)) {
                marshal.Deserialize(new BinaryReader(mem));
            }

            var world = new FSO.LotView.RC.WorldRC(GameFacade.GraphicsDevice);

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

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

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

            vm.Init();

            vm.Load(marshal);

            SetOutsideTime(GameFacade.GraphicsDevice, vm, world, 0.5f, false);
            world.State.PrepareLighting();
            var facade = new LotFacadeGenerator();

            facade.FLOOR_TILES        = 64;
            facade.GROUND_SUBDIV      = 5;
            facade.FLOOR_RES_PER_TILE = 2;

            SetAllLights(vm, world, 0.5f, 0);

            var result = facade.GetFSOF(GameFacade.GraphicsDevice, world, vm.Context.Blueprint, () => { SetAllLights(vm, world, 0.0f, 100); }, true);

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

            return(result);
        }
示例#6
0
        public void ResetVM()
        {
            LOG.Info("Resetting VM for lot with dbid = " + Context.DbId);
            VMGlobalLink              = Kernel.Get <LotServerGlobalLink>();
            VMDriver                  = new VMServerDriver(VMGlobalLink);
            VMDriver.OnTickBroadcast += TickBroadcast;
            VMDriver.OnDirectMessage += DirectMessage;
            VMDriver.OnDropClient    += DropClient;

            Lot = new VM(new VMContext(null), VMDriver, new VMNullHeadlineProvider());
            Lot.Init();

            bool isNew   = false;
            bool isMoved = (LotPersist.move_flags > 0);

            LoadAdj();
            if (!JobLot && LotPersist.ring_backup_num > -1 && AttemptLoadRing())
            {
                LOG.Info("Successfully loaded and cleaned fsov for dbid = " + Context.DbId);
            }
            else
            {
                isNew = true;
                BlueprintReset();
            }

            Lot.TSOState.Terrain          = Terrain;
            Lot.TSOState.Name             = LotPersist.name;
            Lot.TSOState.OwnerID          = LotPersist.owner_id;
            Lot.TSOState.Roommates        = new HashSet <uint>();
            Lot.TSOState.BuildRoommates   = new HashSet <uint>();
            Lot.TSOState.PropertyCategory = (byte)LotPersist.category;
            foreach (var roomie in LotRoommates)
            {
                if (roomie.is_pending > 0)
                {
                    continue;
                }
                Lot.TSOState.Roommates.Add(roomie.avatar_id);
                if (roomie.permissions_level > 0)
                {
                    Lot.TSOState.BuildRoommates.Add(roomie.avatar_id);
                }
                if (roomie.permissions_level > 1)
                {
                    Lot.TSOState.OwnerID = roomie.avatar_id;
                }
            }

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

            Lot.Context.UpdateTSOBuildableArea();

            Lot.MyUID = uint.MaxValue - 1;
            if ((LotPersist.move_flags & 2) > 0)
            {
                isNew = true;
            }
            ReturnInvalidObjects();
            if (!JobLot)
            {
                ReturnOOWObjects();
            }

            if (isMoved || isNew)
            {
                VMLotTerrainRestoreTools.RestoreTerrain(Lot);
            }
            if (isNew)
            {
                VMLotTerrainRestoreTools.PopulateBlankTerrain(Lot);
            }

            Lot.Context.Clock.Hours   = tsoTime.Item1;
            Lot.Context.Clock.Minutes = tsoTime.Item2;

            Lot.Context.UpdateTSOBuildableArea();

            var entClone = new List <VMEntity>(Lot.Entities);

            foreach (var ent in entClone)
            {
                if (ent is VMGameObject)
                {
                    ((VMGameObject)ent).Disabled &= ~VMGameObjectDisableFlags.TransactionIncomplete;
                    ((VMGameObject)ent).DisableIfTSOCategoryWrong(Lot.Context);
                    if (ent.GetFlag(VMEntityFlags.Occupied))
                    {
                        ent.ResetData();
                        ent.Init(Lot.Context); //objects should not be occupied when we join the lot...
                    }
                    {
                        ent.ExecuteEntryPoint(2, Lot.Context, true);
                    }
                }
            }
            LotActive.Set();
            ActiveYet = true;
        }
示例#7
0
        public void InitializeLot(string lotName, bool external)
        {
            if (lotName == "")
            {
                return;
            }
            var recording = lotName.ToLowerInvariant().EndsWith(".fsor");

            CleanupLastWorld();

            Content.Content.Get().Upgrades.LoadJSONTuning();

            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,
                //CustomGUID = 0x396CD3D1,
                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; //11 is community
                vm.TSOState.ActivateValidator(vm);
                vm.Context.Clock.Hours = 0;
                vm.TSOState.Size      &= unchecked ((int)0xFFFF0000);
                vm.TSOState.Size      |= (10) | (3 << 8);
                vm.Context.UpdateTSOBuildableArea();

                if (vm.GetGlobalValue(11) > -1)
                {
                    for (int y = 0; y < 3; y++)
                    {
                        for (int x = 0; x < 3; x++)
                        {
                            vm.TSOState.Terrain.Roads[x, y] = 0xF; //crossroads everywhere
                        }
                    }
                    VMLotTerrainRestoreTools.RestoreTerrain(vm);
                }

                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;
        }
示例#8
0
        public void InitTestLot(string path, bool host)
        {
            if (Connecting)
            {
                return;
            }

            if (vm != null)
            {
                CleanupLastWorld();
            }

            World = new LotView.World(GameFacade.Game.GraphicsDevice);
            GameFacade.Scenes.Add(World);

            VMNetDriver driver;

            if (host)
            {
                driver = new VMServerDriver(37564, null);
            }
            else
            {
                Connecting       = true;
                ConnectingDialog = new UILoginProgress();

                ConnectingDialog.Caption         = GameFacade.Strings.GetString("211", "1");
                ConnectingDialog.ProgressCaption = GameFacade.Strings.GetString("211", "24");
                //this.Add(ConnectingDialog);

                UIScreen.ShowDialog(ConnectingDialog, true);

                driver = new VMClientDriver(path, 37564, ClientStateChange);
            }

            vm = new VM(new VMContext(World), driver, new UIHeadlineRendererProvider());
            vm.Init();
            vm.LotName = (path == null) ? "localhost" : path.Split('/').LastOrDefault(); //quick hack just so we can remember where we are

            if (host)
            {
                //check: do we have an fsov to try loading from?

                string filename = Path.GetFileName(path);
                try
                {
                    using (var file = new BinaryReader(File.OpenRead("Content/LocalHouse/" + filename.Substring(0, filename.Length - 4) + ".fsov")))
                    {
                        var marshal = new SimAntics.Marshals.VMMarshal();
                        marshal.Deserialize(file);
                        vm.Load(marshal);
                        vm.Reset();
                    }
                }
                catch (Exception) {
                    short jobLevel = -1;

                    //quick hack to find the job level from the chosen blueprint
                    //the final server will know this from the fact that it wants to create a job lot in the first place...

                    try
                    {
                        if (filename.StartsWith("nightclub") || filename.StartsWith("restaurant") || filename.StartsWith("robotfactory"))
                        {
                            jobLevel = Convert.ToInt16(filename.Substring(filename.Length - 9, 2));
                        }
                    }
                    catch (Exception) { }

                    vm.SendCommand(new VMBlueprintRestoreCmd
                    {
                        JobLevel = jobLevel,
                        XMLData  = File.ReadAllBytes(path)
                    });
                }
            }

            uint simID = (uint)(new Random()).Next();

            vm.MyUID = simID;

            vm.SendCommand(new VMNetSimJoinCmd
            {
                ActorUID = simID,
                HeadID   = GlobalSettings.Default.DebugHead,
                BodyID   = GlobalSettings.Default.DebugBody,
                SkinTone = (byte)GlobalSettings.Default.DebugSkin,
                Gender   = !GlobalSettings.Default.DebugGender,
                Name     = GlobalSettings.Default.LastUser
            });

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

            vm.Context.Clock.Hours = 10;
            if (m_ZoomLevel > 3)
            {
                World.Visible         = false;
                LotController.Visible = false;
            }

            if (host)
            {
                ZoomLevel = 1;
                ucp.SetInLot(true);
            }
            else
            {
                ZoomLevel = Math.Max(ZoomLevel, 4);
            }

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

            vm.OnFullRefresh += VMRefreshed;
            vm.OnChatEvent   += Vm_OnChatEvent;
            vm.OnEODMessage  += LotController.EODs.OnEODMessage;
        }
        public void InitTestLot(string path, bool host)
        {
            if (Connecting)
            {
                return;
            }

            lotName = path;



            Characters = new List <XmlCharacter>();

            SaveHouseButton.Visible = true;
            CreateChar.Visible      = false;

            if (vm != null)
            {
                CleanupLastWorld();
            }

            World = new LotView.World(GameFacade.Game.GraphicsDevice);
            GameFacade.Scenes.Add(World);



            vm = new VM(new VMContext(World), new UIHeadlineRendererProvider());
            vm.Init();
            vm.LotName = (path == null) ? "localhost" : path.Split('/').LastOrDefault(); //quick hack just so we can remember where we are


            var DirectoryInfo = new DirectoryInfo(Path.Combine(FSOEnvironment.UserDir, "Characters/"));

            for (int i = 0; i <= DirectoryInfo.GetFiles().Count() - 1; i++)
            {
                var file = DirectoryInfo.GetFiles()[i];
                CharacterInfos[i] = Path.GetFileNameWithoutExtension(file.FullName);

                if (CharacterInfos[i] != null && CharacterInfos[i] != gizmo.SelectedCharInfo.Name)
                {
                    Characters.Add(XmlCharacter.Parse(file.FullName));
                }
            }


            VMNetDriver driver;

            if (host)
            {
                driver = new VMServerDriver(37564, null);
            }
            else
            {
                Connecting       = true;
                ConnectingDialog = new UILoginProgress();

                ConnectingDialog.Caption         = GameFacade.Strings.GetString("211", "1");
                ConnectingDialog.ProgressCaption = GameFacade.Strings.GetString("211", "24");
                //this.Add(ConnectingDialog);

                UIScreen.ShowDialog(ConnectingDialog, true);

                driver = new VMClientDriver(path, 37564, ClientStateChange);
            }


            vm.VM_SetDriver(driver);



            if (host)
            {
                //check: do we have an fsov to try loading from?

                string filename = Path.GetFileName(path);
                try
                {
                    using (var file = new BinaryReader(File.OpenRead(Path.Combine(FSOEnvironment.UserDir, "Houses/") + filename.Substring(0, filename.Length - 4) + ".fsov")))
                    {
                        var marshal = new SimAntics.Marshals.VMMarshal();
                        marshal.Deserialize(file);
                        vm.Load(marshal);
                        vm.Reset();
                    }
                }
                catch (Exception)
                {
                    short jobLevel = -1;

                    //quick hack to find the job level from the chosen blueprint
                    //the final server will know this from the fact that it wants to create a job lot in the first place...

                    try
                    {
                        if (filename.StartsWith("nightclub") || filename.StartsWith("restaurant") || filename.StartsWith("robotfactory"))
                        {
                            jobLevel = Convert.ToInt16(filename.Substring(filename.Length - 9, 2));
                        }
                    }
                    catch (Exception) { }

                    vm.SendCommand(new VMBlueprintRestoreCmd
                    {
                        JobLevel   = jobLevel,
                        XMLData    = File.ReadAllBytes(path),
                        Characters = Characters
                    });
                }
            }

            //Check the clients loaded;
            List <VMAvatar> Clients = new List <VMAvatar>();

            foreach (VMEntity entity in vm.Entities)
            {
                if (entity is VMAvatar && entity.PersistID > 0)
                {
                    Clients.Add((VMAvatar)entity);
                }
            }


            if (Clients.Count == 0)
            {
                Permissions = true;
            }

            uint simID = (uint)(new Random()).Next();

            vm.MyUID = simID;


            var headPurchasable = Content.Content.Get().AvatarPurchasables.Get(Convert.ToUInt64(gizmo.SelectedCharInfo.Head, 16));
            var bodyPurchasable = Content.Content.Get().AvatarPurchasables.Get(Convert.ToUInt64(gizmo.SelectedCharInfo.Body, 16));
            var HeadID          = headPurchasable != null ? headPurchasable.OutfitID :
                                  Convert.ToUInt64(gizmo.SelectedCharInfo.Head, 16);
            var BodyID = bodyPurchasable != null ? bodyPurchasable.OutfitID :
                         Convert.ToUInt64(gizmo.SelectedCharInfo.Body, 16);

            AppearanceType type;

            Enum.TryParse(gizmo.SelectedCharInfo.Appearance, out type);
            bool Male = (gizmo.SelectedCharInfo.Gender == "male") ? true:false;

            vm.SendCommand(new VMNetSimJoinCmd
            {
                ActorUID    = simID,
                HeadID      = HeadID,
                BodyID      = BodyID,
                SkinTone    = (byte)type,
                Gender      = Male,
                Name        = gizmo.SelectedCharInfo.Name,
                Permissions = (Permissions == true) ?
                              VMTSOAvatarPermissions.Owner : VMTSOAvatarPermissions.Visitor
            });

            VMWorldActivator activator = new VMWorldActivator(vm, World);

            if (host)
            {
            }
            else
            {
                foreach (XmlCharacter Char in Characters)
                {
                    uint vsimID = (uint)(new Random()).Next();
                    Enum.TryParse(Char.Appearance, out type);

                    var vheadPurchasable = Content.Content.Get().AvatarPurchasables.Get(Convert.ToUInt64(Char.Head, 16));
                    var vbodyPurchasable = Content.Content.Get().AvatarPurchasables.Get(Convert.ToUInt64(Char.Body, 16));
                    var vHeadID          = vheadPurchasable != null ? vheadPurchasable.OutfitID :
                                           Convert.ToUInt64(Char.Head, 16);
                    var vBodyID = vbodyPurchasable != null ? vbodyPurchasable.OutfitID :
                                  Convert.ToUInt64(Char.Body, 16);

                    VMEntity vEntity = vm.Entities.FirstOrDefault(x => (x.Object.OBJ.GUID == 0x7FD96B54 && x.Name == Char.Name));

                    if (vEntity != null)
                    {
                        ((VMAvatar)vEntity).SetAvatarData(Char);
                    }
                }
            }

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

            vm.Context.Clock.Hours = 10;

            if (m_ZoomLevel > 3)
            {
                World.Visible         = false;
                LotController.Visible = false;
            }


            if (host)
            {
                ZoomLevel = 1;
                ucp.SetInLot(true);
            }
            else
            {
                ZoomLevel = Math.Max(ZoomLevel, 4);
            }

            vm.OnFullRefresh += VMRefreshed;
            vm.OnChatEvent   += Vm_OnChatEvent;
            vm.OnEODMessage  += LotController.EODs.OnEODMessage;
        }
示例#10
0
        public void ResetVM()
        {
            VMNetDriver driver;

            driver = new VMServerDriver(Port, NetClosed);

            var vm = new VM(new VMContext(null), new VMNullHeadlineProvider());

            state = vm;
            vm.Init();
            vm.VM_SetDriver(driver);
            vm.OnChatEvent += Vm_OnChatEvent;

            Console.WriteLine("Select the lot type");
            Console.WriteLine("1-Empty");
            Console.WriteLine("2-Blueprint");
            Console.WriteLine("3-House");

            string path = "";
            int    lot  = Convert.ToInt32(Console.ReadLine());

            if (lot == 1)
            {
                if (Settings.Default.DebugLot != String.Empty)
                {
                    path = AppDomain.CurrentDomain.BaseDirectory + "Content/Houses/" + Settings.Default.DebugLot;
                }
                else
                {
                    path = AppDomain.CurrentDomain.BaseDirectory + "Content/Houses/empty_lot.xml";
                }
            }
            else if (lot == 2)
            {
                Console.WriteLine("Specify lot name");
                path = AppDomain.CurrentDomain.BaseDirectory + "Content/Houses/" + Console.ReadLine() + ".xml";
            }
            else if (lot == 3)
            {
                Console.WriteLine("Specify house name");
                path = AppDomain.CurrentDomain.BaseDirectory + "Content/Houses/" + Console.ReadLine() + ".iff";
                TS1  = true;
            }


            XmlHouseData lotInfo;
            IffFile      HouseInfo = null;
            string       filename  = Path.GetFileName(path);

            if (!TS1)
            {
                try
                {
                    //try to load from FSOV first.
                    LoadState(vm, "Content/LocalHouse/" + filename.Substring(0, filename.Length - 4) + ".fsov");
                }
                catch (Exception)
                {
                    try
                    {
                        Console.WriteLine("Failed FSOV load... Trying Backup");
                        LoadState(vm, "Content/LocalHouse/" + filename.Substring(0, filename.Length - 4) + "_backup.fsov");
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("CRITICAL::: Failed FSOV load... Trying Blueprint (first run or something went wrong)");
                        short jobLevel = -1;

                        //quick hack to find the job level from the chosen blueprint
                        //the final server will know this from the fact that it wants to create a job lot in the first place...

                        try
                        {
                            if (filename.StartsWith("nightclub") || filename.StartsWith("restaurant") || filename.StartsWith("robotfactory"))
                            {
                                jobLevel = Convert.ToInt16(filename.Substring(filename.Length - 9, 2));
                            }
                        }
                        catch (Exception) { }

                        //vm.SendCommand(new VMBlueprintRestoreCmd
                        //{
                        // JobLevel = jobLevel,
                        // XMLData = File.ReadAllBytes(path)
                        //});

                        using (var stream = new MemoryStream(File.ReadAllBytes(path)))
                        {
                            lotInfo = XmlHouseData.Parse(stream);
                        }

                        VMWorldActivator activator = new VMWorldActivator(vm, vm.Context.World);

                        vm.Activator = activator;

                        var blueprint = activator.LoadFromXML(lotInfo);

                        if (VM.UseWorld)
                        {
                            vm.Context.World.InitBlueprint(blueprint);
                            vm.Context.Blueprint = blueprint;
                        }


                        vm.Context.Clock.Hours = 10;

                        vm.MyUID = uint.MaxValue - 1;
                    }
                }
            }
            else
            {
                if (File.Exists(path))
                {
                    HouseInfo = new IffFile(path);
                }

                VMWorldActivator activator = new VMWorldActivator(vm, vm.Context.World);

                vm.Activator = activator;

                var blueprint = activator.LoadFromIff(HouseInfo);

                if (VM.UseWorld)
                {
                    vm.Context.World.InitBlueprint(blueprint);
                    vm.Context.Blueprint = blueprint;
                }


                vm.Context.Clock.Hours = 10;

                vm.MyUID = uint.MaxValue - 1;
            }



            Console.WriteLine("Select the server type");
            Console.WriteLine("1-Host");
            Console.WriteLine("2-Dedicated");

            int host = Convert.ToInt32(Console.ReadLine());

            if (host == 1)
            {
                vm.SendCommand(new VMNetSimJoinCmd
                {
                    ActorUID = uint.MaxValue - 1,
                    Name     = "server"
                });
            }
            else if (host == 2)
            {
                Dedicated = true;
            }
        }
示例#11
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();
        }
示例#12
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();
                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.ActivateFamily(ActiveFamily);
                }
                BlueprintReset(lotName);

                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;
        }