public static void Initialize(GraphicsDevice device) { // register convar r_hdr_enable = ConVar.Register("r_hdr_enable", true, "Enable high dynamic range rendering.", ConVarFlags.Archived); // create render targets int width = device.PresentationParameters.BackBufferWidth; int height = device.PresentationParameters.BackBufferHeight; _colorRT = new RenderTarget2D(device, width, height, false, SurfaceFormat.Color, DepthFormat.Depth16); _depthRT = new RenderTarget2D(device, width, height, false, SurfaceFormat.Single, DepthFormat.Depth16); _normalRT = new RenderTarget2D(device, width, height, false, SurfaceFormat.Color, DepthFormat.Depth16); _lightRT = new RenderTarget2D(device, width, height, false, (r_hdr_enable.GetValue <bool>()) ? SurfaceFormat.Rgba1010102 : SurfaceFormat.Color, DepthFormat.Depth16); if (r_hdr_enable.GetValue <bool>()) { _hdrRT = new RenderTarget2D(device, width, height, false, SurfaceFormat.Rgba1010102, DepthFormat.None); _hdrBloomRT = new RenderTarget2D(device, width, height, false, SurfaceFormat.Rgba1010102, DepthFormat.None); int sampleEntries = 1; int startSize = Math.Min(width / 16, height / 16); int size = 16; for (size = 16; size < startSize; size *= 4) { sampleEntries++; } _lightDownsampleRTs = new RenderTarget2D[sampleEntries]; size /= 4; for (int i = 0; i < sampleEntries; i++) { _lightDownsampleRTs[i] = new RenderTarget2D(device, size, size, false, SurfaceFormat.Single, DepthFormat.None); size /= 4; } _avgLightRT = new RenderTarget2D(device, 1, 1, false, SurfaceFormat.Single, DepthFormat.None); } // load shaders _baseEffect = EffectManager.Load("BaseDraw", device); _compositeEffect = EffectManager.Load("ScreenComposite", device); _bloomEffect = EffectManager.Load("Bloom", device); _lightnessEffect = EffectManager.Load("Lightness", device); // light renderer LightRenderer.Initialize(device); // shadow renderer ShadowRenderer.Initialize(device); }
private static void RenderShadowOcclusion(GraphicsDevice graphicsDevice, RenderTarget2D depthTexture) { // Set the device to render to our shadow occlusion texture, and to use // the original DepthStencilSurface graphicsDevice.SetRenderTarget(_shadowOcclusion); Matrix cameraTransform; Camera.MainCamera.GetWorldMatrix(out cameraTransform); // Setup the Effect _shadowEffect.CurrentTechnique = shadowOcclusionTechniques[sm_filterType.GetValue <int>()]; _shadowEffect.Parameters["InvertViewProjection"].SetValue(Matrix.Invert(Camera.MainCamera.ViewProjectionMatrix)); _shadowEffect.Parameters["g_matInvView"].SetValue(cameraTransform); _shadowEffect.Parameters["g_matLightViewProj"].SetValue(_lightCamera.ViewProjectionMatrix); _shadowEffect.Parameters["g_vFrustumCornersVS"].SetValue(_farFrustumCornersVS); _shadowEffect.Parameters["ShadowMap"].SetValue(_shadowMap); _shadowEffect.Parameters["DepthTexture"].SetValue(depthTexture); _shadowEffect.Parameters["g_vOcclusionTextureSize"].SetValue(new Vector2(_shadowOcclusion.Width, _shadowOcclusion.Height)); _shadowEffect.Parameters["g_vShadowMapSize"].SetValue(new Vector2(2048, 2048)); // Begin effect _shadowEffect.CurrentTechnique.Passes[0].Apply(); // Draw the full screen quad DeferredRenderer.RenderFullScreenQuad(graphicsDevice); }
public static void Connect_f(string[] args) { if (ConVar.GetValue <string>("nicknamee") == ("")) // baddd { Log.Write(LogLevel.Info, "You haven't set a nickname, set one now:)"); return; } if (args.Length != 2) { Log.Write(LogLevel.Info, "usage: connect [ip]"); return; } if (args[1] != "localhost") { ConVar.SetValue <bool>("sv_running", false); } var server = NetAddress.Resolve(args[1]); if (_currentServer != server) { _currentServer = server; State = ClientState.Challenging; _lastMessageReceivedAt = _clientTime; _lastConnectPacketTime = -999999; } }
/// <summary> /// kill client command /// </summary> /// <param name="name">player to kill</param> // Welcome to operation KillClient. In this operation you were given the choice to kill a client. You choose to so now we are at this function // Now, first things first we need to check if your the host and not just some random clinet trying to troll! // Right, so now we've past that we need to fetch our client, once we have him we'll just make him respawn. // once respawned we now increase his death count by one! Yes one, not two, not three - one! // now, i come to think about it this just seems pointles.. But oh well, what can you do - I don't like backspace or ctrl+z, so meh. public static void KillClient(string name) { // check that it's the server that used the command if (!ConVar.GetValue <bool>("sv_running")) { Log.Write(LogLevel.Error, "Server is not running."); return; } foreach (ServerClient client in _clients) { if (client != null) { if (client.Name.ToLower() == name.ToLower()) { // now to actually kill the client.. SendReliableCommand(null, "print \"{0} was killed...\"", client.Name); // spawn him client.Entity.Spawn(); // add up his death count client.Deaths = 123; } } } }
public static RenderTarget2D RenderShadows(GraphicsDevice device) { if (sm_enable.GetValue <bool>()) { Matrix cameraTransform, viewMatrix; Camera.MainCamera.GetWorldMatrix(out cameraTransform); Camera.MainCamera.GetViewMatrix(out viewMatrix); Camera.MainCamera.BoundingFrustum.GetCorners(_frustumCornersWS); Vector3.Transform(_frustumCornersWS, ref viewMatrix, _frustumCornersVS); for (int i = 0; i < 4; i++) { _farFrustumCornersVS[i] = _frustumCornersVS[i + 4]; } CalculateFrustum(); RenderShadowMap(device); //return null; RenderShadowOcclusion(device, DeferredRenderer.DepthRT); return(_shadowOcclusion); } else { var renderTargets = device.GetRenderTargets(); device.SetRenderTarget(_disabledShadowOcclusion); device.Clear(ClearOptions.Target, Color.White, 1.0f, 0); device.SetRenderTargets(renderTargets); return(_disabledShadowOcclusion); } }
public static void Process() { var fakeTarget = new Vector3(MainCamera.Position.X, MainCamera.Position.Y, 0f); MainCamera.ViewMatrix = Matrix.CreateLookAt(MainCamera.Position, fakeTarget, new Vector3(0f, 1f, 0f)); MainCamera.FieldOfView = MathHelper.ToRadians(FOV.GetValue <float>()); MainCamera.FarClip = MainCamera.Position.Z + 5f; // +5 works around a weird issue with the lighting breaking; +1 doesn't seem to fix it so I just went with +5 }
private static void ProcessPacket(NetAddress from, byte[] buffer) { if (ConVar.GetValue <bool>("sv_running")) { Server.ProcessPacket(from, buffer); } else { Client.ProcessPacket(from, buffer); } }
public static void RenderDirectionalLight(GraphicsDevice device, RenderTarget2D normalRT, RenderTarget2D depthRT, RenderTarget2D shadowRT) { _dirAmbEffect.Parameters["HalfPixel"].SetValue(_halfPixel); _dirAmbEffect.Parameters["NormalMap"].SetValue(normalRT); //_dirAmbEffect.Parameters["DepthMap"].SetValue(depthRT); _dirAmbEffect.Parameters["ShadowMap"].SetValue(shadowRT); _dirAmbEffect.Parameters["InvertViewProjection"].SetValue(Matrix.Invert(Camera.MainCamera.ViewProjectionMatrix)); _dirAmbEffect.Parameters["g_directional"].SetValue(r_sunIntensity.GetValue <float>()); _dirAmbEffect.CurrentTechnique.Passes[0].Apply(); DeferredRenderer.RenderFullScreenQuad(device); }
private static void SetRenderSnapshot() { if (_snapHistory[0] == null) { return; } if (_curSnap != null) { _snap = Snapshot.InterpolateBetween(_lastSnap, _curSnap, (uint)(_clientTime - cl_snapDelay.GetValue <int>())); } }
private static void ProcessOutOfBand(NetAddress from, byte[] packet) { var message = Encoding.UTF8.GetString(packet, 4, packet.Length - 4); var args = Command.Tokenize(message); if (args.Length == 0) { return; } switch (args[0]) { case "challengeResponse": if (State != ClientState.Challenging) { return; } _lastConnectPacketTime = -999999; _lastMessageReceivedAt = _clientTime; _challenge = int.Parse(args[1]); State = ClientState.Connecting; break; case "connectResponse": if (State != ClientState.Connecting) { return; } _clientNum = int.Parse(args[1]); if (!ConVar.GetValue <bool>("sv_running")) { Server.CreatePhysicsWorld(); MapManager.Load(string.Format("Maps/{0}.gmp", args[2])); } _lastConnectPacketTime = -999999; _lastMessageReceivedAt = _clientTime; _serverChannel = new NetChannel(NetChannelType.ClientToServer, from); InitializeConnection(); State = ClientState.Connected; break; } }
private static void CheckCommandPacket() { if (State != ClientState.Connected && State != ClientState.Ingame) { return; } _timeSinceLastPacket += Game.FrameMsec; if (_timeSinceLastPacket > (1000 / cl_maxpackets.GetValue <int>())) { SendCommandPacket(); _timeSinceLastPacket = 0; } }
/// <summary> /// 'kick' command handler /// </summary> /// <param name="name">player to kick</param> public static void Kick_f(string name) { if (!ConVar.GetValue <bool>("sv_running")) { Log.Write(LogLevel.Error, "Server is not running."); return; } foreach (ServerClient thisClient in _clients) { if (thisClient != null) { if (thisClient.Name.ToLower() == name.ToLower()) { DropClient(thisClient, "Player kicked"); } } } }
public void SendMessage(byte[] message) { // message header var outMessage = new BitStream(); outMessage.WriteUInt32(SequenceOut); SequenceOut++; // write the message outMessage.WriteBytes(message); NetManager.SendPacket(ChannelType, Address, outMessage.Bytes); // log the packet if (ConVar.GetValue <bool>("net_showpackets")) { Log.Write(LogLevel.Debug, "sending {0}b, seq={1}", outMessage.Bytes.Length, SequenceOut); } }
/// <summary> /// Per-frame server processing function /// </summary> public static void Process() { if (!ConVar.GetValue <bool>("sv_running")) { return; } CellManager.Recenter(from client in _clients where client != null && client.Entity != null select client.Entity.Position); _residualTime += Game.FrameMsec; // 20 FPS = 50msec intervals while (_residualTime > 50) { _residualTime -= 50; _serverTime += 50; ProcessGame(); } }
/// <summary> /// 'status' command handler /// </summary> public static void Status_f() { if (!ConVar.GetValue <bool>("sv_running")) { Log.Write(LogLevel.Error, "Server is not running."); } else { Log.Write(LogLevel.Info, "map: {0}", _mapName); Log.Write(LogLevel.Info, "num name state address "); Log.Write(LogLevel.Info, "--- ------------------ ----- ---------------------"); foreach (ServerClient client in _clients) { if (client != null) { var num = client.ClientNum.ToString().PadLeft(3); var name = client.Name.ToString().PadRight(18); var state = " "; switch (client.State) { case ServerClientState.Connected: case ServerClientState.Initialized: state = "CNCT "; break; case ServerClientState.Zombie: state = "ZMBI "; break; } var ip = client.ExternalIP.ToString().PadRight(21); Log.Write(LogLevel.Info, "{0} {1} {2} {3}", num, name, state, ip); } } } }
private static void CheckConnectPacket() { switch (State) { case ClientState.Challenging: if ((_clientTime - _lastConnectPacketTime) > 2000) { NetManager.SendOOBPacket(NetChannelType.ClientToServer, _currentServer, "getchallenge"); _lastConnectPacketTime = (int)_clientTime; } break; case ClientState.Connecting: if ((_clientTime - _lastConnectPacketTime) > 2000) { // TODO: use a proper nickname here // TODO: make nickname changes *dynamic* :o var nicknameToUse = ConVar.GetValue <string>("nicknamee"); NetManager.SendOOBPacket(NetChannelType.ClientToServer, _currentServer, "connect {0} \"{1}\"", _challenge, nicknameToUse); _lastConnectPacketTime = (int)_clientTime; } break; } }
public static void Initialize() { // set the current culture to the invariant culture Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; // initialize the logging service Log.Initialize(LogLevel.All); Log.AddListener(new ConsoleLogListener()); Log.AddListener(new GameLogListener()); Log.AddListener(new FileLogListener("GBHGame.log", false)); Log.Write(LogLevel.Info, "GBH2 v0 initializing"); Log.Write(LogLevel.Critical, "jeremych is an egghead and a nabsalad"); ConVar.Initialize(); FileSystem.Initialize(); Win32System.Initialize(); MapGeometry.Initialize(); //StyleManager.Load("Styles/bil.sty"); //MapManager.Load("Maps/MP1-comp.gmp"); Camera.Initialize(); NetManager.Initialize(29960); Client.Initialize(); Server.Initialize(); GameWindow.Initialize(); com_maxFPS = ConVar.Register("com_maxFPS", 0, "Maximum framerate for the game loop.", ConVarFlags.Archived); timescale = ConVar.Register("timescale", 1.0f, "Scale time by this amount", ConVarFlags.Cheat); sv_running = ConVar.Register("sv_running", true, "Is the server running?", ConVarFlags.ReadOnly); cl_running = ConVar.Register("cl_running", false, "Is the client running?", ConVarFlags.ReadOnly); sv_paused = ConVar.Register("sv_paused", false, "Is the server paused?", ConVarFlags.ReadOnly); cl_paused = ConVar.Register("cl_paused", false, "Is the client paused?", ConVarFlags.ReadOnly); net_showpackets = ConVar.Register("net_showpackets", false, "Show network packets.", ConVarFlags.None); mapname = ConVar.Register("mapname", "", "Current mapname", ConVarFlags.ReadOnly); nickname = ConVar.Register("nickname", Environment.GetEnvironmentVariable("username"), "Your nickname", ConVarFlags.Archived); Renderer.Initialize(); MaterialManager.ReadMaterialFile("base.material"); MaterialManager.ReadMaterialFile("Styles/bil.material"); ConsoleRenderer.Initialize(); //StyleManager.CreateTextures(Renderer.Device); MapRenderer.Initialize(Renderer.Device); DeferredRenderer.Initialize(Renderer.Device); Renderer2D.Initialize(Renderer.Device); // jeez, people these days just need to get a *proper* nickname if (ConVar.GetValue <string>("nicknamee") == Environment.GetEnvironmentVariable("username")) { Log.Write(LogLevel.Info, "It looks it's your first time running GBH2. Please type 'nickname <WANTED NICKNAME>' to set your nickname."); } var path = Directory.GetCurrentDirectory() + "\\config.ini"; IniFile ini = new IniFile(path); var value = ini.IniReadValue("CONFIG", "nickname"); if (value != null) { ConVar.SetValue <string>("nicknamee", value); } }
public static void Process() { byte[] buffer = new byte[16384]; int bytes = 0; EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); while (true) { try { bytes = _socket.ReceiveFrom(buffer, buffer.Length, SocketFlags.None, ref remoteEP); } catch (SocketException e) { if (e.SocketErrorCode != SocketError.WouldBlock && e.SocketErrorCode != SocketError.ConnectionReset) { Log.Write(LogLevel.Info, "socket error {0}", e.SocketErrorCode); } else { break; } } if (bytes > 0) { byte[] cutBuffer = new byte[bytes]; Array.Copy(buffer, cutBuffer, bytes); NetAddress from = new NetAddress((IPEndPoint)remoteEP); if (net_forceLatency.GetValue <int>() == 0) { ProcessPacket(from, cutBuffer); } else { _receiveQueue.Add(new NetPacket(from, cutBuffer)); } } } if (_sendQueue.Count > 0) { var toSend = _sendQueue.ToArray(); var time = Game.Time; var latency = net_forceLatency.GetValue <int>(); foreach (var item in toSend) { if (time >= (item.time + latency)) { SendPacketInternal(item.adr, item.data); _sendQueue.Remove(item); } } } if (_receiveQueue.Count > 0) { var toReceive = _receiveQueue.ToArray(); var time = Game.Time; var latency = net_forceLatency.GetValue <int>(); foreach (var item in toReceive) { if (time >= (item.time + latency)) { ProcessPacket(item.adr, item.data); _receiveQueue.Remove(item); } } } }
public static void HandleCommand(string[] args) { ConVar command = Find(args[0]); if (command == null) { return; } if (args.Length == 1) { Log.Write(LogLevel.Info, "\"{0}\" is:\"{1}^7\" default:\"{2}^7\"", command.Name, command.GetValue <string>(), command._defaultValue.ToString()); return; } command.SetValue <string>(args[1], false); }
public static void Process() { // limit FPS and handle events int minMsec = (com_maxFPS.GetValue <int>() > 0) ? (1000 / com_maxFPS.GetValue <int>()) : 1; uint msec = 0; do { _frameTime = EventSystem.HandleEvents(); msec = _frameTime - _lastTime; } while (msec < minMsec); // handle time scaling var scale = timescale.GetValue <float>(); msec = (uint)(msec * scale); if (msec < 1) { msec = 1; } else if (msec > 5000) { msec = 5000; } if (msec > 500) { Log.Write(LogLevel.Info, "Hitch warning: {0} msec frame time", msec); } DeltaTime = msec / 1000f; FrameMsec = msec; _lastTime = _frameTime; // process the command buffer Command.ExecuteBuffer(); // handle network stuff NetManager.Process(); // process game stuff Server.Process(); // process client Client.Process(); // more stuff (needs to be moved) Camera.Process(); if (!sv_running.GetValue <bool>()) { CellManager.Recenter(new[] { Camera.MainCamera.Position }); } Renderer2D.InitPerFrame(); FontManager.SetColor(Color.White); // camera moving DebugCamera.Process(); ConsoleRenderer.Process(); // render stuff if (Renderer.MakeDeviceAvailable()) { Renderer.Clear(); if (Client.State == Client.ClientState.Ingame) { DeferredRenderer.Render3DStuff(Renderer.Device); } Renderer2D.Render(Renderer.Device); Renderer.Device.Present(); } }
private static void Walk() { Vector3 direction = Vector3.Zero; // possibly change this to be more shared (only do forward/backward difference) var heading = 0f; if (_command.TestButton(ClientButtons.Forward)) { heading = MathHelper.ToRadians(_entity.Rotation.Z); direction = new Vector3((float)Math.Sin(heading) * -1f, (float)Math.Cos(heading) * 1f, 0f); } if (_command.TestButton(ClientButtons.Backward)) { heading = MathHelper.ToRadians(_entity.Rotation.Z + 180f); direction = new Vector3((float)Math.Sin(heading) * -1f, (float)Math.Cos(heading) * 1f, 0f); } /*if (direction == Vector3.Zero) * { * return; * }*/ float slopeZ = 1.0f * _dT + 0.25f; var velocity = direction * _dT; velocity.Z = _entity.VelocityZ; velocity.Z -= ConVar.GetValue <float>("sv_gravity") * _dT; // perform collision tests JVector normal; float fraction; RigidBody body; JVector testDirection; if (direction != Vector3.Zero) { // X axis testDirection = new JVector(velocity.X, 0f, 0f); testDirection += new JVector(0.25f * direction.X, 0f, 0f); _pw.CollisionSystem.Raycast((_entity.Position + new Vector3(0f, 0f, slopeZ)).ToJVector(), testDirection, null, out body, out normal, out fraction); if (fraction <= 1.0f) { // hit a wall // float pedBorder = -0.25f; // if (testDirection.X < 0f) // { // pedBorder = -pedBorder; // } velocity.X = 0.0f; // _entity.Position = new Vector3(_entity.Position.X + (testDirection * fraction).X + pedBorder, _entity.Position.Y, _entity.Position.Z); } // Y axis testDirection = new JVector(0f, velocity.Y, 0f); testDirection += new JVector(0f, 0.25f * direction.Y, 0f); _pw.CollisionSystem.Raycast((_entity.Position + new Vector3(0f, 0f, slopeZ)).ToJVector(), testDirection, null, out body, out normal, out fraction); if (fraction <= 1.0f) { // hit a wall velocity.Y = 0.0f; } } // Z axis Vector3 basePosition = (_entity.Position + new Vector3(0f, 0f, slopeZ)); testDirection = new JVector(0f, 0f, velocity.Z - slopeZ); _pw.CollisionSystem.Raycast((basePosition).ToJVector(), testDirection, null, out body, out normal, out fraction); if (fraction <= 1.0f) { // hit the ground velocity.Z = 0.0f; _entity.Position = new Vector3(basePosition.X, basePosition.Y, basePosition.Z + (testDirection * fraction).Z); } _entity.Position += velocity; _entity.VelocityZ = velocity.Z; }