protected override void DrawCore(RenderContext context, RenderFrame output) { var input = Input.GetSafeRenderFrame(context); // If RenderFrame input or output are null, we can't do anything if (input == null) { return; } // If an effect is set, we are using it if (Effect != null) { Effect.SetInput(0, input); if (input.DepthStencil != null) { Effect.SetInput(1, input.DepthStencil); } Effect.SetOutput(output); Effect.Draw(context); } else if (input != output) { // Else only use a scaler if input and output don't match // TODO: Is this something we want by default or we just don't output anything? var effect = context.GetSharedEffect<ImageScaler>(); effect.SetInput(0, input); effect.SetOutput(output); effect.Draw(context); } }
protected override void DrawCore(RenderContext context, RenderFrame output) { var graphicsDevice = context.GraphicsDevice; // clear the targets if (output.DepthStencil != null && (ClearFlags == ClearRenderFrameFlags.ColorAndDepth || ClearFlags == ClearRenderFrameFlags.DepthOnly)) { const DepthStencilClearOptions ClearOptions = DepthStencilClearOptions.DepthBuffer | DepthStencilClearOptions.Stencil; graphicsDevice.Clear(output.DepthStencil, ClearOptions, Depth, Stencil); } if (ClearFlags == ClearRenderFrameFlags.ColorAndDepth || ClearFlags == ClearRenderFrameFlags.ColorOnly) { foreach (var renderTarget in output.RenderTargets) { if (renderTarget != null) { // If color is in GammeSpace and rendertarget is either SRgb or HDR, use a linear value to clear the buffer. // TODO: We will need to move this color transform code to a shareable component var color = Color.ToColorSpace(ColorSpace, (renderTarget.Format.IsSRgb() || renderTarget.Format.IsHDR()) ? ColorSpace.Linear : graphicsDevice.ColorSpace); graphicsDevice.Clear(renderTarget, color); } } } }
protected override void DrawCore(RenderContext context, RenderFrame output) { // Early exit if some properties are null if (Mode == null) { return; } // Gets the current camera state from the slot var camera = context.GetCameraFromSlot(Camera); // Draw this camera. using (context.PushTagAndRestore(Current, this)) using (context.PushTagAndRestore(CameraComponentRenderer.Current, camera)) { // Run all pre-renderers foreach (var renderer in PreRenderers) { renderer.Draw(context); } // Draw the scene based on its drawing mode (e.g. implementation forward or deferred... etc.) Mode.Draw(context); // Run all post-renderers foreach (var renderer in PostRenderers) { renderer.Draw(context); } } }
protected override void DrawCore(RenderDrawContext context, RenderFrame output) { var input = Input.GetSafeRenderFrame(context.RenderContext); // If RenderFrame input or output are null, we can't do anything if (input == null) { return; } // If an effect is set, we are using it if (Effect != null) { Effect.SetInput(0, input); if (input.DepthStencil != null) { Effect.SetInput(1, input.DepthStencil); } Effect.SetOutput(output); Effect.Draw(context); } else if (input != output) { // Else only use a scaler if input and output don't match // TODO: Is this something we want by default or we just don't output anything? var effect = context.GetSharedEffect<ImageScaler>(); effect.SetInput(0, input); effect.SetOutput(output); ((RendererBase)effect).Draw(context); } // Switch back last output as render target context.CommandList.ResourceBarrierTransition(output, GraphicsResourceState.RenderTarget); }
private void RenderQuad(RenderDrawContext renderContext, RenderFrame frame) { customEffectInstance.Parameters.Set(EffectKeys.Phase, -3 * (float)Game.UpdateTime.Total.TotalSeconds); spriteBatch.Begin(renderContext.GraphicsContext, blendState: BlendStates.NonPremultiplied, depthStencilState: DepthStencilStates.None, effect: customEffectInstance); spriteBatch.Draw(Logo, new RectangleF(0, 0, 1, 1), Color.White); spriteBatch.End(); }
public override void Dispose() { if (currentFrame != null) { currentFrame.Dispose(); currentFrame = null; } }
public void DrawParallax(RenderContext context, RenderFrame frame) { spriteBatch.Begin(); foreach (var pallaraxBackground in backgroundParallax) pallaraxBackground.DrawSprite(spriteBatch); spriteBatch.End(); }
protected override void DrawCore(RenderDrawContext context, RenderFrame output) { var sceneInstance = GetChildSceneInstance(); if (sceneInstance == null) return; // Draw scene recursively sceneInstance.Draw(context, output, GraphicsCompositorOverride); }
/// <summary> /// Activates the output to the current <see cref="GraphicsDevice" />. /// </summary> /// <param name="context">The context.</param> /// <param name="output">The output.</param> /// <param name="disableDepth">if set to <c>true</c> [disable depth].</param> protected virtual void ActivateOutputCore(RenderDrawContext context, RenderFrame output, bool disableDepth) { // Set default render target states foreach (var renderTarget in output.RenderTargets) { context.CommandList.ResourceBarrierTransition(renderTarget, GraphicsResourceState.RenderTarget); } context.CommandList.ResourceBarrierTransition(output.DepthStencil, GraphicsResourceState.DepthWrite); // Setup the render target context.CommandList.SetRenderTargetsAndViewport(disableDepth ? null : output.DepthStencil, output.RenderTargets); }
public override RenderFrame GetRenderFrame(RenderContext context) { // Get the relative frame var relativeFrame = context.Tags.Get(RelativeSizeSource == RenderFrameRelativeMode.Current ? RenderFrame.Current : SceneGraphicsLayer.Master); // Check if we need to resize it if (currentFrame != null && (currentFrame.Descriptor != Descriptor || currentFrame.CheckIfResizeRequired(relativeFrame))) { Dispose(); } // Allocate the render frame if necessary // TODO: Should we use allocated shared textures from RenderContext? return currentFrame ?? (currentFrame = RenderFrame.New(context.GraphicsDevice, Descriptor, relativeFrame)); }
protected override void ActivateOutputCore(RenderContext context, RenderFrame output, bool disableDepth) { base.ActivateOutputCore(context, output, disableDepth); Viewport viewport; var rect = Viewport; // Setup the viewport if (IsViewportInPercentage) { var width = output.Width; var height = output.Height; viewport = new Viewport((int)(rect.X * width / 100.0f), (int)(rect.Y * height / 100.0f), (int)(rect.Width * width / 100.0f), (int)(rect.Height * height / 100.0f)); } else { viewport = new Viewport((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height); } context.GraphicsDevice.SetViewport(viewport); }
protected override void DrawCore(RenderContext context, RenderFrame output) { if (ChildScene == null || !ChildScene.Enabled) { return; } currentSceneInstance = SceneInstance.GetCurrent(Context); childSceneProcessor = childSceneProcessor ?? currentSceneInstance.GetProcessor<ChildSceneProcessor>(); if (childSceneProcessor == null) { return; } SceneInstance sceneInstance = childSceneProcessor.GetSceneInstance(ChildScene); if (sceneInstance != null) { sceneInstance.Draw(context, output, GraphicsCompositorOverride); } }
protected override void DrawCore(RenderContext context, RenderFrame output) { var graphicsDevice = context.GraphicsDevice; // clear the targets if (output.DepthStencil != null) { const DepthStencilClearOptions ClearOptions = DepthStencilClearOptions.DepthBuffer | DepthStencilClearOptions.Stencil; graphicsDevice.Clear(output.DepthStencil, ClearOptions, Depth, Stencil); } if (ClearFlags == ClearRenderFrameFlags.Color) { foreach (var renderTarget in output.RenderTargets) { if (renderTarget != null) { graphicsDevice.Clear(renderTarget, Color); } } } }
public void imageBegin(int w, int h, int bucketSize) { if (frame == null) { frame = new RenderFrame(); frame.imagePanel.imageBegin(w, h, bucketSize); Dimension screenRes = Toolkit.getDefaultToolkit().getScreenSize(); bool needFit = false; if (w >= (screenRes.getWidth() - 200) || h >= (screenRes.getHeight() - 200)) { frame.imagePanel.setPreferredSize(new Dimension((int)screenRes.getWidth() - 200, (int)screenRes.getHeight() - 200)); needFit = true; } else frame.imagePanel.setPreferredSize(new Dimension(w, h)); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); if (needFit) frame.imagePanel.fit(); } else frame.imagePanel.imageBegin(w, h, bucketSize); }
protected override void PostDrawCore(RenderContext context) { base.PostDrawCore(context); CurrentRenderFrame = null; }
/// <summary> /// Initializes a new instance of the <see cref="DirectRenderFrameProvider"/> class. /// </summary> /// <param name="renderFrame">The render frame.</param> public DirectRenderFrameProvider(RenderFrame renderFrame) // Provide only this constructor so that this class doesn't appear in the editor { RenderFrame = renderFrame; }
private void Render(RenderDrawContext context, RenderFrame frame) { // depth test off mode spriteBatch.Begin(context.GraphicsContext, depthStencilState: DepthStencilStates.None); // render the keyboard key states spriteBatch.DrawString(Font, KeyboardSessionString, textLeftTopCorner, fontColor); spriteBatch.DrawString(Font, "Key pressed/released: " + keyEvents, textLeftTopCorner + new Vector2(TextSubSectionOffsetX, 1 * (textHeight + TextSpaceY)), fontColor); spriteBatch.DrawString(Font, "Key down: " + keyDown, textLeftTopCorner + new Vector2(TextSubSectionOffsetX, 2 * (textHeight + TextSpaceY)), fontColor); // render the mouse key states spriteBatch.DrawString(Font, "Mouse :", textLeftTopCorner + new Vector2(0, 4 * (textHeight + TextSpaceY)), fontColor); spriteBatch.DrawString(Font, "Mouse position: " + mousePosition, textLeftTopCorner + new Vector2(TextSubSectionOffsetX, 5 * (textHeight + TextSpaceY)), fontColor); spriteBatch.DrawString(Font, "Mouse button pressed: " + mouseButtonPressed, textLeftTopCorner + new Vector2(TextSubSectionOffsetX, 6 * (textHeight + TextSpaceY)), fontColor); spriteBatch.DrawString(Font, "Mouse button down: " + mouseButtonDown, textLeftTopCorner + new Vector2(TextSubSectionOffsetX, 7 * (textHeight + TextSpaceY)), fontColor); spriteBatch.DrawString(Font, "Mouse button released: " + mouseButtonReleased, textLeftTopCorner + new Vector2(TextSubSectionOffsetX, 8 * (textHeight + TextSpaceY)), fontColor); var mouseScreenPosition = new Vector2(mousePosition.X * screenSize.X, mousePosition.Y * screenSize.Y); spriteBatch.Draw(RoundTexture, mouseScreenPosition, mouseColor, 0, roundTextureSize / 2, 0.1f); // render the pointer states foreach (var tuple in pointerPressed) DrawPointers(tuple, 1.5f, Color.Blue); foreach (var tuple in pointerMoved) DrawPointers(tuple, 1f, Color.Green); foreach (var tuple in pointerReleased) DrawPointers(tuple, 2f, Color.Red); // render the gesture states spriteBatch.DrawString(Font, "Gestures :", textLeftTopCorner + new Vector2(0, 10 * (textHeight + TextSpaceY)), fontColor); spriteBatch.DrawString(Font, "Drag: " + dragEvent, textLeftTopCorner + new Vector2(TextSubSectionOffsetX, 11 * (textHeight + TextSpaceY)), fontColor); spriteBatch.DrawString(Font, "Flick: " + flickEvent, textLeftTopCorner + new Vector2(TextSubSectionOffsetX, 12 * (textHeight + TextSpaceY)), fontColor); spriteBatch.DrawString(Font, "LongPress: " + longPressEvent, textLeftTopCorner + new Vector2(TextSubSectionOffsetX, 13 * (textHeight + TextSpaceY)), fontColor); spriteBatch.DrawString(Font, "Composite: " + compositeEvent, textLeftTopCorner + new Vector2(TextSubSectionOffsetX, 14 * (textHeight + TextSpaceY)), fontColor); spriteBatch.DrawString(Font, "Tap: " + tapEvent, textLeftTopCorner + new Vector2(TextSubSectionOffsetX, 15 * (textHeight + TextSpaceY)), fontColor); spriteBatch.DrawString(Font, "GamePads: " + gamePadText, textLeftTopCorner + new Vector2(TextSubSectionOffsetX, 17 * (textHeight + TextSpaceY)), fontColor); spriteBatch.End(); }
private void RenderSpheres(RenderContext renderContext, RenderFrame frame) { spriteBatch.Begin(); // draw the ball var time = (float)Game.DrawTime.Total.TotalSeconds; var rotation = time * (float)Math.PI * 0.5f; var sourceRectangle = GetSphereAnimation(1.25f * time); spriteBatch.Draw(sphere, ballPosition, sourceRectangle, Color.White, rotation, ballHalfSize); spriteBatch.End(); }
public static void Main() { using (RenderFrame frame = RenderFrame.Create("", 640, 480, 32, false)) { Counter timer = new Counter(); Setup.basicOpenGL(); FileSystem fs = new FileSystem(); fs.addDefaultRoots("pretty good", "simple test"); MediaLoader loader = new MediaLoader(fs); //Texture sample = loader.fetch<Texture>("sample.bmp"); bool running = true; World world = World.Load(loader, "level01.lvl"); //world.add(new MeshInstance(loader.fetch<Mesh>("basicroad.obj"))); Camera cam = new Camera(); //Gl.glLoadIdentity(); float delta = 0; Key rightleft = new PlusMinus(new Hold(new Ckey(Keys.D)), new Hold(new Ckey(Keys.A))); Key forback = new PlusMinus(new Hold(new Ckey(Keys.W)), new Hold(new Ckey(Keys.S))); Key updown = new PlusMinus(new Hold(new Ckey(Keys.Space)), new Hold(new Ckey(Keys.ControlKey))); Hold sprint = new Hold(new Ckey(Keys.ShiftKey)); frame.setCursorPos(frame.Center); vec2 mousesmooth = new vec2(0, 0); vec3 movement = new vec3(0, 0, 0); float sensitivity = 0.1f; float mousesmoothing = 6; Pipeline pipe = Pipeline.Create("pipeline.xml", loader, frame.Width, frame.Height); while (running) { timer.Start(); Application.DoEvents(); /*fbo.updateTexture(delegate() * { * world.render(frame.Width, frame.Height, cam); * });*/ frame.begin(); pipe.render(new RenderArgs(world, cam, frame.Width, frame.Height)); /*Shader.Bind(shader); * FullscreenQuad.render(fbo, frame.Width, frame.Height); * Shader.Unbind();*/ frame.swap(); /*frame.begin(); * world.render(frame.Width, frame.Height, cam); * frame.swap();*/ System.Drawing.Point p = frame.getCursorPos(); System.Drawing.Point center = frame.Center; frame.setCursorPos(center); mousesmooth = vec2.Curve(new vec2(p.X - center.X, p.Y - center.Y), mousesmooth, mousesmoothing); movement = vec3.Curve(Key.Combine(rightleft, updown, forback).Normalized *(3 + sprint.Value * 3), movement, 5); // math::Quaternion(math::op::vec3::yAxisPositive, -x) * math::Quaternion(mRotation.getRight(), y) * mRotation; quat final = quat.FpsQuat(cam.rotation, mousesmooth.x * sensitivity, mousesmooth.y * sensitivity); cam.location += cam.rotation.getRUI(movement) * delta; cam.rotate(final); foreach (RenderFrame.Event e in frame.Events) { System.Diagnostics.Debug.WriteLine(e); if (e.button.equals(new Ckey(Keys.Escape))) { running = false; } else { Key.Run(e.button, e.down, rightleft, forback, updown, sprint); } } timer.Stop(); delta = timer.Duration; } } }
/// <summary> /// Invokes the <see cref="RenderFrame"/> event. /// </summary> protected virtual void OnRenderFrame() { RenderFrame?.Invoke(this, EventArgs.Empty); }
protected virtual void PostCameraRendererDraw(RenderContext context, RenderFrame frame) { }
/// <summary> /// We are about to display a video frame. Calculate positions for /// animated objects, and add their primitives to the RenderFrame list. /// </summary> public override void PrepareFrame(RenderFrame frame, ElapsedTime elapsedTime) { base.PrepareFrame(frame, elapsedTime); }
protected override void SpecificDrawBeforeUI(RenderDrawContext context, RenderFrame renderFrame) { base.SpecificDrawBeforeUI(context, renderFrame); context.GraphicsContext.DrawTexture(sprites["GameScreen"].Texture); }
/// <summary> /// Called just after a frame is drawn. /// </summary> /// <param name="frame">The <see cref="RenderFrame"/> containing everything that was drawn.</param> //[CallOnThread("Render")] internal virtual void EndRender(RenderFrame frame) { }
/// <summary> /// Called just before a frame is drawn. /// </summary> /// <param name="frame">The <see cref="RenderFrame"/> containing everything to be drawn.</param> //[CallOnThread("Render")] internal virtual void BeginRender(RenderFrame frame) { }
/// <summary> /// Called at the full frame rate /// elapsedTime is time since last frame /// Executes in the UpdaterThread /// </summary> public abstract void PrepareFrame(RenderFrame frame, ElapsedTime elapsedTime);
public FrameDisplay(string filename) { this.filename = filename; frame = null; }
protected override void SpecificDrawBeforeUI(RenderContext context, RenderFrame renderFrame) { base.SpecificDrawBeforeUI(context, renderFrame); GraphicsDevice.DrawTexture(uiImages["GameScreen"].Texture); }
public override void PrepareFrame(RenderFrame frame, in ElapsedTime elapsedTime)
protected abstract void DrawCore(RenderContext context, RenderFrame output);
internal void Start() { Game.WatchdogProcess.Register(WatchdogToken); DisplaySize = new Point(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height); // Validate that the DirectX feature level is one we understand if (!Enum.IsDefined(typeof(ORTS.Settings.UserSettings.DirectXFeature), "Level" + Game.Settings.DirectXFeatureLevel)) { Game.Settings.DirectXFeatureLevel = ""; } if (Game.Settings.DirectXFeatureLevel == "") { // Choose default feature level based on profile if (GraphicsDevice.GraphicsProfile == GraphicsProfile.HiDef) { Game.Settings.DirectXFeatureLevel = "10_0"; } else { Game.Settings.DirectXFeatureLevel = "9_1"; } } if (Game.Settings.ShadowMapDistance == 0) { Game.Settings.ShadowMapDistance = Game.Settings.ViewingDistance / 2; } ShadowMapCount = Game.Settings.ShadowMapCount; if (!Game.Settings.DynamicShadows) { ShadowMapCount = 0; } else if ((ShadowMapCount > 1) && !Game.Settings.IsDirectXFeatureLevelIncluded(ORTS.Settings.UserSettings.DirectXFeature.Level9_3)) { ShadowMapCount = 1; } else if (ShadowMapCount < 0) { ShadowMapCount = 0; } else if (ShadowMapCount > ShadowMapCountMaximum) { ShadowMapCount = ShadowMapCountMaximum; } if (ShadowMapCount < 1) { Game.Settings.DynamicShadows = false; } ShadowMapDistance = new int[ShadowMapCount]; ShadowMapDiameter = new int[ShadowMapCount]; ShadowMapLimit = new float[ShadowMapCount]; ShadowPrimitiveCount = new int[ShadowMapCount]; ShadowPrimitivePerFrame = new int[ShadowMapCount]; InitializeShadowMapLocations(); CurrentFrame = new RenderFrame(Game); NextFrame = new RenderFrame(Game); }
private void RenderQuad(RenderContext renderContext, RenderFrame frame) { GraphicsDevice.Clear(frame.DepthStencil, DepthStencilClearOptions.DepthBuffer); if (_tile != null) { _spriteBatch.Begin(); _spriteBatch.Draw(_tile, Vector2.Zero); _spriteBatch.End(); } }
private void DisplayGBuffer(RenderContext context, RenderFrame frame) { GraphicsDevice.DrawTexture(textures[renderTargetToDisplayIndex]); }
public override void PrepareFrame(RenderFrame frame, in ElapsedTime elapsedTime, bool updateFull)
protected virtual void SpecificDrawBeforeUI(RenderContext context, RenderFrame renderFrame) { }
private void UpdateAnimation(RenderFrame frame, ElapsedTime elapsedTime) { float distanceTravelledM; if (MSTSWagon.IsDriveable && MSTSWagon.Simulator.UseAdvancedAdhesion) { //TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. // To achieve the same result with other means, without flipping trainset physics, the line should be changed as follows: // distanceTravelledM = MSTSWagon.WheelSpeedMpS * elapsedTime.ClockSeconds; distanceTravelledM = ((MSTSWagon.Train != null && MSTSWagon.Train.IsPlayerDriven && ((MSTSLocomotive)MSTSWagon).UsingRearCab) ? -1 : 1) * MSTSWagon.WheelSpeedMpS * elapsedTime.ClockSeconds; } else { distanceTravelledM = MSTSWagon.SpeedMpS * elapsedTime.ClockSeconds; } // Running gear animation if (!RunningGear.Empty() && MSTSWagon.DriverWheelRadiusM > 0.001) { RunningGear.UpdateLoop(distanceTravelledM / MathHelper.TwoPi / MSTSWagon.DriverWheelRadiusM); } // Wheel animation if (WheelPartIndexes.Count > 0) { var wheelCircumferenceM = MathHelper.TwoPi * MSTSWagon.WheelRadiusM; var rotationalDistanceR = MathHelper.TwoPi * distanceTravelledM / wheelCircumferenceM; // in radians WheelRotationR = MathHelper.WrapAngle(WheelRotationR - rotationalDistanceR); var wheelRotationMatrix = Matrix.CreateRotationX(WheelRotationR); foreach (var iMatrix in WheelPartIndexes) { TrainCarShape.XNAMatrices[iMatrix] = wheelRotationMatrix * TrainCarShape.SharedShape.Matrices[iMatrix]; } } // truck angle animation foreach (var p in Car.Parts) { if (p.iMatrix <= 0) { continue; } Matrix m = Matrix.Identity; m.Translation = TrainCarShape.SharedShape.Matrices[p.iMatrix].Translation; m.M11 = p.Cos; m.M13 = p.Sin; m.M31 = -p.Sin; m.M33 = p.Cos; // To cancel out any vibration, apply the inverse here. If no vibration is present, this matrix will be Matrix.Identity. TrainCarShape.XNAMatrices[p.iMatrix] = Car.VibrationInverseMatrix * m; } if (FreightShape != null) { FreightShape.Location.XNAMatrix = Car.WorldPosition.XNAMatrix; FreightShape.Location.TileX = Car.WorldPosition.TileX; FreightShape.Location.TileZ = Car.WorldPosition.TileZ; if (MSTSWagon.WagonType == TrainCar.WagonTypes.Tender) { if (MSTSWagon.TendersSteamLocomotive == null) { MSTSWagon.FindTendersSteamLocomotive(); } if (FreightShape.XNAMatrices.Length > 0 && MSTSWagon.TendersSteamLocomotive != null) { if (MSTSWagon.FreightAnimFlag > 0 && MSTSWagon.FreightAnimMaxLevelM > MSTSWagon.FreightAnimMinLevelM) { FreightShape.XNAMatrices[0].M42 = MSTSWagon.FreightAnimMinLevelM + MSTSWagon.TendersSteamLocomotive.FuelController.CurrentValue * (MSTSWagon.FreightAnimMaxLevelM - MSTSWagon.FreightAnimMinLevelM); } else // reproducing MSTS strange behavior; used to display loco crew { FreightShape.Location.XNAMatrix.M42 += MSTSWagon.FreightAnimMaxLevelM; } } } FreightShape.PrepareFrame(frame, elapsedTime); } if (FreightAnimations != null) { foreach (var freightAnim in FreightAnimations.Animations) { if (freightAnim.FreightShape != null && !((freightAnim.Animation is FreightAnimationContinuous) && (freightAnim.Animation as FreightAnimationContinuous).LoadPerCent == 0)) { freightAnim.FreightShape.Location.XNAMatrix = Car.WorldPosition.XNAMatrix; freightAnim.FreightShape.Location.TileX = Car.WorldPosition.TileX; freightAnim.FreightShape.Location.TileZ = Car.WorldPosition.TileZ; if (freightAnim.FreightShape.XNAMatrices.Length > 0) { if (freightAnim.Animation is FreightAnimationContinuous) { var continuousFreightAnim = freightAnim.Animation as FreightAnimationContinuous; if (MSTSWagon.FreightAnimations.IsGondola) { freightAnim.FreightShape.XNAMatrices[0] = TrainCarShape.XNAMatrices[1]; } freightAnim.FreightShape.XNAMatrices[0].M42 = continuousFreightAnim.MinHeight + continuousFreightAnim.LoadPerCent / 100 * (continuousFreightAnim.MaxHeight - continuousFreightAnim.MinHeight); } if (freightAnim.Animation is FreightAnimationStatic) { var staticFreightAnim = freightAnim.Animation as FreightAnimationStatic; freightAnim.FreightShape.XNAMatrices[0].M41 = staticFreightAnim.XOffset; freightAnim.FreightShape.XNAMatrices[0].M42 = staticFreightAnim.YOffset; freightAnim.FreightShape.XNAMatrices[0].M43 = staticFreightAnim.ZOffset; } } // Forcing rotation of freight shape freightAnim.FreightShape.PrepareFrame(frame, elapsedTime); } } } // Control visibility of passenger cabin when inside it if (Viewer.Camera.AttachedCar == this.MSTSWagon && //( Viewer.ViewPoint == Viewer.ViewPoints.Cab || // TODO, restore when we complete cab views - Viewer.Camera.Style == Camera.Styles.Passenger) { // We are in the passenger cabin if (InteriorShape != null) { InteriorShape.PrepareFrame(frame, elapsedTime); } else { TrainCarShape.PrepareFrame(frame, elapsedTime); } } else { // Skip drawing if CAB view - draw 2D view instead - by GeorgeS if (Viewer.Camera.AttachedCar == this.MSTSWagon && Viewer.Camera.Style == Camera.Styles.Cab) { return; } // We are outside the passenger cabin TrainCarShape.PrepareFrame(frame, elapsedTime); } }
/// <summary> /// Draws this scene instance with the specified context and <see cref="RenderFrame"/>. /// </summary> /// <param name="context">The context.</param> /// <param name="toFrame">To frame.</param> /// <param name="compositorOverride">The compositor overload. Set this value to by-pass the default compositor of a scene.</param> /// <exception cref="System.ArgumentNullException"> /// context /// or /// toFrame /// </exception> public void Draw(RenderContext context, RenderFrame toFrame, ISceneGraphicsCompositor compositorOverride = null) { if (context == null) { throw new ArgumentNullException("context"); } if (toFrame == null) { throw new ArgumentNullException("toFrame"); } // If no scene, then we can return immediately if (Scene == null) { return; } var graphicsDevice = context.GraphicsDevice; bool hasGraphicsBegin = false; // Update global time var gameTime = context.Time; context.GraphicsDevice.Parameters.Set(GlobalKeys.Time, (float)gameTime.Total.TotalSeconds); context.GraphicsDevice.Parameters.Set(GlobalKeys.TimeStep, (float)gameTime.Elapsed.TotalSeconds); try { graphicsDevice.Begin(); hasGraphicsBegin = true; // Always clear the state of the GraphicsDevice to make sure a scene doesn't start with a wrong setup graphicsDevice.ClearState(); // Draw the main scene using the current compositor (or the provided override) var graphicsCompositor = compositorOverride ?? Scene.Settings.GraphicsCompositor; if (graphicsCompositor != null) { // Push context (pop after using) using (context.PushTagAndRestore(RenderFrame.Current, toFrame)) using (context.PushTagAndRestore(SceneGraphicsLayer.Master, toFrame)) using (context.PushTagAndRestore(Current, this)) using (context.PushTagAndRestore(CameraRendererMode.RendererTypesKey, RendererTypes)) { graphicsCompositor.Draw(context); } } } catch (Exception ex) { Log.Error("An exception occurred while rendering", ex); } finally { if (hasGraphicsBegin) { graphicsDevice.End(); } } }
public override void PrepareFrame(RenderFrame frame, ORTS.Common.ElapsedTime elapsedTime, bool updateFull) { if (updateFull) { UpdateLabelLists(); var labels = Labels; var newLabels = new Dictionary <TrItemLabel, LabelPrimitive>(labels.Count); var worldFiles = Owner.Viewer.World.Scenery.WorldFiles; var cameraLocation = Owner.Viewer.Camera.CameraWorldLocation; foreach (var worldFile in worldFiles) { if ((State & DisplayState.Platforms) != 0 && worldFile.platforms != null) { foreach (var platform in worldFile.platforms) { if (State == DisplayState.Auto && Platforms != null && (!Platforms.ContainsKey(platform.ItemName) || !Platforms[platform.ItemName])) { continue; } // Calculates distance between camera and platform label. var distance = WorldLocation.GetDistance(platform.Location.WorldLocation, cameraLocation).Length(); if (distance <= MaximumDistancePlatform) { if (labels.ContainsKey(platform)) { newLabels[platform] = labels[platform]; } else { newLabels[platform] = new LabelPrimitive(Owner.Label3DMaterial, Color.Yellow, Color.Black, 0) { Position = platform.Location, Text = platform.ItemName } }; // Change color with distance. var ratio = (MathHelper.Clamp(distance, MinimumDistance, MaximumDistancePlatform) - MinimumDistance) / (MaximumDistancePlatform - MinimumDistance); newLabels[platform].Color.A = newLabels[platform].Outline.A = (byte)MathHelper.Lerp(255, 0, ratio); } } } if ((State & DisplayState.Sidings) != 0 && worldFile.sidings != null) { foreach (var siding in worldFile.sidings) { if (State == DisplayState.Auto && Sidings != null && (!Sidings.ContainsKey(siding.ItemName) || !Sidings[siding.ItemName])) { continue; } // Calculates distance between camera and siding label. var distance = WorldLocation.GetDistance(siding.Location.WorldLocation, cameraLocation).Length(); if (distance <= MaximumDistanceSiding) { if (labels.ContainsKey(siding)) { newLabels[siding] = labels[siding]; } else { newLabels[siding] = new LabelPrimitive(Owner.Label3DMaterial, Color.Orange, Color.Black, 0) { Position = siding.Location, Text = siding.ItemName } }; // Change color with distance. var ratio = (MathHelper.Clamp(distance, MinimumDistance, MaximumDistanceSiding) - MinimumDistance) / (MaximumDistanceSiding - MinimumDistance); newLabels[siding].Color.A = newLabels[siding].Outline.A = (byte)MathHelper.Lerp(255, 0, ratio); } } } } Labels = newLabels; } foreach (var primitive in Labels.Values) { frame.AddPrimitive(Owner.Label3DMaterial, primitive, RenderPrimitiveGroup.Labels, ref Identity); } }
/// <summary> /// Activates the output to the current <see cref="GraphicsDevice" />. /// </summary> /// <param name="context">The context.</param> /// <param name="output">The output.</param> /// <param name="disableDepth">if set to <c>true</c> [disable depth].</param> protected virtual void ActivateOutputCore(RenderDrawContext context, RenderFrame output, bool disableDepth) { // Setup the render target context.CommandList.SetRenderTargetsAndViewport(disableDepth ? null : output.DepthStencil, output.RenderTargets); }
protected override void PostCameraRendererDraw(RenderContext context, RenderFrame frame) { if (!debug) return; spriteBatch.Begin(); spriteBatch.DrawString(font, "Desired triangle size: {0}".ToFormat(currentMaterial.Parameters.Get(TessellationKeys.DesiredTriangleSize)), new Vector2(0), Color.Black); spriteBatch.DrawString(font, "FPS: {0}".ToFormat(DrawTime.FramePerSecond), new Vector2(0, 20), Color.Black); spriteBatch.End(); }
protected override void PreDrawCore(RenderContext context) { base.PreDrawCore(context); CurrentRenderFrame = context.Tags.GetSafe(RenderFrame.Current); }
protected override void DrawCore(RenderContext context, RenderFrame output) { drawAction(context, output); }
protected override void SpecificDrawBeforeUI(RenderContext context, RenderFrame renderFrame) { base.SpecificDrawBeforeUI(context, renderFrame); GraphicsDevice.DrawTexture(Sprites["GameScreen"].Texture); }
public abstract void OnRender(RenderFrame renderFrame);
private void RenderQuad(RenderContext renderContext, RenderFrame frame) { GraphicsDevice.SetBlendState(GraphicsDevice.BlendStates.NonPremultiplied); quad.Parameters.Set(EffectKeys.Phase, -3 * (float)Game.UpdateTime.Total.TotalSeconds); quad.Draw(Logo, samplingState, Color.White); }
internal void StartUpdate(RenderFrame frame, GameTime gameTime) { CurrentFrame = frame; this.gameTime = gameTime; State.SignalStart(); }
/// <summary> /// Activates the output to the current <see cref="GraphicsDevice" />. /// </summary> /// <param name="context">The context.</param> /// <param name="output">The output.</param> /// <param name="disableDepth">if set to <c>true</c> [disable depth].</param> protected virtual void ActivateOutputCore(RenderContext context, RenderFrame output, bool disableDepth) { // Setup the render target context.GraphicsDevice.SetDepthAndRenderTargets(disableDepth ? null : output.DepthStencil, output.RenderTargets); }
private void UpdateAnimation(RenderFrame frame, ElapsedTime elapsedTime) { float distanceTravelledM = 0.0f; // Distance travelled by non-driven wheels float distanceTravelledDrivenM = 0.0f; // Distance travelled by driven wheels float AnimationWheelRadiusM = 0.0f; // Radius of non driven wheels float AnimationDriveWheelRadiusM = 0.0f; // Radius of driven wheels if (MSTSWagon.IsDriveable && MSTSWagon.Simulator.UseAdvancedAdhesion) { //TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. // To achieve the same result with other means, without flipping trainset physics, the line should be changed as follows: // distanceTravelledM = MSTSWagon.WheelSpeedMpS * elapsedTime.ClockSeconds; if (Car.EngineType == Orts.Simulation.RollingStocks.TrainCar.EngineTypes.Steam) // Steam locomotive so set up different speeds for different driver and non-driver wheels { distanceTravelledM = ((MSTSWagon.Train != null && MSTSWagon.Train.IsPlayerDriven && ((MSTSLocomotive)MSTSWagon).UsingRearCab) ? -1 : 1) * MSTSWagon.WheelSpeedMpS * elapsedTime.ClockSeconds; distanceTravelledDrivenM = ((MSTSWagon.Train != null && MSTSWagon.Train.IsPlayerDriven && ((MSTSLocomotive)MSTSWagon).UsingRearCab) ? -1 : 1) * MSTSWagon.WheelSpeedSlipMpS * elapsedTime.ClockSeconds; // Set values of wheel radius - assume that drive wheel and non driven wheel are different sizes AnimationWheelRadiusM = MSTSWagon.WheelRadiusM; AnimationDriveWheelRadiusM = MSTSWagon.DriverWheelRadiusM; } else // Other driveable rolling stock - all wheels have same speed. { distanceTravelledM = ((MSTSWagon.Train != null && MSTSWagon.Train.IsPlayerDriven && ((MSTSLocomotive)MSTSWagon).UsingRearCab) ? -1 : 1) * MSTSWagon.WheelSpeedMpS * elapsedTime.ClockSeconds; distanceTravelledDrivenM = ((MSTSWagon.Train != null && MSTSWagon.Train.IsPlayerDriven && ((MSTSLocomotive)MSTSWagon).UsingRearCab) ? -1 : 1) * MSTSWagon.WheelSpeedMpS * elapsedTime.ClockSeconds; // Set values of wheel radius - assume that drive wheel and non driven wheel are same sizes AnimationWheelRadiusM = MSTSWagon.WheelRadiusM; AnimationDriveWheelRadiusM = MSTSWagon.WheelRadiusM; } } else // set values for simple adhesion { distanceTravelledM = MSTSWagon.SpeedMpS * elapsedTime.ClockSeconds; distanceTravelledDrivenM = MSTSWagon.SpeedMpS * elapsedTime.ClockSeconds; // Set values of wheel radius - assume that drive wheel and non driven wheel are same sizes if (Car.EngineType == Orts.Simulation.RollingStocks.TrainCar.EngineTypes.Steam) // set values for steam stock { AnimationWheelRadiusM = MSTSWagon.WheelRadiusM; AnimationDriveWheelRadiusM = MSTSWagon.DriverWheelRadiusM; } else // set values for non-driveable stock, eg wagons, and driveable stock such as diesels, electric locomotives { AnimationWheelRadiusM = MSTSWagon.WheelRadiusM; AnimationDriveWheelRadiusM = MSTSWagon.WheelRadiusM; } } if (Car.BrakeSkid) // if car wheels are skidding because of brakes lockin wheels up then stop wheels rotating. { distanceTravelledM = 0.0f; distanceTravelledDrivenM = 0.0f; } // Running gear and drive wheel rotation (animation) in steam locomotives if (!RunningGear.Empty() && AnimationDriveWheelRadiusM > 0.001) { RunningGear.UpdateLoop(distanceTravelledDrivenM / MathHelper.TwoPi / AnimationDriveWheelRadiusM); } // Wheel rotation (animation) - for non-drive wheels in steam locomotives and all wheels in other stock if (WheelPartIndexes.Count > 0) { var wheelCircumferenceM = MathHelper.TwoPi * AnimationWheelRadiusM; var rotationalDistanceR = MathHelper.TwoPi * distanceTravelledM / wheelCircumferenceM; // in radians WheelRotationR = MathHelper.WrapAngle(WheelRotationR - rotationalDistanceR); var wheelRotationMatrix = Matrix.CreateRotationX(WheelRotationR); foreach (var iMatrix in WheelPartIndexes) { TrainCarShape.XNAMatrices[iMatrix] = wheelRotationMatrix * TrainCarShape.SharedShape.Matrices[iMatrix]; } } #if DEBUG_WHEEL_ANIMATION Trace.TraceInformation("========================== Debug Animation in MSTSWagonViewer.cs =========================================="); Trace.TraceInformation("Slip speed - Car ID: {0} WheelDistance: {1} SlipWheelDistance: {2}", Car.CarID, distanceTravelledM, distanceTravelledDrivenM); Trace.TraceInformation("Wag Speed - Wheelspeed: {0} Slip: {1} Train: {2}", MSTSWagon.WheelSpeedMpS, MSTSWagon.WheelSpeedSlipMpS, MSTSWagon.SpeedMpS); Trace.TraceInformation("Wheel Radius - DriveWheel: {0} NonDriveWheel: {1}", AnimationDriveWheelRadiusM, AnimationWheelRadiusM); #endif // truck angle animation foreach (var p in Car.Parts) { if (p.iMatrix <= 0) { continue; } Matrix m = Matrix.Identity; m.Translation = TrainCarShape.SharedShape.Matrices[p.iMatrix].Translation; m.M11 = p.Cos; m.M13 = p.Sin; m.M31 = -p.Sin; m.M33 = p.Cos; // To cancel out any vibration, apply the inverse here. If no vibration is present, this matrix will be Matrix.Identity. TrainCarShape.XNAMatrices[p.iMatrix] = Car.VibrationInverseMatrix * m; } if (FreightShape != null) { FreightShape.Location.XNAMatrix = Car.WorldPosition.XNAMatrix; FreightShape.Location.TileX = Car.WorldPosition.TileX; FreightShape.Location.TileZ = Car.WorldPosition.TileZ; if (MSTSWagon.WagonType == TrainCar.WagonTypes.Tender) { if (MSTSWagon.TendersSteamLocomotive == null) { MSTSWagon.FindTendersSteamLocomotive(); } if (FreightShape.XNAMatrices.Length > 0 && MSTSWagon.TendersSteamLocomotive != null) { if (MSTSWagon.FreightAnimFlag > 0 && MSTSWagon.FreightAnimMaxLevelM > MSTSWagon.FreightAnimMinLevelM) { FreightShape.XNAMatrices[0].M42 = MSTSWagon.FreightAnimMinLevelM + MSTSWagon.TendersSteamLocomotive.FuelController.CurrentValue * (MSTSWagon.FreightAnimMaxLevelM - MSTSWagon.FreightAnimMinLevelM); } else // reproducing MSTS strange behavior; used to display loco crew { FreightShape.Location.XNAMatrix.M42 += MSTSWagon.FreightAnimMaxLevelM; } } } FreightShape.PrepareFrame(frame, elapsedTime); } if (FreightAnimations != null) { foreach (var freightAnim in FreightAnimations.Animations) { if (freightAnim.FreightShape != null && !((freightAnim.Animation is FreightAnimationContinuous) && (freightAnim.Animation as FreightAnimationContinuous).LoadPerCent == 0)) { freightAnim.FreightShape.Location.XNAMatrix = Car.WorldPosition.XNAMatrix; freightAnim.FreightShape.Location.TileX = Car.WorldPosition.TileX; freightAnim.FreightShape.Location.TileZ = Car.WorldPosition.TileZ; if (freightAnim.FreightShape.XNAMatrices.Length > 0) { if (freightAnim.Animation is FreightAnimationContinuous) { var continuousFreightAnim = freightAnim.Animation as FreightAnimationContinuous; if (MSTSWagon.FreightAnimations.IsGondola) { freightAnim.FreightShape.XNAMatrices[0] = TrainCarShape.XNAMatrices[1]; } freightAnim.FreightShape.XNAMatrices[0].M42 = continuousFreightAnim.MinHeight + continuousFreightAnim.LoadPerCent / 100 * (continuousFreightAnim.MaxHeight - continuousFreightAnim.MinHeight); } if (freightAnim.Animation is FreightAnimationStatic) { var staticFreightAnim = freightAnim.Animation as FreightAnimationStatic; freightAnim.FreightShape.XNAMatrices[0].M41 = staticFreightAnim.XOffset; freightAnim.FreightShape.XNAMatrices[0].M42 = staticFreightAnim.YOffset; freightAnim.FreightShape.XNAMatrices[0].M43 = staticFreightAnim.ZOffset; } } // Forcing rotation of freight shape freightAnim.FreightShape.PrepareFrame(frame, elapsedTime); } } } // Control visibility of passenger cabin when inside it if (Viewer.Camera.AttachedCar == this.MSTSWagon && //( Viewer.ViewPoint == Viewer.ViewPoints.Cab || // TODO, restore when we complete cab views - Viewer.Camera.Style == Camera.Styles.Passenger) { // We are in the passenger cabin if (InteriorShape != null) { InteriorShape.PrepareFrame(frame, elapsedTime); } else { TrainCarShape.PrepareFrame(frame, elapsedTime); } } else { // Skip drawing if CAB view - draw 2D view instead - by GeorgeS if (Viewer.Camera.AttachedCar == this.MSTSWagon && Viewer.Camera.Style == Camera.Styles.Cab) { return; } // We are outside the passenger cabin TrainCarShape.PrepareFrame(frame, elapsedTime); } }
internal override void EndRender(RenderFrame frame) { Viewer.EndRender(frame); }
//[CallOnThread("Updater")] public virtual void PrepareFrame(RenderFrame frame, in ElapsedTime elapsedTime, bool updateFull)
public override void OnRender(RenderFrame renderFrame) { }
public abstract void RenderOverlay(RenderFrame frame, bool keyboardOnly);
/// <summary> /// We are about to display a video frame. Calculate positions for /// animated objects, and add their primitives to the RenderFrame list. /// </summary> public override void PrepareFrame(RenderFrame frame, ElapsedTime elapsedTime) { var car = Car as MSTSSteamLocomotive; foreach (var drawer in Cylinders) { drawer.SetOutput(car.Cylinders1SteamVelocityMpS, car.Cylinders1SteamVolumeM3pS, car.Cylinder1ParticleDurationS); } foreach (var drawer in Cylinders2) { drawer.SetOutput(car.Cylinders2SteamVelocityMpS, car.Cylinders2SteamVolumeM3pS, car.Cylinder2ParticleDurationS); } foreach (var drawer in Blowdown) { drawer.SetOutput(car.BlowdownSteamVelocityMpS, car.BlowdownSteamVolumeM3pS, car.BlowdownParticleDurationS); } // TODO: Drainpipe - Not used in either MSTS or OR - currently disabled by zero values set in SteamLocomotive file foreach (var drawer in Drainpipe) { drawer.SetOutput(car.DrainpipeSteamVelocityMpS, car.DrainpipeSteamVolumeM3pS, car.DrainpipeParticleDurationS); } foreach (var drawer in Injectors1) { drawer.SetOutput(car.Injector1SteamVelocityMpS, car.Injector1SteamVolumeM3pS, car.Injector1ParticleDurationS); } foreach (var drawer in Injectors2) { drawer.SetOutput(car.Injector2SteamVelocityMpS, car.Injector2SteamVolumeM3pS, car.Injector2ParticleDurationS); } foreach (var drawer in SmallEjector) { drawer.SetOutput(car.SmallEjectorSteamVelocityMpS, car.SmallEjectorSteamVolumeM3pS, car.SmallEjectorParticleDurationS); } foreach (var drawer in LargeEjector) { drawer.SetOutput(car.LargeEjectorSteamVelocityMpS, car.LargeEjectorSteamVolumeM3pS, car.LargeEjectorParticleDurationS); } foreach (var drawer in Compressor) { drawer.SetOutput(car.CompressorSteamVelocityMpS, car.CompressorSteamVolumeM3pS, car.CompressorParticleDurationS); } foreach (var drawer in Generator) { drawer.SetOutput(car.GeneratorSteamVelocityMpS, car.GeneratorSteamVolumeM3pS, car.GeneratorParticleDurationS); } foreach (var drawer in SafetyValves) { drawer.SetOutput(car.SafetyValvesSteamVelocityMpS, car.SafetyValvesSteamVolumeM3pS, car.SafetyValvesParticleDurationS); } Throttlepercent = car.ThrottlePercent > 0 ? car.ThrottlePercent / 10f : 0f; foreach (var drawer in Stack) { Color_Value = car.SmokeColor.SmoothedValue; drawer.SetOutput(car.StackSteamVelocityMpS.SmoothedValue, car.StackSteamVolumeM3pS / Stack.Count + car.FireRatio, Throttlepercent + car.FireRatio, new Color(Color_Value, Color_Value, Color_Value)); } foreach (var drawer in Whistle) { drawer.SetOutput(car.WhistleSteamVelocityMpS, car.WhistleSteamVolumeM3pS, car.WhistleParticleDurationS); } base.PrepareFrame(frame, elapsedTime); }
private void Render(RenderDrawContext arg1, RenderFrame arg2) { uiRoot.Draw(Game.UpdateTime.Elapsed.TotalMilliseconds); debug.Draw(); }
static void CaptureFrame( RenderFrame frame, int captureWidth, int captureHeight, float horizontalInc, float verticalInc, float eyeSeparation, string effects, Camera camera, Vector3 capturePos, Material biltMaterial) { var cameraTrans = camera.transform; var horizontalSteps = (int)(360.0f / horizontalInc); var verticalSteps = (int)(180.0f / verticalInc + 1); camera.fieldOfView = 180.0f / verticalSteps; biltMaterial.SetVector("_BlitParams", new Vector4( 1.0f / captureWidth, 1.0f / captureHeight, horizontalSteps, verticalSteps)); for (var i = 0; i < 2; i++) { var left = (i == 0); var eyeOffset = new Vector3(left ? -eyeSeparation : eyeSeparation, 0, 0); var renderTarget = RenderTexture.GetTemporary(captureWidth * 2, captureHeight * 2, 16, RenderTextureFormat.ARGB32); var sliderWidth = (float)renderTarget.width / horizontalSteps; var sliderHeight = (float)renderTarget.height / verticalSteps; // render the slides to the target. RenderTexture.active = renderTarget; camera.targetTexture = renderTarget; for (var row = 0; row < verticalSteps; row++) { for (var col = 0; col < horizontalSteps; col++) { cameraTrans.rotation = Quaternion.Euler( 180.0f * ((verticalSteps / 2) - row) / verticalSteps, 360.0f * col / horizontalSteps, 0); cameraTrans.position = capturePos + cameraTrans.rotation * eyeOffset; // build the viewport. var rect = new Rect(col * sliderWidth, row * sliderHeight, sliderWidth, sliderHeight); camera.pixelRect = rect; camera.Render(); } } camera.targetTexture = null; // slice to SphericalAtlas var sphericalAtlas = RenderTexture.GetTemporary(captureWidth, captureHeight); Graphics.Blit(renderTarget, sphericalAtlas, biltMaterial); RenderTexture.ReleaseTemporary(renderTarget); // process the full screen effects. PostProcessEffects(ref sphericalAtlas, effects); // read the pixels to texture.. RenderTexture.active = sphericalAtlas; Graphics.Blit(sphericalAtlas, left ? frame.RenderTargetLeft : frame.RenderTargetRight); // no need. RenderTexture.active = null; RenderTexture.ReleaseTemporary(sphericalAtlas); } }