Monday, August 1, 2016

Only 12 Enemies, And My Fps Drops To 30, Why Is That?(Solved)

Only 12 Enemies, And My Fps Drops To 30, Why Is That?(Solved)

Guys, I have 7 animated enemies. And my fps is 62 for now( not capped). But when I add 5 more enemies and make them 12, my fps drops to 31. I traced the problem and I finally found it, it's my BoneTransform() function, which fills my vector of TransformMatrices that I use in the vertex shader in order to animate the skeleton. But it rapes my CPU. ( when I comment the BoneTransform() function, framerate goes from 30 to 166!( sometimes jumps between 166 and 200 ). And I kind of stole most of the function from a tutorial on skeletal animation, and I'm sure it's pretty optimized, so there must be some other reason.

 

lowfps.gif

 

I used some models from World of Warcraft. And the interesting thing is that I have the game, and when I play it( when I play WoW ), I can have 20 players around me, and my fps is great, but when I add the same models in my own game, my fps drops like crazy and it's 10 times slower than the original game, why? ( bear in mind that I haven't even loaded any map, I just spawn 12 enemies walking on air, and my cpu runs like a fat truckdriver, wtf is that?? ).


Unity 5 - 2D Tower Defense Tutorial

Unity 5 - 2D Tower Defense Tutorial

Video tutorial:
http://bit.ly/29aQHZs

 

 

Official page of inScope:
 
Description
This tutorial will teach you how to create a 2D tower defense games in Unity. When you have completed the tutorial, you will have a finished game with a "Beginning and an End". Below are some of the things, that we will be implementing in the game.
 
Towers
We will be implementing 4 kinds of towers in our game.
 
Fire tower: This tower shoots fire projectiles, these projectiles has a chance to apply a fire debuff. The fire debuff is a damage over time effect. When applied to a monster it deals damage every x amount of seconds, as long as the debuff is applied to a target.
 
FireTower.png
 
Frost tower: This tower fires frost projectiles. These projectiles has a chance to apply a frost debuff, that slows down the targets movement speed
 
.FrostTower.png
 
Poison tower: This tower fires poison projectiles. These projectiles has a chance to apply a poison debuff, this debuff drops poison on the ground behind the target. If another mob steps in the poison it will take damage.
 
PoisonTower.png
 
Storm tower: This tower fires thunderbolt projectiles, these projectiles has a chance to apply a storm debuff to the target. This debuff will stun the target for an amount of seconds.
 
StormTower.png
 
Monsters
We will also be adding 4 kinds of monsters to the game
 
Red: This monster takes less damage from fire towers, and is immune to fire debuffs.
Blue: This monster takes less damage from frost towers, and is immune to frost debuffs.
Purple: This monster takes less damage from storm towers, and is immune to storm debuffs.
Green: This monster takes less damage from poison towers, and is immune to poison debuffs.
 
 
What will you learn?
General Object oriented C# programming
 
  • Structs
  • Dictionaries
  • Stacks
  • Lambda expressions
  • ICompareable interface
  • Operator overloading
  • Abstract classes
  • Abstract methods
  • Inheritance
  • Constructors
  • Constructor overloading
  • Instantiating objects
  • Virtual methods
  • Overloading methods
  • Enumerations
  • Generics
Design patterns
 
  • Singleton
  • Object pool
Algorithms
 
  • A* algorithm for pathfinding
Game mechanics
 
  • Generating a tile map based on a text document
  • Creating a loading screen with a loading bar
  • Using the A* algorithm to find a path from start to goal
  • Creating debuffs
  • Adding a health bar to the mobs
  • Creating towers with different stats
  • Upgrading towers
  • Showing tooltips ingame
  • Setting win and lose conditions
  • Restarting the game
  • Camera movement inside level bounds
  • Buying and selling towers
  • Spawning waves of monsters
  • Animating the towers and mobs based on their current actions
  • Adding main menu, ingame menu and an options menu
  • Adding SFX -and background sounds.
  • Adjusing the sound levels from the menu

Mess With Matrix Multiplication

Mess With Matrix Multiplication

I am currently refactoring the code and i bumped once again on the shader. There is something definitely wrong. I read the "mul" documentation, the row/column matrix/vector and in my opinion, the math in my shader is wrong, but suddenly it turns out that it renders properly...

 

So, inside my shader file i have

cbuffer cbPerFrameViewProjection : register(b1)
{
    column_major float4x4 PV;
};

cbuffer cbPerObjectWorldMatrix : register(b0)
{
    column_major float4x4 World;
};

Where "PV" is set once at the beginning of a frame, and world is per object.

 

The multiplication inside vertex shader

float4x4 wvp = mul(World, PV);
output.Pos = mul(wvp,inPos);

I set the constant buffers like that:

Camera:

&XMMatrixTranspose(cam.GetViewMatrix()*cam.GetProjectionMatrix())

And for every object:

&XMMatrixTranspose(world.GetTransform())

Now the maths: C++ stores matrices as row major, hlsl as column.

Camera ((view row * projection row) transposed) equals to (((projection column * view column) transposed) transposed) which is (projection column * view column).

World row transposed equals to world column.

So - both constant buffers are fed a column matrices.

Then, inside shader, to count WVP transposed (which in column order is PVW) i should do mul(PV,World) from constant buffers data to get the right answer, but NOT mul(World,PV) as i do now - and the second (wrong in my opinion) solution is correct. Why is that?

 

And second problem.

Why is that correct

output.Pos = mul(inPos, wvp);

And this is wrong??

output.Pos = mul(wvp, inPos);

HLSL uses column matrices, and as far as i know from theory, to transform a vector you multiply matrix * vector.

 

Could someone explain what is goin on here? What am i missing in the matrix mess?

Thanks in advance


Multithreaded User Interface

Multithreaded User Interface

Hello, I want to move the whole UI logic + rendering, which is based on flash, on a separate thread, while the game logic will be on the main thread.

Have any of you met this problem and how did you solve it?

Do think it is practical to make any part of the UI multithreaded, or it should be left in the main thread, since there might be a lot of synchronization in some screens between the UI thread and main thread?


Coding Languages For Starting Game Design

Coding Languages For Starting Game Design

What languages do you guys find that are the easiest to work with when learning how to code for video games?

I'll read the books or take the classes or watch the videos to learn it, but it's a little overwhelming how many coding languages exist out there, so I'm just looking for a language to begin with.

 

Truth is, I've got a small amount of experience with C++ and almost nothing else (HTML doesn't really count.)

I also know there are a fair number of computer languages out there that has the processing capability to create games for all sorts of media (whether its for retro systems, arcades, PC, mobile, whatever.)  I would be most interested in coding for retro systems, but I'm open to suggestions.


Visual Studio Compilation Problem

Visual Studio Compilation Problem

I tried to compile some code and got:

fatal error C1083: Cannot open include file: 'atlimage.h': No such file or directory

 

I searched the whole computer and I have not this file. I checked vc files and microsoft windows sdk. Where I can download this file, is it included in another vc versions? I saw on the internet that not only I had this problem but I didn't find a solution.I think that this file should be in windows SDK. Could you check it?


Need Explanation With Distance Between Two Segments

Need Explanation With Distance Between Two Segments

The code below is from book Real-Time Collection Detection ch5.cpp file

Some of them I don't know where it come from.

 

float denom = a*e-b*b;

 

what does this mean?I know a is square length of d1,e is square length of d2,b is d1 projection on d2,

but what does a*e-b*b means?where this guy come from,for what reason?any rule or fomular ralated??

Can somebody point me the direction or something to figure this out.Thanks

// Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
// S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
// distance between between S1(s) and S2(t)
float ClosestPtSegmentSegment(Point p1, Point q1, Point p2, Point q2,
                              float &s, float &t, Point &c1, Point &c2)
{
    Vector d1 = q1 - p1; // Direction vector of segment S1
    Vector d2 = q2 - p2; // Direction vector of segment S2
    Vector r = p1 - p2;
    float a = Dot(d1, d1); // Squared length of segment S1, always nonnegative
    float e = Dot(d2, d2); // Squared length of segment S2, always nonnegative
    float f = Dot(d2, r);

    // Check if either or both segments degenerate into points
    if (a <= EPSILON && e <= EPSILON) {
        // Both segments degenerate into points
        s = t = 0.0f;
        c1 = p1;
        c2 = p2;
        return Dot(c1 - c2, c1 - c2);
    }
    if (a <= EPSILON) {
        // First segment degenerates into a point
        s = 0.0f;
        t = f / e; // s = 0 => t = (b*s + f) / e = f / e
        t = Clamp(t, 0.0f, 1.0f);
    } else {
        float c = Dot(d1, r);
        if (e <= EPSILON) {
            // Second segment degenerates into a point
            t = 0.0f;
            s = Clamp(-c / a, 0.0f, 1.0f); // t = 0 => s = (b*t - c) / a = -c / a
        } else {
            // The general nondegenerate case starts here
            float b = Dot(d1, d2);
            float denom = a*e-b*b; // Always nonnegative,======================================Here is the one ======================================

            // If segments not parallel, compute closest point on L1 to L2, and
            // clamp to segment S1. Else pick arbitrary s (here 0)
            if (denom != 0.0f) {
                s = Clamp((b*f - c*e) / denom, 0.0f, 1.0f);
            } else s = 0.0f;

            // Compute point on L2 closest to S1(s) using
            // t = Dot((P1+D1*s)-P2,D2) / Dot(D2,D2) = (b*s + f) / e
            t = (b*s + f) / e;

            // If t in [0,1] done. Else clamp t, recompute s for the new value
            // of t using s = Dot((P2+D2*t)-P1,D1) / Dot(D1,D1)= (t*b - c) / a
            // and clamp s to [0, 1]
            if (t < 0.0f) {
                t = 0.0f;
                s = Clamp(-c / a, 0.0f, 1.0f);
            } else if (t > 1.0f) {
                t = 1.0f;
                s = Clamp((b - c) / a, 0.0f, 1.0f);
            }
        }
    }

    c1 = p1 + d1 * s;
    c2 = p2 + d2 * t;
    return Dot(c1 - c2, c1 - c2);
}

The Common Way Of Making Game Localization N Unity

The Common Way Of Making Game Localization N Unity
I'm making a game that require localization(change from one language to another language) what is the common way of doing it?
 
There are two ways that I know but maybe there are some smarter ways to do it, so I wanted to ask people actually starting doing any code
 
1.Use a plugin in Unity called I2
2.Use XML and translate it manual 
 
 
 

Sunday, July 31, 2016

Vs2015 Update 3:template Does Not Work Anymore.

Vs2015 Update 3:template Does Not Work Anymore.

hi

 

I just updated my vs to vs2015 update 3.  After I created a project, i exported it to a template to be use by my other project.  after i created a new project with the template, I see my file and resource name in the solution explorer.  But when i clicked to open it, it popup a windows and said :

 

The document can not be opened.  It has been removed, renamed or deleted.

 

anyone has any idea?

 

thanks in advance


Rendering Gui Or Hud In A Separate Framebuffer

Rendering Gui Or Hud In A Separate Framebuffer

Hello, I have been trying to render the HUD for my game to a separate FrameBuffer so that I can apply my own shader effects to it that are separated from the 3D scene.

 

The problem is that I am having transparency issues. I use glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); with glClearColor(0.0f, 0.0f, 0.0f, 0.0f);, which creates a transparent black background for the HUD FrameBuffer before rendering the HUD.

 

Whenever I render a transparent HUD element to the FrameBuffer, the black gets mixed in with the original colors of the element, which is not what I want. It ends up making the HUD elements look darker than they are supposed to be when I mix the HUD FrameBuffer with the 3D Scene FrameBuffer.

 

I can change the color for glClearColor() and get different colored results, so I know that that is the root of the problem. I decided to use the blend function:

 

glBlendFuncSeparate(/*For color*/ GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,
                                    /*For alpha*/ GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

 

which was requested by someone who had a similar issue. Unfortunately it isn't working for me. I am afraid that I might need to do something involving stencil buffers to get it to work, but I want to try to avoid that and find a simpler solution. Can anyone give me any pointers?

 

Also this is made with OpenGL 4.2 with c++ and compiled with MinGW.


Tweeny, A Modern C++ Tweening Library

Tweeny, A Modern C++ Tweening Library

Hello! This post is to announce Tweeny, an inbetweening library for C++. It provides a fluid API for defining tweens, like:

auto tween = tweeny::from(0).to(50).during(100);
while (tween.progress() < 1) tween.step(1);

It supports tweens with multiple points (e.g, from 0 to 100 then to 200), multiple values (from 0, 0 to 100, 200) and multiple types (from 0, 0.0f to 10, 2.5f). It also has 30+ easing functions (based on those by Robert Penner http://ift.tt/1mCMeMf).

 

Here is a demo, compiled with emscripten, of a sprite using tweens: http://ift.tt/2aJELOV

 

- Source: http://ift.tt/2aHCbMg

- Site: http://ift.tt/2aJDZ4r

- API Doc and Manual: http://ift.tt/2aHBl2o

 

For those wondering what a tween is or why is it useful, every Game UI nowadays has some sort of tween in them: panels fade in/out, buttons wobble when hovered, things slide in/out with acceleration/deacceleration, etc. All of those pretty animations are possible through a tween with a specific easing.

 

The purpose of Tweeny is to facilitate that. For instance, to animate a button size, this is a possible solution:

auto tween = tweeny::from(button.w, button.h).to(button.w + 10, button.h + 10).during(200).via(easing::backOut);
tween.onStep([](int w, int h) { button.w = w; button.h = h; return false; });

/* later, in game loop */
tween.step(dt);

Tweeny is MIT licensed.

 

I hope this can be useful to you. Feedback is much appreciated!


Only 12 Enemies, And My Fps Drops To 30, Why Is That?

Only 12 Enemies, And My Fps Drops To 30, Why Is That?

Guys. What I did so far:

 

1.  I wanted to cap the frame rate of my game, but SDL_GetTicks() returns time since app start in Uint32 milliseconds, so I'm getting slightly wrong fps due to small rounding errors and the second reason why frame cap is bad in my case is that SDL_Delay() is not precise, as is said below.

 

fastcall22 says:

 


I would guess that relying on SDL_Delay to regulate framerate is not a good idea, since suspending a thread is not guaranteed to return exactly at the requested duration. From SDL documentation: This function [SDL_Delay] waits a specified number of milliseconds before returning. It waits at least the specified time, but possible longer due to OS scheduling. The delay granularity is at least 10 ms. Some platforms have shorter clock ticks but this is the most common. 

 

 

 

2. That's why I decided to make a frame-independent movement, so I used a variable called deltaTime which is calculated based on the current fps. Sounds cool. But the problem is that I have 7 enemies and in my 'Enemy' class I have various different functions that include movement in some direction, so I somehow need to put the deltaTime variable in all the Enemy objects every frame.

 

The braindead solution, which is what I did, is:

for( int i = 0; i < enemies.size(); i ++ )
{
    enemies[ i ].setDeltaTime( myrpg.deltaTime );
}

But I have to create 'for' loops for every single thing. For example:

        for( int i = 0; i < enemies.size() ; i ++ )
        {
            //If left mouse button is clicked and the bullet ray collides with an enemy AABB, kill the enemy.
            myrpg.kill( playerCam, enemies[ i ] );
        }

        // Clear the screen
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        for( int i = 0; i < enemies.size(); i ++ )
        {
            //If the enemy is not dead, make him run and rotate towards me.
            if( enemies[ i ].getCurrentAnim() == ANIM_RUN )
            {
                enemies[ i ].moveTowardsPlayer( playerCam.getPosition() );
            }
        }

        //Render all enemies
        for( int i = 0; i < enemies.size(); i ++ )
        {
            myrpg.renderAnimatedModel( enemies[ i ], Timer, shaderAnim, shaderStatic );
        }

It seems like I'm using C, not C++. Is there some other way I can make stuff more compact?

 

For example, can I add some virtual base class and just set deltaTime value in that class and make all the enemies inherit the variable somehow, is it possible? (it's a really stupid question, but I decided to ask in case there is something I have missed. ) I haven't used inheritance by now and I kind of don't know what are the pros it offers.

 

And the next question is:

I have 7 animated enemies. And my fps is 62 for now( not capped). But when I add 5 more enemies and make them 12, my fps drops to 31. I traced the problem and I finally found it, it's my BoneTransform() function, which fills my vector of TransformMatrices that I use in the vertex shader in order to animate the skeleton. But it rapes my CPU. ( when I comment the BoneTransform() function, framerate goes from 30 to 166!( sometimes jumps between 166 and 200 ). And I kind of stole most of the function from a tutorial on skeletal animation, and I'm sure it's pretty optimized, so there must be some other reason.

 

I used some models from World of Warcraft. And the interesting thing is that I have the game, and when I play it( when I play WoW ), I can have 20 players around me, and my fps is great, but when I add the same models in my own game, my fps drops like crazy and it's 10 times slower than the original game, why? ( bear in mind that I haven't even loaded any map, I just spawn 12 enemies walking on air, and my cpu runs like a fat truckdriver, wtf is that?? ).


Do I Need A Virtual Class Here?

Do I Need A Virtual Class Here?

Guys. What I did so far:

 

1.  I wanted to cap the frame rate of my game, but SDL_GetTicks() returns milliseconds in Uint32, so I'm getting slightly wrong fps due to small rounding errors and the second reason why frame cap is bad in my case is that SDL_Delay() is not precise, as is said below.

 

fastcall22 says:

 


I would guess that relying on SDL_Delay to regulate framerate is not a good idea, since suspending a thread is not guaranteed to return exactly at the requested duration. From SDL documentation: This function [SDL_Delay] waits a specified number of milliseconds before returning. It waits at least the specified time, but possible longer due to OS scheduling. The delay granularity is at least 10 ms. Some platforms have shorter clock ticks but this is the most common. 

 

 

 

2. That's why I decided to make a frame-independent movement, so I used a variable called deltaTime which is calculated based on the current fps. Sounds cool. But the problem is that I have 7-8 enemies and in my 'Enemy' class I have various different functions that include movement in some direction, so I somehow need to put the deltaTime variable in all the Enemy objects every frame.

 

The braindead solution, which is what I did, is:

for( int i = 0; i < enemies.size(); i ++ )
{
    enemies[ i ].setDeltaTime( myrpg.deltaTime );
}

But I have to create 'for' loops for every single thing. For example:

        for( int i = 0; i < enemies.size() ; i ++ )
        {
            //If left mouse button is clicked and the bullet ray collides with an enemy AABB, kill the enemy.
            myrpg.kill( playerCam, enemies[ i ] );
        }

        // Clear the screen
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        for( int i = 0; i < enemies.size(); i ++ )
        {
            //If the enemy is not dead, make him run and rotate towards me.
            if( enemies[ i ].getCurrentAnim() == ANIM_RUN )
            {
                enemies[ i ].moveTowardsPlayer( playerCam.getPosition() );
            }
        }

        //Render all enemies
        for( int i = 0; i < enemies.size(); i ++ )
        {
            myrpg.renderAnimatedModel( enemies[ i ], Timer, shaderAnim, shaderStatic );
        }

It seems like I'm using C, not C++. Is there some other way I can make stuff more compact?

 

For example, can I add some virtual base class and just set deltaTime value in that class and make all the enemies inherit the variable somehow, is it possible? (it's a really stupid question, but I decided to ask if there is something I have missed. ) I haven't used inheritance by now and I kind of don't know what are the pros it offers.

 

And the next question is:

I have 7 animated enemies. And my fps is 62 for now( not capped). But when I add 5 more enemies and make them 12, my fps drops below 30. I traced the problem and I finally found it, it's my BoneTransform() function, which fills my vector of TransformMatrices that I use in the vertex shader in order to animate the skeleton.

 

I used some models from World of Warcraft. And the interesting thing is that I have the game, and when I play it( when I play WoW ), I can have 20 players around me, and my fps is great, but when I add the same models in my own game, my fps drops like crazy and it's 10 times slower than the original game, why?


Console.writeline Not Printing Out Expression. C#

Console.writeline Not Printing Out Expression. C#

Why does this code not work?

Console.WriteLine(7/2)

It doesn't print anything on the console.


Vs2015:sdl2 Errors While Building Project

Vs2015:sdl2 Errors While Building Project

hi

 

I am just trying to test whether i can setup the SDL2 in vs2015 update 3.

 

I installed sdl2 by nuget package manager.  

 

after i compiled the project, I got the following error output:

 

1>------ Build started: Project: SDL_test, Configuration: Release x64 ------
1>SDL2main.lib(SDL_windows_main.obj) : error LNK2001: unresolved external symbol __imp_fprintf
1>C:\Users\robert\Documents\Visual Studio 2015\Projects\SDL_test\x64\Release\SDL_test.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
 
and my source file sdl2 wiki:
 
// Example program:
// Using SDL2 to create an application window
//
 
#include "SDL.h"
#include <stdio.h>
extern "C" { FILE __iob_func[3] = { *stdin,*stdout,*stderr }; }  // this is one of the suggestions. it does not work with or w/o the fix
 
int main(int argc, char* argv[]) {
 
SDL_Window *window;                    // Declare a pointer
 
SDL_Init(SDL_INIT_VIDEO);              // Initialize SDL2
 
  // Create an application window with the following settings:
window = SDL_CreateWindow(
"An SDL2 window",                  // window title
SDL_WINDOWPOS_UNDEFINED,           // initial x position
SDL_WINDOWPOS_UNDEFINED,           // initial y position
640,                               // width, in pixels
480,                               // height, in pixels
SDL_WINDOW_OPENGL                  // flags - see below
);
 
// Check that the window was successfully created
if (window == NULL) {
// In the case that the window could not be made...
printf("Could not create window: %s\n", SDL_GetError());
return 1;
}
 
// The window is open: could enter program loop here (see SDL_PollEvent())
 
SDL_Delay(3000);  // Pause execution for 3000 milliseconds, for example
 
 // Close and destroy the window
SDL_DestroyWindow(window);
 
// Clean up
SDL_Quit();
return 0;
}
 
I googled lnk2001 but do not understand what it meant, it was as if they are not english.  I also tried some of the suggestions on the web but still can not build the project.
 
any help is welcome.
 
thanks in advance

Approximate Average Brightness Of Rendered Image

Approximate Average Brightness Of Rendered Image

So in GLSL shader I have an FBO RGB image. What I need to find out is how bright it is. I need to do it real-time inside shader. How to do it?


How Can I Create A Successful Game In Unreal Engine

How Can I Create A Successful Game In Unreal Engine

can you help for a sucessful game devlopment on unreal engine 4?

i really want to make realistic and sucessful.


Height Map Through Compute Shader, Need Some Pointers

Height Map Through Compute Shader, Need Some Pointers

Hi all,

For about 2 weeks now I've been struggling with an exercise I can't figure out so far.

Here's the goal, in short:

 

- render waves through a vertex and pixel shader

-- where the height of the waves vertices are read from a texture, containing floats (each float contains the height of a wave vertex)

- use a compute shader to update the wave heights

- update them, and render again etc.

 

My first goal is to achieve a situation where at least I get no errors/ warnings and the Compute shader works, stores the new texture, which then is read by the rendering effect, fetching these height map values for the wave vertices.

 

In my book it says to do this, I would need 4 textures in the compute shader:

// textures containing single floats
Texture2D       gPrevSolInput;
Texture2D       gCurrSolInput;

RWTexture2D<float> gCurrSolOutput;
RWTexture2D<float> gNextSolOutput;

Here are some relevant code snippers of my current (non-working) approach.
Let me know if you need other parts to be able to identify the issue.

 

The extra line in the existing rendering function, right before drawint the waves:

        Effects::mBasicFX->SetWavesHeightMap(mWavesCS.mOutputNextSolUAV);

The basic rendering effects (VS and PS), which should fetch the height map:

Texture2D gWavesHeightMap;

SamplerState samHeightMap
{
        Filter = MIN_MAG_MIP_POINT;

        AddressU = WRAP;
        AddressV = WRAP;
};

VertexOut VS(VertexIn vin)
{
        VertexOut vout;

        // Retrieve wave height map data
        if(gIsWaves)
        {
                float heightMapVal = gWavesHeightMap.SampleLevel(samHeightMap, vin.Tex, 0.0f).r;
                vin.PosL.y = heightMapVal;
        }

Calling the compute shader and the compute shader itself:

void CSWrapper::ExecuteCS(ID3D11DeviceContext *dc)
{
        ID3D11ShaderResourceView *nullSRV[2] = { 0, 0 };
        ID3D11UnorderedAccessView *nullUAV[2] = { 0, 0 };

        D3DX11_TECHNIQUE_DESC techDesc;
        Effects::mWavesCSFX->mWavesTech->GetDesc(&techDesc);

        for(UINT p=0;p<techDesc.Passes;++p)
        {
                Effects::mWavesCSFX->SetInputPrevSolSRV(mInputPrevSolSRV);
                Effects::mWavesCSFX->SetInputCurrSolSRV(mInputCurrSolSRV);

                Effects::mWavesCSFX->SetOutputCurrSolUAV(mOutputCurrSolUAV);
                Effects::mWavesCSFX->SetOutputNextSolUAV(mOutputNextSolUAV);

                Effects::mWavesCSFX->mWavesTech->GetPassByIndex(p)->Apply(0, dc);

                // grid 160x160 = 25.600 threads needed, /64 (group size 64,1,1) = 400
                dc->Dispatch(400, 1, 1);
        }

        // clean up
        dc->CSSetShaderResources(0, 2, nullSRV);
        dc->CSSetUnorderedAccessViews(0, 2, nullUAV, 0);

        // disable compute shader
        dc->CSSetShader(0, 0, 0);
}

[numthreads(64, 1, 1)]
void CS(int3 dispatchThreadID : SV_DispatchThreadID)
{
        gNextSolOutput[dispatchThreadID.xy] = gCurrSolInput[dispatchThreadID.xy] + 0.01f;

        gCurrSolOutput[dispatchThreadID.xy] = gNextSolOutput[dispatchThreadID.xy];
}

Creating the 4 textures and SRV/UAV's for (compute) shader:

void CSWrapper::Init(ID3D11Device *pDevice, ID3D11DeviceContext *dc, DirectX::XMFLOAT3* pPrevSolution, DirectX::XMFLOAT3* pCurrSolution, const int pM, const int pN)
{
        // There are 4 views

        // 2 input SRV's        -> prev and curr solution
        // 2 output UAV's       -> curr and next solution

        // The SRV's has to initially be filled and created: textures
        
        /***************************************/
        /**** 1: input SRV (prev solution)      ****/
        /***************************************/

        // create texture
        D3D11_TEXTURE2D_DESC inputPrevSolTexDesc;
        inputPrevSolTexDesc.Width                               = pM;           // grid size of the waves, rows
        inputPrevSolTexDesc.Height                              = pN;           // grid size of the waves, colums
        inputPrevSolTexDesc.MipLevels                   = 1;
        inputPrevSolTexDesc.ArraySize                   = 1;
        inputPrevSolTexDesc.Format                              = DXGI_FORMAT_R32_FLOAT;
        inputPrevSolTexDesc.SampleDesc.Count    = 1;
        inputPrevSolTexDesc.SampleDesc.Quality  = 0;
        inputPrevSolTexDesc.Usage                               = D3D11_USAGE_DEFAULT;
        inputPrevSolTexDesc.BindFlags                   = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
        inputPrevSolTexDesc.CPUAccessFlags              = 0;
        inputPrevSolTexDesc.MiscFlags                   = 0;

        // initial texture data
        float *tempArrayA = new float[pM*pN];
        for(int i=0;i<pM*pN;++i) tempArrayA[i] = pPrevSolution[i].y;
        
        D3D11_SUBRESOURCE_DATA vinitDataA;
        vinitDataA.SysMemPitch = sizeof(float) * pM;
        vinitDataA.pSysMem = &tempArrayA[0];

        // create the texture
        ID3D11Texture2D *inputPrevSolTex = 0;
        HR(pDevice->CreateTexture2D(&inputPrevSolTexDesc, &vinitDataA, &inputPrevSolTex));
        
        delete[] tempArrayA;

        // create SRV
        D3D11_SHADER_RESOURCE_VIEW_DESC prevSolSrvDesc;
        prevSolSrvDesc.Format                                   = DXGI_FORMAT_R32_FLOAT;
        prevSolSrvDesc.ViewDimension                    = D3D11_SRV_DIMENSION_TEXTURE2D;
        prevSolSrvDesc.BufferEx.FirstElement    = 0;
        prevSolSrvDesc.BufferEx.Flags                   = 0;
        prevSolSrvDesc.BufferEx.NumElements             = pM * pN;

        prevSolSrvDesc.Texture2D.MipLevels                      = 1;
        prevSolSrvDesc.Texture2D.MostDetailedMip        = 0;

        pDevice->CreateShaderResourceView(inputPrevSolTex, &prevSolSrvDesc, &mInputPrevSolSRV);
        ReleaseCOM(inputPrevSolTex);

        /***************************************/
        /**** 2: input SRV (curr solution)      ****/
        /***************************************/

        // create texture
        D3D11_TEXTURE2D_DESC inputCurrSolTexDesc;
        inputCurrSolTexDesc.Width                               = pM;           // grid size of the waves, rows
        inputCurrSolTexDesc.Height                              = pN;           // grid size of the waves, colums
        inputCurrSolTexDesc.MipLevels                   = 1;
        inputCurrSolTexDesc.ArraySize                   = 1;
        inputCurrSolTexDesc.Format                              = DXGI_FORMAT_R32_FLOAT;
        inputCurrSolTexDesc.SampleDesc.Count    = 1;
        inputCurrSolTexDesc.SampleDesc.Quality  = 0;
        inputCurrSolTexDesc.Usage                               = D3D11_USAGE_DEFAULT;
        inputCurrSolTexDesc.BindFlags                   = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
        inputCurrSolTexDesc.CPUAccessFlags              = 0;
        inputCurrSolTexDesc.MiscFlags                   = 0;

        // initial texture data
        float *tempArrayB = new float[pM*pN];
        for(int i=0;i<pM*pN;++i) tempArrayB[i] = pCurrSolution[i].y;
        
        D3D11_SUBRESOURCE_DATA vinitDataB;
        vinitDataB.SysMemPitch = sizeof(float) * pM;
        vinitDataB.pSysMem = &tempArrayB[0];

        // create the texture
        ID3D11Texture2D *inputCurrSolTex = 0;
        HR(pDevice->CreateTexture2D(&inputCurrSolTexDesc, &vinitDataB, &inputCurrSolTex));
        
        delete[] tempArrayB;

        // create SRV
        D3D11_SHADER_RESOURCE_VIEW_DESC currSolSrvDesc;
        currSolSrvDesc.Format                                   = DXGI_FORMAT_R32_FLOAT;
        currSolSrvDesc.ViewDimension                    = D3D11_SRV_DIMENSION_TEXTURE2D;
        currSolSrvDesc.BufferEx.FirstElement    = 0;
        currSolSrvDesc.BufferEx.Flags                   = 0;
        currSolSrvDesc.BufferEx.NumElements             = pM * pN;

        currSolSrvDesc.Texture2D.MipLevels                      = 1;
        currSolSrvDesc.Texture2D.MostDetailedMip        = 0;

        pDevice->CreateShaderResourceView(inputCurrSolTex, &currSolSrvDesc, &mInputCurrSolSRV);

        /***************************************/
        /**** 3: output UAV (curr solution)     ****/
        /***************************************/

        D3D11_UNORDERED_ACCESS_VIEW_DESC uavCurrDesc;
        uavCurrDesc.Format                                      = DXGI_FORMAT_R32_FLOAT;
        uavCurrDesc.ViewDimension                       = D3D11_UAV_DIMENSION_TEXTURE2D;
        uavCurrDesc.Buffer.FirstElement         = 0;
        uavCurrDesc.Buffer.Flags                        = 0;
        uavCurrDesc.Buffer.NumElements          = pM * pN;

        pDevice->CreateUnorderedAccessView(inputCurrSolTex, &uavCurrDesc, &mOutputCurrSolUAV);

//      ReleaseCOM(inputCurrSolTex);            // release texture, both SRV and UAV created

        /***************************************/
        /**** 4: output UAV (next solution)     ****/
        /***************************************/

        D3D11_UNORDERED_ACCESS_VIEW_DESC uavNextDesc;
        uavNextDesc.Format                                      = DXGI_FORMAT_R32_FLOAT;
        uavNextDesc.ViewDimension                       = D3D11_UAV_DIMENSION_TEXTURE2D;
        uavNextDesc.Buffer.FirstElement         = 0;
        uavNextDesc.Buffer.Flags                        = 0;
        uavNextDesc.Buffer.NumElements          = pM * pN;

        pDevice->CreateUnorderedAccessView(inputCurrSolTex, &uavNextDesc, &mOutputNextSolUAV);

        ReleaseCOM(inputCurrSolTex);            // release texture, both SRV and UAV created

}

I would really appreciate if someone could help me in the right direction, to finally get this case solved..

Thanks in advance.


Chess Game Pieces Not Moving

Chess Game Pieces Not Moving
#include "Tile.h"

Tile::Tile() : sf::RectangleShape(sf::Vector2f(105, 105)), m_isHighlighted(false) 
{
if (!m_cBuffer.loadFromFile("penclick.wav")) {
std::cout << "Failed to load penclick.wav" << std::endl;
}
}

bool Tile::isTileHighlighted() const {
return m_isHighlighted;
}

void Tile::turnOffHighlight(){
m_clickSound.setBuffer(m_cBuffer);
m_clickSound.setVolume(15);
m_clickSound.play();
setPosition(sf::Vector2f(getPosition().x - 5, getPosition().y - 5));
setSize(sf::Vector2f(getSize().x + 10, getSize().y + 10));
setOutlineThickness(0);
m_isHighlighted = false; 
}

void Tile::highlightTile() {

m_clickSound.setBuffer(m_cBuffer);
m_clickSound.setVolume(15);
m_clickSound.play();
setPosition(sf::Vector2f(getPosition().x + 5, getPosition().y + 5));
setSize(sf::Vector2f(95, 95)); //decrease size to be able to render border without clashes
setOutlineThickness(5);
setOutlineColor(sf::Color::Yellow);

m_isHighlighted = true;
}

Tile::~Tile(){
}


#include "GamePieces.h"

float GamePieces::m_speed = 52.5;

GamePieces::GamePieces()
{
}

GamePieces::GamePieces(const std::string& type, const Color& c, const sf::Vector2f& position) : m_type(type), m_col(c), m_position(position)
{
std::string filePath = ((c == Color::White) ? "w_" : "b_") + type + ".png";
std::cout << filePath << std::endl;

if (!m_gamePiece.loadFromFile(filePath)) {
std::cout << "Failed" << std::endl; 
}
else {
m_gamePieceSprite.setTexture(m_gamePiece);
m_gamePieceSprite.setOrigin(sf::Vector2f(m_gamePiece.getSize().x / 2, m_gamePiece.getSize().y / 2));
m_gamePieceSprite.setPosition(position);
}
}

sf::Sprite GamePieces::getPieceSprite() const
{
return m_gamePieceSprite;
}

bool GamePieces::isWhite() const
{
return (m_col==Color::White);
}

sf::Vector2f GamePieces::getPosition() const
{
return m_position;
}

std::string GamePieces::getPieceType() const
{
return m_type;
}

void GamePieces::movePiece(const Tile& tile, float dt)
{
sf::Vector2f tileCoords = sf::Vector2f(tile.getPosition().x + 52.5, tile.getPosition().y + 52.5);
std::cout << tileCoords.y << std::endl;
while (m_gamePieceSprite.getPosition().y >= tileCoords.y) {
m_gamePieceSprite.setPosition(sf::Vector2f(m_gamePieceSprite.getPosition().x, m_gamePieceSprite.getPosition().y - (m_speed*dt)));
std::cout << m_gamePieceSprite.getPosition().y << std::endl;
}
m_position = sf::Vector2f(tileCoords.x, tileCoords.y);
}

void GamePieces::setPos(const sf::Vector2f& pos) 
{
m_position = pos;
}


GamePieces::~GamePieces()
{
}


void Grid::update(Windows& wind, const sf::Event& event, const Team& w, const Team& b, float dt)
{
if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {

try {
sf::Vector2f mousePosFloat = static_cast<sf::Vector2f>(sf::Mouse::getPosition(*wind.getWindows()));

if ((mousePosFloat.x > (wind.getWindows()->getSize().x) || mousePosFloat.x < 0)) {
throw 99;
}
if ((mousePosFloat.y > wind.getWindows()->getSize().y || mousePosFloat.y < 0)) {
throw 99;
}

sf::Vector2f rowCol = windowCoordsToRowCol(mousePosFloat);
Tile& tile = m_tileSet[(int)rowCol.x][(int)rowCol.y];
//std::cout << tile.getPosition().x << ", " << tile.getPosition().y << std::endl;
GamePieces* gamePiece = getGamePieceOnTile(rowCol.x, rowCol.y, w, b);

if (tile.isTileHighlighted()) {
tile.turnOffHighlight(); //moves square back in place and turns off outline

} 
else if (gamePiece != nullptr && gamePiece->isWhite() && !(isOneTileHighlighted(w))) { //only highlight tile if its white and no one in the team is
//highlited
tile.highlightTile();
}
else if (isOneTileHighlighted(w)&& (gamePiece == nullptr || !gamePiece->isWhite())) {

if (gamePiece == nullptr) {//space clicked on is empty
getHighlightedGamePiece(w).movePiece(tile, dt); 
}
else if (!gamePiece->isWhite()) {
//TODO move to space and eat opposing gamePiece
}
}
else {
if (!ebuffer.loadFromFile("error.wav")) {
std::cout << "Failed to load error.wav" << std::endl;
}
errorSound.setBuffer(ebuffer);
errorSound.setVolume(8);
errorSound.play();
}

//TODO find way of deleting the gamePiece pointer
}
catch (int x) {
std::cout << "hello" << std::endl;
}
}

void Field::update(sf::Event& event)
{ 
float elapsedTime = m_elapsed.getElapsedTime().asSeconds();
if (elapsedTime >= frameTime) {
if (m_secondClock.getElapsedTime().asSeconds() >= 1.0f) {
elapsedFrames = 0;
m_secondClock.restart();
}
elapsedFrames++;
m_elapsed.restart();
while (m_windows.getWindows()->pollEvent(event)) { // max 60 fps - cant go faster
m_windows.Update(event);
m_chessBoard.update(m_windows, event, m_wTeam, m_bTeam, elapsedTime);
}
}
}

So for now I'm just trying to select a game piece and then move it to an empty tile, and according to the debugger all of this executes fine as per the flow of the program. I event print out the location of the sprite as it makes its way to the new tile and it seems right. The "dt" time variable in this case is just the time between updates that exceeds 16 ms (so this is a fixed time step). I'm also wondering how I can make it so that it goes exactly to a specific point, while the printed location of the gamepiece sprite's y coord is close, i want it to be exact. My idea is for this gamepiece to move at a rate of 52.5 units per second, so a distance of around 2 tiles away or (105 units) in abt 2 seconds or ideally 120 frames. The counter in my while loop says it runs abt 230 times which is a bit odd as ive printed the frame rate in past...consistently at 59 fps.

Thanks for the help.

 

Confusion Of Assimp Sdk, Animation System Design Need Advice

Confusion Of Assimp Sdk, Animation System Design Need Advice

Hellow !

I 'm going to make an animation system for game......

I will export models to custom format model using the assimp sdk.  I will only export joint nodes and mesh nodes, and animation data.  

The  output scene file format will look like these:

<ModelNode>

  <JointNode>  lcltransform  .....

     <meshNode>  lcltransform....  <\meshNode>

  <\JointNode>

  ......many joints to omit.

<\ModelNode>

 

The JointNode holds inverse bind pose matrix .

As for the MeshNode, I know , I know, the static mesh is not completely static, the "static" means it can not be deformed,

it can also have motions, so mesh will be implemented as MeshNode. It will inherit transform from  ancestors, so it will move!!  

As for the ModelNode, why it inherit from SceneNode is that  it act as the root node of all joint nodes and model nodes,   somewhat look like  assimp root node.

All these node will hold local transform.

 

 

The question is, assimp scene nodes are not just joint nodes and mesh nodes, and "pure node", which is used to pass transform, the root is the most apparent one.

I 'm confusing that  whether it will go wrong, if I don't export these nodes, because I'm afraid that some "pure nodes" would have a non-identity transform !!

 

In the animation export part , I will use these code:

std::map<std::string, int> name2Joint;

struct animation 

{
  void export() 
   {
     export(duration, tickPersecond);
     for(node in influenced nodes) 
     {
        jointID = name2Joint[node.name];
        export(jointID, frame.pos, frame.rot, frame.scale);
     }
    }  
};
 
 
My animation system is the one of the most naivest animation system in the world , it can only import, and display .
I have not begin to code, and I don't know if it will work, so
I will show my code,  and if someone find any mistake or have a better implementation, please tell. 
 
 
 
Here's are my data structure regarding animation in the engine side:
struct Frame 
{
   _pos, _rot, _scale; // all are  reference to parent
};
 
struct JointFrame 
{
  _jointID;                                        // will be used to find joint node at update time
  vector<Frame> _frames;
};
 
struct Animation 
{
  vector<JointFrame> _jointFrames;
  void update();
};
 
 
And here's the data structure of Model in engine side:
 
struct SceneNode 
  SceneNode  *_parent;
    pos, rot, scale;             // all are  reference to parent
  _globalTransform;
  virtual  void update();
  virtual   void postUpdate()=0;
};
 
struct Joint : public SceneNode 
{
  Matrix4f _invBindMat;  // inverse bind matrix
};
 
 
struct Model  : public SceneNode  
//why it inherit from SceneNode is that 
// it act as the root node of all joint nodes and model nodes,   somewhat look like  assimp root node
{
   vector<Mesh> _meshes;  
   vector<Joint*> _joints;
   vector<Matrix4f> _JointFinalMats
   void PostUpdate();       // use to update _JointFinalMats after all Joints' GlobalTransform have updated, will be called by Scene
};
 
struct Scene
{
  vector<SceneNode*> _nodes;
  void update();
};
 

 

The flowchart of big big updates :

scene::update()

{

   animation.update();  //  update joint's local transform by keyframes

    foreach(node in _nodes) node.update();    // update joint's global transform

    foreach(node in _nodes) node.postUpdate();  // update jointFinalMat array

     

}

 

void Animation ::update() 
{
   for(jointFrame in   _jointFrames) 

   {

      frame = jointFrame.findFrame(gametime);

      joint =   this->parentModel.findJoint(jointFrame._jointID);

 

      // all are reference to parent

      joint->setPos(frame._pos);

      joint->setRot(frame._rot); 

      joint->setScale(frame._scale);  

   }

}

 

void SceneNode::update() 
{
   _globalTransform = localTransform(_pos, _rot, _scale)  *    _parent->_globalTransform ;

}

 

void Model::postUpdate() 
{

   
    foreach(joint in _joints) 

    {

       _JointFinalMats[joint.ID] =  joint._invBindMat * joint._globalTransform;

   }
}

 

 

After I have attached joints to scene graph,  and Scene::update will call joint::update, where  jointFinalMat = inverseBindposeMat *  jointGlobalTransform

will take place. Since the jointGlobalTransform has contain  ToRootMat,  I will pass a identity matrix to shader as a world matrix.

The code will look like :

if(mesh.hasBone) 
{

    worldMat = Identity;

else 
{
  worldMat =  mesh.globalTransfom

 

the shader code:

cbuffer cbPerObject : register(b0)
{
row_major float4x4 worldMat;
row_major float4x4 worldInvTransposeMat;
row_major float4x4 worldviewprojMat;
};
 
cbuffer cbSkinned : register(b1)
{
row_major float4x4 boneMat[96];
};

 

 
struct SkinnedVertexIn
{
float3 PosL       : POSITION;
float3 NormalL    : NORMAL;
float3 TangentL   : TANGENT;
float2 Tex        : TEXCOORD;
uint4 BoneIndices : BONEINDICES;
float4 Weights    : WEIGHTS;
};

 

 
VertexOut vsmain(SkinnedVertexIn vin)
{
VertexOut vout;
float weights[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
weights[0] = vin.Weights.x;
weights[1] = vin.Weights.y;
weights[2] = vin.Weights.z;
weights[3] = 1.0f - weights[0] - weights[1] - weights[2];
 
float3 posL = float3(0.0f, 0.0f, 0.0f);
float3 normalL = float3(0.0f, 0.0f, 0.0f);
float3 tangentL = float3(0.0f, 0.0f, 0.0f);
for (int i = 0; i < 4; ++i)
{
posL += weights[i] * mul(float4(vin.PosL, 1.0f), boneMat[vin.BoneIndices[i]]).xyz;
normalL += weights[i] * mul(vin.NormalL, (float3x3)boneMat[vin.BoneIndices[i]]);
tangentL += weights[i] * mul(vin.TangentL.xyz, (float3x3)boneMat[vin.BoneIndices[i]]);
}
 
vout.PosW = mul(float4(posL, 1.0f), worldMat).xyz;
vout.NormalW = mul(normalL, (float3x3) worldInvTransposeMat);
vout.TangentW = mul(tangentL, (float3x3)worldMat);
vout.PosH = mul(float4(posL, 1.0f), worldviewprojMat);
vout.Tex = vin.Tex;
return vout;
}

Confusion Of Exporting Model, Animation

Confusion Of Exporting Model, Animation

Hellow !

I 'm going to export models using the assimp sdk.  I will only export joint nodes and mesh nodes, and animation data.

The output format will look like this:

<JointNode>  lcltransform  .....

    <meshNode>  lcltransform....  <\meshNode>

<\JointNode>

 

But, assimp scene nodes are not just joint nodes and mesh nodes, and "pure node", which is used to pass transform, the root is the most apparent one.

I 'm confusing that  whether it will go wrong, if I don't export these nodes, because I'm afraid that some "pure nodes" would have a non-identity transform !!

 

In the animation part , I will use these code:

std::map<std::string, Joint*> name2Joint;

struct animation 

{
  void export() 
   {
     export(duration, tickPersecond);
     for(node in influenced nodes) 
     {
        jointID = name2Joint[node.name];
        export(jointID, frame.pos, frame.rot, frame.scale);
     }
    }  
};
 
 
My animation system is the one of the most naivest animation system in the world , it can only import, and display .
I have not begin to code, and I don't know if it will work, so
I will show my code,  and if someone find any mistake or have a better implementation, please tell. 
 
 
 
Here's are my data structure regarding animation in the engine side:
struct Frame 
{
   _pos, _rot, _scale; // all are  reference to parent
};
 
struct JointFrame 
{
  _jointID;                                        // will be used to find joint node at update time
  vector<Frame> _frames;
};
 
struct Animation 
{
  vector<JointFrame> _jointFrames;
  void update();
};
 
 
And here's the data structure of Model in engine side:
 
struct SceneNode 
  SceneNode  *_parent;
    pos, rot, scale;             // all are  reference to parent
  _globalTransform;
  virtual  void update();
  virtual   void postUpdate()=0;
};
 
struct Joint : public SceneNode 
{
  Matrix4f _invBindMat;  // inverse bind matrix
};
 
 
struct Model  : public SceneNode  
//why it inherit from SceneNode is that 
// it act as the root node of all joint nodes and model nodes,   somewhat look like  assimp root node
{
   vector<Mesh> _meshes;  
   vector<Joint*> _joints;
   vector<Matrix4f> _JointFinalMats
   void PostUpdate();       // use to update _JointFinalMats after all Joints' GlobalTransform have updated, will be called by Scene
};
 
struct Scene
{
  vector<SceneNode*> _nodes;
};
 

 

The flowchart of updates :

scene::update()

{

   animation.update();  // joint.lcltransform = ...

    foreach(node in _nodes) node.update();

    foreach(node in _nodes) node.postUpdate();

     

}

 

void Animation ::update() 
{
   for(jointFrame in   _jointFrames) 

   {

      frame = jointFrame.findFrame(gametime);

      joint =   this->parentModel.findJoint(jointFrame._jointID);

 

      // all are reference to parent

      joint->setPos(frame._pos);

      joint->setRot(frame._rot); 

      joint->setScale(frame._scale);  

   }

}

 

void SceneNode::update() 
{
   _globalTransform = localTransform(_pos, _rot, _scale)  *    _parent->_globalTransform ;

}

 

void Model::postUpdate() 
{

   
    foreach(joint in _joints) 

    {

       _JointFinalMats[joint.ID] =  joint._invBindMat * joint._globalTransform;

   }
}

 

 

After I have attached joints to scene graph,  and Scene::update will call joint::update, where  jointFinalMat = inverseBindposeMat *  jointGlobalTransform

will take place. Since the jointGlobalTransform has contain  ToRootMat,  I will pass a identity matrix to shader as a world matrix.

The code will look like :

if(mesh.hasBone) 
{

    worldMat = Identity;

else 
{
  worldMat =  mesh.globalTransfom

 

the shader code:

cbuffer cbPerObject : register(b0)
{
row_major float4x4 worldMat;
row_major float4x4 worldInvTransposeMat;
row_major float4x4 worldviewprojMat;
};
 
cbuffer cbSkinned : register(b1)
{
row_major float4x4 boneMat[96];
};

 

 
struct SkinnedVertexIn
{
float3 PosL       : POSITION;
float3 NormalL    : NORMAL;
float3 TangentL   : TANGENT;
float2 Tex        : TEXCOORD;
uint4 BoneIndices : BONEINDICES;
float4 Weights    : WEIGHTS;
};

 

 
VertexOut vsmain(SkinnedVertexIn vin)
{
VertexOut vout;
float weights[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
weights[0] = vin.Weights.x;
weights[1] = vin.Weights.y;
weights[2] = vin.Weights.z;
weights[3] = 1.0f - weights[0] - weights[1] - weights[2];
 
float3 posL = float3(0.0f, 0.0f, 0.0f);
float3 normalL = float3(0.0f, 0.0f, 0.0f);
float3 tangentL = float3(0.0f, 0.0f, 0.0f);
for (int i = 0; i < 4; ++i)
{
posL += weights[i] * mul(float4(vin.PosL, 1.0f), boneMat[vin.BoneIndices[i]]).xyz;
normalL += weights[i] * mul(vin.NormalL, (float3x3)boneMat[vin.BoneIndices[i]]);
tangentL += weights[i] * mul(vin.TangentL.xyz, (float3x3)boneMat[vin.BoneIndices[i]]);
}
 
vout.PosW = mul(float4(posL, 1.0f), worldMat).xyz;
vout.NormalW = mul(normalL, (float3x3) worldInvTransposeMat);
vout.TangentW = mul(tangentL, (float3x3)worldMat);
vout.PosH = mul(float4(posL, 1.0f), worldviewprojMat);
vout.Tex = vin.Tex;
return vout;
}

Windows.h Issues Since Visual Studio 2015 Update 3

Windows.h Issues Since Visual Studio 2015 Update 3

Hi !

Since I updated to Visual Studio 2015 Update 3 I have compilation issue for Windows.h stuff like TIMECAPS and InitializeConditionVariable.

To solve the TIMECAPS issue I have to include "timeapi.h", it was not needed before.

To solve the InitializeConditionVariable and other of the same kind I have to set "_WIN32_WINNT=0x0600" as compilation macro.

Is it normal ?

Thanks


Ecs Inheritance Problem (C++)

Ecs Inheritance Problem (C++)

Hey guys,

 

Im working on creating an entity component system but I am stuck on one particular problem that I need some help with.

 

 

Currently i have a base class entity that have a vector of component pointers like the following 

class entity
{
  int id;
  std::vector<component*> mycomponents;
  int entity_type;
  bool deleteme;

}

 I have public functions that will allow me to both add and delete components from the entity. after this i will have a bunch of systems that will do the updating for me (the components will just have information other then maybe the ai component which would contain a behaviour tree/FSM)

 

The problem that I am trying to figure out is how would i get the correct component i need for a system  (say i need the position and velocity components for the movement system). After having a google a round I can see that i could do a dynamic cast (as my base component class will have variable to say what type of component it is) but i have heard that this is not really a very efficient method and not really good practice (feel free to correct me). I could also do some kind of messaging system for changing the data in a component but getting data out of it would be harder (would need a virtual return function of each data type). 

 

Any advice on a way I could get around this problem. is their a method that i have over looked? 


Ai Advance Wars Unity C#

Ai Advance Wars Unity C#
Hello, I'm making an advance wars game, my AI can attack/defend/capture building and so on... like the original game.
I follow the AI behavior guide on the wiki, it works very well.
Actually, I am stuck when the AI wants to buy unit, I can't find any information about how the AI can buy a unit, anyone can tell me how is it working.
thank you.

Game Development

Game Development

I am currently in development of an upcoming 2d Multiplayer game called "Zed" . It will be unique as it will open world game & will be survival game , gaining elemental powers as they level up and select their skills . The game will dive from completing mini quests to huge with evolutions and game world will be having random mystery's cave generated through algorithms as they move around in game. They have to dig into these caves alone or with a team with earn some beautiful rewards .

The Game will start with a crash of meteor which breaks the earth into pieces causing a wormhole where the player gets pulled & get abilities to control elements .

 

We are currently a team of 5 . One programmer (me) & 3 artists & a writer .

We need two C# programmers who will be able to work in unity 3d engine .

Requirements : 

  • They should know how to use git
  • They should have atleast 2+ years of experience with c#

We all will be starting working with on the Game within a week .

 

Facebook Page : http://ift.tt/2a8NaO2

 

I have already a basic setup of server and game ready . 

Contact Info : therealzoel@gmail.com


Saturday, July 30, 2016

How To Perform Matrix Dot Product On D3Dx9?

How To Perform Matrix Dot Product On D3Dx9?

http://ift.tt/2aFHBra

 

Is it possible to do dot product on a vector with matrices in D3DX9?

 

I am trying to convert this project into C++ equivalence...

 

http://ift.tt/2aHIsod

 

In the python code

np.dot(rotz(pi/2), np.array([cos(anglstart), sin(anglstart), 0]).T)

It is trying to compute the dot product of a rotation matrix around z axis and dot with

a column vector...

 

http://ift.tt/2aFHFHu

 

The D3DXVec3Dot only works with dotting two vectors together?

 

Thanks

Jack


Vs2015:error After Canceled Vs2015 Update 3 Update

Vs2015:error After Canceled Vs2015 Update 3 Update

hi

 

I had vs2015 update 2 installed.  then i found out that they just release update 3, do i tried to update to update 3.  in the process of installing update 3, i loaded photoshop cc to do something.  photoshop then said that my scratch disk was full and could not load.  I realized that my c: ssd was almost full and photoshop could not load.  so i canceled updating vs 3, bad idea.  Then my vs2015 did not load anymore.  so i uninstalled it and installed the old verson of vs2015.  after installed and loaded vs2015, vs gave me error whenever i clicked on file command or the x on the top right to get out of the vs i got a windows popped up as i will show below.  any suggestion?

 

thanks for your help.

Attached Thumbnails

  • Screenshot (17).png

Problem With Hlsl Of Blur

Problem With Hlsl Of Blur

Im trying run some shader of blur in my game, but nothing happen and the render be normal, without blur..

 

HLSL Code:

sampler ColorSampler1 : register(s0);

#define SAMPLE_SIZE 15

float2 texelSize = {1/1024,1/768};
float offsets[SAMPLE_SIZE] = {-0.006836,-0.005859,-0.004883,-0.003906,-0.002930,-0.001953,-0.000977,0.000000,0.000977,0.001953,0.002930,0.003906,0.004883,0.005859,0.006836};
float weights[SAMPLE_SIZE] = {0.008847,0.018216,0.033562,0.055335,0.081638,0.107778,0.127325,0.134598,0.127325,0.107778,0.081638,0.055335,0.033562,0.018216,0.008847};

float4 PS_BlurH(float2 texCoord : TEXCOORD0) : COLOR0
{
        float4 sum = float4(0.0, 0.0, 0.0, 1.0);
        
        for (int i = 0; i < SAMPLE_SIZE; i++)
                sum += tex2D(ColorSampler1, float2(texCoord.x + (offsets[i] * texelSize.x), texCoord.y)) * weights[i];
        
        clip(sum.a < 0.01f ? -1 : 1);
        
        return sum;
}

float4 PS_BlurV(float2 texCoord : TEXCOORD0) : COLOR0
{
        float4 sum = float4(0.0, 0.0, 0.0, 1.0);
        
        for (int i = 0; i < SAMPLE_SIZE; i++)
                sum += tex2D(ColorSampler1, float2(texCoord.x, texCoord.y + (offsets[i] * texelSize.y))) * weights[i];
        
        clip(sum.a < 0.01f ? -1 : 1);
        
        return sum;
}

technique Glow
{
        pass BlurHorizontal
        {
                PixelShader = compile ps_2_0 PS_BlurH();
        }
        
        pass BlurVertical
        {
                PixelShader = compile ps_2_0 PS_BlurV();
        }
}

Screenshot:

b7189a0e52.png

 

As can see in pic, nothing happens with meshe, dno why.. If i change values of offsets and weights same thing... Blur dont work.

Someone know what can be? Thanks