Custom vertex data and effect problem

First Im using the crossplatform template on windows. Second really stink with shaders in monogame.

What im trying to do is draw a custom vertex quad and shade it with a simple effect Not a basic effect but one loaded in from the content manager.

Question while this builds, why wont it work.
im getting varying shades of blue depending on the value * .55 but no image at all

sampler TextureSampler : register(s0);
Texture2D myTex2D;

float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float2 texCoord : TEXCOORD0) : SV_TARGET0
{
float4 tex;
tex = myTex2D.Sample(TextureSampler, color1) *.55;
return tex;
}
technique Technique1
{
pass Pass1
{
PixelShader = compile ps_3_0 PixelShaderFunction();
}
}

    public void DrawShaded(GameTime gameTime)
    {
        // cant pass a texture to a regular effect ?
        //TestEffectB.Parameters["myTex2D"].SetValue(_tex2d);
        // set the render target clear it
        GraphicsDevice.SetRenderTarget(_renderTarget);
        GraphicsDevice.Clear(Color.CornflowerBlue);
        // draw quad
        foreach (EffectPass pass in _basicEffect.CurrentTechnique.Passes)
        {
            pass.Apply();
            GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, _vertices, 0, 4, _indices, 0, 2);
        }
        // set and clear the screen target
        GraphicsDevice.SetRenderTarget(null) ;
        GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.CornflowerBlue);
        // alter it with spritebatch and the effect shader
        _spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
        TestEffectB.CurrentTechnique.Passes[0].Apply();
        _spriteBatch.Draw(_renderTarget, new Vector2(0, 0), Color.White);
        _spriteBatch.End();
        base.Draw(gameTime);
    }

Now i can use a basic effect to draw the texture to a custom vertex quad but if i try to use a effect that i load in myself. I just can’t get it to work. In the above if i change the code in the shader, my screen just alters the entire shade of blue blackground.

Further i can’t seem to pass a texture using a parameter to a effect directly.
TestEffectB.Parameters[“myTex2D”].SetValue(_tex2d); // errors out.
^ i could do this in xna.

Which makes no sense because i can pass in a matrix.
Though even this monogame generated .fx has a problem, its drawing everything red

public void DrawEffectA(GameTime gameTime)
{
//TestEffectA.Parameters[“myTex2D”].SetValue(_tex2d);
TestEffectA.Parameters[“WorldViewProjection”].SetValue(_worldviewprojection);
GraphicsDevice.Clear(Color.CornflowerBlue);
foreach (EffectPass pass in TestEffectA.CurrentTechnique.Passes)
{
pass.Apply();
GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, _vertices, 0, 4, _indices, 0, 2);
}
base.Draw(gameTime);
}

Where is a code sample when ya need one lol.

I never could get a effect to work on custom vertex data and it seems i cant even cheat my way around it by rendering to a target and then shading but
What i really want is to alter the custom vertex positions themselves in the vertex shader. Does anyone have a simple dumbed down example of how to do this with a quad.

    private VertexPositionNormalTexture[] _vertices;
    private int[] _indices;
    private RenderTarget2D _renderTarget;
    private void CreateQuad()
    {
        _vertices = new VertexPositionNormalTexture[4];
        _vertices[0].Position = new Vector3(-0.5f, -0.5f, 0f);
        _vertices[0].TextureCoordinate = new Vector2(0f, 1f);
        _vertices[0].Normal = Vector3.Backward;
        _vertices[1].Position = new Vector3(-0.5f, 0.5f, 0f);
        _vertices[1].TextureCoordinate = new Vector2(0f, 0f);
        _vertices[1].Normal = Vector3.Backward;
        _vertices[2].Position = new Vector3(0.5f, -0.5f, 0f);
        _vertices[2].TextureCoordinate = new Vector2(1f, 1f);
        _vertices[2].Normal = Vector3.Backward;
        _vertices[3].Position = new Vector3(0.5f, 0.5f, 0f);
        _vertices[3].TextureCoordinate = new Vector2(1f, 0f);
        _vertices[3].Normal = Vector3.Backward;
        _indices = new int[6];
        _indices[0] = 0;
        _indices[1] = 1;
        _indices[2] = 2;
        _indices[3] = 2;
        _indices[4] = 1;
        _indices[5] = 3;
    }
}

(1) You don’t need to use a render target here.
(2) Your vertex type is VertexPositionNormalTexture. You need a vertex shader in your HLSL file that accepts a vertex with those attributes as input and outputs the data necessary for the pixel shader’s input.
(3) Check the compiled HLSL code (.mgfxo file) to see what the parameter names are available to use via C# code. You can compile it by hand on Windows using 2MGFX.exe.

Hi,
Where is your Vertex Shader for drawing the quad? :smiley:
You need it when you want to render a quad without using a spritebatch.

Check the compiled HLSL code (.mgfxo file) to see what the parameter names are available to use via C# code.

Do you mean the shaders xnb file that is compiled looking within it the contents of which are unintelligiable to me. Im not sure i know what you mean here.

You can compile it by hand on Windows using 2MGFX.exe

I have never been able to successfully manually do this in the past without errors.
As well doesn’t the pipeline tool simply call the 2mgfx.exe to build the effect.

I fear i would need a lot more information.

Based on the .fx Generated by the MonoGame Pipeline tool itself. Its the same problem →
I cannot pass a texture into the effect i cannot find a single example after even searching for hours of how to do this not even a skeleton code version.

shader

 #if OPENGL
     #define SV_POSITION POSITION
     #define VS_SHADERMODEL vs_3_0
     #define PS_SHADERMODEL ps_3_0
 #else
     #define VS_SHADERMODEL vs_4_0_level_9_1
     #define PS_SHADERMODEL ps_4_0_level_9_1
 #endif
 matrix WorldViewProjection;
 sampler TextureSampler : register(s0);
 Texture2D  myTex2D;
 struct VertexShaderInput
 {
     float4 Position : SV_POSITION;
     float4 Color : COLOR0;
 };
 struct VertexShaderOutput
 {
     float4 Position : SV_POSITION;
     float4 Color : COLOR0;
 };
 VertexShaderOutput MainVS(in VertexShaderInput input)
 {
     VertexShaderOutput output = (VertexShaderOutput)0;
     output.Position = mul(input.Position, WorldViewProjection);
     output.Color = input.Color;
     return output;
 }
 float4 MainPS(VertexShaderOutput input) : COLOR
 {
     return input.Color;
 }
 technique BasicColorDrawing
 {
     pass P0
     {
         VertexShader = compile VS_SHADERMODEL MainVS();
         PixelShader = compile PS_SHADERMODEL MainPS();
     }
 };

code

I can not pass in the texture to a Effect ???

This actually draws a red square were the texture should be.

public void DrawEffectA(GameTime gameTime)
{

        // when uncommented 
        // the compiler errors on the below with a null error
        // but i don't see why
        //TestEffectA.Parameters["myTex2D"].SetValue(_tex2d);
        TestEffectA.Parameters["WorldViewProjection"].SetValue(_worldviewprojection);
        GraphicsDevice.Clear(Color.CornflowerBlue);
        foreach (EffectPass pass in TestEffectA.CurrentTechnique.Passes)
        {
            pass.Apply();
            GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, _vertices, 0, 4, _indices, 0, 2);
        }
        base.Draw(gameTime);
    }

But i can to a BasicEffect ?

if i change the TestEffect to a BasicEffect the above code will allow a texture.

basicEffect TestEffectA; // instead of Effect TestEffectA; then loading the .fx

as shown below i can set the texture to a basic effect

private void SetupBasicEffect(BasicEffect b)
{
b.World = Matrix.Identity;
b.View = _view;
b.Projection = _projection;
b.TextureEnabled = true;
b.Texture = _tex2d;
}

But it wont let me do the above for just a Effect ?
I can’t load a Effect from Content load as a BasicEffect either.

A basic effect is fine and all but i want to use a vertex shader on the custom vertex data like a quad with a texture and for the life of me i can’t see how to do it.
Not being able to send a texture to a effect is very limiting for custom vertex data if this is possible id love to see a simple barebones example.

This is what is in the compiled XNB file there is more but it doesn’t show up on the forum due to formating basically a bunch of null fields.

> XNBd в  zMicrosoft.Xna.Framework.Content.EffectReader, MonoGame.Framework, Version=3.6.0.1187, Culture=neutral, PublicKeyToken=null     R  MGFX ʘвуvs_uniforms_vec4@     Ж   #ifdef GL_ES
> precision mediump float;
> precision mediump int;
> #endif

> varying vec4 vFrontColor;
> #define ps_v0 vFrontColor
> #define ps_oC0 gl_FragColor

> void main()
> {
>     ps_oC0 = ps_v0;
> }

>    Й  #ifdef GL_ES
> precision highp float;
> precision mediump int;
> #endif

> uniform vec4 vs_uniforms_vec4[4];
> uniform vec4 posFixup;
> #define vs_c0 vs_uniforms_vec4[0]
> #define vs_c1 vs_uniforms_vec4[1]
> #define vs_c2 vs_uniforms_vec4[2]
> #define vs_c3 vs_uniforms_vec4[3]
> attribute vec4 vs_v0;
> #define vs_o0 gl_Position
> attribute vec4 vs_v1;
> varying vec4 vFrontColor;
> #define vs_o1 vFrontColor

> void main()
> {
>     vs_o0.x = dot(vs_v0, vs_c0);
>     vs_o0.y = dot(vs_v0, vs_c1);
>     vs_o0.z = dot(vs_v0, vs_c2);
>     vs_o0.w = dot(vs_v0, vs_c3);
>     vs_o1 = vs_v1;
>     gl_Position.y = gl_Position.y * posFixup.y;
>     gl_Position.xy += posFixup.zw * gl_Position.ww;
>     gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;
> }

>   vs_v0    vs_v1   WorldViewProjection                                                                    BasicColorDrawing P0 

This line is wrong, it should be …Sample(TextureSampler, texCoord) …

Otherwise the whole quad is one color, because your texture coordinate is wrong (you pass the color as texture coordinate)

with just the original pixel shader using the render target code

tex = myTex2D.Sample(TextureSampler, texCoord);

result black screen

tex = myTex2D.Sample(TextureSampler, texCoord) *.55;

result dark blue screen ?

same as if i use color1 as the variable;

If i try to integrate this at all with the vertex shader too i get a nothing but cornflower blue. Based on the monogame generated .fx below i tried to see if i could get either to show thru by combining inputs.
I really am a noob with the monogame pixel shader.
Though i could do this in xna by just assigning effect parameters i can’t seem to even hack around it.
It would make sense to me if i could pass a texture to a effect parameter.

i dunno i keep trying different stuff just can’t get it to work

> #if OPENGL
>     #define SV_POSITION POSITION
>     #define VS_SHADERMODEL vs_3_0
>     #define PS_SHADERMODEL ps_3_0
> #else
>     #define VS_SHADERMODEL vs_4_0_level_9_1
>     #define PS_SHADERMODEL ps_4_0_level_9_1
> #endif

matrix WorldViewProjection;

sampler TextureSampler : register(s0);
Texture2D myTex2D;

struct VertexShaderInput
{
float4 Position : SV_POSITION;
float4 Color : COLOR0;
//float2 texCoord : TEXCOORD // sheesh really
};

struct VertexShaderOutput
{
float4 Position : SV_POSITION;
float4 Color : COLOR0;
//float2 texCoord : TEXCOORD
};

VertexShaderOutput MainVS(in VertexShaderInput input)
{
VertexShaderOutput output = (VertexShaderOutput)0;

output.Position = mul(input.Position, WorldViewProjection);
output.Color = input.Color;
return output;

}

float4 MainPS(VertexShaderOutput input, float2 texCoord : TEXCOORD0) : SV_TARGET0
{
float4 tex;

tex = myTex2D.Sample(TextureSampler, texCoord.xy) * input.Color * .5;
return tex;
//return input.Color;

}

technique BasicColorDrawing
{
pass P0
{
VertexShader = compile VS_SHADERMODEL MainVS();
PixelShader = compile PS_SHADERMODEL MainPS();
}
}

code

private void SetupBasicEffect(BasicEffect b)
{
b.World = Matrix.Identity;
b.View = _view;
b.Projection = _projection;
b.TextureEnabled = true;
b.Texture = _tex2d;
}
public void DrawEffectAWithRT(GameTime gameTime)
{

        //TestEffectA.Parameters["myTex2D"].SetValue(_tex2d); //An unhandled exception of type 'System.NullReferenceException' occurred...

        // set the render target clear it
        GraphicsDevice.SetRenderTarget(_renderTarget);
        GraphicsDevice.Clear(Color.CornflowerBlue);
        // draw quad
        foreach (EffectPass pass in _basicEffect.CurrentTechnique.Passes)
        {
            pass.Apply();
            GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, _vertices, 0, 4, _indices, 0, 2);
        }
        // set and clear the screen target
        GraphicsDevice.SetRenderTarget(null);
        GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.CornflowerBlue);
        // alter it with spritebatch and the effect shader
        // _spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, SamplerState.PointClamp ,DepthStencilState.Default,RasterizerState.CullNone, TestEffectA, _worldviewprojection);// no difference grrrrrrr
        _spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
        TestEffectA.CurrentTechnique.Passes[0].Apply();
         // arrgggggg !!!!
        _spriteBatch.Draw(_renderTarget, new Vector2(0, 0), Color.White);
        _spriteBatch.End();
        base.Draw(gameTime);
    }

result Cornflower blue

sry am on mobile, hard to take a closer look. I’m not sure you need the #ifdefs for OpenGL, i thought monogame would translate any hlsl code

In the recent thread about 2D normals a Spritebatc shader is implemented, maybe look at that. In my bloom sample i also have some quad rendering, you can also check thar

If take a look at the compiled HLSL, the bottom of the file has the available parameters that can be accessed. So the texture field didn’t make the list as a parameter when compiled; probably optimized out because you were not using it in any pixel shader function.

Here’s my working simple shader that works with SpriteBatch (vertices of type VertexPositionColorTexture).

float4x4 WorldViewProjection;
Texture2D Texture : register(t0);
sampler TextureSampler : register(s0)
{
	Texture = (Texture);
};

struct VertexShaderInput
{
	float4 Position : POSITION0;
	float4 Color : COLOR0;
	float2 TexureCoordinate : TEXCOORD0;
};

struct VertexShaderOutput
{
	float4 Position : SV_Position;
	float4 Color : COLOR0;
	float2 TexureCoordinate : TEXCOORD0;
};

struct PixelShaderOutput
{
	float4 Color : COLOR0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
	VertexShaderOutput output;
	output.Position = mul(input.Position, WorldViewProjection);
	output.Color = input.Color;
	output.TexureCoordinate = input.TexureCoordinate;
	return output;
}

PixelShaderOutput PixelShaderFunction(VertexShaderOutput input)
{
	PixelShaderOutput output;
	output.Color = tex2D(TextureSampler, input.TexureCoordinate) * input.Color;
	return output;
}

technique
{
	pass
	{
		VertexShader = compile vs_2_0 VertexShaderFunction();
		PixelShader = compile ps_2_0 PixelShaderFunction();
	}
}

Running your test.

Well its drawing a little messed up but at least it renders in spritebatch.

The vs compiler doesn’t complain about the texture either under effect however now its saying its missing a parameter or something.

So this still wont work

public void DrawEffectA(GameTime gameTime)
{
//TestEffectA.Parameters[“myTex2D”].SetValue(_tex2d);

        TestEffectA.Parameters["Texture"].SetValue(_tex2d);
        TestEffectA.Parameters["WorldViewProjection"].SetValue(_worldviewprojection);
        GraphicsDevice.Clear(Color.CornflowerBlue);
        foreach (EffectPass pass in TestEffectA.CurrentTechnique.Passes)
        {
            pass.Apply();
            GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, _vertices, 0, 4, _indices, 0, 2);
        }
        base.Draw(gameTime);
    }

Which is what i really wanted.

The error is on drawUserIndexedPrimitives →

An unhandled exception of type ‘System.InvalidOperationException’ occurred in MonoGame.Framework.dll

Additional information: An error occurred while preparing to draw. This is probably because the current vertex declaration does not include all the elements required by the current vertex shader. The current vertex declaration

any idea why im getting that error ?

The vertex attributes needs to to match in the vertex shader with whatever you supply it. If you are using my example HLSL, the vertex shader is using a VertexPositionColorTexture with a position, color and texture coordinates as input attributes. It looks like you are using a VertexPositionNormalTexture with a position, normal and texture coordinates as input attributes. These do not match, hence the "This is probably because the current vertex declaration does not include all the elements required by the current vertex shader.

Lithium. Ah man im glad you swung by here that was right on the money.

probably optimized out because you were not using it in any pixel shader function.

That’s crazy, wow optimized.
I thinks we needs a DoNotOptimizeOut tag for the shaders lol.

Though there is still one more anomaly a pretty bad one that is very strange to me. But i dont think this is actually the shader messing this part up but it might be.

Question …

Does the spritebatch do something internally with the window bounds or something ?
Im getting what appears to be a super zoomed in result in the spriteBatch render target version of the call.

Re: Edit: its the camera setup.
How do i manually recreate the spritebatch camera using createLookAt ?

Using the regular call without the render target it looks like this which is proper in both dx and gl. the problem is shown below that.

public void DrawEffectA(GameTime gameTime)
{
TestEffectA.Parameters[“Texture”].SetValue(tex2d);
TestEffectA.Parameters[“WorldViewProjection”].SetValue(worldviewprojection);
GraphicsDevice.Clear(Color.CornflowerBlue);
foreach (EffectPass pass in TestEffectA.CurrentTechnique.Passes)
{
pass.Apply();
GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, 4, indices, 0, 2);
}
base.Draw(gameTime);
}

With the rendertarget version of the call in dx it looks like the below.
messing around with the camera translation manually. I realized its way zoomed in and translated to a strange position. Im pretty sure that’s just the corner of the image blown way up like a few pixels. Still testing.

With the gl version im not sure whats happening yet but all i see is blue screen.
This was run with the same code exactly in all four tests so there is at definitely some inconsistency. But i can only say for certain that it is unintended between the gl dx tests using the rt version. As im unsure if spritebatch is intentionally changing the view frustrum or how so under the hood vs by passing spritebatch.

Camera code is just basic place holder stuff here so something weird is going on.

> private void SetCameraOrientation()
>         {
>             // arrrrrgggg test
>             offset = new Vector3(graphics.GraphicsDevice.Viewport.Width * .5f, graphics.GraphicsDevice.Viewport.Height * .5f, 2);
>             Vector3 offsetb = offset;
>             offsetb.X = 0; // weird wth !

>             view = Matrix.CreateLookAt(offsetb, Vector3.Forward, Vector3.Up);

>             //view = Matrix.CreateLookAt(new Vector3(0, 0, 2), Vector3.Forward, Vector3.Up);

>             projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 4.0f / 3.0f, 1, 500);

>             worldviewprojection = Matrix.Identity * view * projection;

>         }

Re: edit: this fakes it kind of.
> private void SetCameraOrientation()
> {
> offset = new Vector3(graphics.GraphicsDevice.Viewport.Width * .5f, graphics.GraphicsDevice.Viewport.Height * .5f, -500f);
> Vector3 forward = new Vector3(offset.X, offset.Y, 0);
> view = Matrix.CreateLookAt(offset, forward, -Vector3.Up);
> projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver2, graphics.GraphicsDevice.DisplayMode.AspectRatio, 1f, 500);
> worldviewprojection = Matrix.Identity * view * projection;
> }

nothing major changed with the call…

    public void DrawEffectAWithRT(GameTime gameTime)
    {
        TestEffectA.Parameters["Texture"].SetValue(tex2d);
        TestEffectA.Parameters["WorldViewProjection"].SetValue(worldviewprojection);
        // set the render target clear it
        GraphicsDevice.SetRenderTarget(renderTarget);
        GraphicsDevice.Clear(Color.CornflowerBlue);
        // draw quad
        foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
        {
            pass.Apply();
            GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, 4, indices, 0, 2);
        }
        // set and clear the screen target
        GraphicsDevice.SetRenderTarget(null);
        GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.CornflowerBlue);
        // alter it with spritebatch and the effect shader
        //_spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone, TestEffectA, worldviewprojection);
        TestEffectA.CurrentTechnique.Passes[0].Apply();
        spriteBatch.Draw(renderTarget, new Vector2(0, 0), Color.White);
        //_spriteBatch.Draw(_renderTarget, new Vector2(-offset.X, offset.Y), Color.White);
        spriteBatch.End();
        base.Draw(gameTime);
    }

Use Matrix.Identity for both World and View and Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, -1f); for projection to match SpriteBatch.

ill try that
oh wait, wouldn’t that mess up the non spritebatch rendertarget draw?
Would i have to switch cameras between the rendertarget draw and the spritebatch ?
Though i suppose its kinda non sequitur if i can do it all with the first call now.

Re: It works on dx for both. Well with a little fov aspect ratio rigging i can get the non-rt call to look the same as the rt call (though its not close to properly mimicing it i just sort of spliced it in like that.) bout to test Gl now.

Edit Acckk The RenderTarget draw call version on GL only gives off a cornflower blue screen of death, the other one works though.

The primary topic objective problem is fulfilled solved, unless anyone knows why that isn’t working ill stop and take the opportunity to say

thanks for all your guys help.

Here’s the full game1 code. For Reference.

  //using System;
  //using System.Text;
  //using System.Collections.Generic;
  //using System.Linq;
  //using Microsoft.Xna.Framework;
  //using Microsoft.Xna.Framework.Graphics;
  //using Microsoft.Xna.Framework.Input;
  //namespace CustomVertexExperimentDX_dec_23_16
  //{
public class Game1 : Game
{
    public const float PI = (float)(Math.PI);
    public const float PI2 = (float)(Math.PI * 2.0d);
    public const float TODEGREES = 360.0f / PI2;
    public const float TORADIANS = PI2 / 360.0f;
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    private Texture2D tex2d;
    private Matrix view, projection;
    private Matrix worldviewprojection;
    private Matrix worldviewprojectionorthagonal;
    private VertexPositionColorTexture[] vertices;
    //private VertexPositionNormalTexture[] _vertices;
    private int[] indices;
    private RenderTarget2D renderTarget;
    private BasicEffect basicEffect;
    Effect TestEffectA;
    Vector3 offset = Vector3.Zero;
    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }
    protected override void Initialize()
    {
        base.Initialize();
    }
    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        SetCameraOrientation3D();
        SetCameraOrientationOrthagonal();
        CreateQuad();
        tex2d = Content.Load<Texture2D>("a_lookingood19");
        TestEffectA = Content.Load<Effect>("TestEffect");
        basicEffect = new BasicEffect(GraphicsDevice);
        SetupBasicEffect(basicEffect);
        renderTarget = new RenderTarget2D(GraphicsDevice,
            GraphicsDevice.PresentationParameters.BackBufferWidth,
            GraphicsDevice.PresentationParameters.BackBufferHeight,
            false,
            GraphicsDevice.PresentationParameters.BackBufferFormat,
            DepthFormat.Depth24);
    }
    protected override void UnloadContent()
    {
    }
    private void SetCameraOrientation3D() // just a hack for the test
    {
        view = Matrix.CreateLookAt(new Vector3(0, 0, 2), Vector3.Forward, Vector3.Up);
        projection = Matrix.CreatePerspectiveFieldOfView(TORADIANS * 28, GraphicsDevice.PresentationParameters.BackBufferWidth / GraphicsDevice.PresentationParameters.BackBufferHeight, 1, 500);
        //projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver2, graphics.GraphicsDevice.DisplayMode.AspectRatio, 1f, 500);
        worldviewprojection = Matrix.Identity * view * projection;
    }
    private void SetCameraOrientationOrthagonal()
    {
        view = Matrix.Identity;
        projection = Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, -1f);
        worldviewprojectionorthagonal = Matrix.Identity * view * projection;
    }
    private void SetupBasicEffect(BasicEffect f)
    {
        f.World = Matrix.Identity;
        f.View = view;
        f.Projection = projection;
        f.TextureEnabled = true;
        f.Texture = tex2d;
    }
    //private void SetupEffect(Effect f)
    //{
        //f.Parameters["Texture"].SetValue(tex2d);
        //f.Parameters["WorldViewProjection"].SetValue(worldviewprojection);
    //}
    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();
        base.Update(gameTime);
    }
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        //DrawEffectA(gameTime);
        DrawEffectAWithRT(gameTime);
        base.Draw(gameTime);
    }
    public void DrawEffectA(GameTime gameTime)
    {
        SetCameraOrientation3D();
        TestEffectA.Parameters["Texture"].SetValue(tex2d);
        TestEffectA.Parameters["WorldViewProjection"].SetValue(worldviewprojection);
        GraphicsDevice.Clear(Color.CornflowerBlue);
        foreach (EffectPass pass in TestEffectA.CurrentTechnique.Passes)
        {
            pass.Apply();
            // VertexPositionNormalTexture    VertexPositionColorTexture  bah dont need either
            GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, 4, indices, 0, 2);
        }
        base.Draw(gameTime);
    }
    public void DrawEffectAWithRT(GameTime gameTime)
    {
        SetCameraOrientationOrthagonal();
        TestEffectA.Parameters["Texture"].SetValue(tex2d);
        TestEffectA.Parameters["WorldViewProjection"].SetValue(worldviewprojectionorthagonal);
        // set the render target clear it
        GraphicsDevice.SetRenderTarget(renderTarget);
        GraphicsDevice.Clear(Color.CornflowerBlue);
        // draw quad
        foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
        {
            pass.Apply();
            GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, 4, indices, 0, 2);
        }
        // set and clear the screen target
        GraphicsDevice.SetRenderTarget(null);
        GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.CornflowerBlue);
        // alter it with spritebatch and the effect shader
        //_spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone, TestEffectA, worldviewprojection);
        TestEffectA.CurrentTechnique.Passes[0].Apply();
        //test
        spriteBatch.Draw(renderTarget, new Vector2(0, 0), Color.White);
        spriteBatch.End();
        base.Draw(gameTime);
    }
    private void CreateQuad()
    {
        //_vertices = new VertexPositionNormalTexture[4];
        vertices = new VertexPositionColorTexture[4];
        vertices[0].Position = new Vector3(-0.5f, -0.5f, 0f);
        //_vertices[0].Normal = Vector3.Backward;
        vertices[0].Color = Color.White;
        vertices[0].TextureCoordinate = new Vector2(0f, 1f);
        vertices[1].Position = new Vector3(-0.5f, 0.5f, 0f);
        //_vertices[1].Normal = Vector3.Backward;
        vertices[1].Color = Color.White;
        vertices[1].TextureCoordinate = new Vector2(0f, 0f);
        vertices[2].Position = new Vector3(0.5f, -0.5f, 0f);
        //_vertices[2].Normal = Vector3.Backward;
        vertices[2].Color = Color.White;
        vertices[2].TextureCoordinate = new Vector2(1f, 1f);
        vertices[3].Position = new Vector3(0.5f, 0.5f, 0f);
        //_vertices[3].Normal = Vector3.Backward;
        vertices[3].Color = Color.White;
        vertices[3].TextureCoordinate = new Vector2(1f, 0f);
        indices = new int[6];
        indices[0] = 0;
        indices[1] = 1;
        indices[2] = 2;
        indices[3] = 2;
        indices[4] = 1;
        indices[5] = 3;
    } 
}`

Lithiums testing shader

> // Lithiums shader Example
> #if OPENGL
> #define SV_POSITION POSITION
> #define VS_SHADERMODEL vs_2_0
> #define PS_SHADERMODEL ps_2_0
> #else
> #define VS_SHADERMODEL vs_4_0_level_9_1
> #define PS_SHADERMODEL ps_4_0_level_9_1
> #endif


> float4x4 WorldViewProjection;
> Texture2D Texture : register(t0);
> sampler TextureSampler : register(s0)
> {
>     Texture = (Texture);
> };

> struct VertexShaderInput
> {
>     float4 Position : POSITION0;
>     float4 Color : COLOR0;
>     float2 TexureCoordinate : TEXCOORD0;
> };

> struct VertexShaderOutput
> {
>     float4 Position : SV_Position;
>     float4 Color : COLOR0;
>     float2 TexureCoordinate : TEXCOORD0;
> };

> struct PixelShaderOutput
> {
>     float4 Color : COLOR0;
> };

> VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
> {
>     VertexShaderOutput output;
>     output.Position = mul(input.Position, WorldViewProjection);
>     output.Color = input.Color;
>     output.TexureCoordinate = input.TexureCoordinate;
>     return output;
> }

> PixelShaderOutput PixelShaderFunction(VertexShaderOutput input)
> {
>     PixelShaderOutput output;
>     output.Color = tex2D(TextureSampler, input.TexureCoordinate) * input.Color;
>     return output;
> }

> technique
> {
>     pass
>     {
>         VertexShader = compile VS_SHADERMODEL VertexShaderFunction();
>         PixelShader = compile PS_SHADERMODEL PixelShaderFunction();
>     }
> }

Hello everyone, sorry for old thread

I have problem with loading shader with color into vertices…

I really don’t know how do I write HLSL? I want only color from loading shader into passed vertices.

Thanks

Please make a new thread.

The above shader in this thread accepts vertices with color.
the line here shades the textures color with that vertice color.

output.Color = tex2D(TextureSampler, input.TexureCoordinate)*input.Color;

input.Color in the above is coming from the vertice.
This below would remove the texture color and leave only the vertices color.

output.Color = input.Color;

You can optionally create a global variable and pass it in and multiply by that to shade or recolor all the pixels.

float4x4 WorldViewProjection;
float4 ShadingColor;

// in the pixel shader function
output.Color = ShadingColor;
// or
// output.Color = input.Color * ShadingColor;

then

public void DrawEffectA(GameTime gameTime)
{
    SetCameraOrientation3D();
    TestEffectA.Parameters["Texture"].SetValue(tex2d);
    TestEffectA.Parameters["ShadingColor"].SetValue(Color.Red);

Argument 1: cannot convert from 'Microsoft.Xna.Framework.Color' to 'bool'

And I tried no success…

PS: Yeah - I have told you “I am sorry for old thread”.

// Edit: It means 4 different colors from HLSL-Shaders

Like this I made with OpenTK:

It is real original Shader from VertexShader:
private const string VertexSource =
@"#version 450 core
in vec3 position;
out vec3 colour;

    void main()
    {
        gl_Position = vec4(position, 1.0);
        colour = vec3(position.x + 0.5, 1.0, position.y + 0.5);
    }";

It is like example for 4 different colors in 4 corners to vertices.

But I have problem with MonoGame:
float4 ShadingColor;

struct VertexShaderInput
{
	float4 Position : POSITION0;
	float4 Color : COLOR0;
};

struct VertexShaderOutput
{
	float4 Position : SV_Position;
	float4 Color : COLOR0;
};

struct PixelShaderOutput
{
	float4 Color : COLOR0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
	VertexShaderOutput output;
	output.Position = input.Position;
	output.Color = input.Color;
	return output;
}

PixelShaderOutput PixelShaderFunction(VertexShaderOutput input)
{
	PixelShaderOutput output;
	// here is like colour = vec3(position.x + 0.5, 1.0, position.y + 0.5);
	output.Color = { input.Position.X + 0.5, 1.0, input.Position.Y + 0.5, 1.0 };
	return output;
}

technique
{
	pass
	{
		VertexShader = compile vs_2_0 VertexShaderFunction();
		PixelShader = compile ps_2_0 PixelShaderFunction();
	}
}

and my source:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);

    basicEffect.World = world;
    basicEffect.View = view;
    basicEffect.Projection = projection;
    // Shader from OpenTK into MonoGame:
    // vec3(position.x + 0.5, 1.0, position.y + 0.5);
    // topleft: aquablue, topright: white
    // buttonleft: green, buttonright: yellow
    Vector3 pos = new Vector3();
    basicEffect.Parameters["ShadingColor"].SetValue(new Vector3(pos.X + 0.5f, 1.0f, pos.Y + 0.5f));

    GraphicsDevice.SetVertexBuffer(vertexBuffer);
    GraphicsDevice.Indices = indexBuffer;

    RasterizerState rasterizerState = new RasterizerState();
    rasterizerState.CullMode = CullMode.None;
    GraphicsDevice.RasterizerState = rasterizerState;

    foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
    {
        pass.Apply();
        GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, 0, 2, 4, 0, 6);
    }

    base.Draw(gameTime);
}

And it result before very blue-green = It is wrong.
But i want 4 colors from loading shader into basiceffect.

Thanks!

See my answer in your other post.