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

what is the best structure for a game?

$
0
0

@pavul wrote:

hello im new to monogame it looks a lot like libGDX, however i cannot find good tutorials for game development, i have been watching only indroductions where they explain how to render images, how to add them, input, i already know how to do that, but im looking a better structure i can use, like levels, support for diferent screen sizes, how to xport to xbox, etc.etc.

any help or link to more advanced tutorials would be appreciated.

Posts: 13

Participants: 4

Read full topic


How to have a flat sprite in a 3D environment?

$
0
0

@Rockford wrote:

Hi :slight_smile:

I would like to integrate 2D sprite in my 3D environnement.
The idea is not to "mix", but really integrate, like if the sprite is a model in the scene.

I managed to display a sprite + a 3D scene, but the sprite is a kind of background and huge compared to my 3D model. The game is a Dungeon Master like (in 3D) but I want the monsters in 2D. So the sprites need to by "in" the dungeon, not behind or on top.

Here is, kindly, the idea:

Thanks for your help!

Posts: 4

Participants: 2

Read full topic

How to load text file on Android?

$
0
0

@wkurnikumnieniema wrote:

Hello.
I'm trying to load text file by

        var filePath = Path.Combine(Content.RootDirectory, "l1.dat");
        using (var stream = TitleContainer.OpenStream(filePath))
        {
            text = File.ReadAllText(filePath);
        }

It's just for test, but I don't know where to put l1.dat, because whatever i try (with content directory or not), I get

System.IO.DirectoryNotFoundException: Could not find a part of the path "/Content/l1.dat".

First time I do something for Android so I have no idea what should I do with this.

Edit:
The main question is:
how to add a existing file with data to a project and what path to it will be on device after compile.

Posts: 6

Participants: 3

Read full topic

Forward rendering - multiple lights and shadows

$
0
0

@YTN wrote:

How do you guys handle multiple shadow casting lights and forward rendering?

The most common way seems to be having multiple shadowmaps (one per light shadow casting light), and then rendering each model using each shadowmap.

However, that seems highly inefficient. I am wondering if there's any other ways to tackle this. Anyone have any techniques that make this more efficient?

Do you limit your shadowcasting lights etc? If so, how many of each light type?

Thanks!

Posts: 1

Participants: 1

Read full topic

MonoGame.Extended.Input Gesture recognition.

$
0
0

@BrettAnthony wrote:

Currently doing some work on adding Touch support to the NuclexGui. I was thinking that gestures (tap) especially will be handy for simulating mouse clicks etc. There doesnt seem to be any support for Gesture recognition in the Extended.Input libs. (as we know Monogame handles all gesture recognition fine, but it has to be setup). My main question is, is this intentional? As in its always going to be up to the consumer to implement any Touchpanel calls
This is all cool by the way, but it made me think that some Gesture setup (boilerplate) inside Extended.Input may be a good thing?

Cheers
Brett :wink:

Posts: 2

Participants: 2

Read full topic

How to use custom reference points in sprites?

$
0
0

@Tobias_Endres wrote:

I am using TexturePacker to generate my sprite-sheet and texture-atlas file (using the JSON output format). Alongside that I have a ".aa" file describing my animations which I manually created. This setup is pretty much as it is done with the zombie-animations in the demo and works great (after I have learned that sprite-rotating is not supported by MonoGame.Extended currently).

Now for some animations I need to specify reference points in the frame to render other sprites to. For example when picking up objects, displaying a weapon or showing effects. I am aware of pivot-points in TexturePacker, but as far as I understood, this is used for other purposes and is limited to one point per frame. In fact I need to be able to setup multiple custom points (or even areas) per frame.

I am wondering how this could be done most efficiently. I do not see anything that fits my needs in the ".aa" format or the texture-atlas. So my best guess is to add the attributes I need to the ".aa" file and extend the currently used "Astrid Animator Importer/Processor". However this means manually adjusting these points whenever the sprites change and overriding the Importer/Processor seems no easy task to me. Also to me setting these reference points in a sprite seems such a basic functionality that I guess there has to be a best-practice way on how to do this. Maybe I am currently thinking in the wrong direction. How are you handling reference-points in your 2D animations?

Posts: 1

Participants: 1

Read full topic

how to Jump

$
0
0

@Valentin_Honore wrote:

Hello,

I have some problem with "Jump" I don't have the result I would like. Actually, wth the Jump part of the code, my player go a little into the platform and I don't know why. More over, If I continue to press space button my player become crazy by shaking very fast and I don't want that. I would like that the player has to release the space button before do another jump.

There it is the code to make my "player" jump :

public void playerUpdate(GameTime gameTime)
{
KeyboardState kState = Keyboard.GetState();
float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
hitBoxPlayer = new Vector2(position.X + 45, position.Y + 35);
// Fall because of gravity part code
Vector2 tempPos = position;
tempPos.Y += speed * increment * dt;
tempPos.X += speed * increment * dt;
if (Platform.DidCollideVertical(tempPos) && Platform.DidCollideHorizontal(position))
{
jumping = false;
}
else
{
position.Y += speed * increment * dt;
if (increment < 10)
increment += 0.1f;
jumping = true;

        }

// "Jump" part of the code

        if (kState.IsKeyDown(Keys.Space) && spaceRelease == true)
        {
            position.Y -= 5 * speed * dt;


        }
        if (kState.IsKeyUp(Keys.Space) && Platform.DidCollideVertical(tempPos))
        {
            spaceRelease = true;
            increment = 0f;

        }

        else if (kState.IsKeyUp(Keys.Space) )
        {
            spaceRelease = false;
        }

Here the DidCollide 's functions (that are in class Platform) :

>     public static bool DidCollideVertical(Vector2 otherPos)
>     {
>         foreach (Platform p in Platform.platforms)
>         {
>             float sumY =  128 + 26;
>             if (Math.Abs(p.HitBox.Y - otherPos.Y) < sumY)
>             {
>                 return true;
>             }
>         }
>         return false;
>     }
>     public static bool DidCollideHorizontal(Vector2 otherPos)
>     {
>         foreach (Platform p in Platform.platforms)
>         {
>             
>             if (otherPos.X >= (p.position.X-20) && otherPos.X < p.hitBox.X)
>             {
>                 return true;
>             }
>         }
>         return false;
>     }

(The boolean "jump" will be used in the draw method later)

you can download the all project here : https://www.dropbox.com/s/im74pk9zbm2wllj/Bumble2.rar?dl=0

Thanks in advance for your help,

Valentin

Posts: 1

Participants: 1

Read full topic

How to rewrite a XML file in monogame?

$
0
0

@FreedeX_Official wrote:

Hi, I trying to rewrite a xml file in monogame from the code for save the score, but my game crash with this error:
System.UnauthorizedAccessException: Access to the path "/name.xml" is denied.

For write XML file I writed this code:
XMLData.RecordClass data = new XMLData.RecordClass();
data.record = "5";
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create("name.xml", settings))
{ Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate.IntermediateSerializer.Serialize(writer, data, null);
}

Posts: 1

Participants: 1

Read full topic


Image Corruption

$
0
0

@Mattlekim wrote:

Hi every time I run my game from visual studies different images are corrupted.
For example see screen shot

Now If I rebuild all content it fixes it for 1 time. The next time I run the game random images will be corrupted.
The source Img is here

Do you have any idea whats happening and what I can do to fix it.

running windows 10 visual stuides 2017.
Direct X platform

Posts: 1

Participants: 1

Read full topic

Linux Support

my gpu/windows updates broke monogame? I dont even know where to begin...

$
0
0

@Tafellappen wrote:

im not really sure where to begin with this. i tried googling by copying and pasting and just by paraphrasing but nothing has come up. My only guess is that it has something to do with windows updates because i've never had a problem before and i updated just last night.

for reference im using monogame 3.6

Posts: 2

Participants: 2

Read full topic

HLSL - Clip Pixel based on Screen Position

$
0
0

@Kimimaru wrote:

Hello all, I have an HLSL question for a DesktopGL project. I'm making a dialogue box like in the screenshot below:

All the text in black is associated with the box.

Text prints itself on the box, and when told to, has a prompt for progressing to the next set of text (the star on the lower right).

When that happens, all previous text is moved up (the "Hello World!"), and the next set of text gets printed. If it has already been printed - you can go back to previous text - it's simply shown by moving all the text down.

Basically, I need any text not in the box to be invisible. I decided that using a shader for this would work well, as I eventually need to use it to render the text with other special effects. My approach is to check the position of the pixels, and if they're out of the textbox bounds, clip them. However, I can't seem to get the position in the pixel shader.

Here's my shader:

#if OPENGL
    #define SV_POSITION POSITION
    #define VS_SHADERMODEL vs_3_0
    #define PS_SHADERMODEL ps_3_0
#else
    #define VS_SHADERMODEL vs_5_0
    #define PS_SHADERMODEL ps_5_0
#endif

matrix WorldViewProjection;

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

struct VertexShaderOutput
{
    float4 Position : SV_POSITION;
    float4 Color : COLOR0;
    float2 TextureCoordinates : TEXCOORD0;
};

float YMin;
float YMax;

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
{
    //This is what I want to do
    //if (input.Position.y <= YMin || input.Position.y >= YMax)
    //    clip(-1);

    return input.Color;
}

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

I've read online that specifying the position with the VPOS semantic would work for shader model 3, but I get errors whenever I try using it for either the VertexShaderInput, VertexShaderOutput, or both. I even tried defining another float4 in the VertexShaderOutput and setting the Position to that, but it ended up clipping all of the pixels even when I set YMin and YMax to impossibly low/high values (-10,000 and 10,000, respectively).

I would greatly appreciate it if anyone can point me in the right direction for handling this. Thanks in advance!

Posts: 2

Participants: 2

Read full topic

How to force game to always be in windowed mode?

$
0
0

@LunaArgenteus wrote:

Hi there,

I'm writing a small application for a friend and I've noticed that when the preferred back buffer is set to a size the same as or greater than my screen size, it automatically makes the game run full screen. Is it possible to set the game size to be a large value like 1920x1080 but still keep the game in windowed mode, even if the window size exceeds my screen size?

For reference, here is the code I'm currently using in my constructor:

    graphics.PreferredBackBufferHeight = 1080;
    graphics.PreferredBackBufferWidth = 1920;
    graphics.IsFullScreen = false; //This doesn't seem to matter with large sizes
    graphics.ApplyChanges();

Thank you!

Posts: 3

Participants: 3

Read full topic

Triangles appear transparent under certain angles

$
0
0

@SquareBread wrote:

Hi guys, I've started using MonoGame over the weekend and I love it! After doing the Hello World of graphics programming, I want to dive a little deeper. I have implemented the diamond square algorithm to procedurally generate some low poly terrain. I generate a heightmap and then group three of the vertices to a triangle together. It works like a charm, except that some of my triangles, usually high ones, appear transparent under certain camera angles.

Video where it shows the problem

Because of the way I numbered the triangles in my head, I had to flip every other triangles normal, because it appeared only black. But in the video, it doesn't seem to follow a pattern, other than its the highest triangles that have this transparency problem. Now that I think about it. The "highest" triangles are the only ones that are in front of other triangles. So is this maybe a problem of the order I draw the triangles in?
Does someone have an idea where this problem might come from? Is it a lighting problem? Or is it the Normals?

These are my lighting settings:

basicEffect = new BasicEffect(GraphicsDevice)
            {
                Alpha = 1.0f,
                VertexColorEnabled = false,
                LightingEnabled = true,
                DiffuseColor = new Vector3(0.949f, 0.854f, 0.431f),
                SpecularColor = new Vector3(0.2f, 0.2f, 0.2f),
                SpecularPower = 5f,
                //AmbientLightColor = new Vector3(0.5f, 0.5f, 0.5f),
                Texture = Content.Load<Texture2D>("terrain_texture"),
                TextureEnabled = true,
            };
            basicEffect.DirectionalLight0.Direction = Vector3.Normalize(new Vector3(1, -1, 0));
            basicEffect.DirectionalLight0.DiffuseColor = Color.Yellow.ToVector3();
            basicEffect.DirectionalLight0.SpecularColor = Color.Red.ToVector3();
            basicEffect.DirectionalLight0.Enabled = true;

Posts: 5

Participants: 2

Read full topic

[SOLVED] XML Importer failure

$
0
0

@Tankerpat wrote:

Hi guys
Sorry in advance for my bad english level.

This week I had a big pb.I had a link to the file, and delete it ......
I make backup all the week but, my serialize method doesnt exist now.

I remember my try hard for a successful.

Serialize method

using (XmlWriter writer = XmlWriter.Create(fileName))
            {
                    IntermediateSerializer.Serialize(writer, level.renderer._lightListEmitter, null);
            }

My XML file

<?xml version="1.0" encoding="UTF-8"?>
-<XnaContent xmlns:Generic="System.Collections.Generic">
-<Asset Type="Generic:List[Setting.LightEmitter]">
+<Item>
-<Item>
<name>InStory</name>
-<_LightList>
-<Item>
<Createposition>576 384 100</Createposition>
<position>576 384 100</position>
<color>0 0 255</color>
<normal>1 0 0</normal>
<corrector>1</corrector>
<Lenght>768 768</Lenght>
<AxisZ>1</AxisZ>
<InvDir>false</InvDir>
<theta>0</theta>
<renderer>0</renderer>
<nameOfEngine Null="true"/>
<radius>0</radius>
<bounds>768 768</bounds>
<intensity>1</intensity>
<extend>1 1 1</extend>
<additiveblendBool>true</additiveblendBool>
<isFullScreen>false</isFullScreen>
<is_Selectioned>false</is_Selectioned>
<Id_Light>0</Id_Light>
<select>true</select>
<technique>0</technique>
</Item>
</_LightList>
<ID_>0</ID_>
<MaxLight>1</MaxLight>
<MaxLightAutorisation>10</MaxLightAutorisation>
<technique>0</technique>
</Item>
-<Item>
<name>Layer</name>
-<_LightList>
-<Item>
<Createposition>768 384 100</Createposition>
<position>768 384 100</position>
<color>0 0 255</color>
<normal>1 0 0</normal>
<corrector>1</corrector>
<Lenght>768 768</Lenght>
<AxisZ>1</AxisZ>
<InvDir>false</InvDir>
<theta>0</theta>
<renderer>0</renderer>
<nameOfEngine Null="true"/>
<radius>0</radius>
<bounds>768 768</bounds>
<intensity>1</intensity>
<extend>1 1 1</extend>
<additiveblendBool>false</additiveblendBool>
<isFullScreen>true</isFullScreen>
<is_Selectioned>false</is_Selectioned>
<Id_Light>0</Id_Light>
<select>true</select>
<technique>0</technique>
</Item>
-<Item>
<Createposition>768 704 100</Createposition>
<position>768 704 100</position>
<color>0 0 255</color>
<normal>1 0 0</normal>
<corrector>1</corrector>
<Lenght>768 768</Lenght>
<AxisZ>1</AxisZ>
<InvDir>false</InvDir>
<theta>0</theta>
<renderer>0</renderer>
<nameOfEngine Null="true"/>
<radius>0</radius>
<bounds>768 768</bounds>
<intensity>1</intensity>
<extend>1 1 1</extend>
<additiveblendBool>true</additiveblendBool>
<isFullScreen>false</isFullScreen>
<is_Selectioned>false</is_Selectioned>
<Id_Light>1</Id_Light>
<select>true</select>
<technique>0</technique>
</Item>
</_LightList>
<ID_>1</ID_>
<MaxLight>2</MaxLight>
<MaxLightAutorisation>10</MaxLightAutorisation>
<technique>0</technique>
</Item>
</Asset>
</XnaContent>

I have create a library, add my dll into my project reference.
I use [ContentSerializerIgnore].
I load like that

string filename = string.Format("C:/NSOMSettings/Light/light{0}", levelIndex); //Light C:/NSOMSettings/
            if (System.IO.File.Exists(filename))
            {
                    renderer._lightListEmitter = game.Content.Load<List<LightEmitter>>(filename);
            }

But now no light0.xnb was created :frowning:

Before my mistake it works perfectly :confused:

If you want more information, let me known.

Thank you in advance

Posts: 4

Participants: 2

Read full topic


How to properly add a matrix to a Instanced Vertex definition ?

$
0
0

@willmotil wrote:

Im not very good at hlsl semantics.
What is the prefered or proper way to pass a orientation matrix thru to a shader.

Specifically the questions i have at the moment are related to passing and accessing.

Which data type should i use?
Is it ok to use position or should i use blendweights or texturecoordinates whats the difference ?
Are there limits to how many i can pass of a type ?
Are there specific cavets or hlsl access rules for them ?

the cs.

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Runtime.InteropServices;

namespace GLParticleTestTrimed
{
    public class Game2_HwiShader05 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        SpriteFont font;
        ParticleSystem05 particleSystem;
        Matrix viewProjection;
        Texture2D particleTexture;
        Effect particlesEffect;

        // basically a elaborate timing device.
        float cyclePercentage = 0f;
        double fullCycleTimeInSeconds = 1.2d;
        double cycleTime = 0d;
        double elapsedUpdateTime = 0;
        double last = 0d;
        double now = 0d;

        public Game2_HwiShader05()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.GraphicsProfile = GraphicsProfile.HiDef;
            graphics.PreferMultiSampling = false;
            Window.AllowUserResizing = true;
            graphics.PreferredBackBufferWidth = 1024;
            graphics.PreferredBackBufferHeight = 768;
            Content.RootDirectory = "Content";
        }

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

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            font = Content.Load<SpriteFont>("MgFont");

            particlesEffect = Content.Load<Effect>("ParticleEffect03GL");
            particleTexture = Content.Load<Texture2D>("particle");

            particleSystem = new ParticleSystem05(particlesEffect)
            {
                // Set this to blast out more particles
                InstanceCount = 10000,
                ParticleSize = new Vector2(3.0f, 7.0f),
                ParticleTexture = particleTexture
            };

            SetUpViewProjection();

            particleSystem.IntializeParticleSystemBuffers(GraphicsDevice);
        }

        public void SetUpViewProjection()
        {
            // Setup the worldViewProj matrix
            float width = GraphicsDevice.PresentationParameters.BackBufferWidth;
            float height = GraphicsDevice.PresentationParameters.BackBufferHeight;
            float aspect = width / height;
            Matrix viewMatrix = Matrix.CreateLookAt(new Vector3(0.01f, 0.01f, 5.0f), Vector3.Forward, Vector3.Up);
            Matrix projMatrix = Matrix.CreatePerspectiveFieldOfView(1.56f, aspect, .1f, 1000);
            viewProjection = viewMatrix * projMatrix;
        }

        protected override void UnloadContent()
        {
            Content.Unload();
        }

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

            CycleTiming(gameTime);
            particleSystem.UpdateParticleTime((float)(cyclePercentage));

            base.Update(gameTime);
        }

        public void CycleTiming(GameTime gameTime)
        {
            last = now;
            now = gameTime.TotalGameTime.TotalSeconds;
            elapsedUpdateTime = now - last;
            cycleTime += elapsedUpdateTime;
            if (cycleTime >= fullCycleTimeInSeconds)
                cycleTime -= fullCycleTimeInSeconds;
            cyclePercentage = (float)(cycleTime / fullCycleTimeInSeconds);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
            GraphicsDevice.BlendState = BlendState.Additive;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            particleSystem.DrawParticles(viewProjection, GraphicsDevice);

            spriteBatch.Begin();
            spriteBatch.DrawString(font, cyclePercentage.ToString(), new Vector2(20, 20), Color.Green);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }

    public class ParticleSystem05
    {
        // Vertex data
        VertexBuffer vertexBuffer;
        IndexBuffer indexBuffer;
        VertexBufferBinding vertexBufferBinding;

        // Instance data
        InstanceDataOrientation[] instanceDataOrientaion;
        VertexBuffer instanceBuffer;
        VertexBufferBinding instanceBufferBinding;

        int numInstancesToDraw;
        float cyclePercentageTime = 0;

        Effect particlesEffect;

        public Vector2 ParticleSize { get; set; }
        public Texture2D ParticleTexture { get; set; }
        public uint InstanceCount { get; set; }
        public int MaxVisibleParticles
        {
            get; private set;
        }

        public ParticleSystem05(Effect effect)
        {
            particlesEffect = effect;
        }

        public void IntializeParticleSystemBuffers(GraphicsDevice graphicsDevice)
        {
            // set up the indice stuff

            int[] indices = new int[6];
            // indices to triangle vertices
            indices[0] = 1; indices[1] = 0; indices[2] = 2; // ccw
            indices[3] = 3; indices[4] = 1; indices[5] = 2;
            // 
            indexBuffer = new IndexBuffer(graphicsDevice, typeof(int), 6, BufferUsage.WriteOnly);
            indexBuffer.SetData(indices);

            // set up the vertex stuff

            // Create a single quad centered at the origin
            float halfParticleWidth = ParticleSize.X / 2;
            float halfParticleHeight = ParticleSize.Y / 2;
            float z = 0.0f;
            VertexPositionTexture[] vertices = new VertexPositionTexture[4];
            //vertices[3].texCoordinate = new Vector2(1.0f, 1.0f);
            vertices[0].position = new Vector3(-halfParticleWidth, -halfParticleHeight, z); // lt 0
            vertices[1].position = new Vector3(halfParticleWidth, -halfParticleHeight, z); // rt 1
            vertices[2].position = new Vector3(-halfParticleWidth, halfParticleHeight, z); // lb 2
            vertices[3].position = new Vector3(halfParticleWidth, halfParticleHeight, z); // rb 3
            // u,v texture coords
            vertices[0].texCoordinate = new Vector2(0.0f, 0.0f);
            vertices[1].texCoordinate = new Vector2(1.0f, 0.0f);
            vertices[2].texCoordinate = new Vector2(0.0f, 1.0f);
            vertices[3].texCoordinate = new Vector2(1.0f, 1.0f);
            // 
            vertexBuffer = new VertexBuffer(graphicsDevice, VertexPositionTexture.VertexDeclaration, 4, BufferUsage.WriteOnly);
            vertexBuffer.SetData(vertices);
            vertexBufferBinding = new VertexBufferBinding(vertexBuffer);

            // set up the instance stuff

            MaxVisibleParticles = (int)(InstanceCount);
            instanceDataOrientaion = new InstanceDataOrientation[MaxVisibleParticles];

            // set particles randomly
            Random rnd = new Random();

            /* randomly places the particle positions, and color changer */

            float halfWidth = graphicsDevice.PresentationParameters.BackBufferWidth * .5f;
            float halfHeight = graphicsDevice.PresentationParameters.BackBufferHeight * .5f;
            for (int i = 0; i < MaxVisibleParticles; ++i)
            {
                // instance orientation;
                instanceDataOrientaion[i].instanceForward = Vector3.Forward;
                instanceDataOrientaion[i].instanceUp = Vector3.Up;
                instanceDataOrientaion[i].instanceLeft = Vector3.Left;
                // instance data float position
                instanceDataOrientaion[i].instancePosition = new Vector3
                    (
                    (rnd.Next(0, (int)(halfWidth) * 2) - halfWidth),
                    (rnd.Next(0, (int)(halfHeight * 2)) - halfHeight),
                    ((float)(rnd.Next(1, MaxVisibleParticles + 1)) / (float)(MaxVisibleParticles + 1) * 650 + 350) * -1f
                    );
                // instance data float time
                instanceDataOrientaion[i].instanceTimeOrId = (float)(rnd.Next(0, MaxVisibleParticles + 1)) / (float)(MaxVisibleParticles + 1);//(float)(i) / (float)(MaxVisibleParticles + 1f); // for a timed id
            }
            
            instanceBuffer = new VertexBuffer(graphicsDevice, InstanceDataOrientation.VertexDeclaration, MaxVisibleParticles, BufferUsage.WriteOnly);
            instanceBufferBinding = new VertexBufferBinding(instanceBuffer, 0, 1);
            instanceBuffer.SetData(instanceDataOrientaion);
        }

        // We could draw less instances here.
        public void UpdateParticleTime(float seconds)
        {
            // i could use my dynamic dead alive buffer here to keep the sorting smooth.
            numInstancesToDraw = MaxVisibleParticles;
            cyclePercentageTime = seconds;
        }

        public void DrawParticles(Matrix viewProj, GraphicsDevice graphicsDevice)
        {
            // Select the technique.
            particlesEffect.CurrentTechnique = particlesEffect.Techniques["ParticleDrawingSimple"];
            // Initialise our shader constants
            particlesEffect.Parameters["ViewProjection"].SetValue(viewProj);
            particlesEffect.Parameters["ParticleTexture"].SetValue(ParticleTexture);
            particlesEffect.Parameters["CyclePercentageTime"].SetValue(cyclePercentageTime);
            // Set buffers to device
            graphicsDevice.SetVertexBuffers(vertexBufferBinding, instanceBufferBinding);
            graphicsDevice.Indices = indexBuffer;
            // Draw
            particlesEffect.CurrentTechnique.Passes[0].Apply();
            graphicsDevice.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0, 2, numInstancesToDraw);
        }
    }

    // the instanceDataType
    [StructLayout(LayoutKind.Sequential)]
    public struct InstanceDataOrientation : IVertexType
    {
        public Vector3 instanceForward;
        public Vector3 instanceUp;
        public Vector3 instanceLeft;
        public Vector3 instancePosition;
        public float instanceTimeOrId;
        public static readonly VertexDeclaration VertexDeclaration;
        static InstanceDataOrientation()
        {
            var elements = new VertexElement[]
                {
                    new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 1), // The usage index must match.
                    new VertexElement(12, VertexElementFormat.Single, VertexElementUsage.BlendWeight, 0),
                    new VertexElement(24, VertexElementFormat.Vector3, VertexElementUsage.BlendWeight, 1),
                    new VertexElement(36, VertexElementFormat.Vector3, VertexElementUsage.BlendWeight, 2),
                    new VertexElement(48, VertexElementFormat.Vector3, VertexElementUsage.BlendWeight, 3),
                    //new VertexElement( offset in bytes, VertexElementFormat.Single, VertexElementUsage. option, shader element usage id number )
                };
            VertexDeclaration = new VertexDeclaration(elements);
        }
        VertexDeclaration IVertexType.VertexDeclaration
        {
            get { return VertexDeclaration; }
        }
    }

    // the vertexDataType
    [StructLayout(LayoutKind.Sequential)]
    public struct VertexPositionTextureNormal : IVertexType
    {
        public Vector3 position;
        public Vector2 texCoordinate;
        public static readonly VertexDeclaration VertexDeclaration;
        static VertexPositionTextureNormal()
        {
            var elements = new VertexElement[]
                {
                    new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
                    new VertexElement(12, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0),
                };
            VertexDeclaration = new VertexDeclaration(elements);
        }
        VertexDeclaration IVertexType.VertexDeclaration
        {
            get { return VertexDeclaration; }
        }
    }
}

the shader

// FxHwInstanceing05.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
#define PS_SHADERMODEL ps_4_0
#endif
//_________________________________________________________________

static const float PI = 3.14159;
static const float PI2 = 6.28318;
static const float EIGHT_PI = 25.13274;

matrix ViewProjection;
float CyclePercentageTime;

Texture2D ParticleTexture;
sampler2D TexSampler = sampler_state
{
    Texture = <ParticleTexture>;
    //AddressU = Wrap;//AddressV = Wrap;//MinFilter = Anisotropic;//MagFilter = Anisotropic;//MipFilter = Point;
};

//__________________________________________________________

struct VSInstanceInputSimple
{

    float3 InstancePosition : POSITION1;
    float InstanceTimeOrId : BLENDWEIGHT0;
    float3 InstanceForward : BLENDWEIGHT1;
    float3 InstanceUp : BLENDWEIGHT2;
    float3 InstanceLeft : BLENDWEIGHT3;
};

struct VSVertexInputSimple
{
    float4 Position : POSITION0;//SV_POSITION;
    float2 TexCoord : TEXCOORD0;
    //float3 Normal : NORMAL0;
};

struct VSOutputSimple
{
    float4 Position : SV_POSITION;
    float2 TexCoord : TEXCOORD0;
    float4 Color : COLOR0;
};

VSOutputSimple MainVSSimple(in VSVertexInputSimple vertexInput, VSInstanceInputSimple instanceInput)
{
        VSOutputSimple output;
        // first i have to get this all to compile without error.
        float3 instancePosition = instanceInput.InstancePosition;
        float instanceTimeOrId = instanceInput.InstanceTimeOrId;
        // create the world
        float4x4 world;
        world[0] = float4(instanceInput.InstanceForward, 0.0f);
        world[1] = float4(instanceInput.InstanceUp, 0.0f);
        world[2] = float4(instanceInput.InstanceLeft, 0.0f);
        world[3] = float4(instancePosition, 0.0f); // <- i may need to zero this out first lets see.
        matrix worldViewProjection = mul(world, ViewProjection);
        // here is the tricky part the intention is to put this into the proper wvp position in one shot.
        // however i might have to mult the world without translation.
        // then translate the vertexposition by the instanceposition and multiply.
        float4 posVert = mul(vertexInput.Position, ViewProjection);
        output.Position = posVert;

        // pass textcoords thru
        output.TexCoord = vertexInput.TexCoord;

        // change color
        float4 colRed = float4(1.0f, 0.0f, 0.0f, .99f);
        float4 colGreen = float4(0.0f, 1.0f, 0.0f, .99f);
        float4 colBlue = float4(0.0f, 0.0f, 1.0f, .99f);
        output.Color =
            (colRed * instanceTimeOrId) + // colors are based on the instance id or time not x y order as such they go from zero to 1 and blue is drawn first.
            (colGreen* ((0.5f - abs(instanceTimeOrId - 0.5f))*2.0f)) +
            (colBlue * (1.0f - instanceTimeOrId));
        output.Color.a = 1.0f;

        return output;
}

float4 MainPSSimple(VSOutputSimple input) : COLOR0
{
    float4 col = tex2D(TexSampler, input.TexCoord) *  input.Color;
    // straight clip alpha draws
    clip(col.a - .05f);
    return col;
}

technique ParticleDrawingSimple
{
    pass
    {
        VertexShader = compile VS_SHADERMODEL MainVSSimple();
        PixelShader = compile PS_SHADERMODEL MainPSSimple();
    }
};

it also uses a small texture.

Well it's compiling with blendweights but im getting a error on my passed view projection matrix that says its not set to a instance of a object ? though it looks set to me.

Posts: 1

Participants: 1

Read full topic

Is there a good open source 2D game?

$
0
0

@CidHighwind wrote:

I am currently building a relativ big 2D game with monogame. I am currently redoing my game object code and was wondering how I could make it better. My problem is I do not know where I should look at. Is there a game which is open source (preferably in c# or java) I could take a look at? Or maybe a good book you can recommend? My problem is not that I do not know how it could be done but more that I do not know how it could be done in a nice way.

Posts: 1

Participants: 1

Read full topic

Is there a guide on how the entity/component system works?

$
0
0

@exts wrote:

It's kind of strange how little documentation there is for Monogame.Extended, after tinkering with Screens I understand how that works, now I'm trying to understand the entity component system as the only examples are in the demos and each demo varies from demo to demo not making it clear how the entity component system actually works.

Basically I'm trying to understand how to make entities and entity components, then understand how they work together.

Also, some of those demos have attributes are there any explanations how those are incorporated as well?

Posts: 2

Participants: 2

Read full topic

A simple monogame fps display class.

$
0
0

@willmotil wrote:

I was organizing my examples and thought i would post this for anyone who just wants a quick fps counter or to see how to do it.

Here is the game1 example of the class being used.
Its very simple to use 3 lines of code;

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

namespace SimpleFpsCounter
{
    public class Game1 : Game
    {
        private GraphicsDeviceManager graphics;
        private SpriteBatch spriteBatch;
        SpriteFont font;
        KeyboardState previousState;
        
        // Add the class
        SimpleFps fps = new SimpleFps();

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

        protected override void Initialize()
        {
            this.TargetElapsedTime = TimeSpan.FromSeconds(1d / 60d);
            this.IsFixedTimeStep = false;
            graphics.SynchronizeWithVerticalRetrace = false;
            graphics.ApplyChanges();
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            font = Content.Load<SpriteFont>("PipeLineToolCreatedFont");
        }

        protected override void UnloadContent() { }

        protected override void Update(GameTime gameTime)
        {
            KeyboardState state = Keyboard.GetState();
            if (state.IsKeyDown(Keys.Escape))
                Exit();

            // Update the fps
            fps.Update(gameTime);

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Moccasin);

            spriteBatch.Begin();

            // Draw the fps msg
            fps.DrawFps(spriteBatch, font, new Vector2(10f, 10f), Color.MonoGameOrange);

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

Here is the class.
You can just add the class below the game1 class to test it.

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace SimpleFpsCounter
{
    public class SimpleFps
    {
        private double frames = 0;
        private double updates = 0;
        private double elapsed = 0;
        private double last = 0;
        private double now = 0;
        public double msgFrequency = 1.0f; 
        public string msg = "";

        /// <summary>
        /// The msgFrequency here is the reporting time to update the message.
        /// </summary>
        public void Update(GameTime gameTime)
        {
            now = gameTime.TotalGameTime.TotalSeconds;
            elapsed = (double)(now - last);
            if (elapsed > msgFrequency)
            {
                msg = " Fps: " + (frames / elapsed).ToString() + "\n Elapsed time: " + elapsed.ToString() +  "\n Updates: " + updates.ToString() + "\n Frames: " + frames.ToString();
                //Console.WriteLine(msg);
                elapsed = 0;
                frames = 0;
                updates = 0;
                last = now;
            }
            updates++;
        }

        public void DrawFps(SpriteBatch spriteBatch, SpriteFont font, Vector2 fpsDisplayPosition, Color fpsTextColor)
        {
            spriteBatch.DrawString(font, msg, fpsDisplayPosition, fpsTextColor);
            frames++;
        }
}
}

Posts: 1

Participants: 1

Read full topic

Artifacts on tilemap when scaling [Solved]

$
0
0

@DrBasse wrote:


As you can see on the pictures, I get artifacts when scaling my tilemap. This happens both if I resize the rectangle and if I use proper scaling in the draw call.

I cant figure this out. What am I missing here?

Best,
Dr

Posts: 3

Participants: 2

Read full topic

Viewing all 6821 articles
Browse latest View live