示例#1
0
        public override void InitializeProperties()
        {
            this.EnabledWhenPaused.Value = true;
            this.Add(new NotifyBinding(delegate() { this.needResize = true; }, this.main.ScreenSize));
            this.Add(new Binding<bool>(this.EnableReflection, ((GameMain)this.main).Settings.EnableReflections));

            Action removeFluid = delegate()
            {
                if (this.fluid.Space != null)
                    this.main.Space.Remove(this.fluid);
            };

            Action addFluid = delegate()
            {
                if (this.fluid.Space == null && this.Enabled && !this.Suspended)
                    this.main.Space.Add(this.fluid);
            };

            this.Add(new CommandBinding(this.OnSuspended, removeFluid));
            this.Add(new CommandBinding(this.OnDisabled, removeFluid));
            this.Add(new CommandBinding(this.OnResumed, addFluid));
            this.Add(new CommandBinding(this.OnEnabled, addFluid));

            this.DrawOrder = new Property<int> { Editable = false, Value = 10 };

            this.camera = new Camera();
            this.main.AddComponent(this.camera);
            this.parameters = new RenderParameters
            {
                Camera = this.camera,
                Technique = Technique.Clip,
                ReverseCullOrder = true,
            };

            this.Color.Set = delegate(Vector3 value)
            {
                this.Color.InternalValue = value;
                this.effect.Parameters["Color"].SetValue(value);
            };

            this.UnderwaterColor.Set = delegate(Vector3 value)
            {
                this.UnderwaterColor.InternalValue = value;
                this.effect.Parameters["UnderwaterColor"].SetValue(value);
            };

            this.Fresnel.Set = delegate(float value)
            {
                this.Fresnel.InternalValue = value;
                this.effect.Parameters["Fresnel"].SetValue(value);
            };

            this.Speed.Set = delegate(float value)
            {
                this.Speed.InternalValue = value;
                this.effect.Parameters["Speed"].SetValue(value);
            };

            this.RippleDensity.Set = delegate(float value)
            {
                this.RippleDensity.InternalValue = value;
                this.effect.Parameters["RippleDensity"].SetValue(value);
            };

            this.Distortion.Set = delegate(float value)
            {
                this.Distortion.InternalValue = value;
                this.effect.Parameters["Distortion"].SetValue(value);
            };

            this.Brightness.Set = delegate(float value)
            {
                this.Brightness.InternalValue = value;
                this.effect.Parameters["Brightness"].SetValue(value);
            };

            this.Clearness.Set = delegate(float value)
            {
                this.Clearness.InternalValue = value;
                this.effect.Parameters["Clearness"].SetValue(value);
            };

            List<Vector3[]> tris = new List<Vector3[]>();
            const float basinWidth = 2500.0f;
            const float basinLength = 2500.0f;
            float waterHeight = this.Position.Value.Y;

            tris.Add(new[]
            {
                new Vector3(-basinWidth / 2, waterHeight, -basinLength / 2), new Vector3(basinWidth / 2, waterHeight, -basinLength / 2),
                new Vector3(-basinWidth / 2, waterHeight, basinLength / 2)
            });
            tris.Add(new[]
            {
                new Vector3(-basinWidth / 2, waterHeight, basinLength / 2), new Vector3(basinWidth / 2, waterHeight, -basinLength / 2),
                new Vector3(basinWidth / 2, waterHeight, basinLength / 2)
            });

            this.fluid = new Util.CustomFluidVolume(Vector3.Up, this.main.Space.ForceUpdater.Gravity.Y, tris, 1000.0f, 1.25f, 0.997f, 0.2f, this.main.Space.BroadPhase.QueryAccelerator, this.main.Space.ThreadManager);
            this.main.Space.Add(this.fluid);

            instances.Add(this);
        }
示例#2
0
文件: Main.cs 项目: kleril/Lemma
		public Main(int monitor)
		{
#endif
			Factory<Main>.Initialize();
			Voxel.States.Init();
			Editor.SetupDefaultEditorComponents();

#if STEAMWORKS
			if (!SteamWorker.Init())
				Log.d("Failed to initialize Steamworks.");
#if VR
			if (SteamWorker.Initialized && Steamworks.SteamUtils.IsSteamRunningInVR())
				this.VR = vr = true;
#endif
#endif

#if VR
			if (this.VR)
			{
				if (!Ovr.Hmd.Initialize(new Ovr.InitParams()))
					throw new Exception("Failed to initialize Oculus runtime.");
				this.VRHmd = new Ovr.Hmd(0);
				if (this.VRHmd == null)
				{
					Log.d("Error: no Oculus found.");
					this.VR = false;
					this.oculusNotFound = true;
				}
				else
				{
					if (!this.VRHmd.ConfigureTracking(
						(uint)Ovr.TrackingCaps.Orientation
						| (uint)Ovr.TrackingCaps.MagYawCorrection
						| (uint)Ovr.TrackingCaps.Position, 0))
						throw new Exception("Failed to configure head tracking.");
					this.vrHmdDesc = this.VRHmd.GetDesc();
					this.vrLeftFov = this.vrHmdDesc.MaxEyeFov[0];
					this.vrRightFov = this.vrHmdDesc.MaxEyeFov[1];
					Ovr.FovPort maxFov = new Ovr.FovPort();
					maxFov.UpTan = Math.Max(this.vrLeftFov.UpTan, this.vrRightFov.UpTan);
					maxFov.DownTan = Math.Max(this.vrLeftFov.DownTan, this.vrRightFov.DownTan);
					maxFov.LeftTan = Math.Max(this.vrLeftFov.LeftTan, this.vrRightFov.LeftTan);
					maxFov.RightTan = Math.Max(this.vrLeftFov.RightTan, this.vrRightFov.RightTan);
					float combinedTanHalfFovHorizontal = Math.Max(maxFov.LeftTan, maxFov.RightTan);
					float combinedTanHalfFovVertical = Math.Max(maxFov.UpTan, maxFov.DownTan);
					this.vrLeftEyeRenderDesc = this.VRHmd.GetRenderDesc(Ovr.Eye.Left, this.vrLeftFov);
					this.vrRightEyeRenderDesc = this.VRHmd.GetRenderDesc(Ovr.Eye.Right, this.vrRightFov);
				}
			}
#endif

			this.Space = new Space();
			this.Space.TimeStepSettings.TimeStepDuration = 1.0f / (float)maxPhysicsFramerate;
			this.ScreenSize.Value = new Point(this.Window.ClientBounds.Width, this.Window.ClientBounds.Height);

			// Give the space some threads to work with.
			// Just throw a thread at every processor. The thread scheduler will take care of where to put them.
			for (int i = 0; i < Environment.ProcessorCount - 1; i++)
				this.Space.ThreadManager.AddThread();
			this.Space.ForceUpdater.Gravity = new Vector3(0, -18.0f, 0);

			this.IsFixedTimeStep = false;

			this.Window.AllowUserResizing = true;
			this.Window.ClientSizeChanged += new EventHandler<EventArgs>(delegate(object obj, EventArgs e)
			{
				if (!this.Settings.Fullscreen)
				{
					Rectangle bounds = this.Window.ClientBounds;
					this.ScreenSize.Value = new Point(bounds.Width, bounds.Height);
					this.resize = new Point(bounds.Width, bounds.Height);
				}
			});

			this.Graphics = new GraphicsDeviceManager(this);

			this.Content = new ContentManager(this.Services);
			this.Content.RootDirectory = "Content";

			this.Entities = new ListProperty<Entity>();

			this.Camera = new Camera();
			this.AddComponent(this.Camera);

			Lemma.Console.Console.AddConVar(new ConVar("player_speed", "Player speed.", s =>
			{
				Entity playerData = PlayerDataFactory.Instance;
				if (playerData != null)
					playerData.Get<PlayerData>().MaxSpeed.Value = (float)Lemma.Console.Console.GetConVar("player_speed").GetCastedValue();
			}, "10") { TypeConstraint = typeof(float), Validate = o => (float)o > 0 && (float)o < 200 });

			Lemma.Console.Console.AddConCommand(new ConCommand("help", "List all commands or get info about a specific command.",
			delegate(ConCommand.ArgCollection args)
			{
				string cmd = (string)args.Get("command");
				if (string.IsNullOrEmpty(cmd))
					Lemma.Console.Console.Instance.ListAllConsoleStuff();
				else
					Lemma.Console.Console.Instance.PrintConCommandDescription(cmd);
			},
			new ConCommand.CommandArgument() { Name = "command", Optional = true }));

			Lemma.Console.Console.AddConVar(new ConVar("time_scale", "Time scale (percentage).", s =>
			{
				float result;
				if (float.TryParse(s, out result))
					this.BaseTimeMultiplier.Value = result / 100.0f;
			}, "100") { TypeConstraint = typeof(int), Validate = o => (int)o > 0 && (int)o <= 400 });

			Lemma.Console.Console.AddConCommand(new ConCommand
			(
				"load", "Load a map.", collection =>
				{
					ConsoleUI.Showing.Value = false;
					this.Menu.Toggle();
					IO.MapLoader.Transition(this, collection.ParsedArgs[0].StrValue);
				},
				new ConCommand.CommandArgument { Name = "map", CommandType = typeof(string), Optional = false }
			));

			Lemma.Console.Console.AddConVar(new ConVar("blocks", "Player block cheat (white, yellow, blue)", s =>
			{
				Entity player = PlayerFactory.Instance;
				if (player != null && player.Active)
				{
					Voxel.t result = Voxel.t.Empty;
					switch (s.ToLower())
					{
						case "white":
							result = Voxel.t.WhitePermanent;
							break;
						case "yellow":
							result = Voxel.t.GlowYellow;
							break;
						case "blue":
							result = Voxel.t.GlowBlue;
							break;
						default:
							break;
					}
					BlockCloud cloud = player.Get<BlockCloud>();
					cloud.Blocks.Clear();
					cloud.Type.Value = result;
				}
			}, "none"));

			Lemma.Console.Console.AddConCommand(new ConCommand("moves", "Enable all parkour moves.", delegate(ConCommand.ArgCollection args)
			{
				if (PlayerDataFactory.Instance != null)
				{
					PlayerData playerData = PlayerDataFactory.Instance.Get<PlayerData>();
					playerData.EnableRoll.Value = true;
					playerData.EnableKick.Value = true;
					playerData.EnableWallRun.Value = true;
					playerData.EnableWallRunHorizontal.Value = true;
					playerData.EnableMoves.Value = true;
					playerData.EnableCrouch.Value = true;
					playerData.EnableSlowMotion.Value = true;
				}
			}));

#if DEVELOPMENT
			Lemma.Console.Console.AddConCommand(new ConCommand("diavar", "Set a dialogue variable.", delegate(ConCommand.ArgCollection args)
			{
				if (args.ParsedArgs.Length == 2)
				{
					if (PlayerDataFactory.Instance != null)
					{
						Phone phone = PlayerDataFactory.Instance.Get<Phone>();
						phone[args.ParsedArgs[0].StrValue] = args.ParsedArgs[1].StrValue;
					}
				}
			},
			new ConCommand.CommandArgument { Name = "variable", CommandType = typeof(string), Optional = false, },
			new ConCommand.CommandArgument { Name = "value", CommandType = typeof(string), Optional = false }
			));
#endif

			Lemma.Console.Console.AddConCommand(new ConCommand("specials", "Enable all special abilities.", delegate(ConCommand.ArgCollection args)
			{
				if (PlayerDataFactory.Instance != null)
				{
					PlayerData playerData = PlayerDataFactory.Instance.Get<PlayerData>();
					playerData.EnableEnhancedWallRun.Value = true;
				}
			}));

			new SetBinding<float>(this.PauseAudioEffect, delegate(float value)
			{
				AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.PAUSE_PARAMETER, MathHelper.Clamp(value, 0.0f, 1.0f));
			});

			new CommandBinding(this.MapLoaded, delegate()
			{
				this.mapLoaded = true;
			});

#if DEVELOPMENT
			this.EditorEnabled.Value = true;
#else
			this.EditorEnabled.Value = false;
#endif

			if (!Directory.Exists(Main.DataDirectory))
				Directory.CreateDirectory(Main.DataDirectory);
			this.settingsFile = Path.Combine(Main.DataDirectory, "settings.json");
			this.SaveDirectory = Path.Combine(Main.DataDirectory, "saves");
			if (!Directory.Exists(this.SaveDirectory))
				Directory.CreateDirectory(this.SaveDirectory);
			this.analyticsDirectory = Path.Combine(Main.DataDirectory, "analytics");
			if (!Directory.Exists(this.analyticsDirectory))
				Directory.CreateDirectory(this.analyticsDirectory);
			this.CustomMapDirectory = Path.Combine(Main.DataDirectory, "maps");
			if (!Directory.Exists(this.CustomMapDirectory))
				Directory.CreateDirectory(this.CustomMapDirectory);
			this.MapDirectory = Path.Combine(this.Content.RootDirectory, IO.MapLoader.MapDirectory);

			this.timesFile = Path.Combine(Main.DataDirectory, "times.dat");
			try
			{
				using (Stream fs = new FileStream(this.timesFile, FileMode.Open, FileAccess.Read, FileShare.None))
				using (Stream stream = new GZipInputStream(fs))
				using (StreamReader reader = new StreamReader(stream))
					this.times = JsonConvert.DeserializeObject<Dictionary<string, float>>(reader.ReadToEnd());
			}
			catch (Exception)
			{
			}

			if (this.times == null)
				this.times = new Dictionary<string, float>();

			try
			{
				// Attempt to load previous window state
				this.Settings = JsonConvert.DeserializeObject<Config>(File.ReadAllText(this.settingsFile));
				if (this.Settings.Version != Main.ConfigVersion)
					throw new Exception();
			}
			catch (Exception) // File doesn't exist, there was a deserialization error, or we are on a new version. Use default window settings
			{
				this.Settings = new Config();
			}

			if (string.IsNullOrEmpty(this.Settings.UUID))
				this.Settings.UUID = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 32);
			this.Settings.MinimizeCameraMovementVR.Value |= this.Settings.MinimizeCameraMovement;
			this.MinimizeCameraMovement = this.VR ? this.Settings.MinimizeCameraMovementVR : this.Settings.MinimizeCameraMovement;
			this.Settings.GodModeProperty.Value = this.Settings.GodMode;
			this.Settings.LevelIndexProperty.Value = this.Settings.LevelIndex;
			new NotifyBinding(delegate() { this.Settings.GodMode = this.Settings.GodModeProperty; }, this.Settings.GodModeProperty);
			new NotifyBinding(delegate() { this.Settings.LevelIndex = this.Settings.LevelIndexProperty; }, this.Settings.LevelIndexProperty);
			
			TextElement.BindableProperties.Add("Forward", this.Settings.Forward);
			TextElement.BindableProperties.Add("Left", this.Settings.Left);
			TextElement.BindableProperties.Add("Backward", this.Settings.Backward);
			TextElement.BindableProperties.Add("Right", this.Settings.Right);
			TextElement.BindableProperties.Add("Jump", this.Settings.Jump);
			TextElement.BindableProperties.Add("Parkour", this.Settings.Parkour);
			TextElement.BindableProperties.Add("RollKick", this.Settings.RollKick);
			TextElement.BindableProperties.Add("TogglePhone", this.Settings.TogglePhone);
			TextElement.BindableProperties.Add("QuickSave", this.Settings.QuickSave);
			TextElement.BindableProperties.Add("ToggleFullscreen", this.Settings.ToggleFullscreen);
			TextElement.BindableProperties.Add("RecenterVRPose", this.Settings.RecenterVRPose);
			TextElement.BindableProperties.Add("ToggleConsole", this.Settings.ToggleConsole);

			new NotifyBinding
			(
				this.updateTimesteps,
				this.BaseTimeMultiplier, this.TimeMultiplier, this.Settings.FPSLimit
			);
			this.updateTimesteps();

			if (this.Settings.FullscreenResolution.Value.X == 0)
				this.Settings.FullscreenResolution.Value = new Point(this.nativeDisplayMode.Width, this.nativeDisplayMode.Height);

			// Have to create the menu here so it can catch the PreparingDeviceSettings event
			// We call AddComponent(this.Menu) later on in LoadContent.
			this.Menu = new Menu();
			this.Graphics.PreparingDeviceSettings += delegate(object sender, PreparingDeviceSettingsEventArgs args)
			{
				args.GraphicsDeviceInformation.Adapter = GraphicsAdapter.Adapters[this.monitor];

				args.GraphicsDeviceInformation.PresentationParameters.PresentationInterval = PresentInterval.Immediate;

				List<DisplayMode> supportedDisplayModes = args.GraphicsDeviceInformation.Adapter.SupportedDisplayModes.Where(x => x.Width <= 4096 && x.Height <= 4096).ToList();
				int displayModeIndex = 0;
				foreach (DisplayMode mode in supportedDisplayModes)
				{
					if (mode.Format == SurfaceFormat.Color && mode.Width == this.Settings.FullscreenResolution.Value.X && mode.Height == this.Settings.FullscreenResolution.Value.Y)
						break;
					displayModeIndex++;
				}
				this.Menu.SetupDisplayModes(supportedDisplayModes, displayModeIndex);
			};

			this.Screenshot = new Screenshot();
			this.AddComponent(this.Screenshot);

			this.Graphics.SynchronizeWithVerticalRetrace = this.Settings.Vsync;
			new NotifyBinding(delegate()
			{
				this.Graphics.SynchronizeWithVerticalRetrace = this.Settings.Vsync;
				if (this.Settings.Fullscreen)
					this.Graphics.ApplyChanges();
			}, this.Settings.Vsync);

#if VR
			if (this.VR)
				this.ResizeViewport(this.nativeDisplayMode.Width, this.nativeDisplayMode.Height, true, false, false);
			else
#endif
			if (this.Settings.Fullscreen)
				this.ResizeViewport(this.Settings.FullscreenResolution.Value.X, this.Settings.FullscreenResolution.Value.Y, true, this.Settings.Borderless, false);
			else
				this.ResizeViewport(this.Settings.Size.Value.X, this.Settings.Size.Value.Y, false, this.Settings.Borderless, false);
		}
示例#3
0
文件: Main.cs 项目: kleril/Lemma
		protected override void LoadContent()
		{
			this.MapContent = new ContentManager(this.Services);
			this.MapContent.RootDirectory = this.Content.RootDirectory;

			GeeUIMain.Font = this.Content.Load<SpriteFont>(this.Font);

			if (this.firstLoadContentCall)
			{
				this.firstLoadContentCall = false;

				if (!Directory.Exists(this.MapDirectory))
					Directory.CreateDirectory(this.MapDirectory);
				string challengeDirectory = Path.Combine(this.MapDirectory, "Challenge");
				if (!Directory.Exists(challengeDirectory))
					Directory.CreateDirectory(challengeDirectory);

#if VR
				if (this.VR)
				{
					this.vrLeftMesh.Load(this, Ovr.Eye.Left, this.vrLeftFov);
					this.vrRightMesh.Load(this, Ovr.Eye.Right, this.vrRightFov);
					new CommandBinding(this.ReloadedContent, (Action)this.vrLeftMesh.Reload);
					new CommandBinding(this.ReloadedContent, (Action)this.vrRightMesh.Reload);
					this.reallocateVrTargets();

					this.vrCamera = new Camera();
					this.AddComponent(this.vrCamera);
				}
#endif

				this.GraphicsDevice.PresentationParameters.PresentationInterval = PresentInterval.Immediate;
				this.GeeUI = new GeeUIMain();
				this.AddComponent(GeeUI);

				this.ConsoleUI = new ConsoleUI();
				this.AddComponent(ConsoleUI);

				this.Console = new Console.Console();
				this.AddComponent(Console);

				Lemma.Console.Console.BindType(null, this);
				Lemma.Console.Console.BindType(null, Console);

				// Initialize Wwise
				AkGlobalSoundEngineInitializer initializer = new AkGlobalSoundEngineInitializer(Path.Combine(this.Content.RootDirectory, "Wwise"));
				this.AddComponent(initializer);

				this.Listener = new AkListener();
				this.Listener.Add(new Binding<Vector3>(this.Listener.Position, this.Camera.Position));
				this.Listener.Add(new Binding<Vector3>(this.Listener.Forward, this.Camera.Forward));
				this.Listener.Add(new Binding<Vector3>(this.Listener.Up, this.Camera.Up));
				this.AddComponent(this.Listener);

				// Create the renderer.
				this.LightingManager = new LightingManager();
				this.AddComponent(this.LightingManager);
				this.Renderer = new Renderer(this, true, true, true, true, true);

				this.AddComponent(this.Renderer);
				this.Renderer.ReallocateBuffers(this.ScreenSize);

				this.renderParameters = new RenderParameters
				{
					Camera = this.Camera,
					IsMainRender = true
				};

				// Load strings
				this.Strings.Load(Path.Combine(this.Content.RootDirectory, "Strings.xlsx"));

				this.UI = new UIRenderer();
				this.UI.GeeUI = this.GeeUI;
				this.AddComponent(this.UI);

				PCInput input = new PCInput();
				this.AddComponent(input);

				Lemma.Console.Console.BindType(null, input);
				Lemma.Console.Console.BindType(null, UI);
				Lemma.Console.Console.BindType(null, Renderer);
				Lemma.Console.Console.BindType(null, LightingManager);

				input.Add(new CommandBinding(input.GetChord(new PCInput.Chord { Modifier = Keys.LeftAlt, Key = Keys.S }), delegate()
				{
					// High-resolution screenshot
					bool originalModelsVisible = Editor.EditorModelsVisible;
					Editor.EditorModelsVisible.Value = false;
					Screenshot s = new Screenshot();
					this.AddComponent(s);
					s.Take(new Point(4096, 2304), delegate()
					{
						string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
						string path;
						int i = 0;
						do
						{
							path = Path.Combine(desktop, string.Format("lemma-screen{0}.png", i));
							i++;
						}
						while (File.Exists(path));

						Screenshot.SavePng(s.Buffer, path);

						Editor.EditorModelsVisible.Value = originalModelsVisible;

						s.Delete.Execute();
					});
				}));

				this.performanceMonitor = new ListContainer();
				this.performanceMonitor.Add(new Binding<Vector2, Point>(performanceMonitor.Position, x => new Vector2(x.X, 0), this.ScreenSize));
				this.performanceMonitor.AnchorPoint.Value = new Vector2(1, 0);
				this.performanceMonitor.Visible.Value = false;
				this.performanceMonitor.Name.Value = "PerformanceMonitor";
				this.UI.Root.Children.Add(this.performanceMonitor);

				Action<string, Property<double>> addTimer = delegate(string label, Property<double> property)
				{
					TextElement text = new TextElement();
					text.FontFile.Value = this.Font;
					text.Add(new Binding<string, double>(text.Text, x => label + ": " + (x * 1000.0).ToString("F") + "ms", property));
					this.performanceMonitor.Children.Add(text);
				};

				Action<string, Property<int>> addCounter = delegate(string label, Property<int> property)
				{
					TextElement text = new TextElement();
					text.FontFile.Value = this.Font;
					text.Add(new Binding<string, int>(text.Text, x => label + ": " + x.ToString(), property));
					this.performanceMonitor.Children.Add(text);
				};

				TextElement frameRateText = new TextElement();
				frameRateText.FontFile.Value = this.Font;
				frameRateText.Add(new Binding<string, float>(frameRateText.Text, x => "FPS: " + x.ToString("0"), this.frameRate));
				this.performanceMonitor.Children.Add(frameRateText);

				addTimer("Physics", this.physicsTime);
				addTimer("Update", this.updateTime);
				addTimer("Render", this.renderTime);
				addCounter("Draw calls", this.drawCalls);
				addCounter("Triangles", this.triangles);
				addCounter("Working set", this.workingSet);

				Lemma.Console.Console.AddConCommand(new ConCommand("perf", "Toggle the performance monitor", delegate(ConCommand.ArgCollection args)
				{
					this.performanceMonitor.Visible.Value = !this.performanceMonitor.Visible;
				}));

				try
				{
					IEnumerable<string> globalStaticScripts = Directory.GetFiles(Path.Combine(this.Content.RootDirectory, "GlobalStaticScripts"), "*", SearchOption.AllDirectories).Select(x => Path.Combine("..\\GlobalStaticScripts", Path.GetFileNameWithoutExtension(x)));
					foreach (string scriptName in globalStaticScripts)
						this.executeStaticScript(scriptName);
				}
				catch (IOException)
				{

				}

				this.UIFactory = new UIFactory();
				this.AddComponent(this.UIFactory);
				this.AddComponent(this.Menu); // Have to do this here so the menu's Awake can use all our loaded stuff

				this.Spawner = new Spawner();
				this.AddComponent(this.Spawner);

				this.UI.IsMouseVisible.Value = true;

				AKRESULT akresult = AkBankLoader.LoadBank("SFX_Bank_01.bnk");
				if (akresult != AKRESULT.AK_Success)
					Log.d(string.Format("Failed to load main sound bank: {0}", akresult));

#if ANALYTICS
				this.SessionRecorder = new Session.Recorder(this);

				this.SessionRecorder.Add("Position", delegate()
				{
					Entity p = PlayerFactory.Instance;
					if (p != null && p.Active)
						return p.Get<Transform>().Position;
					else
						return Vector3.Zero;
				});

				this.SessionRecorder.Add("Health", delegate()
				{
					Entity p = PlayerFactory.Instance;
					if (p != null && p.Active)
						return p.Get<Player>().Health;
					else
						return 0.0f;
				});

				this.SessionRecorder.Add("Framerate", delegate()
				{
					return this.frameRate;
				});

				this.SessionRecorder.Add("WorkingSet", delegate()
				{
					return this.workingSet;
				});
				this.AddComponent(this.SessionRecorder);
				this.SessionRecorder.Add(new Binding<bool, Config.RecordAnalytics>(this.SessionRecorder.EnableUpload, x => x == Config.RecordAnalytics.On, this.Settings.Analytics));
#endif

				this.DefaultLighting();

				new SetBinding<float>(this.Settings.SoundEffectVolume, delegate(float value)
				{
					AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.VOLUME_SFX, MathHelper.Clamp(value, 0.0f, 1.0f));
				});

				new SetBinding<float>(this.Settings.MusicVolume, delegate(float value)
				{
					AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.VOLUME_MUSIC, MathHelper.Clamp(value, 0.0f, 1.0f));
				});

				new TwoWayBinding<LightingManager.DynamicShadowSetting>(this.Settings.DynamicShadows, this.LightingManager.DynamicShadows);
				new TwoWayBinding<float>(this.Settings.MotionBlurAmount, this.Renderer.MotionBlurAmount);
				new TwoWayBinding<float>(this.Settings.Gamma, this.Renderer.Gamma);
				new TwoWayBinding<bool>(this.Settings.Bloom, this.Renderer.EnableBloom);
				new TwoWayBinding<bool>(this.Settings.SSAO, this.Renderer.EnableSSAO);
				new Binding<float>(this.Camera.FieldOfView, this.Settings.FieldOfView);

				foreach (string file in Directory.GetFiles(this.MapDirectory, "*.xlsx", SearchOption.TopDirectoryOnly))
					this.Strings.Load(file);

				new Binding<string, Config.Lang>(this.Strings.Language, x => x.ToString(), this.Settings.Language);
				new NotifyBinding(this.SaveSettings, this.Settings.Language);

				new CommandBinding(this.MapLoaded, delegate()
				{
					this.Renderer.BlurAmount.Value = 0.0f;
					this.Renderer.Tint.Value = new Vector3(1.0f);
				});

#if VR
				if (this.VR)
				{
					Action loadVrEffect = delegate()
					{
						this.vrEffect = this.Content.Load<Effect>("Effects\\Oculus");
					};
					loadVrEffect();
					new CommandBinding(this.ReloadedContent, loadVrEffect);

					this.UI.Add(new Binding<Point>(this.UI.RenderTargetSize, this.ScreenSize));

					this.VRUI = new Lemma.Components.ModelNonPostProcessed();
					this.VRUI.MapContent = false;
					this.VRUI.DrawOrder.Value = 100000; // On top of everything
					this.VRUI.Filename.Value = "Models\\plane";
					this.VRUI.EffectFile.Value = "Effects\\VirtualUI";
					this.VRUI.Add(new Binding<Microsoft.Xna.Framework.Graphics.RenderTarget2D>(this.VRUI.GetRenderTarget2DParameter("Diffuse" + Lemma.Components.Model.SamplerPostfix), this.UI.RenderTarget));
					this.VRUI.Add(new Binding<Matrix>(this.VRUI.Transform, delegate()
					{
						Matrix rot = this.Camera.RotationMatrix;
						Matrix mat = Matrix.Identity;
						mat.Forward = rot.Right;
						mat.Right = rot.Forward;
						mat.Up = rot.Up;
						mat *= Matrix.CreateScale(7);
						mat.Translation = this.Camera.Position + rot.Forward * 4.0f;
						return mat;
					}, this.Camera.Position, this.Camera.RotationMatrix));
					this.AddComponent(this.VRUI);

					this.UI.Setup3D(this.VRUI.Transform);
				}
#endif

#if ANALYTICS
				bool editorLastEnabled = this.EditorEnabled;
				new CommandBinding<string>(this.LoadingMap, delegate(string newMap)
				{
					if (this.MapFile.Value != null && !editorLastEnabled)
					{
						this.SessionRecorder.RecordEvent("ChangedMap", newMap);
						if (!this.IsChallengeMap(this.MapFile) && this.MapFile.Value != Main.MenuMap)
							this.SaveAnalytics();
					}
					this.SessionRecorder.Reset();
					editorLastEnabled = this.EditorEnabled;
				});
#endif
				new CommandBinding<string>(this.LoadingMap, delegate(string newMap)
				{
					this.CancelScheduledSave();
				});

#if !DEVELOPMENT
				IO.MapLoader.Load(this, MenuMap);
				this.Menu.Show(initial: true);
#endif

#if ANALYTICS
				if (this.Settings.Analytics.Value == Config.RecordAnalytics.Ask)
				{
					this.Menu.ShowDialog("\\analytics prompt", "\\enable analytics", delegate()
					{
						this.Settings.Analytics.Value = Config.RecordAnalytics.On;
					},
					"\\disable analytics", delegate()
					{
						this.Settings.Analytics.Value = Config.RecordAnalytics.Off;
					});
				}
#endif

#if VR
				if (this.oculusNotFound)
					this.Menu.HideMessage(null, this.Menu.ShowMessage(null, "Error: no Oculus found."), 6.0f);

				if (this.VR)
				{
					this.Menu.EnableInput(false);
					Container vrMsg = this.Menu.BuildMessage("\\vr message", 300.0f);
					vrMsg.AnchorPoint.Value = new Vector2(0.5f, 0.5f);
					vrMsg.Add(new Binding<Vector2, Point>(vrMsg.Position, x => new Vector2(x.X * 0.5f, x.Y * 0.5f), this.ScreenSize));
					this.UI.Root.Children.Add(vrMsg);
					input.Bind(this.Settings.RecenterVRPose, PCInput.InputState.Down, this.VRHmd.RecenterPose);
					input.Bind(this.Settings.RecenterVRPose, PCInput.InputState.Down, delegate()
					{
						if (vrMsg != null)
						{
							vrMsg.Delete.Execute();
							vrMsg = null;
						}
						this.Menu.EnableInput(true);
					});
				}
				else
#endif
				{
					input.Bind(this.Settings.ToggleFullscreen, PCInput.InputState.Down, delegate()
					{
						if (this.Settings.Fullscreen) // Already fullscreen. Go to windowed mode.
							this.ExitFullscreen();
						else // In windowed mode. Go to fullscreen.
							this.EnterFullscreen();
					});
				}

				input.Bind(this.Settings.QuickSave, PCInput.InputState.Down, delegate()
				{
					this.SaveWithNotification(true);
				});
			}
			else
			{
				this.ReloadingContent.Execute();
				foreach (IGraphicsComponent c in this.graphicsComponents)
					c.LoadContent(true);
				this.ReloadedContent.Execute();
			}

			this.GraphicsDevice.RasterizerState = new RasterizerState { MultiSampleAntiAlias = false };

			if (this.spriteBatch != null)
				this.spriteBatch.Dispose();
			this.spriteBatch = new SpriteBatch(this.GraphicsDevice);
		}
示例#4
0
文件: Main.cs 项目: kleril/Lemma
		protected override void Draw(GameTime gameTime)
		{
			if (this.GraphicsDevice == null || this.GraphicsDevice.IsDisposed || this.GraphicsDevice.GraphicsDeviceStatus != GraphicsDeviceStatus.Normal)
				return;

			Lemma.Components.Model.DrawCallCounter = 0;
			Lemma.Components.Model.TriangleCounter = 0;

			this.renderParameters.Technique = Technique.Render;

			this.timer.Restart();

#if VR
			Ovr.FrameTiming frameTiming = new Ovr.FrameTiming();
			if (this.VR)
			{
				frameTiming = this.VRHmd.BeginFrameTiming(0);

				Camera originalCamera = this.renderParameters.Camera;
				this.vrCamera.SetFromCamera(originalCamera);
				this.vrCamera.ProjectionType.Value = Camera.ProjectionMode.Custom;
				this.renderParameters.Camera = this.vrCamera;

				Ovr.Posef[] eyes = this.VRHmd.GetEyePoses(0);

				// Position limitation
				{
					Vector3 left = new Vector3(eyes[0].Position.x, eyes[0].Position.y, eyes[0].Position.z);
					Vector3 right = new Vector3(eyes[1].Position.x, eyes[1].Position.y, eyes[1].Position.z);
					Vector3 target = new Vector3(0, 0.0f / VRUnitToWorldUnit, -0.25f / VRUnitToWorldUnit);
					Vector3 targetToEyes = ((left + right) * 0.5f) - target;
					float distance = targetToEyes.Length();
					const float limit = 0.5f / VRUnitToWorldUnit;
					if (distance > limit)
					{
						Vector3 correction = targetToEyes * ((limit / distance) - 1.0f);
						left += correction;
						right += correction;
						eyes[0].Position.x = left.X;
						eyes[0].Position.y = left.Y;
						eyes[0].Position.z = left.Z;
						eyes[1].Position.x = right.X;
						eyes[1].Position.y = right.Y;
						eyes[1].Position.z = right.Z;
					}
				}

				if (this.vrHmdDesc.EyeRenderOrder[0] == Ovr.Eye.Left)
				{
					this.drawEye(originalCamera, gameTime, eyes[0], this.vrLeftEyeTarget, true);
					this.drawEye(originalCamera, gameTime, eyes[1], this.vrRightEyeTarget, false);
				}
				else
				{
					this.drawEye(originalCamera, gameTime, eyes[1], this.vrRightEyeTarget, true);
					this.drawEye(originalCamera, gameTime, eyes[0], this.vrLeftEyeTarget, false);
				}

				this.GraphicsDevice.SetRenderTarget(this.RenderTarget);
				this.GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.Black);

				/*
				this.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
				this.spriteBatch.Draw(this.vrLeftEyeTarget, Vector2.Zero, Color.White);
				this.spriteBatch.Draw(this.vrRightEyeTarget, new Vector2(this.vrLeftEyeTarget.Width, 0), Color.White);
				this.spriteBatch.End();
				*/
				Ovr.Hmd.WaitTillTime(frameTiming.TimewarpPointSeconds);

				this.vrLeftMesh.Render(this.vrLeftEyeTarget, eyes[0], this.vrEffect);
				this.vrRightMesh.Render(this.vrRightEyeTarget, eyes[1], this.vrEffect);

				// Update view projection matrix
				this.VRLastViewProjection.Value = this.vrCamera.ViewProjection;

				this.renderParameters.Camera = originalCamera;
			}
			else
#endif
			{
				for (int i = 0; i < this.preframeDrawables.Count; i++)
				{
					IDrawablePreFrameComponent c = this.preframeDrawables[i];
					if (this.componentEnabled(c))
						c.DrawPreFrame(gameTime, this.renderParameters);
				}

				this.Renderer.SetRenderTargets(this.renderParameters);

				this.DrawScene(this.renderParameters);

				this.LightingManager.UpdateGlobalLights();
				this.LightingManager.RenderShadowMaps(this.Camera);

				this.Renderer.PostProcess(this.RenderTarget, this.renderParameters);

				for (int i = 0; i < this.nonPostProcessedDrawables.Count; i++)
				{
					INonPostProcessedDrawableComponent c = this.nonPostProcessedDrawables[i];
					if (this.componentEnabled(c))
						c.DrawNonPostProcessed(gameTime, this.renderParameters);
				}
			}

			this.drawCallCounter = Math.Max(this.drawCallCounter, Lemma.Components.Model.DrawCallCounter);
			this.triangleCounter = Math.Max(this.triangleCounter, Lemma.Components.Model.TriangleCounter);

			if (this.RenderTarget != null)
			{
				// We just rendered to a target other than the screen.
				// So make it so we're rendering to the screen again, then copy the render target to the screen.
				this.GraphicsDevice.SetRenderTarget(null);

				if (!this.RenderTarget.IsDisposed)
				{
					this.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
					this.spriteBatch.Draw(this.RenderTarget, Vector2.Zero, Color.White);
					this.spriteBatch.End();
				}
				this.RenderTarget = null;
			}
		}
示例#5
0
文件: Main.cs 项目: kleril/Lemma
		private void drawEye(Camera originalCamera, GameTime gameTime, Ovr.Posef pose, RenderTarget2D renderTarget, bool updateLights)
		{
			Quaternion quat = new Quaternion(pose.Orientation.x, pose.Orientation.y, pose.Orientation.z, pose.Orientation.w);
			this.vrCamera.RotationMatrix.Value = Matrix.CreateFromQuaternion(quat) * originalCamera.RotationMatrix;
			Vector3 viewAdjust = Vector3.TransformNormal(new Vector3(pose.Position.x, pose.Position.y, pose.Position.z), originalCamera.RotationMatrix);
			this.vrCamera.Position.Value = originalCamera.Position.Value + viewAdjust * Main.VRUnitToWorldUnit;
			Ovr.Matrix4f proj = Ovr.Hmd.GetProjection(this.vrLeftFov, originalCamera.NearPlaneDistance, originalCamera.FarPlaneDistance, (uint)Ovr.Hmd.ProjectionModifier.RightHanded);
			this.vrCamera.Projection.Value = Oculus.MatrixOvrToXna(proj);

			for (int i = 0; i < this.preframeDrawables.Count; i++)
			{
				IDrawablePreFrameComponent c = this.preframeDrawables[i];
				if (this.componentEnabled(c))
					c.DrawPreFrame(gameTime, this.renderParameters);
			}

			this.Renderer.SetRenderTargets(this.renderParameters);

			this.DrawScene(this.renderParameters);

			if (updateLights)
			{
				this.LightingManager.UpdateGlobalLights();
				this.LightingManager.RenderShadowMaps(originalCamera);
			}

			this.Renderer.PostProcess(renderTarget, this.renderParameters);

			for (int i = 0; i < this.nonPostProcessedDrawables.Count; i++)
			{
				INonPostProcessedDrawableComponent c = this.nonPostProcessedDrawables[i];
				if (this.componentEnabled(c))
					c.DrawNonPostProcessed(gameTime, this.renderParameters);
			}
		}
示例#6
0
 private static IEnumerable<NonAxisAlignedBoundingBox> getActiveBoundingBoxes(Camera camera, Zone currentZone)
 {
     if (currentZone == null)
     {
         Vector3 pos = camera.Position;
         float radius = camera.FarPlaneDistance;
         return new[] { new NonAxisAlignedBoundingBox { BoundingBox = new BoundingBox(pos - new Vector3(radius), pos + new Vector3(radius)), Transform = Matrix.Identity } };
     }
     else
         return Zone.GetConnectedZones(currentZone).Select(x => new NonAxisAlignedBoundingBox { BoundingBox = x.BoundingBox, Transform = Matrix.Invert(x.Transform) }).ToList();
 }
示例#7
0
文件: Main.cs 项目: kernelbitch/Lemma
        public Main()
        {
            this.Space = new Space();
            this.ScreenSize.Value = new Point(this.Window.ClientBounds.Width, this.Window.ClientBounds.Height);

            // Give the space some threads to work with.
            // Just throw a thread at every processor. The thread scheduler will take care of where to put them.
            for (int i = 0; i < Environment.ProcessorCount; i++)
                this.Space.ThreadManager.AddThread();
            this.Space.ForceUpdater.Gravity = new Vector3(0, -18.0f, 0);

            this.IsFixedTimeStep = false;
            //this.IsFixedTimeStep = true;
            //this.TargetElapsedTime = new TimeSpan((long)((1.0f / 30.0f) * (float)TimeSpan.TicksPerSecond));

            this.Window.AllowUserResizing = true;
            this.Window.ClientSizeChanged += new EventHandler<EventArgs>(delegate(object obj, EventArgs e)
            {
                if (!this.graphics.IsFullScreen)
                {
                    Rectangle bounds = this.Window.ClientBounds;
                    this.ScreenSize.Value = new Point(bounds.Width, bounds.Height);
                    this.resize = new Point(bounds.Width, bounds.Height);
                }
            });

            this.graphics = new GraphicsDeviceManager(this);
            this.graphics.SynchronizeWithVerticalRetrace = false;

            this.Content = new ContentManager(this.Services);
            this.Content.RootDirectory = "Content";

            this.Entities = new List<Entity>();

            this.AudioEngine = new AudioEngine("Content\\Sounds\\WinSettings.xgs");
            this.waveBank = new WaveBank(this.AudioEngine, "Content\\Sounds\\Waves.xwb");
            this.musicBank = new WaveBank(this.AudioEngine, "Content\\Sounds\\Music.xwb");
            this.SoundBank = new SoundBank(this.AudioEngine, "Content\\Sounds\\Sounds.xsb");

            this.Camera = new Camera();
            this.Camera.Add(new Binding<Point>(this.Camera.ViewportSize, this.ScreenSize));
            this.AddComponent(this.Camera);

            this.IsMouseVisible.Value = false;
            this.IsMouseVisible.Set = delegate(bool value)
            {
                base.IsMouseVisible = value;
            };
            this.IsMouseVisible.Get = delegate()
            {
                return base.IsMouseVisible;
            };

            this.TimeMultiplier.Set = delegate(float value)
            {
                this.TimeMultiplier.InternalValue = value;
                this.AudioEngine.SetGlobalVariable("TimeShift", (value - 1.0f) * 12.0f);
            };

            new CommandBinding(this.MapLoaded, delegate()
            {
                this.mapLoaded = true;
            });
        }
示例#8
0
文件: Main.cs 项目: sparker/Lemma
		public Main()
		{
			Factory<Main>.Initialize();

#if STEAMWORKS
			SteamWorker.Init();
#endif

			this.Space = new Space();
			this.ScreenSize.Value = new Point(this.Window.ClientBounds.Width, this.Window.ClientBounds.Height);

			// Give the space some threads to work with.
			// Just throw a thread at every processor. The thread scheduler will take care of where to put them.
			for (int i = 0; i < Environment.ProcessorCount - 1; i++)
				this.Space.ThreadManager.AddThread();
			this.Space.ForceUpdater.Gravity = new Vector3(0, -18.0f, 0);

			this.IsFixedTimeStep = false;

			this.Window.AllowUserResizing = true;
			this.Window.ClientSizeChanged += new EventHandler<EventArgs>(delegate(object obj, EventArgs e)
			{
				if (!this.Graphics.IsFullScreen)
				{
					Rectangle bounds = this.Window.ClientBounds;
					this.ScreenSize.Value = new Point(bounds.Width, bounds.Height);
					this.resize = new Point(bounds.Width, bounds.Height);
				}
			});

			this.Graphics = new GraphicsDeviceManager(this);
			this.Graphics.SynchronizeWithVerticalRetrace = false;

			this.Content = new ContentManager(this.Services);
			this.Content.RootDirectory = "Content";

			this.Entities = new List<Entity>();

			this.Camera = new Camera();
			this.AddComponent(this.Camera);

			this.IsMouseVisible.Value = false;
			this.IsMouseVisible.Set = delegate(bool value)
			{
				base.IsMouseVisible = value;
			};
			this.IsMouseVisible.Get = delegate()
			{
				return base.IsMouseVisible;
			};

			this.TimeMultiplier.Set = delegate(float value)
			{
				this.TimeMultiplier.InternalValue = value;
				AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.SLOWMOTION, Math.Min(1.0f, (1.0f - value) / 0.6f));
			};

			new CommandBinding(this.MapLoaded, delegate()
			{
				this.mapLoaded = true;
			});

			Action updateLanguage = delegate()
			{
				Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(this.Strings.Language.Value.ToString());
			};
			new NotifyBinding(updateLanguage, this.Strings.Language);
			updateLanguage();

		}