public override bool Render(RenderContext dest) { dest.Append("with("); Expression.Render(dest); dest.Append(")"); return Code.RenderIndented(dest); }
public override void Render(RenderContext context) { if (renderHost.RenderTechnique == renderHost.RenderTechniquesManager.RenderTechniques.Get(DeferredRenderTechniqueNames.Deferred) || renderHost.RenderTechnique == renderHost.RenderTechniquesManager.RenderTechniques.Get(DeferredRenderTechniqueNames.GBuffer)) { return; } if (this.IsRendering) { /// --- turn-on the light lightColors[lightIndex] = this.Color; } else { // --- turn-off the light lightColors[lightIndex] = new global::SharpDX.Color4(0, 0, 0, 0); } /// --- Set lighting parameters lightPositions[lightIndex] = this.Position.ToVector4(); lightAtt[lightIndex] = new Vector4((float)this.Attenuation.X, (float)this.Attenuation.Y, (float)this.Attenuation.Z, (float)this.Range); /// --- Update lighting variables this.vLightPos.Set(lightPositions); this.vLightColor.Set(lightColors); this.vLightAtt.Set(lightAtt); this.iLightType.Set(lightTypes); }
public override void Render(RenderContext context) { foreach (var c in this.Children) { c.Render(context); } }
protected override void DrawCore(RenderContext context, RenderItemCollection renderItems, int fromIndex, int toIndex) { var graphicsDevice = context.GraphicsDevice; var destination = new RectangleF(0, 0, 1, 1); spriteBatch.Begin(SpriteSortMode.FrontToBack, graphicsDevice.BlendStates.Opaque, graphicsDevice.SamplerStates.LinearClamp, graphicsDevice.DepthStencilStates.None); for(var i = fromIndex; i <= toIndex; ++i) { var background = (BackgroundComponent)renderItems[i].DrawContext; var texture = background.Texture; if (texture == null) continue; var target = CurrentRenderFrame; var imageBufferMinRatio = Math.Min(texture.ViewWidth / (float)target.Width, texture.ViewHeight / (float)target.Height); var sourceSize = new Vector2(target.Width * imageBufferMinRatio, target.Height * imageBufferMinRatio); var source = new RectangleF((texture.ViewWidth - sourceSize.X) / 2, (texture.ViewHeight - sourceSize.Y) / 2, sourceSize.X, sourceSize.Y); spriteBatch.Draw(texture, destination, source, Color.White, 0, Vector2.Zero); } spriteBatch.End(); }
protected override void PrepareCore(RenderContext context, RenderItemCollection opaqueList, RenderItemCollection transparentList) { if (lightComponentForwardRenderer != null) { lightComponentForwardRenderer.Draw(context); } }
protected override void OnRenderContent(RenderContext context) { if (Head != null) Head.OnRender(context); if (Body != null) Body.OnRender(context); }
public override void Render(RenderContext context) { // buffered comment is not rendered if (_text.StartsWith("-")) return; context.Output.WriteComment(_text); }
public override bool Render(RenderContext dest) { dest.Append("("); Inner.Render(dest); dest.Append(")"); return true; }
/// <summary> /// Create a new instance of the class. /// </summary> /// <param name="context">the context</param> public RadiancePrefilteringGGXNoCompute(RenderContext context) : base(context, "RadiancePrefilteringGGX") { shader = new ImageEffectShader("RadiancePrefilteringGGXNoComputeEffect"); DoNotFilterHighestLevel = true; samplingsCount = 1024; }
protected override void DrawCore(RenderContext context, RenderItemCollection renderItems, int fromIndex, int toIndex) { var graphicsDevice = context.GraphicsDevice; var destination = new RectangleF(0, 0, 1, 1); // find the last background to display with valid texture BackgroundComponent background = null; for (var i = toIndex; i >= fromIndex; --i) { background = (BackgroundComponent)renderItems[i].DrawContext; if (background.Texture != null) break; } // Abort if not valid background component if (background == null || background.Texture == null) return; var texture = background.Texture; var target = CurrentRenderFrame; var imageBufferMinRatio = Math.Min(texture.ViewWidth / (float)target.Width, texture.ViewHeight / (float)target.Height); var sourceSize = new Vector2(target.Width * imageBufferMinRatio, target.Height * imageBufferMinRatio); var source = new RectangleF((texture.ViewWidth - sourceSize.X) / 2, (texture.ViewHeight - sourceSize.Y) / 2, sourceSize.X, sourceSize.Y); spriteBatch.Parameters.Add(BackgroundEffectKeys.Intensity, background.Intensity); spriteBatch.Begin(SpriteSortMode.FrontToBack, graphicsDevice.BlendStates.Opaque, graphicsDevice.SamplerStates.LinearClamp, graphicsDevice.DepthStencilStates.None, null, backgroundEffect); spriteBatch.Draw(texture, destination, source, Color.White, 0, Vector2.Zero); spriteBatch.End(); }
public override Color shade(RenderContext rc, Ray ray, HitRecord hrec, int depth) { Point hp = ray.pointOn(hrec.getT()); Vector normal = hrec.getPrimitive().normal(hp); hp += 0.0001f * normal; Scene scene = rc.getScene(); int numlights = scene.numberOfLights(); Color finalc = new Color(0,0,0); for ( int i = 0; i < numlights; i++ ) { Vector ldir = new Vector(); Color lcolor = new Color(); float ldist = scene.getLight(i).getLight(ref lcolor, ref ldir, rc, hp); HitRecord shadowhr = new HitRecord(); Ray shadowray = new Ray(hp, ldir); scene.getObject().intersect(ref shadowhr, rc, shadowray); if ( shadowhr.getT() >= ldist || shadowhr.getT() < 0.01 ) { float dp = Vector.dot(normal, ldir); if( dp > 0 ) { finalc += dp*lcolor; } } } return color * ( finalc * kd + scene.getAmbient() * ka ); }
protected override void DrawCore(RenderContext context) { var input = GetSafeInput(0); // TODO: Check that input is power of two // input.Size.Width Texture fromTexture = input; Texture downTexture = null; var nextSize = input.Size; bool isFirstPass = true; while (nextSize.Width > 3 && nextSize.Height > 3) { var previousSize = nextSize; nextSize = nextSize.Down2(); // If the next half size of the texture is not an exact *2, make it 1 pixel larger to avoid loosing pixels min/max. if ((nextSize.Width * 2) < previousSize.Width) { nextSize.Width += 1; } if ((nextSize.Height * 2) < previousSize.Height) { nextSize.Height += 1; } downTexture = NewScopedRenderTarget2D(nextSize.Width, nextSize.Height, PixelFormat.R32G32_Float, 1); effect.Parameters.Set(DepthMinMaxShaderKeys.TextureMap, fromTexture); effect.Parameters.Set(DepthMinMaxShaderKeys.TextureReduction, fromTexture); effect.SetOutput(downTexture); effect.Parameters.Set(IsFirstPassKey, isFirstPass); effect.Draw(context); fromTexture = downTexture; isFirstPass = false; } readback.SetInput(downTexture); readback.Draw(); IsResultAvailable = readback.IsResultAvailable; if (IsResultAvailable) { float min = float.MaxValue; float max = -float.MaxValue; var results = readback.Result; foreach (var result in results) { min = Math.Min(result.X, min); if (result.Y != 1.0f) { max = Math.Max(result.Y, max); } } Result = new Vector2(min, max); } }
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(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 OnProcess(RenderContext context) { var graphicsDevice = GraphicsService.GraphicsDevice; if (TextureHelper.IsFloatingPointFormat(context.SourceTexture.Format)) graphicsDevice.SamplerStates[0] = SamplerState.PointClamp; else graphicsDevice.SamplerStates[0] = SamplerState.LinearClamp; graphicsDevice.SetRenderTarget(context.RenderTarget); graphicsDevice.Viewport = context.Viewport; _viewportSizeParameter.SetValue(new Vector2(graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height)); _sourceTextureParameter.SetValue(context.SourceTexture); if (Numeric.AreEqual(Strength, 1)) { _fullSepiaPass.Apply(); } else { _strengthParameter.SetValue(Strength); _partialSepiaPass.Apply(); } graphicsDevice.DrawFullScreenQuad(); _sourceTextureParameter.SetValue((Texture2D)null); }
public static void Draw(this Rectangle rectangle, RenderContext renderContext, Color color) { renderContext.SpriteBatch.DrawLine(new Vector2(rectangle.Left, rectangle.Top), new Vector2(rectangle.Right, rectangle.Top), color); renderContext.SpriteBatch.DrawLine(new Vector2(rectangle.Left, rectangle.Top), new Vector2(rectangle.Left, rectangle.Bottom), color); renderContext.SpriteBatch.DrawLine(new Vector2(rectangle.Left, rectangle.Bottom), new Vector2(rectangle.Right, rectangle.Bottom), color); renderContext.SpriteBatch.DrawLine(new Vector2(rectangle.Right, rectangle.Bottom), new Vector2(rectangle.Right, rectangle.Top), color); }
static SceneManager() { GameScenes = new List<GameScene>(); RenderContext = new RenderContext(); //Default Camera RenderContext.Camera = new BaseCamera(); }
public Color renderPixel(int x, int y) { Color color; HitRecord hitRecord = new HitRecord(); Ray ray; RenderContext renderContext = new RenderContext( this.scene ); float step = 2 / (float)this.scene.getXResolution(); float xStart = -1 + ( 0.5f * step ); float yStart = (-(float)this.scene.getYResolution() * (0.5f * step)) + (0.5f * step); ray = this.scene.getCamera().generateRay( xStart + (x * step), yStart + (y * step) ); this.scene.traceRay( ray, hitRecord, renderContext ); if ( hitRecord.getT() == float.PositiveInfinity || hitRecord.getMaterial() == null || hitRecord.getPrimitive() == null ) { color = this.scene.getBackground().getColor( renderContext, ray ); } else { color = hitRecord.getMaterial().shade( renderContext, ray, hitRecord, 1 ); } return color; }
public override bool Render(RenderContext dest) { dest.Append("while("); Condition.Render(dest); dest.Append(")"); return Code.RenderIndented(dest); }
public override void Update(RenderContext renderContext) { if (CanDrop) return; if (_isFalling) { var deltaTime = (float)renderContext.GameTime.ElapsedGameTime.TotalSeconds; _currentSpeed += Gravity * deltaTime; var rockPos = _rockSprite.LocalPosition; rockPos.Y += _currentSpeed * deltaTime; _rockSprite.Translate(rockPos); if (rockPos.Y >= 390) { _isFalling = false; _rockSprite.CanDraw = false; _explosionSprite.CanDraw = true; _explosionSprite.Translate(rockPos); _explosionSprite.PlayAnimation(); } } else { if (!_explosionSprite.IsPlaying) { _explosionSprite.CanDraw = false; CanDrop = true; } } base.Update(renderContext); }
protected override void OnProcess(RenderContext context) { var graphicsDevice = GraphicsService.GraphicsDevice; // Set sampler state. (Floating-point textures cannot use linear filtering. (XNA would throw an exception.)) if (TextureHelper.IsFloatingPointFormat(context.SourceTexture.Format)) graphicsDevice.SamplerStates[0] = SamplerState.PointClamp; else graphicsDevice.SamplerStates[0] = SamplerState.LinearClamp; // Set the render target - but only if no kind of alpha blending is currently set. // If alpha-blending is set, then we have to assume that the render target is already // set - everything else does not make sense. if (graphicsDevice.BlendState.ColorDestinationBlend == Blend.Zero && graphicsDevice.BlendState.AlphaDestinationBlend == Blend.Zero) { graphicsDevice.SetRenderTarget(context.RenderTarget); graphicsDevice.Viewport = context.Viewport; } _viewportSizeParameter.SetValue(new Vector2(graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height)); _sourceTextureParameter.SetValue(context.SourceTexture); _effect.CurrentTechnique.Passes[0].Apply(); graphicsDevice.DrawFullScreenQuad(); _sourceTextureParameter.SetValue((Texture2D)null); }
/// <summary> /// Create a new instance of the class. /// </summary> /// <param name="context">the context</param> public RadiancePrefilteringGGX(RenderContext context) : base(context, "RadiancePrefilteringGGX") { computeShader = new ComputeEffectShader(context) { ShaderSourceName = "RadiancePrefilteringGGXEffect" }; DoNotFilterHighestLevel = true; samplingsCount = 1024; }
protected override void PreDrawCore(RenderContext context) { base.PreDrawCore(context); Parameters.Set(FactorCount, InputCount); Parameters.Set(ColorCombinerShaderKeys.Factors, factors); Parameters.Set(ColorCombinerShaderKeys.ModulateRGB, ModulateRGB); }
public override bool Render(RenderContext dest) { dest.ForceLineBreak(); dest.Append(Comment); dest.ForceLineBreak(); return false; }
// TODO: Find a way to replug this /// <summary> /// Adds a default frustum culling for rendering only meshes that are only inside the frustum/ /// </summary> /// <param name="modelRenderer">The model renderer.</param> /// <returns>ModelRenderer.</returns> //public static ModelComponentRenderer AddDefaultFrustumCulling(this ModelComponentRenderer modelRenderer) //{ // modelRenderer.UpdateMeshes = FrustumCulling; // return modelRenderer; //} private static void FrustumCulling(RenderContext context, FastList<RenderMesh> meshes) { Matrix viewProjection, mat1, mat2; // Compute view * projection context.Parameters.Get(TransformationKeys.View, out mat1); context.Parameters.Get(TransformationKeys.Projection, out mat2); Matrix.Multiply(ref mat1, ref mat2, out viewProjection); var frustum = new BoundingFrustum(ref viewProjection); for (var i = 0; i < meshes.Count; ++i) { var renderMesh = meshes[i]; // Fast AABB transform: http://zeuxcg.org/2010/10/17/aabb-from-obb-with-component-wise-abs/ // Get world matrix renderMesh.Mesh.Parameters.Get(TransformationKeys.World, out mat1); // Compute transformed AABB (by world) var boundingBoxExt = new BoundingBoxExt(renderMesh.Mesh.BoundingBox); boundingBoxExt.Transform(mat1); // Perform frustum culling if (!frustum.Contains(ref boundingBoxExt)) { meshes.SwapRemoveAt(i--); } } }
public static void UpdateParameters(RenderContext context, CameraComponent camera) { if (camera == null) throw new ArgumentNullException("camera"); // Setup viewport size var currentViewport = context.GraphicsDevice.Viewport; var aspectRatio = currentViewport.AspectRatio; // Update the aspect ratio if (camera.UseCustomAspectRatio) { aspectRatio = camera.AspectRatio; } // If the aspect ratio is calculated automatically from the current viewport, update matrices here camera.Update(aspectRatio); // Store the current view/projection matrix in the context var viewParameters = context.Parameters; viewParameters.Set(TransformationKeys.View, camera.ViewMatrix); viewParameters.Set(TransformationKeys.Projection, camera.ProjectionMatrix); viewParameters.Set(TransformationKeys.ViewProjection, camera.ViewProjectionMatrix); viewParameters.Set(CameraKeys.NearClipPlane, camera.NearClipPlane); viewParameters.Set(CameraKeys.FarClipPlane, camera.FarClipPlane); viewParameters.Set(CameraKeys.VerticalFieldOfView, camera.VerticalFieldOfView); viewParameters.Set(CameraKeys.OrthoSize, camera.OrthographicSize); viewParameters.Set(CameraKeys.ViewSize, new Vector2(currentViewport.Width, currentViewport.Height)); viewParameters.Set(CameraKeys.AspectRatio, aspectRatio); //viewParameters.Set(CameraKeys.FocusDistance, camera.FocusDistance); }
public void Render(RenderContext context) { var value = Template.GetValue(context.RenderModel, this.Key); if(context.RenderValue != null) { var rendered = context.RenderValue(this.Key, value, context); if(rendered) { return; } } if(value == null) { return; } var iRenderizable = value as IRenderizable; if(iRenderizable != null) { iRenderizable.Render(context); } else { context.Writer.Write(value.ToString()); } }
/// <summary> /// Clears the current render target (which must be the G-buffer). /// </summary> /// <param name="context">The render context.</param> public void Render(RenderContext context) { if (context == null) throw new ArgumentNullException("context"); context.Validate(_effect); var graphicsDevice = _effect.GraphicsDevice; var savedRenderState = new RenderStateSnapshot(graphicsDevice); graphicsDevice.DepthStencilState = DepthStencilState.None; graphicsDevice.RasterizerState = RasterizerState.CullNone; graphicsDevice.BlendState = BlendState.Opaque; // Clear to maximum depth. _parameterDepth.SetValue(1.0f); // The environment is facing the camera. // --> Set normal = cameraBackward. var cameraNode = context.CameraNode; _parameterNormal.SetValue((cameraNode != null) ? (Vector3)cameraNode.ViewInverse.GetColumn(2).XYZ : Vector3.Backward); // Clear specular to arbitrary value. _parameterSpecularPower.SetValue(1.0f); _effect.CurrentTechnique.Passes[0].Apply(); // Draw full-screen quad using clip space coordinates. graphicsDevice.DrawQuad( new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 0)), new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 1))); savedRenderState.Restore(); }
public void Render(RenderContext context) { if (this.files != null) { foreach (string file in this.files) { context.Writer.WriteLine("<script type='text/javascript' src='{0}'></script>", file); } } if (this.variables != null) { context.Writer.WriteLine("<script type='text/javascript'>var scriptVars="); context.Writer.WriteLine(Json.Serialize(variables)); context.Writer.WriteLine("</script>"); } if(scripts != null) { context.Writer.WriteLine("<script type='text/javascript'>"); foreach(string script in scripts) { context.Writer.WriteLine(script); } context.Writer.WriteLine("</script>"); } }
public ComboBoxElement(RenderContext renderContext): base (renderContext) { Items = new List<ComboboxItem>(); Items.Add(new ComboboxTextItem() { Value = "1"}); Items.Add(new ComboboxTextItem() { Value = "2" }); Items.Add(new ComboboxTextItem() { Value = "3" }); }
// Header is always the same public static string FormatHeader(RenderContext context) => "AuthorID,Author,Date,Content,Attachments,Reactions";
protected override async Task LoadContent() { await base.LoadContent(); spriteBatch = new SpriteBatch(GraphicsDevice); font = Content.Load <SpriteFont>("Font"); wireframeState = new RasterizerStateDescription(CullMode.Back) { FillMode = FillMode.Wireframe }; materials.Add(Content.Load <Material>("NoTessellation")); materials.Add(Content.Load <Material>("FlatTessellation")); materials.Add(Content.Load <Material>("PNTessellation")); materials.Add(Content.Load <Material>("PNTessellationAE")); materials.Add(Content.Load <Material>("FlatTessellationDispl")); materials.Add(Content.Load <Material>("FlatTessellationDisplAE")); materials.Add(Content.Load <Material>("PNTessellationDisplAE")); RenderContext.GetShared(Services).RendererInitialized += RendererInitialized; var cube = new Entity("Cube") { new ModelComponent(new ProceduralModelDescriptor(new CubeProceduralModel { Size = new Vector3(80), MaterialInstance = { Material = materials[0] } }).GenerateModel(Services)) }; var sphere = new Entity("Sphere") { new ModelComponent(new ProceduralModelDescriptor(new SphereProceduralModel { Radius = 50, Tessellation = 5, MaterialInstance = { Material = materials[0] } }).GenerateModel(Services)) }; var megalodon = new Entity { new ModelComponent { Model = Content.Load <Model>("megalodon Model") } }; megalodon.Transform.Position = new Vector3(0, -30f, -10f); var knight = new Entity { new ModelComponent { Model = Content.Load <Model>("knight Model") } }; knight.Transform.RotationEulerXYZ = new Vector3(-MathUtil.Pi / 2, MathUtil.Pi / 4, 0); knight.Transform.Position = new Vector3(0, -50f, 20f); knight.Transform.Scale = new Vector3(0.6f); entities.Add(sphere); entities.Add(cube); entities.Add(megalodon); entities.Add(knight); camera = new TestCamera(Services.GetSafeServiceAs <SceneSystem>().GraphicsCompositor); CameraComponent = camera.Camera; Script.Add(camera); // TODO GRAPHICS REFACTOR ChangeModel(0); camera.Position = new Vector3(25, 45, 80); camera.SetTarget(currentEntity, true); }
public static string FormatMarkdown(RenderContext context, string markdown) => PlainTextRenderingLogic.FormatMarkdown(context, markdown);
/* * The parameters to the Execute() function are, beyond what we covered so far, the rendering context. * The context primarily deals with resolving your I/O ports into safe, read/write memory. * * Inside this function, you would then use the parameters/data found in your kernel data * to read your inputs and write something to your outputs. * * You can also keep persistent state on your graph kernel itself. For example, a common use for this would be in audio for * free-running recursive style IIR DSP, where you would have state variables on your kernel (or even * buffers / delay lines). */ public void Execute(RenderContext ctx, KernelData data, ref KernelDefs ports) { Debug.Log("Hello, world!"); }
internal override void RenderContent(RenderContext ctx, bool isOnChannel) { DUCE.Channel channel = ctx.Channel; // // At this point, the visual has to be marshalled. Force // marshalling of the camera and viewport in case we have // just created a new visual resource. // Debug.Assert(IsOnChannel(channel)); VisualProxyFlags flags = _proxy.GetFlags(channel); // // Make sure the camera resource is being marshalled properly. // if ((flags & VisualProxyFlags.Viewport3DVisual_IsCameraDirty) != 0) { Camera camera = Camera; if (camera != null) { DUCE.Viewport3DVisualNode.SetCamera( ((DUCE.IResource) this).GetHandle(channel), ((DUCE.IResource)camera).AddRefOnChannel(channel), channel); } else if (isOnChannel) /* camera == null */ { DUCE.Viewport3DVisualNode.SetCamera( ((DUCE.IResource) this).GetHandle(channel), DUCE.ResourceHandle.Null, channel); } SetFlags(channel, false, VisualProxyFlags.Viewport3DVisual_IsCameraDirty); } // // Set the viewport if it's dirty. // if ((flags & VisualProxyFlags.Viewport3DVisual_IsViewportDirty) != 0) { DUCE.Viewport3DVisualNode.SetViewport( ((DUCE.IResource) this).GetHandle(channel), Viewport, channel); SetFlags(channel, false, VisualProxyFlags.Viewport3DVisual_IsViewportDirty); } //we only want to recurse in the children if the visual does not have a bitmap effect //or we are in the BitmapVisualManager render pass // Visit children of this node ----------------------------------------------------------------------- Debug.Assert(!CheckFlagsAnd(channel, VisualProxyFlags.IsContentNodeConnected), "Only HostVisuals are expected to have a content node."); if (_children != null) { for (uint i = 0; i < _children.InternalCount; i++) { Visual3D child = _children.InternalGetItem((int)i); if (child != null) { if (child.CheckFlagsAnd(channel, VisualProxyFlags.IsSubtreeDirtyForRender) || // or the visual is dirty !(child.IsOnChannel(channel))) // or the child has not been marshalled yet. { child.RenderRecursive(ctx); } if (child.IsOnChannel(channel)) { if (!child.CheckFlagsAnd(channel, VisualProxyFlags.IsConnectedToParent)) { DUCE.Visual3DNode.InsertChildAt( _proxy3D.GetHandle(channel), ((DUCE.IResource)child).GetHandle(channel), /* iPosition = */ i, channel); child.SetFlags(channel, true, VisualProxyFlags.IsConnectedToParent); } } } } } }
protected override void OnUpdatePerModelStruct(ref ModelStruct model, RenderContext context) { base.OnUpdatePerModelStruct(ref model, context); model.RenderOIT = context.IsOITPass ? 1 : 0; }
public void Render(RenderContext context) { context.SpriteBatch.Begin(); context.SpriteBatch.Draw(_radarTexture, new Rectangle(GraphicsDevice.Viewport.Width - 300, GraphicsDevice.Viewport.Height - 200, 300, 200), _colour); context.SpriteBatch.End(); }
/// <inheritdoc/> protected override Measurement Measure(RenderContext context, int maxWidth) { var width = Math.Min(Width ?? maxWidth, maxWidth); return(new Measurement(width, width)); }
protected LightShaderGroupDynamic(RenderContext renderContext, ILightShadowMapShaderGroupData shadowGroup) { graphicsProfile = renderContext.GraphicsDevice.Features.RequestedProfile; ShadowGroup = shadowGroup; }
protected override bool OnHitTest(RenderContext context, Matrix totalModelMatrix, ref Ray ray, ref List <HitTestResult> hits) { return(false); }
protected override bool CanHitTest(RenderContext context) { return(false); }
/// <summary> /// Hits the test. /// </summary> /// <param name="context">The context.</param> /// <param name="ray">The ray.</param> /// <param name="hits">The hits.</param> /// <returns></returns> public virtual bool HitTest(RenderContext context, Ray ray, ref List <HitTestResult> hits) { return(SceneNode.HitTest(context, ray, ref hits)); }
/// <summary> /// Hits the test. /// </summary> /// <param name="context">The context.</param> /// <param name="ray">The ray.</param> /// <param name="hits">The hits.</param> /// <returns></returns> public override bool HitTest(RenderContext context, Ray ray, ref List <HitTestResult> hits) { return(false); }
public override void Collect(RenderContext context, RenderView sourceView, LightShadowMapTexture lightShadowMap) { var shadow = (LightDirectionalShadowMap)lightShadowMap.Shadow; // TODO: Min and Max distance can be auto-computed from readback from Z buffer Matrix.Invert(ref sourceView.View, out var viewToWorld); // Update the frustum infos UpdateFrustum(sourceView); // Computes the cascade splits var minMaxDistance = ComputeCascadeSplits(context, sourceView, ref lightShadowMap); var direction = lightShadowMap.RenderLight.Direction; // Fake value // It will be setup by next loop Vector3 side = Vector3.UnitX; Vector3 upDirection = Vector3.UnitX; // Select best Up vector // TODO: User preference? foreach (var vectorUp in VectorUps) { if (MathF.Abs(Vector3.Dot(direction, vectorUp)) < (1.0 - 0.0001)) { side = Vector3.Normalize(Vector3.Cross(vectorUp, direction)); upDirection = Vector3.Normalize(Vector3.Cross(direction, side)); break; } } int cascadeCount = lightShadowMap.CascadeCount; // Get new shader data from pool ShaderData shaderData; if (cascadeCount == 1) { shaderData = shaderDataPoolCascade1.Add(); } else if (cascadeCount == 2) { shaderData = shaderDataPoolCascade2.Add(); } else { shaderData = shaderDataPoolCascade4.Add(); } lightShadowMap.ShaderData = shaderData; shaderData.Texture = lightShadowMap.Atlas.Texture; shaderData.DepthBias = shadow.BiasParameters.DepthBias; shaderData.OffsetScale = shadow.BiasParameters.NormalOffsetScale; float splitMaxRatio = (minMaxDistance.X - sourceView.NearClipPlane) / (sourceView.FarClipPlane - sourceView.NearClipPlane); float splitMinRatio = 0; for (int cascadeLevel = 0; cascadeLevel < cascadeCount; ++cascadeLevel) { var oldSplitMinRatio = splitMinRatio; // Calculate frustum corners for this cascade splitMinRatio = splitMaxRatio; splitMaxRatio = cascadeSplitRatios[cascadeLevel]; for (int j = 0; j < 4; j++) { // Calculate frustum in WS and VS float overlap = 0; if (cascadeLevel > 0 && shadow.DepthRange.IsBlendingCascades) { overlap = 0.2f * (splitMinRatio - oldSplitMinRatio); } var frustumRangeWS = frustumCornersWS[j + 4] - frustumCornersWS[j]; var frustumRangeVS = frustumCornersVS[j + 4] - frustumCornersVS[j]; cascadeFrustumCornersWS[j] = frustumCornersWS[j] + frustumRangeWS * (splitMinRatio - overlap); cascadeFrustumCornersWS[j + 4] = frustumCornersWS[j] + frustumRangeWS * splitMaxRatio; cascadeFrustumCornersVS[j] = frustumCornersVS[j] + frustumRangeVS * (splitMinRatio - overlap); cascadeFrustumCornersVS[j + 4] = frustumCornersVS[j] + frustumRangeVS * splitMaxRatio; } Vector3 cascadeMinBoundLS; Vector3 cascadeMaxBoundLS; Vector3 target; if (shadow.StabilizationMode == LightShadowMapStabilizationMode.ViewSnapping || shadow.StabilizationMode == LightShadowMapStabilizationMode.ProjectionSnapping) { // Make sure we are using the same direction when stabilizing var boundingVS = BoundingSphere.FromPoints(cascadeFrustumCornersVS); // Compute bounding box center & radius target = Vector3.TransformCoordinate(boundingVS.Center, viewToWorld); var radius = boundingVS.Radius; //if (shadow.AutoComputeMinMax) //{ // var snapRadius = (float)Math.Ceiling(radius / snapRadiusValue) * snapRadiusValue; // Debug.WriteLine("Radius: {0} SnapRadius: {1} (snap: {2})", radius, snapRadius, snapRadiusValue); // radius = snapRadius; //} cascadeMaxBoundLS = new Vector3(radius, radius, radius); cascadeMinBoundLS = -cascadeMaxBoundLS; if (shadow.StabilizationMode == LightShadowMapStabilizationMode.ViewSnapping) { // Snap camera to texel units (so that shadow doesn't jitter when light doesn't change direction but camera is moving) // Technique from ShaderX7 - Practical Cascaded Shadows Maps - p310-311 var shadowMapHalfSize = lightShadowMap.Size * 0.5f; float x = MathF.Ceiling(Vector3.Dot(target, upDirection) * shadowMapHalfSize / radius) * radius / shadowMapHalfSize; float y = MathF.Ceiling(Vector3.Dot(target, side) * shadowMapHalfSize / radius) * radius / shadowMapHalfSize; float z = Vector3.Dot(target, direction); //target = up * x + side * y + direction * R32G32B32_Float.Dot(target, direction); target = upDirection * x + side * y + direction * z; } } else { var cascadeBoundWS = BoundingBox.FromPoints(cascadeFrustumCornersWS); target = cascadeBoundWS.Center; // Computes the bouding box of the frustum cascade in light space var lightViewMatrix = Matrix.LookAtRH(target, target + direction, upDirection); cascadeMinBoundLS = new Vector3(float.MaxValue); cascadeMaxBoundLS = new Vector3(-float.MaxValue); for (int i = 0; i < cascadeFrustumCornersWS.Length; i++) { Vector3 cornerViewSpace; Vector3.TransformCoordinate(ref cascadeFrustumCornersWS[i], ref lightViewMatrix, out cornerViewSpace); cascadeMinBoundLS = Vector3.Min(cascadeMinBoundLS, cornerViewSpace); cascadeMaxBoundLS = Vector3.Max(cascadeMaxBoundLS, cornerViewSpace); } // TODO: Adjust orthoSize by taking into account filtering size } // Update the shadow camera. The calculation of the eye position assumes RH coordinates. var viewMatrix = Matrix.LookAtRH(target - direction * cascadeMaxBoundLS.Z, target, upDirection); // View;; var nearClip = 0.0f; var farClip = cascadeMaxBoundLS.Z - cascadeMinBoundLS.Z; var projectionMatrix = Matrix.OrthoOffCenterRH(cascadeMinBoundLS.X, cascadeMaxBoundLS.X, cascadeMinBoundLS.Y, cascadeMaxBoundLS.Y, nearClip, farClip); // Projection Matrix viewProjectionMatrix; Matrix.Multiply(ref viewMatrix, ref projectionMatrix, out viewProjectionMatrix); // Stabilize the Shadow matrix on the projection if (shadow.StabilizationMode == LightShadowMapStabilizationMode.ProjectionSnapping) { var shadowPixelPosition = viewProjectionMatrix.TranslationVector * lightShadowMap.Size * 0.5f; // shouln't it be scale and not translation ? shadowPixelPosition.Z = 0; var shadowPixelPositionRounded = new Vector3(MathF.Round(shadowPixelPosition.X), MathF.Round(shadowPixelPosition.Y), 0.0f); var shadowPixelOffset = new Vector4(shadowPixelPositionRounded - shadowPixelPosition, 0.0f); shadowPixelOffset *= 2.0f / lightShadowMap.Size; projectionMatrix.Row4 += shadowPixelOffset; Matrix.Multiply(ref viewMatrix, ref projectionMatrix, out viewProjectionMatrix); } shaderData.ViewMatrix[cascadeLevel] = viewMatrix; shaderData.ProjectionMatrix[cascadeLevel] = projectionMatrix; shaderData.DepthRange[cascadeLevel] = new Vector2(nearClip, farClip); ////////////////////// // Cascade splits in light space using depth: Store depth on first CascaderCasterMatrix in last column of each row shaderData.CascadeSplits[cascadeLevel] = MathUtil.Lerp(sourceView.NearClipPlane, sourceView.FarClipPlane, cascadeSplitRatios[cascadeLevel]); var shadowMapRectangle = lightShadowMap.GetRectangle(cascadeLevel); var cascadeTextureCoords = new Vector4((float)shadowMapRectangle.Left / lightShadowMap.Atlas.Width, (float)shadowMapRectangle.Top / lightShadowMap.Atlas.Height, (float)shadowMapRectangle.Right / lightShadowMap.Atlas.Width, (float)shadowMapRectangle.Bottom / lightShadowMap.Atlas.Height); shaderData.TextureCoords[cascadeLevel] = cascadeTextureCoords; //// Add border (avoid using edges due to bilinear filtering and blur) //var borderSizeU = VsmBlurSize / lightShadowMap.Atlas.Width; //var borderSizeV = VsmBlurSize / lightShadowMap.Atlas.Height; //cascadeTextureCoords.X += borderSizeU; //cascadeTextureCoords.Y += borderSizeV; //cascadeTextureCoords.Z -= borderSizeU; //cascadeTextureCoords.W -= borderSizeV; float leftX = (float)lightShadowMap.Size / lightShadowMap.Atlas.Width * 0.5f; float leftY = (float)lightShadowMap.Size / lightShadowMap.Atlas.Height * 0.5f; float centerX = 0.5f * (cascadeTextureCoords.X + cascadeTextureCoords.Z); float centerY = 0.5f * (cascadeTextureCoords.Y + cascadeTextureCoords.W); // Compute receiver view proj matrix Matrix adjustmentMatrix = Matrix.Scaling(leftX, -leftY, 1.0f) * Matrix.Translation(centerX, centerY, 0.0f); // Calculate View Proj matrix from World space to Cascade space Matrix.Multiply(ref viewProjectionMatrix, ref adjustmentMatrix, out shaderData.WorldToShadowCascadeUV[cascadeLevel]); // Allocate shadow render view var shadowRenderView = CreateRenderView(); shadowRenderView.RenderView = sourceView; shadowRenderView.ShadowMapTexture = lightShadowMap; shadowRenderView.Rectangle = shadowMapRectangle; shadowRenderView.View = viewMatrix; shadowRenderView.ViewSize = new Vector2(shadowMapRectangle.Width, shadowMapRectangle.Height); shadowRenderView.Projection = projectionMatrix; shadowRenderView.ViewProjection = viewProjectionMatrix; shadowRenderView.NearClipPlane = nearClip; shadowRenderView.FarClipPlane = farClip; // Add the render view for the current frame context.RenderSystem.Views.Add(shadowRenderView); } }
/// <summary> /// Called when the effect parameter value needs to be applied. /// </summary> /// <param name="context">The render context.</param> /// <remarks> /// <strong>Notes to Inheritors:</strong> Derived classes need to call <see cref="OnApply"/> of /// the base class to ensure that the effect parameter value is properly set. /// </remarks> protected override void OnApply(RenderContext context) { SetValue(Parameter, Value); }
public override void Draw(RenderContext context) { foreach (var associatedData in ComponentDatas.Values) { if (!associatedData.AudioEmitterComponent.Enabled) { if (associatedData.IsPlaying) { //stop any running instance associatedData.IsPlaying = false; foreach (var controller in associatedData.AudioEmitterComponent.SoundToController.Values) { foreach (var instanceListener in controller.InstanceToListener) { instanceListener.Key.Stop(); } } } continue; } var emitter = associatedData.AudioEmitter; emitter.WorldTransform = associatedData.TransformComponent.WorldMatrix; var pos = emitter.WorldTransform.TranslationVector; // First update the emitter data if required. emitter.Velocity = pos - emitter.Position; emitter.Position = pos; // TODO: if the entity has just been added, it might crash because part of the Transform update is done at the Draw and we might have uninitialized values if (emitter.WorldTransform == Matrix.Zero) { return; } emitter.Forward = Vector3.Normalize((Vector3)emitter.WorldTransform.Row3); emitter.Up = Vector3.Normalize((Vector3)emitter.WorldTransform.Row2); // Then apply 3D localization foreach (var controller in associatedData.AudioEmitterComponent.SoundToController.Values) { //deal normal instances foreach (var instanceListener in controller.InstanceToListener) { if (!instanceListener.Value.Enabled) { instanceListener.Key.Stop(); continue; } // Apply3D localization if (instanceListener.Key.PlayState == PlayState.Playing) { instanceListener.Key.Apply3D(emitter); } //Apply parameters if (instanceListener.Key.Volume != controller.Volume) { instanceListener.Key.Volume = controller.Volume; // ensure that instance volume is valid } if (instanceListener.Key.IsLooping != controller.IsLooping) { instanceListener.Key.IsLooping = controller.IsLooping; } //Play if stopped if (instanceListener.Key.PlayState != PlayState.Playing && controller.ShouldBePlayed) { instanceListener.Key.Apply3D(emitter); instanceListener.Key.Play(); associatedData.IsPlaying = true; } } controller.ShouldBePlayed = false; //handle Play and forget instances for (var i = 0; i < controller.FastInstances.Count; i++) { var instance = controller.FastInstances[i]; if (instance.PlayState != PlayState.Playing) { //Decrement the loop counter to iterate this index again, since later elements will get moved down during the remove operation. controller.FastInstances.RemoveAt(i--); controller.DestroySoundInstance(instance); } else { instance.Apply3D(emitter); } } //Create new play and forget instances if (controller.FastInstancePlay) { foreach (var listeners in audioSystem.Listeners) { if (!listeners.Key.Enabled) { continue; } var instance = controller.CreateSoundInstance(listeners.Key, true); if (instance == null) { continue; } instance.Volume = controller.Volume; instance.Pitch = controller.Pitch; instance.Apply3D(emitter); instance.Play(); controller.FastInstances.Add(instance); } controller.FastInstancePlay = false; } } } }
/// <summary> /// Called when the effect parameter value needs to be updated. /// </summary> /// <param name="context">The render context.</param> /// <remarks> /// <strong>Notes to Inheritors:</strong> It is not necessary to call <see cref="OnUpdate"/> of /// the base class in derived classes. /// </remarks> protected override void OnUpdate(RenderContext context) { }
public async Task Invoke(RenderContext context) { FrontContext kooboocontext = new FrontContext(); context.SetItem <FrontContext>(kooboocontext); kooboocontext.RenderContext = context; if (context.WebSite != null) { if (!Kooboo.Web.Security.AccessControl.HasWebsiteAccess(context.WebSite, context)) { if (!CheckIsBackEndOrImageUrl(kooboocontext.RenderContext.Request.RelativeUrl)) { if (context.User == null) { context.Response.Redirect(302, "/_admin/account/login?type=site&returnurl=" + System.Web.HttpUtility.UrlEncode(context.Request.RawRelativeUrl)); context.Response.End = true; return; } else { context.Response.Redirect(302, Kooboo.DataConstants.Default403Page); context.Response.End = true; return; } } } if (kooboocontext.RenderContext.IsSiteBinding || !CheckIsBackEndOrImageUrl(kooboocontext.RenderContext.Request.RelativeUrl)) { ObjectRoute.Parse(kooboocontext); if (kooboocontext.Route != null && kooboocontext.Route.objectId != default(Guid)) { await ExecuteKooboo(kooboocontext); return; } } if (kooboocontext.Route == null && !String.IsNullOrEmpty(kooboocontext.WebSite.LocalRootPath)) { await Next.Invoke(context); return; } if (!CheckIsBackEndOrImageUrl(kooboocontext.RenderContext.Request.RelativeUrl)) { if (kooboocontext.Route == null || kooboocontext.Route.objectId == default(Guid)) { if (kooboocontext.SiteDb.WebSite.ContinueDownload) { if (Data.AppSettings.IsOnlineServer && !Kooboo.Web.Security.ActionControl.CanServerDownloadMorePages(kooboocontext.SiteDb, kooboocontext.RenderContext.Request.RelativeUrl)) { kooboocontext.RenderContext.Response.StatusCode = 402; var errorbody = await WebSiteService.RenderCustomError(kooboocontext, 402); if (!string.IsNullOrWhiteSpace(errorbody)) { kooboocontext.RenderContext.Response.Body = System.Text.Encoding.UTF8.GetBytes(errorbody); } return; } else { var continuedownload = await TransferManager.continueDownload(kooboocontext.SiteDb, kooboocontext.RenderContext.Request.RawRelativeUrl); if (continuedownload != null) { ObjectRoute.Parse(kooboocontext); } } } } if (kooboocontext.Route != null && kooboocontext.Route.objectId != default(Guid)) { await ExecuteKooboo(kooboocontext); return; } else { kooboocontext.RenderContext.Response.StatusCode = 404; var errorbody = await WebSiteService.RenderCustomError(kooboocontext, 404); if (!string.IsNullOrWhiteSpace(errorbody)) { kooboocontext.RenderContext.Response.Body = System.Text.Encoding.UTF8.GetBytes(errorbody); } return; } } else { // reensure siteid... in case of the same url used for login. var siteid = Kooboo.Data.Context.WebServerContext.RequestSiteId(context.Request); if (siteid != kooboocontext.RenderContext.WebSite.Id) { var site = Kooboo.Data.GlobalDb.WebSites.Get(siteid); if (site != null) { kooboocontext.WebSite = site; } } } } if (RenderThumbnail(kooboocontext)) { return; } // access control for allow users... await Next.Invoke(context); }
public string GetDisplayName(RenderContext Context) { return(Hardcoded.GetValue("Events", Context)); }
private void PaintTab(int index, RenderContext renderContext) { bool Selected = (SelectedIndex == index); Rectangle tabRect = GetTabRect(index); if ((Appearance & TabAppearance.Normal) == TabAppearance.Normal) { tabRect.Inflate(0, Selected ? 2 : 1); tabRect.X += 1; } PaletteState State = default(PaletteState); if (Selected) { State = PaletteState.Pressed; } else { State = tabRect.Contains(PointToClient(MousePosition)) ? PaletteState.Tracking : PaletteState.Normal; } VisualOrientation visualOrientation = (VisualOrientation)Alignment; if (m_PaletteTabButtonBackground.GetBackDraw(State) == InheritBool.True) { using (GraphicsPath BackPath = m_Renderer.RenderStandardBorder.GetBackPath(renderContext, tabRect, m_PaletteTabButtonBorder, visualOrientation, State)) { m_MementoTabButtonBackground = m_Renderer.RenderStandardBack.DrawBack(renderContext, tabRect, BackPath, m_PaletteTabButtonBackground, visualOrientation, State, m_MementoTabButtonBackground); } } if (m_PaletteTabButtonBorder.GetBorderDraw(State) == InheritBool.True) { m_Renderer.RenderStandardBorder.DrawBorder(renderContext, tabRect, m_PaletteTabButtonBorder, visualOrientation, State); } else if (Selected) { using (Pen PBorder = new Pen(m_PaletteTabPageBorder.GetBorderColor1(PaletteState.Normal))) { Rectangle RBorder = tabRect; RBorder.Width -= 1; renderContext.Graphics.DrawRectangle(PBorder, RBorder); } } // (TODO: adjust rendering for other Appearance settings) if (ImageList != null) { Image tabImage = null; if (TabPages[index].ImageIndex != -1) { int imageIndex = TabPages[index].ImageIndex; tabImage = ImageList.Images[imageIndex]; } else if (TabPages[index].ImageKey != null) { string imageKey = TabPages[index].ImageKey; tabImage = ImageList.Images[imageKey]; } if (tabImage != null) { int x = tabRect.X + (tabImage.Width / 2); int y = tabRect.Y + (tabRect.Height - tabImage.Height) / 2; renderContext.Graphics.DrawImage(tabImage, x, y); tabRect.X += tabImage.Width; tabRect.Width -= tabImage.Width; } } if (m_TabFont == null || (!object.ReferenceEquals(m_TabFont, g_TabFontBold) & !object.ReferenceEquals(m_TabFont, g_TabFontRegular))) { if (renderContext.Graphics.MeasureString(TabPages[index].Text, g_TabFontBold, tabRect.X, g_StringFormat).Width <= tabRect.Width) { m_TabFont = g_TabFontBold; } else { m_TabFont = g_TabFontRegular; } } renderContext.Graphics.DrawString(TabPages[index].Text, m_TabFont, m_TabBrush, tabRect, g_StringFormat); }
private Vector2 ComputeCascadeSplits(RenderContext context, RenderView sourceView, ref LightShadowMapTexture lightShadowMap) { var shadow = (LightDirectionalShadowMap)lightShadowMap.Shadow; var cameraNear = sourceView.NearClipPlane; var cameraFar = sourceView.FarClipPlane; var cameraRange = cameraFar - cameraNear; var minDistance = cameraNear + LightDirectionalShadowMap.DepthRangeParameters.DefaultMinDistance; var maxDistance = cameraNear + LightDirectionalShadowMap.DepthRangeParameters.DefaultMaxDistance; if (shadow.DepthRange.IsAutomatic) { minDistance = Math.Max(sourceView.MinimumDistance, cameraNear); maxDistance = Math.Max(sourceView.MaximumDistance, minDistance); if (lightShadowMap.CurrentMinDistance <= 0) { lightShadowMap.CurrentMinDistance = minDistance; } if (lightShadowMap.CurrentMaxDistance <= 0) { lightShadowMap.CurrentMaxDistance = maxDistance; } // Increase the maximum depth in small logarithmic steps, decrease it in larger logarithmic steps var threshold = maxDistance > lightShadowMap.CurrentMaxDistance ? DepthIncreaseThreshold : DepthDecreaseThreshold; maxDistance = lightShadowMap.CurrentMaxDistance = LogCeiling(maxDistance / lightShadowMap.CurrentMaxDistance, threshold) * lightShadowMap.CurrentMaxDistance; // Increase/decrease the distance between maximum and minimum depth in small/large logarithmic steps var range = maxDistance - minDistance; var currentRange = lightShadowMap.CurrentMaxDistance - lightShadowMap.CurrentMinDistance; threshold = range > currentRange ? DepthIncreaseThreshold : DepthDecreaseThreshold; minDistance = maxDistance - LogCeiling(range / currentRange, threshold) * currentRange; minDistance = lightShadowMap.CurrentMinDistance = Math.Max(minDistance, cameraNear); } else { minDistance = cameraNear + shadow.DepthRange.ManualMinDistance; maxDistance = cameraNear + shadow.DepthRange.ManualMaxDistance; } var manualPartitionMode = shadow.PartitionMode as LightDirectionalShadowMap.PartitionManual; var logarithmicPartitionMode = shadow.PartitionMode as LightDirectionalShadowMap.PartitionLogarithmic; if (logarithmicPartitionMode != null) { var minZ = minDistance; var maxZ = maxDistance; var range = maxZ - minZ; var ratio = maxZ / minZ; var logRatio = MathUtil.Clamp(1.0f - logarithmicPartitionMode.PSSMFactor, 0.0f, 1.0f); for (int cascadeLevel = 0; cascadeLevel < lightShadowMap.CascadeCount; ++cascadeLevel) { // Compute cascade split (between znear and zfar) float distrib = (float)(cascadeLevel + 1) / lightShadowMap.CascadeCount; float logZ = (float)(minZ * Math.Pow(ratio, distrib)); float uniformZ = minZ + range * distrib; float distance = MathUtil.Lerp(uniformZ, logZ, logRatio); cascadeSplitRatios[cascadeLevel] = distance; } } else if (manualPartitionMode != null) { if (lightShadowMap.CascadeCount == 1) { cascadeSplitRatios[0] = minDistance + manualPartitionMode.SplitDistance1 * maxDistance; } else if (lightShadowMap.CascadeCount == 2) { cascadeSplitRatios[0] = minDistance + manualPartitionMode.SplitDistance1 * maxDistance; cascadeSplitRatios[1] = minDistance + manualPartitionMode.SplitDistance3 * maxDistance; } else if (lightShadowMap.CascadeCount == 4) { cascadeSplitRatios[0] = minDistance + manualPartitionMode.SplitDistance0 * maxDistance; cascadeSplitRatios[1] = minDistance + manualPartitionMode.SplitDistance1 * maxDistance; cascadeSplitRatios[2] = minDistance + manualPartitionMode.SplitDistance2 * maxDistance; cascadeSplitRatios[3] = minDistance + manualPartitionMode.SplitDistance3 * maxDistance; } } // Convert distance splits to ratios cascade in the range [0, 1] for (int i = 0; i < cascadeSplitRatios.Length; i++) { cascadeSplitRatios[i] = (cascadeSplitRatios[i] - cameraNear) / cameraRange; } return(new Vector2(minDistance, maxDistance)); }
protected override void OnRenderShadow(RenderContext context, DeviceContextProxy deviceContext) { }
/// <summary> /// Gets the current scene valid only from a rendering context. May be null. /// </summary> /// <param name="context">The context.</param> /// <returns>Xenko.Engine.SceneInstance.</returns> public static SceneInstance GetCurrent(RenderContext context) { return(context.Tags.Get(Current)); }
public sealed override void RenderShadow(RenderContext context, DeviceContextProxy deviceContext) { }
public sealed override void RenderCustom(RenderContext context, DeviceContextProxy deviceContext) { }
/// <summary> /// Perform rendering before child elements are rendered. /// </summary> /// <param name="context">Rendering context.</param> public override void RenderBefore(RenderContext context) { IPaletteRibbonBack paletteBorder; IPaletteRibbonBack paletteBack; // Are we a group inside a context tab? if (!string.IsNullOrEmpty(_ribbon.SelectedTab?.ContextName)) { ElementState = _viewGroup.Pressed ? PaletteState.Pressed : _viewGroup.Tracking ? PaletteState.ContextTracking : PaletteState.ContextNormal; } else { ElementState = _viewGroup.Pressed ? PaletteState.Pressed : _viewGroup.Tracking ? PaletteState.Tracking : PaletteState.Normal; } // Decide on the palette to use switch (State) { case PaletteState.Pressed: paletteBorder = _ribbon.StatePressed.RibbonGroupCollapsedFrameBorder; paletteBack = _ribbon.StatePressed.RibbonGroupCollapsedFrameBack; break; case PaletteState.ContextNormal: paletteBorder = _ribbon.StateContextNormal.RibbonGroupCollapsedFrameBorder; paletteBack = _ribbon.StateContextNormal.RibbonGroupCollapsedFrameBack; break; case PaletteState.ContextTracking: paletteBorder = _ribbon.StateContextTracking.RibbonGroupCollapsedFrameBorder; paletteBack = _ribbon.StateContextTracking.RibbonGroupCollapsedFrameBack; break; case PaletteState.Tracking: paletteBorder = _ribbon.StateTracking.RibbonGroupCollapsedFrameBorder; paletteBack = _ribbon.StateTracking.RibbonGroupCollapsedFrameBack; break; case PaletteState.Normal: default: paletteBorder = _ribbon.StateNormal.RibbonGroupCollapsedFrameBorder; paletteBack = _ribbon.StateNormal.RibbonGroupCollapsedFrameBack; break; } // The background is slightly inside the rounded border Rectangle backRect = ClientRectangle; backRect.Inflate(-1, -1); // Draw the background for the group image area _memento1 = context.Renderer.RenderRibbon.DrawRibbonBack(_ribbon.RibbonShape, context, backRect, State, paletteBack, VisualOrientation.Top, false, _memento1); // Draw the border around the group image area _memento2 = context.Renderer.RenderRibbon.DrawRibbonBack(_ribbon.RibbonShape, context, ClientRectangle, State, paletteBorder, VisualOrientation.Top, false, _memento2); // If we have an image for drawing if (_ribbonGroup.Image != null) { // Determine the rectangle for the fixed size of image drawing Rectangle drawRect = new Rectangle(new Point(ClientLocation.X + IMAGE_OFFSET_X, ClientLocation.Y + _offsetY), _imageSize); context.Graphics.DrawImage(_ribbonGroup.Image, drawRect); } }
protected override void OnUpdatePerModelStruct(ref PointLineModelStruct model, RenderContext context) { model.World = ModelMatrix; model.HasInstances = InstanceBuffer == null ? 0 : InstanceBuffer.HasElements ? 1 : 0; model.BoolParams.X = FixedSize; var type = billboardBuffer.Type; model.Params.X = (int)type; }
protected override void DrawCore(RenderContext context) { var originalColorBuffer = GetSafeInput(0); var originalDepthBuffer = GetSafeInput(1); var outputTexture = GetSafeOutput(0); if (configurationDirty) { SetupTechnique(); } // Preparation phase: create different downscaled versions of the original image, later needed by the bokeh blur shaders. // TODO use ImageMultiScaler instead? downscaledSources.Clear(); // First we linearize the depth and compute the CoC map based on the user lens configuration. // Render target will contain "CoC"(16 bits) "Linear depth"(16bits). var cocLinearDepthTexture = GetScopedRenderTarget(originalColorBuffer.Description, 1f, PixelFormat.R16G16_Float); var farPlane = context.Parameters.Get(CameraKeys.FarClipPlane); var depthAreas = DOFAreas; if (AutoFocus) { // TODO replace this by physical camera parameters (aperture, focus distance...) var diffToTarget = (autoFocusDistanceTarget - autoFocusDistanceCurrent); var absDiff = Math.Abs(diffToTarget); var maxAmplitude = farPlane * 0.2f; if (absDiff > maxAmplitude) { diffToTarget = diffToTarget / absDiff * maxAmplitude; } autoFocusDistanceCurrent = autoFocusDistanceCurrent + 0.1f * diffToTarget; if (autoFocusDistanceCurrent < 1f) { autoFocusDistanceCurrent = 1f; } depthAreas = new Vector4(0.5f, autoFocusDistanceCurrent, autoFocusDistanceCurrent, autoFocusDistanceCurrent + farPlane * 0.5f); } coclinearDepthMapEffect.SetInput(0, originalDepthBuffer); coclinearDepthMapEffect.SetOutput(cocLinearDepthTexture); coclinearDepthMapEffect.Parameters.Set(CircleOfConfusionKeys.depthAreas, depthAreas); coclinearDepthMapEffect.Draw(context, "CoC_LinearDepth"); if (AutoFocus) { // Reads the center depth of the previous frame and use it as a new target // TODO single pixel is really small, average some disk area instead? pointDepthShader.Parameters.Set(PointDepthKeys.Coordinate, new Vector2(0.5f, 0.5f)); pointDepthShader.SetInput(cocLinearDepthTexture); pointDepthShader.SetOutput(depthCenter1x1); pointDepthShader.Draw("Center Depth"); depthReadBack.Draw("Center_Depth_Readback"); var centerDepth = depthReadBack.Result[0]; autoFocusDistanceTarget = centerDepth; } // Find the smallest downscale we should go down to. var maxDownscale = 0; foreach (var cocLevel in cocLevels) { if (cocLevel.downscaleFactor > maxDownscale) { maxDownscale = cocLevel.downscaleFactor; } } // Create a series of downscale, with anti-bleeding treatment for (int i = 0; i <= maxDownscale; i++) { var downSizedTexture = originalColorBuffer; if (i > 0) { downSizedTexture = GetScopedRenderTarget(originalColorBuffer.Description, 1f / (float)Math.Pow(2f, i), originalColorBuffer.Description.Format); textureScaler.SetInput(0, downscaledSources[i - 1]); textureScaler.SetOutput(downSizedTexture); textureScaler.Draw(context, "DownScale_Factor{0}", i); } downscaledSources[i] = downSizedTexture; } // We create a blurred version of the CoC map. // This is useful to avoid silhouettes appearing when the CoC changes abruptly. var blurredCoCTexture = NewScopedRenderTarget2D(cocLinearDepthTexture.Description); cocMapBlur.Radius = 6f / 720f * cocLinearDepthTexture.Description.Height; // 6 pixels at 720p cocMapBlur.SetInput(0, cocLinearDepthTexture); cocMapBlur.SetOutput(blurredCoCTexture); cocMapBlur.Draw(context, "CoC_BlurredMap"); // Creates all the levels with different CoC strengths. // (Skips level with CoC 0 which is always the original buffer.) combineLevelsEffect.Parameters.Set(CombineLevelsFromCoCKeys.LevelCount, cocLevels.Count); combineLevelsEffect.SetInput(0, cocLinearDepthTexture); combineLevelsEffect.SetInput(1, blurredCoCTexture); combineLevelsEffect.SetInput(2, originalColorBuffer); combineLevelsFrontEffect.Parameters.Set(CombineLevelsFromCoCKeys.LevelCount, cocLevels.Count); combineLevelsFrontEffect.SetInput(0, cocLinearDepthTexture); combineLevelsFrontEffect.SetInput(1, blurredCoCTexture); combineLevelsFrontEffect.SetInput(2, originalColorBuffer); float previousCoC = 0f; for (int i = 1; i < cocLevels.Count; i++) { // We render a blurred version of the original scene into a downscaled render target. // Blur strength depends on the current level CoC value. var levelConfig = cocLevels[i]; var textureToBlur = downscaledSources[levelConfig.downscaleFactor]; float downscaleFactor = 1f / (float)(Math.Pow(2f, levelConfig.downscaleFactor)); var blurOutput = GetScopedRenderTarget(originalColorBuffer.Description, downscaleFactor, originalColorBuffer.Description.Format); var blurOutputFront = NewScopedRenderTarget2D(blurOutput.Description); float blurRadius = (MaxBokehSize * BokehSizeFactor) * levelConfig.CoCValue * downscaleFactor * originalColorBuffer.Width; if (blurRadius < 1f) { blurRadius = 1f; } //--------------------------------- // Far out-of-focus //--------------------------------- // Pre-process the layer for the current CoC // This removes areas which might wrongly bleed into our image when blurring. var alphaTextureToBlur = NewScopedRenderTarget2D(textureToBlur.Description); thresholdAlphaCoC.Parameters.Set(ThresholdAlphaCoCKeys.CoCReference, previousCoC); thresholdAlphaCoC.Parameters.Set(ThresholdAlphaCoCKeys.CoCCurrent, levelConfig.CoCValue); thresholdAlphaCoC.SetInput(0, textureToBlur); thresholdAlphaCoC.SetInput(1, cocLinearDepthTexture); thresholdAlphaCoC.SetOutput(alphaTextureToBlur); thresholdAlphaCoC.Draw(context, "Alphaize_Far_{0}", i); textureToBlur = alphaTextureToBlur; // TODO Quality up: make the opaque areas "bleed" into the areas we just made transparent // Apply the bokeh blur effect BokehBlur levelBlur = levelConfig.blurEffect; levelBlur.CoCStrength = levelConfig.CoCValue; levelBlur.Radius = blurRadius; // This doesn't generate garbage if the radius value doesn't change. levelBlur.SetInput(0, textureToBlur); levelBlur.SetOutput(blurOutput); levelBlur.Draw(context, "CoC_LoD_Layer_Far_{0}", i); combineLevelsEffect.SetInput(i + 2, blurOutput); //--------------------------------- // Near out-of-focus //--------------------------------- // Negates CoC values and makes background objects transparent thresholdAlphaCoCFront.Parameters.Set(ThresholdAlphaCoCFrontKeys.CoCReference, previousCoC); thresholdAlphaCoCFront.Parameters.Set(ThresholdAlphaCoCFrontKeys.CoCCurrent, levelConfig.CoCValue); thresholdAlphaCoCFront.SetInput(0, downscaledSources[levelConfig.downscaleFactor]); thresholdAlphaCoCFront.SetInput(1, cocLinearDepthTexture); thresholdAlphaCoCFront.SetOutput(alphaTextureToBlur); thresholdAlphaCoCFront.Draw(context, "Alphaize_Near_{0}", i); textureToBlur = alphaTextureToBlur; // Apply the bokeh blur effect levelBlur.SetInput(0, textureToBlur); levelBlur.SetOutput(blurOutputFront); levelBlur.Draw(context, "CoC_LoD_Layer_Near_{0}", i); combineLevelsFrontEffect.SetInput(i + 2, blurOutputFront); previousCoC = levelConfig.CoCValue; } // Far out-of-focus: each pixel, depending on its CoC, interpolates its color from // the original color buffer and blurred buffer(s). combineLevelsEffect.Parameters.Set(CombineLevelsFromCoCShaderKeys.CoCLevelValues, combineShaderCocLevelValues); combineLevelsEffect.SetOutput(outputTexture); combineLevelsEffect.Draw(context, "CoCLevelCombineInterpolation"); // Finally add front out-of-focus objects on the top of the scene // TODO Quality up: instead of merging all the layers for each pixel, merge only // the relevant layer(s) closest to the pixel CoC. GraphicsDevice.SetBlendState(GraphicsDevice.BlendStates.AlphaBlend); combineLevelsFrontEffect.SetOutput(outputTexture); combineLevelsFrontEffect.Draw(context, "CoCLevelCombineInterpolationFront"); GraphicsDevice.SetBlendState(GraphicsDevice.BlendStates.Default); // Release any reference downscaledSources.Clear(); }
protected override void OnRenderCustom(RenderContext context, DeviceContextProxy deviceContext, ShaderPass shaderPass) { BindBillboardTexture(deviceContext, DefaultShaderPass.PixelShader); base.OnRenderCustom(context, deviceContext, shaderPass); }
/// <summary> /// Called when [update per model structure]. /// </summary> /// <param name="model">The model.</param> /// <param name="context">The context.</param> protected override void OnUpdatePerModelStruct(ref PointLineModelStruct model, RenderContext context) { model.World = ModelMatrix; model.HasInstances = InstanceBuffer == null ? 0 : InstanceBuffer.HasElements ? 1 : 0; model.BoolParams.X = HasTexture; FrameVariables.RandomVector = VectorGenerator.RandomVector3; }