public Position2D GetScreenCoordinatesFrom3DPosition(Vector3D position, CameraSceneNode camera)
 {
     IntPtr cam = (camera == null ? IntPtr.Zero : camera.Raw);
     int[] sc = new int[2];
     SceneCollisionManager_GetScreenCoordinatesFrom3DPosition(_raw, position.ToUnmanaged(), cam, sc);
     return Position2D.FromUnmanaged(sc);
 }
 public SceneNode GetSceneNodeFromCamera(CameraSceneNode camera, int idBitMask, bool noDebug)
 {
     IntPtr cam = (camera == null ? IntPtr.Zero : camera.Raw);
     return (SceneNode)
         NativeElement.GetObject(SceneCollisionManager_GetSceneNodeFromCameraBB(_raw, cam, idBitMask, noDebug),
                                 typeof(SceneNode));
 }
 public Line3D GetRayFromScreenCoordinates(Position2D position, CameraSceneNode camera)
 {
     IntPtr cam = (camera == null ? IntPtr.Zero : camera.Raw);
     float[] outray = new float[6];
     SceneCollisionManager_GetRayFromScreenCoordinates(_raw, position.ToUnmanaged(), cam, outray);
     return Line3D.FromUnmanaged(outray);
 }
Example #4
0
        public override void Unload()
        {
            if (Root.Children.Length > 0)
                Root.RemoveAll();

            node = null;

            base.Unload();
        }
Example #5
0
        public override void Load()
        {
            node = Render.Scene.AddCameraSceneNode(Root);
            node.FOV = 60 * NewMath.DEGTORAD;
            node.Position = new Vector3D(0, 0, -256);
            node.Target = new Vector3D(0, 0, 0);
            node.UpVector = new Vector3D(0, 0, 1);

            base.Load();
        }
		public WaterSceneNode(SceneNode parent, SceneManager mgr, Dimension2Df tileSize,
		                      Dimension2D tileCount, Dimension2D precision, int id) : 
			base(parent, mgr, id)
		{
			_scene = mgr;
			_driver = mgr.VideoDriver;
			
			AnimatedMesh wmesh =  _scene.AddHillPlaneMesh("watermesh" + _current,
                tileSize,
                tileCount, 0,
                new Dimension2Df(0, 0),
                new Dimension2Df(1, 1));
           	_current++; 
           	 
            int dmat = (int)MaterialType.Reflection2Layer;
            if(_driver.DriverType == DriverType.OpenGL)
                dmat = _driver.GPUProgrammingServices.AddHighLevelShaderMaterial(
                 WATER_VERTEX_GLSL, "main", VertexShaderType._1_1, WATER_FRAGMENT_GLSL,
                 "main", PixelShaderType._1_1, OnShaderSet, MaterialType.TransparentAlphaChannel, 0);
            else
                dmat = _driver.GPUProgrammingServices.AddHighLevelShaderMaterial(
                 WATER_HLSL, "vertexMain", VertexShaderType._2_0, WATER_HLSL,
                 "pixelMain", PixelShaderType._2_0, OnShaderSet, MaterialType.TransparentAlphaChannel, 2);

            if (_driver.DriverType == DriverType.OpenGL)
                ClampShader = _driver.GPUProgrammingServices.AddHighLevelShaderMaterial(
                 CLAMP_VERTEX_GLSL, "main", VertexShaderType._1_1, CLAMP_FRAGMENT_GLSL,
                 "main", PixelShaderType._1_1, OnShaderSet, MaterialType.TransparentAlphaChannel, 1);
            else
                ClampShader = _driver.GPUProgrammingServices.AddHighLevelShaderMaterial(
                 CLAMP_HLSL, "vertexMain", VertexShaderType._2_0, CLAMP_HLSL,
                 "pixelMain", PixelShaderType._2_0, OnShaderSet, MaterialType.TransparentAlphaChannel, 3);
                 
           	_waternode = _scene.AddMeshSceneNode(wmesh.GetMesh(0), this, -1);  
            _waternode.SetMaterialType(dmat);
            _waternode.SetMaterialFlag(MaterialFlag.BackFaceCulling, false);
            _waternode.SetMaterialFlag(MaterialFlag.Lighting, false);
            _waternode.SetMaterialFlag(MaterialFlag.FogEnable, false);
            
            _rt = _driver.CreateRenderTargetTexture(precision);
            _waternode.SetMaterialTexture(0, _rt); 
            
            CameraSceneNode oldcam = _scene.ActiveCamera;
            _fixedcam = _scene.AddCameraSceneNode(null);
            if(oldcam != null)
            	_scene.ActiveCamera = oldcam;
		}
Example #7
0
File: Title.cs Project: yooyke/work
        public override void Initialize()
        {
            base.Initialize();

            // Set title camera
            System.Type type = this.GetType();
            camera = Render.Scene.AddCameraSceneNode(Render.Scene.RootSceneNode);
            camera.Position = new Vector3D(0, 0, -256);
            camera.Target = new Vector3D(0, 0, 0);
            camera.UpVector = new Vector3D(0, 0, 1);
            camera.Name = type.FullName + ".Camera" ;

            root = Render.Scene.AddEmptySceneNode(Render.Scene.RootSceneNode, -1);
            root.Name = type.FullName + ".Root";

            CreateTitle();
        }
Example #8
0
        public override int Load()
        {
            if (WaterSceneNode == null)
            {
                const string filename = "advanced_sea_shader.fx";

                Timer = Reference.Device.Timer;
                Size = new Dimension2Df(256, 256);

                if (Reference.SceneManager.ActiveCamera != null)
                {
                    CameraSceneNode currentCamera = Reference.SceneManager.ActiveCamera;
                    Camera = Reference.SceneManager.AddCameraSceneNode(parentNode);
                    Camera.FarValue = currentCamera.FarValue;
                    Camera.FOV = currentCamera.FOV;
                    Reference.SceneManager.ActiveCamera = currentCamera;
                }
                else
                {
                    Camera = Reference.SceneManager.AddCameraSceneNode(parentNode);
                }

                AnimatedMesh mesh = Reference.SceneManager.AddHillPlaneMesh("terrain", new Dimension2Df(512, 512), new Dimension2D(256, 256), 0.0f, new Dimension2Df(0, 0), new Dimension2Df(1024, 1024));
                SceneNode amsn = Reference.SceneManager.AddOctTreeSceneNode(mesh, parentNode, -1, 128);
                amsn.Position = new Vector3D(128, 0, 128);
                amsn.SetMaterialTexture(0, Reference.VideoDriver.GetTexture(Util.ApplicationDataDirectory + @"\media\textures\sand01.jpg"));

                AnimatedMesh watermesh = Reference.SceneManager.AddHillPlaneMesh("realisticwater", Size, new Dimension2D(1, 1), 0f, new Dimension2Df(0, 0), new Dimension2Df(1, 1));
                WaterSceneNode = Reference.SceneManager.AddOctTreeSceneNode(watermesh, parentNode, -1, 128);

                Texture bumpTexture = Reference.VideoDriver.GetTexture(Util.ApplicationDataDirectory + @"\media\textures\waterbump.jpg");

                GPUProgrammingServices gpuProgrammingServices = Reference.VideoDriver.GPUProgrammingServices;

                string path = Util.ApplicationDataDirectory + @"\media\shaders\" + filename;
                if (System.IO.File.Exists(path))
                {
                    try
                    {
                        ShaderMaterial = Reference.VideoDriver.GPUProgrammingServices.AddHighLevelShaderMaterialFromFiles(
                        path, "VertexShaderFunction", VertexShaderType._2_0,
                        path, "PixelShaderFunction", PixelShaderType._2_0,
                        ShaderEvent, MaterialType.Lightmap, 0
                        );
                    }
                    catch (Exception e)
                    {
                        Reference.Log.Fatal("Load", e);
                    }

                    if (ShaderMaterial > 0)
                        Reference.Log.Debug("Load: Loaded" + path);
                    else
                        Reference.Log.Debug("Load: not Loaded:" + path);
                }
                else
                {
                    Viewer.Log.Warn("[SHADER] [SEA] Shader file was not found: " + Util.ApplicationDataDirectory + @"\media\shaders\" + filename);
                }
                float waterheight = 0;
                if (Reference.Viewer.ProtocolManager.AvatarConnection.m_user.Network.CurrentSim != null)
                {
                    waterheight = Reference.Viewer.ProtocolManager.AvatarConnection.m_user.Network.CurrentSim.WaterHeight;
                }
                WaterSceneNode.Position = new Vector3D(128, waterheight, 128);
                WaterSceneNode.Scale = new Vector3D(200, 1, 200);
                WaterSceneNode.SetMaterialType(ShaderMaterial);
                WaterSceneNode.SetMaterialTexture(0, bumpTexture);
                RefractionMap = Reference.VideoDriver.CreateRenderTargetTexture(renderTargetSize);
                ReflectionMap = Reference.VideoDriver.CreateRenderTargetTexture(renderTargetSize);

                WaterSceneNode.SetMaterialTexture(1, RefractionMap);
                WaterSceneNode.SetMaterialTexture(2, ReflectionMap);
            }
            return ShaderMaterial;
        }
Example #9
0
        /// <summary>
        /// User's Camera
        /// </summary>
        /// <param name="psmgr">Scene Manager</param>
        public Camera(Viewer _viewer)
            : base(_viewer, -1)
        {
            //
            VOtarget = null;
            SNCamera = Reference.SceneManager.AddCameraSceneNode(Reference.SceneManager.RootSceneNode);
            SNCamera.Position = new Vector3D(0f, 235f, -44.70f);
            SNCamera.Target = new Vector3D(-273, -255.3f, 407.3f);
            SNCamera.FarValue = 12800;
            SNCamera.FOV = Reference.Viewer.CameraFOV;
            SNCamera.Name = "Camera";

            LookAtCam[0] = Vector3.Zero;
            LookAtCam[1] = Vector3.Zero;
            LookAtCam[2] = Vector3.Zero;

            nowDistance = Reference.Viewer.CameraDistance;

            UpdateCameraPosition();
        }
Example #10
0
        public void Initialize3D()
        {
            device = new IrrlichtDevice(DriverType.Direct3D9, /* TODO: for Linux/OSX it should be OpenGL */
                new Dimension2D(800, 600), 32, false, true, true, true, GetHandle());
            device.FileSystem.WorkingDirectory = "3d";
            device.Resizeable = true;

            // setup a simple 3d scene
            SceneManager sceneManager = device.SceneManager;

            VideoDriver driver = device.VideoDriver;

            camera = sceneManager.AddCameraSceneNodeFPS(null, 100.0f, 50000.0f, false);
            camera.Position = new Vector3D(1900 * 2, 255 * 2, 3700 * 2);
            camera.Target = new Vector3D(2397 * 2, 343 * 2, 2700 * 2);
            camera.FarValue = 12000.0f;

            camera.InputReceiverEnabled = false;

            /*
            Here comes the terrain renderer scene node: We add it just like any 
            other scene node to the scene using ISceneManager::addTerrainSceneNode(). 
            The only parameter we use is a file name to the heightmap we use. A heightmap
            is simply a gray scale texture. The terrain renderer loads it and creates 
            the 3D terrain from it.
            To make the terrain look more big, we change the scale factor of it to (40, 4.4, 40).
            Because we don't have any dynamic lights in the scene, we switch off the lighting,
            and we set the file terrain-texture.jpg as texture for the terrain and 
            detailmap3.jpg as second texture, called detail map. At last, we set
            the scale values for the texture: The first texture will be repeated only one time over 
            the whole terrain, and the second one (detail map) 20 times. 
            */

            terrain = sceneManager.AddTerrainSceneNode("terrain-heightmap.bmp",
                null,                               // parent node
                -1,									// node id
                new Vector3D(0f, 0f, 0f),			// position
                new Vector3D(0f, 0f, 0f),			// rotation
                new Vector3D(40f, 4.4f, 40f),		// scale
                new Color(255, 255, 255, 255),	    // vertexColor,
                5,									// maxLOD
                TerrainPatchSize.TPS17				// patchSize
            );

            terrain.SetMaterialFlag(MaterialFlag.Lighting, false);
            terrain.SetMaterialTexture(0, driver.GetTexture("terrain-texture.jpg"));
            terrain.SetMaterialTexture(1, driver.GetTexture("detailmap3.jpg"));
            terrain.SetMaterialType(MaterialType.DetailMap);
            terrain.ScaleTexture(1.0f, 20.0f);
            //terrain->setDebugDataVisible ( true );

            /*
            To be able to do collision with the terrain, we create a triangle selector.
            If you want to know what triangle selectors do, just take a look into the 
            collision tutorial. The terrain triangle selector works together with the
            terrain. To demonstrate this, we create a collision response animator 
            and attach it to the camera, so that the camera will not be able to fly 
            through the terrain.
            */

            // create triangle selector for the terrain	
            TriangleSelector selector = sceneManager.CreateTerrainTriangleSelector(terrain, 0);
            terrain.TriangleSelector = selector;

            // create collision response animator and attach it to the camera
            Animator animator = sceneManager.CreateCollisionResponseAnimator(selector, camera, new Vector3D(60, 100, 60), new Vector3D(0, 0, 0), new Vector3D(0, 50, 0), 0);
            selector.Dispose();
            camera.AddAnimator(animator);
            animator.Dispose(); ;

            /*
            To make the user be able to switch between normal and wireframe mode, we create
            an instance of the event reciever from above and let Irrlicht know about it. In 
            addition, we add the skybox which we already used in lots of Irrlicht examples.
            */

            // create skybox
            driver.SetTextureFlag(TextureCreationFlag.CreateMipMaps, false);

            sceneManager.AddSkyBoxSceneNode(null, new Texture[] {
                driver.GetTexture("irrlicht2_up.jpg"),
                driver.GetTexture("irrlicht2_dn.jpg"),
                driver.GetTexture("irrlicht2_lf.jpg"),
                driver.GetTexture("irrlicht2_rt.jpg"),
                driver.GetTexture("irrlicht2_ft.jpg"),
                driver.GetTexture("irrlicht2_bk.jpg")
            }, -1);

            while (device.Run())
            {
                driver.BeginScene(true, true, new Color());
                sceneManager.DrawAll();
                driver.EndScene();
            }

            device.Dispose();

            return;
        }
 public SceneNode GetSceneNodeFromCamera(CameraSceneNode camera)
 {
     return GetSceneNodeFromCamera(camera, 0, false);
 }
Example #12
0
        private void StartupGUI(object target)
        {
            // Enforce the underlying Irrlicht engine to load a local D3DX9_40.dll
            // (Note: Environment.CurrentDirectory is visible to other plug-ins)
            Environment.CurrentDirectory = Util.ApplicationDataDirectory;

            SetupAddins();
            SetupLog();

            f = new RenderForm(this);
            f.Width = width;
            f.Height = height;
            f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            f.ImeMode = System.Windows.Forms.ImeMode.Inherit;
            try
            {
                SetParent(f.Handle, (IntPtr)target);

            #if MANAGED_D3D
                Microsoft.DirectX.Direct3D.PresentParameters pp = new Microsoft.DirectX.Direct3D.PresentParameters();
                pp.Windowed = true;
                pp.SwapEffect = Microsoft.DirectX.Direct3D.SwapEffect.Discard;

                try
                {
                    d3ddevice = new Microsoft.DirectX.Direct3D.Device(
                        0,
                        Microsoft.DirectX.Direct3D.DeviceType.Hardware,
                        f,
                        Microsoft.DirectX.Direct3D.CreateFlags.SoftwareVertexProcessing,
                        pp
                        );
                }
                catch
                {
                    try
                    {
                        d3ddevice = new Microsoft.DirectX.Direct3D.Device(
                            0,
                            Microsoft.DirectX.Direct3D.DeviceType.Reference,
                            f,
                            Microsoft.DirectX.Direct3D.CreateFlags.SoftwareVertexProcessing,
                            pp
                            );
                    }
                    catch
                    {
                    }
                }

                CreateVideoObject();
            #endif
            }
            catch (System.Exception)
            {

            }
            f.Location = new System.Drawing.Point(0, 0);
            //f.FormClosed += new System.Windows.Forms.FormClosedEventHandler(f_FormClosed);
            f.Show();
            renderTarget = f.Handle;

            try
            {
                string iniconfig = System.IO.Path.Combine(Util.ConfigFolder, "OpenViewer.ini");
                m_config.Load(iniconfig);

                // Check and clean cache if request last time.
                string cacheFlag = m_config.Source.Configs["Startup"].Get("cache_delete", "false");
                if (cacheFlag == "true")
                {
                    CleanChache();
                }

            }
            catch (Exception e)
            {
                m_log.Fatal("can't load config file.", e);
            }

            try
            {
                device = new IrrlichtDevice(DriverType.Direct3D9, new Dimension2D(width, height), 32, false, true, false, false, renderTarget);
                if (device == null)
                {
                    m_log.Error("can't create irrlicht device.");
                    System.Windows.Forms.MessageBox.Show(DialogText.ErrorGraphicDriverMessage, DialogText.ErrorGraphicDriverCaption);
                }
            }
            catch (Exception e)
            {
                m_log.Error("can't create irrlicht device.", e);
                System.Windows.Forms.MessageBox.Show(DialogText.ErrorGraphicDriverMessage, DialogText.ErrorGraphicDriverCaption);

                device = null;
            }

            if (device == null)
            {
                // release all.

                // exit application.

                return;
            }
            else
            {
                m_log.InfoFormat("AdapterVendorID: 0x{0:x8}", device.VideoDriver.AdapterVendorId);
                m_log.InfoFormat("AdapterDeviceId: 0x{0:x8}", device.VideoDriver.AdapterDeviceId);
                m_log.InfoFormat("AdapterSubSysId: 0x{0:x8}", device.VideoDriver.AdapterSubSysId);
                m_log.InfoFormat("AdapterRevision: 0x{0:x8}", device.VideoDriver.AdapterRevision);
                m_log.InfoFormat("AdapterMaxTextureHeight: {0}", device.VideoDriver.AdapterMaxTextureHeight);
                m_log.InfoFormat("AdapterMaxTextureWidth: {0}", device.VideoDriver.AdapterMaxTextureWidth);
                m_log.InfoFormat("AdapterMaxActiveLights: {0}", device.VideoDriver.AdapterMaxActiveLights);
                m_log.InfoFormat("AdapterVertexShaderVersion: 0x{0:x8}", device.VideoDriver.AdapterVertexShaderVersion);
                m_log.InfoFormat("AdapterPixelShaderVersion: 0x{0:x8}", device.VideoDriver.AdapterPixelShaderVersion);

                // AdapterVendorId
                // 0x1002 : ATI Technologies Inc.
                // 0x10DE : NVIDIA Corporation
                // 0x102B : Matrox Electronic Systems Ltd.
                // 0x121A : 3dfx Interactive Inc
                // 0x5333 : S3 Graphics Co., Ltd.
                // 0x8086 : Intel Corporation
                //
                if (device.VideoDriver.AdapterVendorId == 0x1002)
                {
                    string warningMessage = DialogText.WarningGraphicCardMessage;
                    string warningCaption = DialogText.WarningGraphicCardCaption;

                    System.Windows.Forms.DialogResult yesno = System.Windows.Forms.MessageBox.Show(warningMessage, warningCaption, System.Windows.Forms.MessageBoxButtons.YesNo);
                    if (System.Windows.Forms.DialogResult.Yes != yesno)
                    {
                        return;
                    }
                }
            }

            reference = new RefController(this);

            device.OnEvent += new OnEventDelegate(device_OnEvent);

            // If enabled is true, videotexture is not correctly render.
            device.VideoDriver.SetTextureFlag(TextureCreationFlag.CreateMipMaps, false);

            #if DEBUG
            device.Logger.LogLevel = LogLevel.Information;
            #endif
            // Create video Textrue
            videoTexture = device.VideoDriver.GetTexture(Util.ApplicationDataDirectory + @"\media\textures\videoTexture.tga");

            IrrlichtNETCP.Extensions.TTFont font = new TTFont(Device.VideoDriver);
            IrrlichtNETCP.Extensions.TTFace face = new TTFace();
            bool font_loaded = false;
            uint fontsize = 16;
            string fontface = Config.Source.Configs["Startup"].GetString("guifont_face");

            if (!string.IsNullOrEmpty(Config.Source.Configs["Startup"].GetString("guifont_size")))
            {
                fontsize = (uint)Config.Source.Configs["Startup"].GetInt("guifont_size");
            }

            if (!string.IsNullOrEmpty(fontface))
            {
                if (System.IO.File.Exists(System.Environment.SystemDirectory + @"\..\Fonts\" + fontface))
                {
                    face.Load(System.Environment.SystemDirectory + @"\..\Fonts\" + fontface);
                    font.Attach(face, fontsize);
                    font.Antialias = true;
                    Reference.GUIEnvironment.Skin.Font = font;
                    font_loaded = true;
                }
                else
                {
                    m_log.Warn("[FONT]: The specified font (" + fontface + ") was not available on this system. Reverting to default.");
                }
            }
            if (!font_loaded)
            {
                if (System.IO.File.Exists(System.Environment.SystemDirectory + @"\..\Fonts\msgothic.ttc"))
                {
                    face.Load(System.Environment.SystemDirectory + @"\..\Fonts\msgothic.ttc");
                    font.Attach(face, fontsize);
                    font.Antialias = true;
                    Reference.GUIEnvironment.Skin.Font = font;
                }
                else
                {
                    JapaneseEnabled = false;
                    Locale = "en";
                    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
                    if (System.IO.File.Exists(System.Environment.SystemDirectory + @"\..\Fonts\arial.ttf"))
                    {
                        face.Load(System.Environment.SystemDirectory + @"\..\Fonts\arial.ttf");
                        font.Attach(face, fontsize);
                        font.Antialias = true;
                        Reference.GUIEnvironment.Skin.Font = font;
                    }
                    else
                    {
                        // Use built in font--- this looks horrible and should be avoided if possible
                        Reference.GUIEnvironment.Skin.Font = Reference.GUIEnvironment.BuiltInFont;
                    }
                }
            }
            font.Drop();
            face.Drop();
            // if font and face are being used, at this point face and font should both have reference counts of 1.
            // if font and face are not being used (last else branch above, using built-in font), font and face should both be deleted at this point.

            // Zaki: Adding Japanese support end

            Reference.VideoDriver.SetFog(new Color(0, 255, 255, 255), false, 9999, 9999, 0, false, false);

            //Reference.Device.FileSystem.WorkingDirectory = Util.UserCacheDirectory;
            Reference.Device.FileSystem.AddFolderFileArchive(Util.ApplicationDataDirectory);
            Reference.Device.FileSystem.AddFolderFileArchive(Util.ModelFolder);
            Reference.Device.FileSystem.AddFolderFileArchive(Util.TextureFolder);

            camera = new Camera(this);

            // Create managers.
            cacheManager = new CacheManager(this, -1);
            try
            {
                string iniconfig = System.IO.Path.Combine(Util.ConfigFolder, "OpenViewer.ini");
                m_config.Load(iniconfig);

                // Check and clean cache if request last time.
                string s_cacheMB = m_config.Source.Configs["Startup"].Get("cache_size", DEFAULT_CACHE_MB_SIZE.ToString());

                long cacheMB = DEFAULT_CACHE_MB_SIZE;
                if (long.TryParse(s_cacheMB, out cacheMB))
                {
                    cacheMB = cacheMB * 1000 * 1000;

                    cacheManager.CacheMaxSize = cacheMB;
                    cacheManager.Clean();
                }
            }
            catch (Exception e)
            {
                m_log.Fatal("can't load config file.", e);
            }

            // Locale can be used from this point on
            if (Locale == "en")
            {
                DialogText.Culture = new System.Globalization.CultureInfo("en-US");
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
            }
            if (Locale == "jp")
            {
                DialogText.Culture = new System.Globalization.CultureInfo("ja-JP");
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ja-JP");
            }

            stateManager = new Managers.StateManager(this);
            protocolManager = new Managers.ProtocolManager(this);
            guiManager = new GuiManager(this);
            menuManager = new MenuManager(this);
            shaderManager = new ShaderManager(this);
            entityManager = new EntityManager(this);
            irrManager = new IrrManager(this, -1);
            textureManager = new TextureManager(this);
            textureManager.OnTextureLoaded += OnTextureComplete;
            terrainManager = new Managers.TerrainManager(this);
            avatarManager = new Managers.AvatarManager(this);
            effectManager = new Managers.EffectManager(this);
            chatManager = new Managers.ChatManager(this);
            soundManager = new Managers.SoundManager(this);
            debugManager = new DebugManager(this, -1);

            // Experimental manager plugin loader
            LoadPlugins();

            // Initialize.
            Initialize();

            // Event
            stateManager.OnChanged += StateChanged;

            clearColor = Color.FromBCL(Util.FromString(BackgroundColor));
            progressBarColor = Color.FromBCL(Util.FromString(ProgressColor, System.Drawing.Color.FromArgb(63, 0, 0, 0)));

            guiManager.LoadBackgrounds();

            soundManager.InitWindowBackgroundMusicURL = InitBackgroundMusicURL;
            soundManager.LoadBackgroundMusic();

            // After all managers all initialized
            stateManager.State = State.INITIALIZED;

            adapter.Initialize(this.reference);

            adapter.CallSetWorldAmbientColor(WorldAmbientColor);
            adapter.CallSetFixDirectional(FixDirectional);
            adapter.CallSetFixDirectionalRotation(FixDirectionalRotation);
            adapter.CallSetFixDirectionalDiffuseColor(FixDirectionalDiffuseColor);
            adapter.CallSetFixDirectionalAmbientColor(FixDirectionalAmbientColor);

            SetLogFilter();

            guiManager.ShowLoginWindow(new LoginInfo(ServerURI, FirstName, LastName, Password, LoginMode, true, true));

            // Hide mouse cursor.
            ShowCursor(false);

            #if _SECOND_SURFACE_ON
            pip = Reference.VideoDriver.CreateRenderTargetTexture(new Dimension2D(256, 256));
            pipImage = Reference.GUIEnvironment.AddImage(pip, new Position2D(Width - pip.OriginalSize.Width - 10, 40), false, Reference.GUIEnvironment.RootElement, -1, "");

            CameraSceneNode oldCam = Reference.SceneManager.ActiveCamera;
            pipCamera = Reference.SceneManager.AddCameraSceneNode(Reference.SceneManager.RootSceneNode);
            material.Lighting = false;
            if (Reference.SceneManager.ActiveCamera.Raw != oldCam.Raw)
                Reference.SceneManager.ActiveCamera = oldCam;
            #endif

            System.Windows.Forms.DialogResult dialogRes = System.Windows.Forms.DialogResult.Retry;
            while (dialogRes == System.Windows.Forms.DialogResult.Retry)
            {
                dialogRes = RenderLoop();
            }

            #if MANAGED_D3D
            try
            {
                if (video != null)
                {
                    lock (video)
                    {
                        video.Stop();
                        video.Dispose();
                    }
                }

                if (d3ddevice != null)
                {
                    lock (d3ddevice)
                    {
                        d3ddevice.Dispose();
                        d3ddevice = null;
                    }
                }
            }
            catch
            {
            }
            #endif

            if (device != null)
            {
                device.Dispose();
                device = null;
            }
        }