Quantcast
Channel: Community | MonoGame - Latest topics
Viewing all 6821 articles
Browse latest View live

UWP windows phones and fullscreen Problems

$
0
0

@Paul_Crawley wrote:

windows 10, VS2017 latest MG dev build 3.6+

have written a UWP game ready for the store, everything is good except running it on a phone, all the emulators produce one of the two following screenshots



the first won't display full screen, the second moves my window to the right.

Heres the code:

  width = 1600; // Windows
  height = 900;

  Constants.mainVirtualWidth = width;
  Constants.mainVirtualHeight = height;
  Game1.graphicsDM.PreferredBackBufferWidth = width;
  Game1.graphicsDM.PreferredBackBufferHeight = height;
  Game1.graphicsDM.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;
  Game1.graphicsDM.SynchronizeWithVerticalRetrace = true;
  Game1.graphicsDM.ApplyChanges();

  ApplicationView.PreferredLaunchViewSize = new Windows.Foundation.Size(width, height);
#if DEBUG
  ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
  var view = ApplicationView.GetForCurrentView();
  view.ExitFullScreenMode();
  bFullScreen = false;
#else
  ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.FullScreen;
  ApplicationView.GetForCurrentView().TryEnterFullScreenMode();
  bFullScreen = true;
#endif
  Game1.graphicsDM.IsFullScreen = bFullScreen;
  Game1.graphicsDM.ApplyChanges();

It's the same code for both screen shots, run it from VS I get screen shot 1, run it from inside the emulator and I get screen shot 2, ANY help would be appreciated, it's bugging me A LOT and could really use some help, runs fine on a desktop and Xbox just these damn mobiles!

Thanks in Advance, oh fyi, it's got MonoGame written all over it!

Posts: 1

Participants: 1

Read full topic


[Solved]How would one render the screen to just a portion of a rendertarget ?

$
0
0

@willmotil wrote:

I want to render the screen to just a portion of a render target.
The idea is to have the camera face one direction render everything scaled down to a portion of the rendertarget say the top left sixth of it.
Turn the camera 90 degrees in another direction with the same render target
Render to the top middle of it.
Repeat.

Id like to do this for all six sides of a cube, as im about to try to make a shadow cube map and im coding the cube atm..
I did the regular shadow map before on a single plane but its not so great i've never tried to make a shadow cube yet.

Or
is that not possible
or a bad idea
ect...

Really i have no idea how to do a shadow cube map skybox's are pretty simple but the shadow cube to me seems fairly confusing especially the part of figuring out were on which texture a pixel equates to when actually drawing the shadows.
I keep imagining about 6 if's in a shader to boot im sort of thinking that isn't the way its done ? Or is it ?

Posts: 6

Participants: 3

Read full topic

Load large text files

$
0
0

@bunnyboonet wrote:

Hi,
I'm developing a quiz app using monogame. I'm going to load questions from a json file, but when read it gives an error. Does monogame support async methods. If not please guide me how to load this questions.

Thanks

Posts: 2

Participants: 2

Read full topic

(SOLVED) Making a waypoint line between nodes

$
0
0

@oblivion165 wrote:

Hello,

I am having trouble making the 3D lines between two waypoints. Here is an example picture from C&C Renegade

(It was the only picture I could find of these waypaths, the red arrows were already on it)

You see the blue triangles with the green lines between them? I am trying to make the green lines. I started with a tiny small box model made in 3dsMax and I am trying to figure out the matrix math to stretch it from one node to another.

My current method is to use a Matrix.Create_Scale(Distance, 1,1); to set the length and then rotate the matrix on the Y axis to spin it in to position BUT that doesn't work if one node is higher than the others. I am thinking there is a better way to do this.

Here is my current code:

       Vector3 Offset = new Vector3(0.5f,.1f,0.5f);
        for (int i = 0; i < Node.Length; i++)
        {

            for (int t = 0; t < Node[i].Neighbors.Length;t++)
            {
                var Position = Node[i].Position;
                var nPosition = Node[i].Neighbors[t].Position;

                float Size = Node_Beam_Model.Meshes[0].BoundingSphere.Radius;


                var direction = Position - nPosition;
                var distance = Position.Distance(nPosition) + (1-Size);

                

                Matrix World = Matrix.Identity;
                float Half = Node_Beam_Model.Meshes[0].BoundingSphere.Radius / 2;
            
                float Angle = genlib.Angle(Node[i].Position, Node[i].Neighbors[t].Position);
                float amount = distance / Size;

                World *= Matrix.CreateTranslation(-new Vector3(-Half, 0, Half));

                World *= Matrix.CreateScale(new Vector3(amount, 1, 1));
                World *= Matrix.CreateRotationY(MathHelper.ToRadians(Angle * -1 + 90));
 
                World *= Matrix.CreateTranslation(Node[i].Position + Offset);
                
                Do(Node_Beam_Model, Camera, Color.White, World);
            }
        }

This does get the result I want as long as everything is flat obviously it would be with any elevation change

Posts: 4

Participants: 2

Read full topic

Keyboard Input Listener what is the correct way to determine which textbox the input comes from?

$
0
0

@lionelthomas wrote:

Have a column of textboxes. Each can receive input from the keyboard.

In my keyboard event handler I have no location parameter to determine which textbox the input is for.
So, I implemented a mouse listener to get the location. But, when the user inputs text into the first textbox without first clicking in that box the input goes into all the textboxes. Not very nice.

Am I missing something in the design to correctly identify which textbox the input is for?

Posts: 1

Participants: 1

Read full topic

Save game data

$
0
0

@bunnyboonet wrote:

Hi, I'm trying to save game data in a text file. But it gives an error "Stream was not writable."
Any idea?

here the code

private void SaveGame(int score, int currentWorksheet, int level)
{
try
{
var worksheet = 1;

            using (var writer = new StreamWriter(TitleContainer.OpenStream("Content/savegame.txt")))
            {
                if (currentWorksheet < 60)
                    worksheet = currentWorksheet++;
                else
                {
                    worksheet = 1;
                    level++;
                }

                writer.Write(string.Format("{0},{1},{2}", score, worksheet, level));
            }
        }

        catch (Exception ex)
        {
        }
    }

Posts: 1

Participants: 1

Read full topic

Scale and rotate Texture and maintaining pixelated look.

$
0
0

@Gronk wrote:

Hi,

I generated some scaled and rotated textures (the gray ones inside the blue rectangle) and they came out looking way to “good”. What i want is for the textures to “pixelate” to the same/close to the zoom of my camera.

I'm guessing i need some custom shader thingemajig to lower the resolution but problem is i don't know where to start. Most articles i find focus on other topics.

I followed some basic shader tutorials and i think i grasp the concept. cool stuff. but it only changes colors im guessing i need to change scale in some form.

So my question:
Is a shader the wrong way of doing this? Can i achieve this effect some other way if so: can you explain how.
If shader is the only way… do you know of any beginner/intermediate article or tutorial that gets a texture and lowers the resolution… if that's a thing! Maybe its called something else in shader land. if so please enlighten me.

Posts: 1

Participants: 1

Read full topic

Render Target Cube Texture Cube How to questions.

$
0
0

@willmotil wrote:

This is a continuation of a solved post here http://community.monogame.net/t/solved-how-would-one-render-the-screen-to-just-a-portion-of-a-rendertarget/10614/11
It was sort of off topic in the other thread.

I still have some questions on how to render this rendercube to a actual quad cube.
Do i set the light position to be the center of a quad cube and then get the rendered scene texels to do reflection mapping onto a cube ? Id like to also be able to colorize the depth and display it in that way onto a cube for visualization and to make sure it looks proper.

Anyways i got it running i have no idea how bugged up this really is till i get a better scene in there im tired so itll have to wait. But it appears to be doing some shadowing.

Gray is the shadow color in the below picture. So it's at least partialy working.

Here's my code so far minus the helper class with the grid.

Game1 and Shader

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace TestTextureCube
{

    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        // whats the difference here what does the textureCube do exactly
        TextureCube textureCube;
        // i get the rendertargetCube
        RenderTargetCube renderTargetCube;
        //
        Effect effect;
        //
        float near = 1.0f;
        float far = 1000f;
        Matrix world, view, projection;
        Matrix worldGrid, worldCamera, worldLight, worldObj1, worldObj2;
        Vector3 worldGridPosition, worldCameraPosition, worldLightPosition, worldObj1Position, worldObj2Position;

        // something to draw
        Grid3dOrientation grid = new Grid3dOrientation(30, 30, .001f);
        // 2.0 is screen scale with a wvp identity matrix.
        Quad quad = new Quad(1.7f);

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = this.LoadBasics("Shadow Cube test");
            effect = Content.Load<Effect>("EffectCubeMap");
            textureCube = new TextureCube(GraphicsDevice, 6, false, SurfaceFormat.Single);
            renderTargetCube = new RenderTargetCube(GraphicsDevice, 256, false, SurfaceFormat.Single, DepthFormat.Depth24);
            effect.Parameters["farPlane"].SetValue(far);

            world = Matrix.Identity;
            SetView(world);
            projection = Matrix.CreatePerspectiveFieldOfView((float)MathHelper.Pi * .5f, GraphicsDevice.Viewport.Width / GraphicsDevice.Viewport.Height, near, far);

            worldLightPosition = new Vector3(3f, .1f, -.5f);
            worldLight = CreateWorldToTarget(worldLightPosition, Vector3.Zero, Vector3.Up);
            worldGridPosition = Vector3.Zero;
            worldGrid = Matrix.CreateScale(30f) * Matrix.CreateWorld(Vector3.Zero, Vector3.Forward, Vector3.Up);
            worldCameraPosition = new Vector3(.5f, -.5f, 2f);
            worldCamera = CreateWorldToTarget(worldCameraPosition, Vector3.Zero, Vector3.Up);

        }

        protected override void UnloadContent()
        {
            this.UnloadBasics();
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            //BasicStuff.Update(gameTime);
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
            GraphicsDevice.Clear(ClearOptions.DepthBuffer, Color.Black, 1, 0);
            GraphicsDevice.RasterizerState = new RasterizerState() { FillMode = FillMode.Solid, CullMode = CullMode.None };
            GraphicsDevice.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true, DepthBufferFunction = CompareFunction.LessEqual };

            // ok so lets take a look
            effect.CurrentTechnique = effect.Techniques["CreateLightShadowCubeDepth"];

            // well set a rendertarget to prepare for drawing
            // we set our own view matrix to match at the light shadow location.
            // we draw some stuff to a depth buffer.
            GraphicsDevice.SetRenderTarget(renderTargetCube, CubeMapFace.NegativeX);
            SetViewToLight(worldLightPosition, Vector3.Left);
            DrawGridToDepth();

            GraphicsDevice.SetRenderTarget(renderTargetCube, CubeMapFace.NegativeY);
            SetViewToLight(worldLightPosition, Vector3.Down);
            DrawGridToDepth();

            GraphicsDevice.SetRenderTarget(renderTargetCube, CubeMapFace.NegativeZ);
            SetViewToLight(worldLightPosition, Vector3.Forward);
            DrawGridToDepth();

            GraphicsDevice.SetRenderTarget(renderTargetCube, CubeMapFace.PositiveX);
            SetViewToLight(worldLightPosition, Vector3.Right);
            DrawGridToDepth();

            GraphicsDevice.SetRenderTarget(renderTargetCube, CubeMapFace.PositiveY);
            SetViewToLight(worldLightPosition, Vector3.Up);
            DrawGridToDepth();

            GraphicsDevice.SetRenderTarget(renderTargetCube, CubeMapFace.PositiveZ);
            SetViewToLight(worldLightPosition, Vector3.Backward);
            DrawGridToDepth();

            // definately going to need a octree too.

            // Ok so we have our depths in this rendertarget cube.
            // I want to draw with the shadowing.
            // So on this calculation side, im guessing it just does the math and thats the attraction.
            // i suppose i can get data on this thing if i want to see it flattened out.

            // switch to backbuffer
            GraphicsDevice.SetRenderTarget(null);

            // we switch our view now to our actual camera and draw our scene with shadow.... but...
            effect.CurrentTechnique = effect.Techniques["LightShadowCubeBasicShader"];
            effect.Parameters["worldLightPosition"].SetValue(worldLightPosition);
            SetView(worldCamera);
            effect.Parameters["WorldViewProjection"].SetValue(GetWvp());

            DrawGridWithShadow();


            BasicStuff.Draw();
            base.Draw(gameTime);
        }

        // yes its wasteful i just want a working test for now.
        void DrawGridToDepth()
        {
            SetWorld(worldGrid);
            effect.Parameters["lightsPovWorldViewProjection"].SetValue(GetWvp());
            grid.Draw(GraphicsDevice, effect, 0);
            grid.Draw(GraphicsDevice, effect, 1);
            grid.Draw(GraphicsDevice, effect, 2);
        }
        void DrawGridWithShadow()
        {
            SetWorld(worldGrid);
            effect.Parameters["lightsPovWorldViewProjection"].SetValue(GetWvp());
            effect.Parameters["TextureB"].SetValue(renderTargetCube);

            effect.Parameters["TextureA"].SetValue(BasicTextures.red);
            grid.Draw(GraphicsDevice, effect, 0);
            effect.Parameters["TextureA"].SetValue(BasicTextures.green);
            grid.Draw(GraphicsDevice, effect, 1);
            effect.Parameters["TextureA"].SetValue(BasicTextures.blue);
            grid.Draw(GraphicsDevice, effect, 2);
        }

        void SetWorld(Matrix world)
        {
            this.world = world;
        }
        void SetView(Matrix worldForCamera)
        {
            var m = worldForCamera;
            view = Matrix.CreateLookAt(m.Translation, m.Forward + m.Translation, m.Up);
        }
        Matrix GetWvp()
        {
            return world * view * projection;
        }
        void SetViewToLight(Vector3 shadowCubePosition, Vector3 direction)
        {
            Matrix m = Matrix.CreateWorld(shadowCubePosition, direction, Vector3.Up);
            view = Matrix.CreateLookAt(m.Translation, 10f * m.Forward + m.Translation, m.Up);
        }
        Matrix CreateWorldToTarget(Vector3 position, Vector3 targetPosition, Vector3 up)
        {
            return Matrix.CreateWorld(position, targetPosition - position, up);
        }
        

    }
}

Shader.

//
//EffectCubeMap.fx
//
#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

//_______________________
// Common Functions

// Calculate depth
float CalculateLightDepth(float pz, float farPlaneValue)
{
    float result = farPlaneValue - pz;
    return result;
}
// encode 3
float3 EncodeFloatRGB(float f)
{
    float3 color;
    f *= 256;
    color.x = floor(f);
    f = (f - color.x) * 256;
    color.y = floor(f);
    color.z = f - color.y;
    color.xy *= 0.00390625; // *= 1.0/256
    return color;
}
// decode 3
float DecodeFloatRGB(float3 color)
{
    const float3 byte_to_float = float3(1.0, 1.0 / 256, 1.0 / (256 * 256));
    return dot(color, byte_to_float);
}

// _______________________
// texture samplers.

Texture TextureA;
Texture TextureB;
sampler TextureSamplerA = sampler_state
{
    texture = <TextureA>;
    //magfilter = LINEAR; //minfilter = LINEAR; //mipfilter = LINEAR; //AddressU = mirror; //AddressV = mirror; 
};
sampler TextureSamplerB = sampler_state
{
    texture = <TextureB>;
    //magfilter = LINEAR; //minfilter = LINEAR; //mipfilter = LINEAR; //AddressU = mirror; //AddressV = mirror; 
};

//_______________________
// specifics

matrix World;
matrix View;
matrix Projection;
matrix WorldViewProjection;
matrix lightsPovWorldViewProjection;

float3  worldLightPosition;
float    farPlane;

//__________________
// Shaders begin now _
// _________________


//
//_______________________________________________________________
// techniques Create depth texture
//_______________________________________________________________
//

struct VsInputCalcSceneDepth
{
    float4 Position : POSITION0;
    float2 TexCoords    : TEXCOORD0;
};
struct VsOutputCalcSceneDepth
{
    float4 Position     : SV_Position;
    float4 Position2D    : TEXCOORD0;
};
struct PsOutputCalcSceneDepth
{
    float4 Color : COLOR0;
};

// ______
// Shader.
//
VsOutputCalcSceneDepth CreateDepthMapVertexShader(VsInputCalcSceneDepth input)//(float4 inPos : POSITION)
{
    VsOutputCalcSceneDepth Output;
    Output.Position = mul(input.Position, lightsPovWorldViewProjection);
    // might need to get changed
    Output.Position2D = Output.Position;
    return Output;
}
//
// I guess we set the render cube side in code so.
// Ok so were going to use the old calculation i guess.
// How does the perspective matrix align with this.
//
PsOutputCalcSceneDepth CreateDepthMapPixelShader(VsOutputCalcSceneDepth input)
{
    PsOutputCalcSceneDepth Output;
    // ABS ?
    float lightDepth = CalculateLightDepth(input.Position2D.z, farPlane);
    float3 temp = EncodeFloatRGB(lightDepth); // 24 bit depth
    float4 result = float4(temp.r, temp.g, temp.b, 1.0f);
    Output.Color = result;
    return Output;
}
//_________
// techniques
technique CreateLightShadowCubeDepth
{
    pass Pass0
    {
        VertexShader = compile VS_SHADERMODEL CreateDepthMapVertexShader();
        PixelShader = compile PS_SHADERMODEL CreateDepthMapPixelShader();
    }
}


//_______________________________________________________________
// techniques DrawLightOrShadow
//_______________________________________________________________
struct VsInLightShadow
{
    float4 Position : POSITION0;
    float3 Normal : NORMAL0;
    float2 TexureCoordinateA : TEXCOORD0;
};
struct VsOutLightShadow
{
    float4 Position : SV_Position;
    float2 TexureCoordinateA : TEXCOORD0;
    float4 Position2D    : TEXCOORD1;
};
struct PsOutLightShadow
{
    float4 Color : COLOR0;
};
//_______
// shaders
//
VsOutLightShadow VsLightShadow(VsInLightShadow input)
{
    VsOutLightShadow output;
    output.Position = mul(input.Position, WorldViewProjection); // basically matrix identity
    output.TexureCoordinateA = input.TexureCoordinateA;
    output.Position2D = output.Position;
    return output;
}
PsOutLightShadow PsLightShadow(VsOutLightShadow input)
{
    PsOutLightShadow output;
    output.Color = tex2D(TextureSamplerA, input.TexureCoordinateA); // *input.Color;
    // ok i think i need to mult the worldLightPosition its really in world space atm.
    float3 lightpos = mul(worldLightPosition, WorldViewProjection);
    float3 dir = input.Position2D - lightpos; //worldLightPosition
    // promlem is i dunno what texcobe does under the hood.
    float shadowDepth = DecodeFloatRGB(texCUBE(TextureSamplerB, dir).xyz);
    // texCUBE(TextureSamplerB, float4(dir, 0)).x;
    if (shadowDepth > input.Position2D.z)
        output.Color = float4(0.7f, 0.7f, 0.7f, 1.0f); // light gray
    return output;
}
//_________
// techniques
technique LightShadowCubeBasicShader
{
    pass
    {
        VertexShader = compile VS_SHADERMODEL VsLightShadow();
        PixelShader = compile PS_SHADERMODEL PsLightShadow();
    }
}

Posts: 3

Participants: 2

Read full topic


Field of View >= 180 deg?

$
0
0

@mgulde wrote:

Dear all,

I am currently working on a project to compute radiative energy transfer across complex geometries. In order to do so between any two objects, one needs to compute the view factor between those objects or - in other words - the amount of surface of one object as seen from the other object.

Traditionally, a lot of this is performed via ray tracing methods. For performance reasons, I would like to use the OcclusionQuery function offered by Monogame / XNA. This function returns the number of pixels which passed the z test after a draw call. To compute the surface area of Object2 visible to Object1, for example, I would perform the following steps:

  • Place the camera at Object1, facing Object2
  • Draw the complete scene (every single object in the scene has a specific color)
  • Perform an OcclusionQuery and redraw Object2
  • The number of pixels returned from the OcclusionQuery can now be computed into the visible surface area (in orthographic projection)

This works pretty well as long as the objects in question are far apart and only span a small angle. For point-source type illumination, e.g., by the sun, this approach hence works fine.

Now, I would like to compute the radiative energy transfer between objects a lot closer to each other, e.g., between individual components inside a satellite. So, again, I would like to find the view factors / visible surface areas of all the surrounding objects. Since in this case, those objects can span a larger viewing angle, things are getting a bit trickier.

One possible way would be to look into many different directions from each radiating point. If assuming a field of view of pi/2, that would mean 8 different perspectives.

It would be way easier, however, to simply use two FoVs which span pi or a single one spanning 2pi (or 4 pi sr, if you like). As soon as I get close to a FoV of pi, Monogame is seemingly getting in trouble and stops drawing things at all. I assume this has to do with the planar image plane of Monogame and is hence a limitation of the algorithm?
Would you have any ideas on how to solve this problem? E.g., rendering to a spherical image plane or sth.?

Thanks!
Max

Posts: 3

Participants: 2

Read full topic

Media Center experience in MonoGame?

$
0
0

@Watercolor_Games wrote:

Alright, I know this is sort of a weird topic given MonoGame is really meant for games. But, I mean, it's very easy to load in audio and textures from respective files on the user's hard drive (skipping Content Pipeline, a.k.a using things like Texture2D.FromStream()), and video playback is coming to 3.7, so...we basically have all the tools necessary to build a decent media center experience. Has anyone ever thought about doing that or even tried doing it? Seems like an interesting project to me.

Furthermore since you'd be designing the UI and a lot of other features from scratch, you'd be able to give yourself the exact experience you want right down to what pixel the "Play" button has its origin point sitting on. I don't know, it just seems like a fun thing to code honestly.

Posts: 1

Participants: 1

Read full topic

Another 2 Months Entry on GameDev Challenge ^_^y

$
0
0

@DexterZ wrote:

I'm already awarded with PACMAN icon on last GameDev Challenge : PACMAN Multiplayer , if you want to try it and beat my score :grinning: here's the download link : DOWNLOAD

Here's my early progress on the new GameDev Challenge : DEFENSE TOWER again wish me luck to get he award and beat the deadline : - D

SPLASH SCREEN :

GAME MENU :

GAME SCREEN :

Posts: 1

Participants: 1

Read full topic

Blending works differently in 3.7?

$
0
0

@Jesuszilla wrote:

I recently updated to MonoGame 3.7 and I'm unsure whether or not this is a bug in the framework or in my code, so I figured I'd ask here first.

I have a method, DrawToScreen, which I use for source/destination blending like so:

        /// <summary>
        /// Draws this entity to the screen.
        /// </summary>
        /// <param name="spriteBatch">The <see cref="SpriteBatch"/> to use.</param>
        internal virtual void DrawToScreen(SpriteBatch spriteBatch)
        {
            // Defaults
            BlendState bs = BlendState.AlphaBlend;
            float srcMul = 1.0F, dstMul = 0.0F;

            if (Anim != null && Anim.CurrElem != null)
            {
                // Additive blending with src/dest
                if (Anim.CurrElem.Transparency.Type == TransparencyType.Add)
                {
                    srcMul = Anim.CurrElem.Transparency.Source / 256.0F;
                    dstMul = Anim.CurrElem.Transparency.Dest / 256.0F;

                    bs = new BlendState()
                    {
                        AlphaBlendFunction = BlendFunction.Add,
                        ColorBlendFunction = BlendFunction.Add,

                        AlphaSourceBlend = Blend.One,
                        ColorSourceBlend = Blend.SourceAlpha,

                        AlphaDestinationBlend = Blend.One,
                        ColorDestinationBlend = Blend.BlendFactor,
                        BlendFactor = new Color(dstMul, dstMul, dstMul, 1.0F)
                    };
                }
                // Subtractive blending
                else if (Anim.CurrElem.Transparency.Type == TransparencyType.Subtract)
                {
                    srcMul = 1.0F;//Anim.CurrElem.Transparency.Source / 256.0F;
                    dstMul = 0F;//Anim.CurrElem.Transparency.Dest / 256.0F;

                    bs = new BlendState()
                    {
                        AlphaBlendFunction = BlendFunction.ReverseSubtract,
                        ColorBlendFunction = BlendFunction.ReverseSubtract,

                        AlphaSourceBlend = Blend.SourceAlpha,
                        ColorSourceBlend = Blend.SourceColor,

                        AlphaDestinationBlend = Blend.One,
                        ColorDestinationBlend = Blend.One,
                    };
                }
            }

            spriteBatch.Begin(SpriteSortMode.BackToFront, bs, SamplerState.PointWrap, DepthStencilState.DepthRead, RasterizerState.CullNone);
            spriteBatch.Draw(SpriteLayer, Vector2.Zero, SpriteLayer.Bounds, new Color(Color.White, srcMul), 0F, Vector2.Zero, Vector2.One, SpriteEffects.None, LayerDepth);
            spriteBatch.End();

            foreach (var child in children)
            {
                child.DrawToScreen(spriteBatch);
            }
        }

For the most part, you can ignore subtractive blending portion as that's never reached in this particular example, but when the dstMul is 0, I get screen flickering for my background every 3 frames. My main draw code in my game class is as follows:

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            //GraphicsDevice.SetRenderTarget(null);
            if (BG != null)
                GraphicsDevice.Clear(BG.BackgroundColor);
            else
                GraphicsDevice.Clear(Color.CornflowerBlue);
            Effect palettize = Content.Load<Effect>("PaletteShader");
            palettize.Parameters["PalSampler"].SetValue(palTexture);

            bool endCalled = false;

            // Draw the players once loading is over.
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointWrap, null, RasterizerState.CullNone, palettize, BG.Camera.GetTransformation(spriteBatch.GraphicsDevice));
            // First, we need to draw to the render targets using the regular Draw() method.
            if (RoundState > RoundState.Loading)
            {
                // Draw the BG
                BG.Draw(spriteBatch, palettize, bgTextures, gameTime);

                for (int i = 0; i < Players.Length; i++)
                {
                    if (Players[i] != null)
                        Players[i].Draw(spriteBatch, palettize, plTextures[i], gameTime);
                }

                spriteBatch.End();

                // Draw the HUD
                spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointWrap, null, RasterizerState.CullNone, palettize);
                HUD.Draw(spriteBatch, palettize, hudTextures, gameTime);
                spriteBatch.End();

                // Now we draw to the screen texture
                GraphicsDevice.SetRenderTarget(screenRenderTarget);
                GraphicsDevice.Clear(BG.BackgroundColor);

                BG.DrawToScreen(spriteBatch);

                for (int i = 0; i < Players.Length; i++)
                {
                    if (Players[i] != null)
                        Players[i].DrawToScreen(spriteBatch);
                }

                // Draw the HUD
                HUD.DrawToScreen(spriteBatch);

                //spriteBatch.End();

                GraphicsDevice.SetRenderTarget(null);

                // Draw everything in the RenderTarget to screen
                spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, RasterizerState.CullNone);
                spriteBatch.Draw(screenRenderTarget, screenRenderTarget.Bounds, Color.White);
                spriteBatch.End();
                endCalled = true;
            }

            base.Draw(gameTime);

            if (!endCalled)
                spriteBatch.End();
        }

I did some trial-and-error testing and it appears the flickering occurs when dstMul is 0. 3.6 didn't do this, yet 3.7 does. Why? The math should check out just the same: if you want to draw a solid sprite, set the destination blend to 0 and the source blend to whatever on top. However, it's as if upper layers aren't blending at all, but rather being drawn on top in this instance, with the transparent region totally ignored. Either that or the destination below is getting set to 0 even after it's been drawn.

Posts: 1

Participants: 1

Read full topic

Any interest in a testable MonoGame wrapper?

$
0
0

@Trinith wrote:

Hey guys,

So a while back I decided I wanted to try to release a game since it's something I've always wanted to do. I think I'm even, maybe, getting fairly close to doing that (lol :P). One of the goals I set out with this project though is that I wanted to ensure that all of the code I write is backed by unit tests.

Since the XNA framework (and by extension, MonoGame) was never really designed with unit testing/mocking in mind, I've ended up creating several wrappers for MonoGame objects so that I can interact with code at a more abstract level. This is generally fairly easy to achieve, involving creating an interface from the existing object and then implementing that interface with a wrapper for the MonoGame object. Your code can then interact with the interface, allowing you to easily mock it in a unit test.

Here's a very brief example of an object responsible for drawing a texture with various parameters. Utilizing the wrappers, I can then write a unit test to ensure that the draw call does the expected things. In this way, if I ever change the code to include more functionality, I can have confidence that my intended functionality still works... or doesn't, resulting in a bunch of failed tests that I can then either address by correcting, or updating the tests.

// Sample object
public class SimpleGameDrawable
{
    private ISpriteBatch _spriteBatch;
    private ITexture2D _texture;

    public Vector2 Location { get; set; } = Vector2.Zero;
    public Color Color { get; set; } = Color.White;

    public SimpleGameDrawable(ISpriteBatch spriteBatch, ITexture2D texture)
    {
        _spriteBatch = spriteBatch ?? throw new ArgumentNullException();
        _texture = texture ?? throw new ArgumentNullException();
    }
    
    public void Draw(GameTime gameTime)
    {
        _spriteBatch.Begin();
        _spriteBatch.Draw(_texture, this.Location, this.Color;
        _spriteBatch.End();
    }
}

// Sample test class using MSTEST and NSubstitute for mocking
[TestClass]
public class SimpleGameDrawable_Tests
{
    private SimpleGameDrawable _sut;
    
    private ISpriteBatch _mockSpriteBatch;
    private ITexture2D _mockTexture;
    
    [TestInitialize]
    public void Initialize()
    {
        _mockSpriteBatch = Substitute.For<ISpriteBatch>();
        _mockTexture = Substitute.For<ITexture2D>();
        
        _sut = new SimpleGameDrawable(_mockSpriteBatch, _mockTexture)
        {
            Location = new Vector2(123, 321),
            Color = Color.Pink,
        };
    }
    
    [TestMethod]
    public void DrawShouldBeginThenEndSpriteBatch()
    {
        _sut.Draw(new GameTime());
        
        Received.InOrder(
            () =>
            {
                _mockSpriteBatch.Begin();
                _mockSpriteBatch.End();
            }
        );
    }
    
    [TestMethod]
    public void DrawShouldCallSpriteBatchDrawWithExpectedParameters()
    {
        _sut.Draw(new GameTime());
        
        _mockSpriteBatch.Received(1).Draw(_mockTexture, new Vector2(123, 321), Color.Pink);
    }
}

Anyway, this has been an ongoing development so the wrapper is by no means complete... my approach is to just implement the things I need to achieve my goals, then stop there. That said, I'm wondering if this is something that would interest other people. I currently have this code sitting in a private repository with the rest of my stuff, but if there were interest I could upload it to github or something, as well as continue the project to include functionality I currently don't use. I could probably also write up some tutorials on applying testing to MonoGame development.

Any thoughts on this?

Posts: 1

Participants: 1

Read full topic

Google Pixel - Immersive Sticky Mode can't get rid of black bars

$
0
0

@bedroomlab wrote:

I have a game which runs full screen fine on various Android devices but on Google Pixel 2XL I can't seem to get rid of the action bar or title bar properly. The icons and buttons tween off but the black background remains.

I think the code is all correct:
styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Splash" parent="android:Theme.Holo.Light.NoActionBar">
<item name="android:windowBackground">@drawable/splash</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
</style>
</resources>

In MainActivity.cs I have this function which is called in OnCreate, OnResum, OnWindowFocusChanged
private void SetImmersive() {
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat) {
Window.DecorView.SystemUiVisibility = (StatusBarVisibility)(SystemUiFlags.LayoutStable | SystemUiFlags.LayoutHideNavigation | SystemUiFlags.LayoutFullscreen | SystemUiFlags.HideNavigation | SystemUiFlags.Fullscreen | SystemUiFlags.ImmersiveSticky);
}
}

OnCreate has this
RequestWindowFeature(WindowFeatures.NoTitle);
Window.SetFlags(WindowManagerFlags.Fullscreen, WindowManagerFlags.Fullscreen);

GraphicsDeviceManger.ResetClientBounds tells me the bounds contain the bars still. If I hack the dimensions here I can get rid of the title bar black area but the action bar remains.

I did some Googling and it sounds like this is expected behaviour on the Pixel, but then some apps dont have this problem implying there must be a way around it.

Any ideas what to do?

Posts: 1

Participants: 1

Read full topic

Help with F# setup

$
0
0

@last-ent wrote:

Hello,

I am trying to create a MonoGame project in F# but I can't find the
option to switch from C# to F# in New Project screen in MonoDevelop. (Please see the image)

I also tried to use VSCode & Ionide but it says can't find
namespace Microsoft.Xna. I have installed MonoGame, Mono &
MonoDevelop to try and make it work.

I have tried it on Mac & Fedora (Linux).

Help much appreciated!

Posts: 1

Participants: 1

Read full topic


Text contains characters that cannot be resolved by this spritefont.

$
0
0

@bunnyboonet wrote:

Hi,

I'm trying to insert multiplication character in my game screen. I get this from a json file.
{
"Q": "5×7",
"A1": "13",
"A2": "14",
"A3": "12",
"A4": "22",
"CA": 3
},

This post describe how to add character region. But i have no idea how to add math characters here.

Any idea?

Thanks

Posts: 2

Participants: 2

Read full topic

Kenney Spritesheet XML importer

$
0
0

@Aurioch wrote:

Since default XML importer requires a very specific XML format, to ease my pain while working with Kenney's spritesheets, I've quickly wrote my own importer for Content Pipeline, which I'd like to share in hope it helps anyone else.
I've also commited a built DLL so there's no need for downloading whole solution. It's located as usual (/bin/Release).

Github:
https://github.com/Aurioch/KenneySpritesheetImporter/tree/master
Prebuilt DLL (right click => Save Link As...)

Posts: 1

Participants: 1

Read full topic

GraphicsAdapter lost features?

$
0
0

@Whackatoe wrote:

I use to gather information about the graphics device such as the device name by using:

GraphicsDevice.Adapter.DeviceName

That functionality is still working on one of my project but I created a new project and the property is not there anymore... I only get the following 4 properties: SupportedDisplayModes, CurrentDisplayModes, Description, and IsWideScreen.

Both Classes extend the Game class, and the graphics device is created as it is in the template for VS2017.

Was this intended?

Posts: 1

Participants: 1

Read full topic

SpriteBatch overiding states and keeping them off ?

$
0
0

@willmotil wrote:

Has anyone else had any problems with spritebatch turning on culling and forcing it to stay on.

              if (turnOnSpriteBatchMsg) // weird spritebatch is torching the shadows with forced culling on all the draws.
                    BasicStuff.DrawBeginEnd(spriteBatch, font);

After the red text goes off, the shadows are still hosed.

if i even use the spritebatch.drawstring it flips something on and when i turn it off my state settings still don't apply.

Posts: 3

Participants: 2

Read full topic

Unexpected Failure while importing Wave files with de MGPipelineTool

$
0
0

@Lufen34 wrote:

Hello guys!

I decided to stop dev on Windows and work on Linux ( Pop!_Os) and I am actually using Visual studio Code for my project.

My problem appears when I try to execute my program. "error : Importer 'WavImporter' had unexpected failure" which is actually weird since he was able to build without any problems.

I really would appreciate if someone could help me to deal with this. I saw on forums that it could be a right issue but even after giving full rights to all the folder and subfolders it seems to still not work. Here is the full error :

Microsoft (R) Build Engine version 15.7.177.53362 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

>   Restore completed in 29.24 ms for /home/lufen/Documents/Monogame/Plateformer/Plateformer.csproj.
>   Skipping /home/lufen/Documents/Monogame/Plateformer/Content/BackGroundMenu.jpg
>   Skipping /home/lufen/Documents/Monogame/Plateformer/Content/Button.png
>   Skipping /home/lufen/Documents/Monogame/Plateformer/Content/player2.png
>   Skipping /home/lufen/Documents/Monogame/Plateformer/Content/mainfont.spritefont
>   Skipping /home/lufen/Documents/Monogame/Plateformer/Content/texte.spritefont
>   /home/lufen/Documents/Monogame/Plateformer/Content/click.wav
> /home/lufen/Documents/Monogame/Plateformer/Content/click.wav : error : Importer 'WavImporter' had unexpected failure! [/home/lufen/Documents/Monogame/Plateformer/Plateformer.csproj]
>   Microsoft.Xna.Framework.Content.Pipeline.InvalidContentException: Failed to open file click. Ensure the file is a valid audio file and is not DRM protected. ---> System.ComponentModel.Win32Exception: ApplicationName='/home/lufen/.nuget/packages/monogame.content.builder/3.7.0.4/build/MGCB/build/ffprobe', CommandLine='-i "/home/lufen/Documents/Monogame/Plateformer/Content/click.wav" -show_format -show_entries streams -v quiet -of flat', CurrentDirectory='', Native error= Access denied
>     at System.Diagnostics.Process.StartWithCreateProcess (System.Diagnostics.ProcessStartInfo startInfo) [0x002dc] in <2740d7148e184840ad6689888c90a56d>:0
>     at System.Diagnostics.Process.Start () [0x0003a] in <2740d7148e184840ad6689888c90a56d>:0
>     at (wrapper remoting-invoke-with-check) System.Diagnostics.Process.Start()
>     at Microsoft.Xna.Framework.Content.Pipeline.ExternalTool.Run (System.String command, System.String arguments, System.String& stdout, System.String& stderr, System.String stdin) [0x000a5] in <21694ce2bd7a4add8c34ca22998e7694>:0
>     at Microsoft.Xna.Framework.Content.Pipeline.Audio.DefaultAudioProfile.ProbeFormat (System.String sourceFile, Microsoft.Xna.Framework.Content.Pipeline.Audio.AudioFileType& audioFileType, Microsoft.Xna.Framework.Content.Pipeline.Audio.AudioFormat& audioFormat, System.TimeSpan& duration, System.Int32& loopStart, System.Int32& loopLength) [0x00010] in <21694ce2bd7a4add8c34ca22998e7694>:0
>     at Microsoft.Xna.Framework.Content.Pipeline.Audio.AudioContent..ctor (System.String audioFileName, Microsoft.Xna.Framework.Content.Pipeline.Audio.AudioFileType audioFileType) [0x00015] in <21694ce2bd7a4add8c34ca22998e7694>:0
>      --- End of inner exception stack trace ---
>     at Microsoft.Xna.Framework.Content.Pipeline.Audio.AudioContent..ctor (System.String audioFileName, Microsoft.Xna.Framework.Content.Pipeline.Audio.AudioFileType audioFileType) [0x0023b] in <21694ce2bd7a4add8c34ca22998e7694>:0
>     at Microsoft.Xna.Framework.Content.Pipeline.WavImporter.Import (System.String filename, Microsoft.Xna.Framework.Content.Pipeline.ContentImporterContext context) [0x0003f] in <21694ce2bd7a4add8c34ca22998e7694>:0
>     at Microsoft.Xna.Framework.Content.Pipeline.ContentImporter`1[T].Microsoft.Xna.Framework.Content.Pipeline.IContentImporter.Import (System.String filename, Microsoft.Xna.Framework.Content.Pipeline.ContentImporterContext context) [0x0001c] in <21694ce2bd7a4add8c34ca22998e7694>:0
>     at MonoGame.Framework.Content.Pipeline.Builder.PipelineManager.ProcessContent (MonoGame.Framework.Content.Pipeline.Builder.PipelineBuildEvent pipelineEvent) [0x00079] in <21694ce2bd7a4add8c34ca22998e7694>:0
>   /home/lufen/Documents/Monogame/Plateformer/Content/load.wav
> /home/lufen/Documents/Monogame/Plateformer/Content/load.wav : error : Importer 'WavImporter' had unexpected failure! [/home/lufen/Documents/Monogame/Plateformer/Plateformer.csproj]
>   Microsoft.Xna.Framework.Content.Pipeline.InvalidContentException: Failed to open file load. Ensure the file is a valid audio file and is not DRM protected. ---> System.ComponentModel.Win32Exception: ApplicationName='/home/lufen/.nuget/packages/monogame.content.builder/3.7.0.4/build/MGCB/build/ffprobe', CommandLine='-i "/home/lufen/Documents/Monogame/Plateformer/Content/load.wav" -show_format -show_entries streams -v quiet -of flat', CurrentDirectory='', Native error= Access denied
>     at System.Diagnostics.Process.StartWithCreateProcess (System.Diagnostics.ProcessStartInfo startInfo) [0x002dc] in <2740d7148e184840ad6689888c90a56d>:0
>     at System.Diagnostics.Process.Start () [0x0003a] in <2740d7148e184840ad6689888c90a56d>:0
>     at (wrapper remoting-invoke-with-check) System.Diagnostics.Process.Start()
>     at Microsoft.Xna.Framework.Content.Pipeline.ExternalTool.Run (System.String command, System.String arguments, System.String& stdout, System.String& stderr, System.String stdin) [0x000a5] in <21694ce2bd7a4add8c34ca22998e7694>:0
>     at Microsoft.Xna.Framework.Content.Pipeline.Audio.DefaultAudioProfile.ProbeFormat (System.String sourceFile, Microsoft.Xna.Framework.Content.Pipeline.Audio.AudioFileType& audioFileType, Microsoft.Xna.Framework.Content.Pipeline.Audio.AudioFormat& audioFormat, System.TimeSpan& duration, System.Int32& loopStart, System.Int32& loopLength) [0x00010] in <21694ce2bd7a4add8c34ca22998e7694>:0
>     at Microsoft.Xna.Framework.Content.Pipeline.Audio.AudioContent..ctor (System.String audioFileName, Microsoft.Xna.Framework.Content.Pipeline.Audio.AudioFileType audioFileType) [0x00015] in <21694ce2bd7a4add8c34ca22998e7694>:0
>      --- End of inner exception stack trace ---
>     at Microsoft.Xna.Framework.Content.Pipeline.Audio.AudioContent..ctor (System.String audioFileName, Microsoft.Xna.Framework.Content.Pipeline.Audio.AudioFileType audioFileType) [0x0023b] in <21694ce2bd7a4add8c34ca22998e7694>:0
>     at Microsoft.Xna.Framework.Content.Pipeline.WavImporter.Import (System.String filename, Microsoft.Xna.Framework.Content.Pipeline.ContentImporterContext context) [0x0003f] in <21694ce2bd7a4add8c34ca22998e7694>:0
>     at Microsoft.Xna.Framework.Content.Pipeline.ContentImporter`1[T].Microsoft.Xna.Framework.Content.Pipeline.IContentImporter.Import (System.String filename, Microsoft.Xna.Framework.Content.Pipeline.ContentImporterContext context) [0x0001c] in <21694ce2bd7a4add8c34ca22998e7694>:0
>     at MonoGame.Framework.Content.Pipeline.Builder.PipelineManager.ProcessContent (MonoGame.Framework.Content.Pipeline.Builder.PipelineBuildEvent pipelineEvent) [0x00079] in <21694ce2bd7a4add8c34ca22998e7694>:0
> /home/lufen/.nuget/packages/monogame.content.builder/3.7.0.4/build/MonoGame.Content.Builder.targets(92,5): error MSB3073: The command "/usr/bin/mono "/home/lufen/.nuget/packages/monogame.content.builder/3.7.0.4/build/MGCB/build/MGCB.exe" /@:"/home/lufen/Documents/Monogame/Plateformer/Content/Content.mgcb" /platform:DesktopGL /quiet /outputDir:"bin/DesktopGL/Content" /intermediateDir:"obj/DesktopGL/Content"" exited with code 2. [/home/lufen/Documents/Monogame/Plateformer/Plateformer.csproj]

> Build FAILED.

> /home/lufen/Documents/Monogame/Plateformer/Content/click.wav : error : Importer 'WavImporter' had unexpected failure! [/home/lufen/Documents/Monogame/Plateformer/Plateformer.csproj]
> /home/lufen/Documents/Monogame/Plateformer/Content/load.wav : error : Importer 'WavImporter' had unexpected failure! [/home/lufen/Documents/Monogame/Plateformer/Plateformer.csproj]
> /home/lufen/.nuget/packages/monogame.content.builder/3.7.0.4/build/MonoGame.Content.Builder.targets(92,5): error MSB3073: The command "/usr/bin/mono "/home/lufen/.nuget/packages/monogame.content.builder/3.7.0.4/build/MGCB/build/MGCB.exe" /@:"/home/lufen/Documents/Monogame/Plateformer/Content/Content.mgcb" /platform:DesktopGL /quiet /outputDir:"bin/DesktopGL/Content" /intermediateDir:"obj/DesktopGL/Content"" exited with code 2. [/home/lufen/Documents/Monogame/Plateformer/Plateformer.csproj]
>     0 Warning(s)
>     3 Error(s)

> Time Elapsed 00:00:00.93`indent preformatted text by 4 spaces`

Thanks in advance for your precious help :smile:

Posts: 5

Participants: 2

Read full topic

Viewing all 6821 articles
Browse latest View live