texts: physically based shading, how to combine specular & diffuse parts?

texts:
After writing 'standard' phong & blinn shaders for a while, I recently started to dabble in physically based shading.
A resource that helped me a lot are these course notes, especially this paper - it explains how to make blinn more shading physically plausible.

I implemted the blinn model propsed in the paper, and I really like how it looks. The most significant change proposed ( imo ) is the inclusion of the fresnel reflectance, and this is also the part that gives me problems. Unfortunately, the author chose to focus on the specular part only, omitting diffuse reflectance. Given e.g. a lambertian diffuse reflection, I just don't know how to combine it with the 'improved' blinn - because just adding diffuse & specular parts does not seem to be right any more.

In some shaders I've seen a floating point 'fresnel term' in range 0 - 1 being used, based on the indices of refraction of the participating media. Schlick's approximation is used every time:

float schlick( in vec3 v0, in vec3 v1, in float n1, in float n2 )
{
    float f0 = ( n1 - n2 ) / ( n1 + n2 );
    f0 *= f0;
    return f0 + ( 1 - f0 ) * pow( dot( v0, v1 ), 5 );
}

Doing it like this, one can then linearly interpolate between diffuse and specular contribution based on the fresnel term, e.g.

float fresnel = schlick( L, H, 1.0002926 /*air*/, 1.5191 /*other material*/ );
vec3 color = mix( diffuseContrib, specularContrib, fresnel );

In the paper, the author states that this approach is incorrect
- because it basically just darkens the specular color whenever L is parallel or nearly parallel to H - and that instead of computing a f0 based on the indices of refraction, you should treat the specular color itself as f0 and have your schlick approximation compute a vec3, like this:

vec3 schlick( in vec3 v0, in vec3 v1, in vec3 spec )
{
    return spec + ( vec3( 1.0 ) - spec ) * pow( dot( v0, v1 ), 5 );
}

This results in the specular color going towards white at glancing angles.

Now my question is, how would I introduce a diffuse component into this? At 90° the specular contribution is fully white, this means all incoming light is reflected, so there can't be a diffuse contribution. For incidence angles < 90°, can I just multiply the whole diffuse part with ( vec3( 1 ) - schlick ), i.e. the proportion of light that isn't reflected?

vec3 diffuseContrib = max( dot( N, L ), 0.0 ) * kDiffuse * ( vec3( 1.0 ) - schlick( L, H, kSpec ) );

Or do I need a completely different approach?


texts: Can I take a finished game based on a licence to the holding company?

texts:
Ok so I went through 11 pages on here and have done a decent amount of Google searching, but found nothing specific to my question. I'm working on a game based on a movie. For the purpose of this I'm going to use a different movie as my example. Let’s say I'm making a game based on "Driving Miss Daisy" (because why not?).

Now I've seen plenty of questions about taking an "idea" to a company (both game and rights holders) and trying to get funding but I have no reputation and this is a side project at this point so that's probably not a good idea. But let’s say I work on my "Driving Miss Daisy" game for a year or so and at some point call it "finished". It has good art, co-op, a campaign, and achievements (because, why not?) all made 100% by me and me alone. Does anyone know the process or the likelihood of me going to Warner Bros. and their games division with some kind of deal splitting profits if they allow the release or help with it etc etc.

Even if I hear "There’s no way, ‘Driving Miss Daisy: the Game’, while awesome, will never see the light of day", I'll probably keep working. I just wanted an idea of what kind of outcome could come from this and this is a different situation than I've generally seen asked. Like I said, most are about getting money for the development itself or trying to re-release old games that have been abandoned.

Thank you to anyone who might have information about this.


texts: How do I find rotation in 3D based on a vector/normal?

texts:
I've been playing with Blender and Python, doing basic things like accessing vertices/normals,etc.

I can get the normal of each face of a mesh. I was wondering, how can I get the rotation of a face based on it's normal ? Can I 'decompose' the normal's rotation into rotation x,y,z ? If so how ?

I remember 3dsmax had something that allowed you to easily place objects on another object's faces/surface. Haven't seen that in Blender, might be handy.


texts:
I am starting out with Maya and just moved my object up to reveal a mystery grey wireframe which I can't work out what it is at all. It appears I can't select or interact with it at all.

I have been playing predominantly with UV Maps, potential cause?

What is it? And how can I hide/remove it?

Thanks.

Image:
http://i.imgur.com/3N8Q0fa.png?1


texts:
I'm doing some stuff with UI-Animations the past days, but I never figured out, whether it is possible to do stuff like this with Unity : https://d13yacurqjgara.cloudfront.net/users/107759/screenshots/1623679/menu.gif

I would guess, that this is not possible, but maybe I just missed some feature :)


texts: Is there a way to validate GLSL syntax build-time instead of run-time? My application takes a long time to start and I want to know at the earliest possible stage that my shaders are ok. I'm using Visual Studio/Xcode. The solution probably involves running a tool as a part of build process, but I'm looking for such a tool.


texts:
So this Graph Shader is using UV0 channel:

As far as I know, UV layout in a 3d model file (e.g. fbx) is stored inside the model itself, is that right?

But the picture above implies that a model can contain multiple UV channels inside of itself. Is that true?


texts: Unity's Animator.GetBehaviour always returning null

texts:
I have the following line:

As you can see "transitionOutAnimator" is null before the line runs. transitionOutAnimator is a StateMachineBehaviour of type ThoughtBubbleTransitionOutAnimator.

We can check that the StateMachineBehaviour of the correct type is actually stored in the run time animator:

Yet when the line runs:

Am I doing something obviously wrong? Is this a bug? I have another identical instance in the code where I do this, and it works perfectly.

EDIT: Immediate window:

EDIT: This is still a problem as of Unity 5.3.5f1.


texts: What is a good method to randomly generate edges between graph nodes?

texts:
I am doing a random map generator for a 4X space game.

Each node in the game is place at a random (x,y) coordinate on a 2d grid. A node can have one or more bi-directional edges to another node (representing wormholes). All nodes must have at least one wormhole, and all nodes must belong to the same graph.

Ideally, a wormhole should not exceed a maximum length and if possible, wormholes should not cross each other.

My naive implementation is to iterate through all the nodes and have the node link to the closest 3 nodes. However, I end up with numerous sub graphs. What's a good method to generate the edges for the nodes?


texts:
I would like to create a basic 2d graphics program to do very simple editing of in game assets.

My question, starting out how could I represent the canvas?

Let's say I know i'll need a canvas 512x512 pixels in siz, each pixel can be up to 256 colors. I can design a pixel as a struct with x,y,z coordinate and the canvas will be a 2d array or something that will hold each of those pixels.

That's a very basic way to model the drawing area, next how do I actually make that view so if I say put red at position 100x100 on my array it'll show up on screen?

Thanks in advance.


texts: Connecting physics simulations with different coordinate-systems

texts:
I want objects to move between two physics simulations through a "window" and collide with those from both simulations in case they intersect the window plane.

The coordinate systems of the simulations don't have the same origin and may have a different orientation. Wrapping a simulation to itself isn't necessary, but would be a plus.

How do I connect the systems efficiently without cloning the individual objects?

Edit:

The calculations should be as accurate as possible, so objects don't get stuck if they cross the window at the same time from opposite sides.


texts: Project rotated matrix to isometric coordinate

texts:
I have a group of soldiers, and each has a vector describing their position in the squad. When the group rotates, I do this math to calculate the desired position of each soldier.

var unitPositions : Array<CGPoint> = []

let cosRadian = cos(rotation)
let sinRadian = sin(rotation)

for var index = 0; index < self.positions.count; ++index {

    // Find the vector for this unit, translate it, then store it
    let targetVector = self.getVectorAtPosition(index) - translate
    let newX  = targetVector.dx * cosRadian - targetVector.dy * sinRadian
    let newY = targetVector.dx * sinRadian + targetVector.dy * cosRadian

    unitPositions.append(CGPoint(x:newX, y:newY))
}

This produces the following result:

The problem with this is that units in an isometric world facing south east should match up with the reference grid. So the next step was to add a multiplier. In the loop above, I changed it to:

    let isoX = newX * 1.414213562373095;
    let isoY = newY

    unitPositions.append(CGPoint(x:isoX, y:isoY))

This produced closer results:

But, it's still not 100% accurate. So, right now I'm going through and trying to get my fundamentals of math, matrices, vectors, etc all figured out in hopes of producing this desired result:

I would love any pointers on what I should be searching for, as right now it is all a bit overwhelming. Thanks much!

UPDATE

Due to the awesome comment by @DMGregory, here are my findings:

If I want to "hack" this and continue to use screen coordinates, I can do so using 1.414213 (the magic number found here) combined with your true isometric projection.

let isoX = newX * 1.414213562373095
let isoY = newY * (1.414213562373095 * 1/sqrt(3))

That will produce:

That approach will work, but won’t solve everything else you mentioned (i.e: units will move faster when going certain directions). To handle that, creating the original formation with isometric vectors, and then just rotating that matrix will produce the same results. So, it looks like I have a lot of work converting my game calculations and coords to default as isometric coordinates. Thanks again!


texts: How and why can Physics2D.Raycast method be used in an if statment, as it does not return a boolean value?

texts:
Pretty much as the title asks, why is this code possible?

if (Physics2D.Raycast(...)) {

}

even though the method itself returns RaycastHit2D?


texts:
All the links here are broken:

http://msdn.microsoft.com/en-us/library/bb172314.aspx


texts:
Ok. So while this isnt a programming question. I wanted to know how do people debug apps? How do you view log cat, and where these exceptions are thrown etc? And do I need to run the app on the emulator to see all the stuff, or is there a way to view this after running the app on my phone(while not being connected to the computer)

Links to plugins and tips would be really helpful, as im gonna start work on my next game, and while the first one works fine, had a lot of problems while debugging.


texts:
Actually I want to edit my previous question titled What is the geometrical interpretation of Input.GetAxis("Mouse X") and add a related question "What is the physical interpretation of Input.GetAxis("Horizontal")?" to it.

However, I was asked to create a new question about it.

The longer I press the key, the greater the value returned by Input.GetAxis("Horizontal"). If I don't press, it returns 0. The value seems to be a function of time interval the key is pressed. What is the empirical relationship between the relevant quantities?


texts:
I'm trying to scale a window's contents so that every pixel displays at a multiple of it's normal size.
Basically I want to achieve larger pixels without scaling each and every individual sprite.
This question is very similar to this one, however that only scales a single sprite. How should I go about this?


texts: Xna Particle Explosion like Geometry Wars

texts:
I am making a game, in similar graphics display as Geometry Wars. In Geometry Wars (noticeable in the title, as well as when you blow up an enemy), there are these colorful explosions that emit, then fade away at the end. An example is this video. I know very little about particles. I already have an effect that will make objects glow (Bloom, if you didn't know). I would like to know if there is an Xna library that can do this effect. If not, is there code that I can use? Or some documentation that I could implement?

And also, could the code for the explosions be modified slightly to simulate the stream effect that the ship emits when it is moving around?


texts: if I want to build a game for web, facebook, and iphone, do I need to build 3 completely different versions? I know there is a new company that is "build once, launch anywhere," but I'm asking about current best/practice and methodology in doing this.


texts: Does it make sense to build a text-based game Facebook app without using Facebook?

texts:
If I am building a text-based browser game, does it make sense to build it on you domain first, without using the Facebook API?  I don't want to buy an SSL if I don't end up following through with everything. I already have a domain for testing.

In other words, can/should I build the whole thing outside of Facebook and then change it later to use the Facebook API?


texts: Shader optimization - Cg/HLSL pseudo and via multiplication

texts:
HLSL/Cg do not allow texture fetching inside conditional blocks. To get around this I am first checking a variable and performing some computations, afterwards I set a float flag to 0.0 or 1.0, depending on the computations. I'd like to trigger a texture fetch only if the flag is 1.0 or not null. I kind of hoped this would do the trick:

float4 TU0_atlas_colour=pseudoBool*tex2Dlod(TU0_texture, float4(tileCoord, 0, mipLevel));

I want to know if pseudoBool is 0, will the texture fetch function still be called and produce overhead? I was hoping to prevent it from getting executed via this trick that usually works in plain C/C++.


texts:
When a player touches a ground peice in a game, he seems to sink through the ground then slowly rise back up, and when he has risen back up, he is very jittery.

 if (touchingTheGround())
 {
     player.velocity.Y -= 2;
     touchground = false;
 }

the collision method sets the variable touchground to true if the player touches a ground peice, and if i dont set it to false, the collision detection wont work at all. i set the players velocity to move 2 up because when he's not touching a platform, his velocity.Y += 1. How do i achieve a way so that the player

Does not sink in the ground before moving up
Stops jittering when its position is higher than the ground its touching


texts: Any technical references for game-oriented icons and symbols?

texts:
To make localizing easier, I'm using icons to show in-game information like achievements and bonuses. Coming up with good designs isn't easy, especially when it has to be integrated into the rest of the game's art style.

Can I do better than looking at some random selection of existing games?

Are there any reference books or sites that cover game graphics specifically?

I'm looking for more theory and best-practices rather than pre-made graphics.


texts:
Basically, I am creating a large iPhone game (with an overwhelming amount of 2d graphics).

I am concerned about the game file size.

Since the iPhone game will accept Retina and Normal display, we need 2 versions of each image (one HD and on normal). Therefore, it is necessary to resize our image files (it is not a good idea to resize the images in-game, an iPhone 3GS would have memory usage problems).

So my team is thinking about using Adobe Fireworks for the image creation, since it has that nice vector-resizing behavior without losing image quality (not-blurry on resize).

And it works alright.

But then I created an image that is pretty much the same in Adobe Photoshop, and it happened to be about 3x smaller in memory.

So naturally, there's something wrong with our Fireworks' files. How can I save my .png Firework file with the smallest memory size possible?

Note: the images require transparency.


texts: How do I fix this "Accessed None trying to read property Save Game" error?

texts:
I have create this blueprint, with a Check for an existing Save-Game and load it in case of true. Else, create a new save game object. While Z is pressed, create a new Save Game, getting the Player Position.
The problem is that when I try to start the game, I have two errors:

How can I solve those problems? This is my blueprint:

Thanks.


texts: The recommended road map to be a good graphics/game engine programmer

texts: I am a computer science student and I am developing with C/C++ and Python and I want to begin learning graphics tools to start developing with game engines, especially the Blender Game Engine. So what is your recommendation for me to learn and to read? And recommend me a road map for it.


texts: Sprite rotation and question about sampler state

texts:
I'm not an expert in creating game engines, but I'm doing fine for now. Recently I reached a point that I couldn't solve any of my problems. I have two questions:

I'm using D3DXMatrixTransformation2D to produce the transformation matrix for my sprites, but I have a problem with rotation. Whenever I try to set a rotation for my sprite, it does turn when there is a fixed value of rotation. If I give 0.5f it won't rotate, but when I set 1, 2, 3, ... it'll work and that's not really cool. And, I searched a lot about pScalingRotation but it seems it's hasn't any influence. My rotation's value is fine, but the produced matrix doesn't act the way I expect it to.
I want to get a smooth edge for my sprites when they're rotating and I saw p_device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);. Where should I set the sampler state? After creating the device or after every update? And, what about texture filters? I use D3DXCreateTextureFromFileEx to load textures from file and it has Filter and MipFilter. Are these related to the sampler state?


texts: How can I make this day/night cycle computation repeat?

texts:
Here's my code for a day/night cycle. I have it set up so that when time (Statistics.duration) is the right number, the light levels switch.
It works great, but I'm at a loss for how to make it work indefinitely - as an actual cycle.
How can I make this code work for all numbers up to 10,000? I know there has to be an easy way to do this, but I'm at a loss...

public void updateTime()
{
    if (!dawn && (Statistics.duration <= 50 ) && Dungeon.depth <= 100){
        dawn = true;
        night = false;
        Dungeon.nightMode = false;
        GLog.i("It is now dawn.");
    }

    if (!noon && Statistics.duration > 50 && Statistics.duration <= 100 && Dungeon.depth <= 100){
       noon = true;
       dawn = false;
        GLog.i("It is now noon.");
    }

    if (!dusk && Statistics.duration > 100 && Statistics.duration <= 150 && Dungeon.depth <= 100){
        dusk = true;
        noon = false;
        GLog.i("It is now dusk.");
    }

    if (!night && Statistics.duration > 150 && Statistics.duration <= 200 && Dungeon.depth <= 100){
        night = true;
        dusk = false;
        GLog.i("It is now night.");
    }

    if (!dawn && Statistics.duration > 200 && Statistics.duration <= 250 && Dungeon.depth <= 100){
        dawn = true;
        night = false;
        GLog.i("It is now dawn.");
    }
}

I'm calling updateTime() whenever the player does something - moving, fighting, sleeping, etc. They perform the action, which gets added to the .duration.


texts: What is the correct way to authenticate a player with password from Unity to a php api server?

texts:
So, I have a game in Unity for mobiles that gives you the possibility to sign-up with username, email and password to unlock extra features.
The datas are sent, through a POST request, to a PHP+MYSQL server that expose an API. I'm developing both so I have complete freedom on how to implement it.

My question is what is the correct way to:

save auth data on player mobile device so it can automatically login
on subsequent runs of the game
how to safely send username and password to my server for the authentication

I want to protect data from man in the middle attacks and I don't want to send clear password because users tends to always use the same email/password combination.

Thank you


texts: Combining mesh on the fly without using gameObject

texts:
I procedurally generate chunks and use the marching cube algorithm to create meshes in 3D.
At first, I just created a gameObject for each cube (of course, I knew it was not optimized, but I wanted to see if the algorithm worked).
For now I stock all gamesObject in child of "blocks" but it would be much more optimized to directly merge the meshes between them and only create a single gameObject.
However, i did not find any way to directly merge the meshes between them.
So my question is: is there a way to directly merge meshes between them without having to use gameObject? (don't worry about texturing)

Here's the code:

    public static GameObject GenerateChunk(int[,,] map, int chunkSize, Vector3 chunkPosition)
    {
        GameObject blocks = new GameObject("BlockList");
        GameObject newMesh;
        int[] cubeVertices = new int[8];

        // create each mesh in a gameObject as child of "blocks"
        for (int x = 0; x < chunkSize; x++)
            for (int z = 0; z < chunkSize; z++)
                for (int y = 0; y < chunkSize; y++) {
                    /*
                    define the vertices (cubeVertices)
                    */
                    Vector3 cubePosition = new Vector3(chunkPosition.x + x, chunkPosition.y + y, chunkPosition.z + z);
                    newMesh = GenerateCube(cubePosition, cubeVertices);

                    if (newMesh != null)
                        newMesh.transform.parent = blocks.transform;
                }

        //combine every children of "blocks" and delete them
        MeshFilter[] filters = blocks.GetComponentsInChildren<MeshFilter>();
        List<CombineInstance> combine = new List<CombineInstance>();
        for (int i = 0; i < filters.Length; i++) {
            if (filters[i].sharedMesh == null)
                continue;
            for (int j = 0; j < filters[i].sharedMesh.subMeshCount; j++) {
                CombineInstance ci = new CombineInstance
                {
                    mesh = filters[i].sharedMesh,
                    subMeshIndex = j,
                    transform = filters[i].transform.localToWorldMatrix
                };
                combine.Add(ci);
            }
            Destroy(filters[i].gameObject);
        }

        //create the chunk and set the final mesh with the CombineMeshes function
        GameObject chunk = new GameObject("Chunk", typeof(MeshFilter), typeof(MeshRenderer));
        chunk.GetComponent<MeshFilter>().mesh.CombineMeshes(combine.ToArray(), true, true);
        Destroy(blocks);
        return chunk;
    }


texts: Why should I forbid real-money trading in my MMO?

texts:
I am soon going to go public with an MMO game, and I am currently in the progress of writing the terms of use I expect players to follow (no swearing, no spamming, no cheating... you get the point).

My game allows players to trade rare items with each other.

I noticed that almost all online games which have trading, usually have a clause in their terms of use which explicitly forbids players to trade ingame items or ingame money for real-world currency.

I was wondering about the reason for this rule. Why should you ban real-money trading in an MMO?


texts: ECS: removal of group of related components

texts:
Currently I'm working with LibGDX and using Ashley for ECS. Everything is fine, until i need to remove groups of related components.

Say we have a player that may use different weapons. For now, in my game a weapon is described by one or more components.

For example we have weapons, each is described by its own components:

weapon1: [ c0, c1, c2 ];
weapon2: [ c3, c4 ];
weapon3: [ c5, c6, c7 ];

It's ok when I want to add a weapon. I know which components are required and can put them to entity. The issue comes when I need to replace one weapon with another.

I can deal with if-else when it's only 3-5 weapons. But what if there are 20?

For now, my idea is to have additional component called WeaponComponent.
Which will contain a family (I mean Ashley Family instance) that contains all information i need to remove the unnecessary components.
But for me it looks more like a workaround, not a solution.

So, does anybody know how to deal with this? Are there any other approaches?

UPDATE

OK, For now I have tried  few implementations. And here is the one that seems to be the best for me. I have combined object-oriented and entity-component designes. The WeaponComponent holds a reference to a Weapon implementation. The Weapon implementations know exaclty which components to attach/remove to/from an entity.

interface Weapon {
    void attachTo(Entity entity);
    void removeFrom(Entity entity);
}
class WeaponComponent {
    private Entity owner;
    private Weapon weapon;
    public void setWeapon(Weapon weapon) {
        if(this.weapon != null)
            this.weapon.removeFrom(owner);
        if(weapon != null) {
            this.weapon = weapon;
            this.weapon.attachTo(owner);
        }
    }
}

So, using this design, changing weapons is very easy now. And I don't have to care what weapon is already attached, and how to remove it:
engity.getComponent(WeaponComponent.class).setWeapon(whatEver);.


texts: How to detect a collision and collision impact?

texts:
I would like to calculate "impact" of collision if its the right word for it.
My scenario is:
I have player, who is driving his vehicle. He then hits the wall while still in vehicle. I want to know if the collision happend and calculate the impact of collision, so later I know how much hp the player should lose depending how hard the hit was. I hope I made clear what I want to achieve.

What I'm currently doing is storing the previous vehicle speed and calculating the impact like this (previousSpeed - currentSpeed) / frameTime. It gives me some results but it's not consistent. Any other idea? It's in 3D so I have access to 3d vectors if it helps in any way.


texts: libgdx UI coordinate consistency in a scaled window

texts:
I'm having an issue that I'm sure boils down to something simple that I've missed: The UI Graphics can't handle a window resize. Either the graphics get stretched, or the placement is incorrect.

For now I'm working with just one UI element consisting of a Sprite, until i've gotten the project to render properly. Its position is defined in a Settings-class when the asset is loaded:

    touchpadBG = new Sprite(assets.get("ui/joystick_background.png", Texture.class));
    touchpadBG.setCenter(Settings.touchpadPositionX, Settings.touchpadPositionY);

... and drawn like so:

batch.setProjectionMatrix(gameCam.combined);
batch.begin();
// Draw the gameworld. This is done without any issues.

batch.setProjectionMatrix(uiCam.combined);
touchpadBG.draw(batch);

batch.end();

uiCam is defined like this:

    this.uiCam = new OrthographicCamera(Settings.windowSize_X, Settings.windowSize_Y);
    uiCam.translate(Settings.windowSize_X / 2, Settings.windowSize_Y / 2, 0);
    uiCam.update();
    uiViewport = new FitViewport(Settings.windowSize_X, Settings.windowSize_Y, uiCam);
    uiViewport.apply();

I've experimented with different viewports (and no viewport), and while correct placement happens at first, resizing the window will result in the UI element being drawn in the wrong position, stretched, or both.

I then suspected my resize/update methods being off, but I can't find anything wrong:

public void resize(int w, int h) {
    uiViewport.update(w, h);
    update();
}

public void update() {
    aspectRatio = (float)Gdx.graphics.getHeight() / (float)Gdx.graphics.getWidth();
    uiCam.update();
    gameCam.update();
}

Any ideas where I'm going wrong with this? If my post is missing a relevant part of my code, leave a comment, and I'll edit it in.


texts: How to do moving Rorschach using Perlin noise in c# without shaders?

texts: I want to be able to make a moving Rorschach using Perlin noise like in this question but I know nothing about shaders. Is there a way to do it in just c#?


texts: What is the correct approach to implement multiplayer in a game?

texts:
I'm developing a game and it is intended to be a multiplayer game. I have experience in writing servers and clients in Java, but the game is written in C++.
The server will be written in Java for sure.

I have 3 questions:

Am I forced to write the client in C++ ?
If not, is there a way to write the client in Java as well, and somehow communicate with the game program?
The game includes characters moving. Is the correct approach to calculate the positions of every dynamic object on the server and for the clients to only receive the current positions of everything from the server? The only thing the clients would send is their input(click, spell casts etc.).


texts: File writing or scriptable object editing in unity webgl

texts: I am using a scriptable object for saving data. I know that scriptable objects are unchangeable means we can't change and save data after runtime but is there any workaround available to update it? Or write any config file (editable for user to change it) on webgl Platform. It seems that file writing permission is not available at unity Webgl.


texts: OBJ Model not being rendered properly in OpenGL ES 2 android app

texts:
I have an Android OpenGL ES 2 app that loads an .OBJ model using Assimp and renders the same.

The vertices data is stored in a object declared like this :

class CGameObject
{
public:
struct _Mesh {
    std::string Name;               // Name of Mesh

    std::vector<float> vertices;    // vertices of Mesh

    GLuint m_vbo;
    // TODO: Add TEXTURE and MATERIAL support
};
...
}

Set various Matrices :

cameraX = 3.0f; cameraY = 3.0f; cameraZ = 5.0f;

// Camera/View matrix
View = glm::lookAt(
    glm::vec3(cameraX, cameraY, cameraZ),     // Camera position
    glm::vec3(0, 0, 0),     // Pointing at
    glm::vec3(0, 1, 0)      // Angle
 );

aspect = (float) width / height;

// Projection Matrix
Projection = glm::perspective(45.0f, aspect, 0.1f, 10000.0f);

glm::mat4 Model = glm::translate(mat4(1.0), glm::vec3(0.0f, 0.0f, 0.0f));
MVP = Projection * View * Model;

Rendering function :

void GLEngine::DrawFrame() {
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

glUseProgram(programObject);
// Draw of VBO ---BEGIN
for (GameObjects::iterator i = gObjects.begin(); i != gObjects.end(); ++i)
{
    CGameObject* pObj = *i;
    /////////////////
    for (int x = 0; x < pObj->Meshes.size(); x++)
    {
        glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
        // bind VBO you want to draw
        glBindBuffer(GL_ARRAY_BUFFER, pObj->Meshes[x]->m_vbo);

        glEnableVertexAttribArray(gvPositionHandle);
        glVertexAttribPointer(gvPositionHandle, 3, GL_FLOAT, GL_FALSE, 0, 0);

        if (x == 0){
            glVertexAttrib3f(gvColorHandle, 0.0f, 0.0f, 1.0f);
            UcheckGLError("glVertexAttrib3f");

            }
        else {
            glVertexAttrib3f(gvColorHandle, 0.0f, 1.0f, 0.0f);
            UcheckGLError("glVertexAttrib3f");

            }

        //glEnableVertexAttribArray(gvColorHandle); // My app crashes if I uncomment this line . .. any reasons why ?
        //UcheckGLError("glEnableVertexAttribArray");

        glDrawArrays(GL_TRIANGLES, 0, pObj->Meshes[x]->vertices.size());
        // unbind VBO
        glBindBuffer(GL_ARRAY_BUFFER, 0);
    }
    /////////////////
}
// Draw of VBO ---END
// unbind program
glUseProgram(0);
}

source for shaders -

vertex shader :

attribute vec3 in_Position;

uniform mat4 MVP;

attribute vec3 in_Color;
varying vec4 fColor;

void main(void) {
    vec4 v = vec4(in_Position, 1.0);
    gl_Position = MVP * v;
    fColor = vec4(in_Color, 1.0);

}

Fragment shader :

varying vec4 fColor;

void main() {
    //gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    gl_FragColor = fColor;
}

But the results is not what I expect.
Expected :

What I get :

Loading of the Assimp model is provided in this question : https://gamedev.stackexchange.com/questions/85808/problem-rendering-simple-obj-model-using-assimp-in-android-app


texts: Map with 20 million tiles makes game run out of memory, how do I avoid it?

texts:
While loading extra huge maps, the loading method throws out of memory exception where a new instance of map tile is created. I'd like to have whole map processed at least on server app (and on client if possible). How should I solve this problem?

UPD: the question here is how to make the game stop crashing when there's still free memory for it to use. As for splitting map in chunks, it's a good approach, but not what I want in my case.

UPD2: At first I went and assigned a texture to every new instance of tile class and that's what took so much memory (also loading time). Now it takes about four times less space. Thanks to everybody, now I can run huge maps without thinking of breaking them up in chunks just yet.

UPD3: After rewriting the code to see if arrays of tile properties work faster or consume less memory (than said properties in their respective tiles as object properties), I found out that not only it took me a lot of time to try that, it didn't bring any performance improvement, and made the game terribly difficult to debug.


texts:
I've tried my hand at writing component systems and entity systems.

What I haven't managed to solve is the problem of event collision.

Say, we have an components A,B and C. A triggers 'kill B' event. When B recieves it, it erases the message (doesn't propagate it further). When C recieves it, it erases B. The order of which component will get the event first is not defined.

When the order is 'A,B,C', B stays alive but with 'A,C,B' B is erased. In other words, side effects of the event are undefined. A,B and C need to know about each other (which I don't want) to handle the event properly.

I intend to use components for games so for a more substantial example: we have an arrow (Projectile component) which fires of a collision event upon striking Link (Collidable component). Link has shield (also Collidable) which stops damage from affecting Link's Health component.

Arrows and health were written without the shield in mind and my component architecture is supposed to be encapsulated, so Health processes the collision event without knowing about the arrow or shield. Whether or not the damage is stopped depends on the order of components, which is random.

The best I've came up with is keeping a 'cache' of actions the event will do at the end of processing but still this solution has the same problems, only delayed. I could ditch events and try entity component system with storing 'mutations' in systems but that's not much different from just using global data for everything.

EDIT:

Okay, my communication skills are terrible. Here's what I've done to make components working without knowing about each other:

Use 'pure' entity system (components are pure data, all logic in systems)
Components do not talk to each other. The systems talk to each other by adding system-exclusive components to entities
Systems for above situation are: Movement, HandleCollision, ApplyArrowDamage. Movemen t appends a Collision component to the 'reciever' of the collision (Link) when calculating movements. HandleCollision reacts to Collision component, appends ArrowDamage component to Link entity and removes Collision component from Link. ApplyArrowDamage does just that and removes ArrowDamage component and maybe appends Dead component to be handled elswere.
Now, to create the situation when the shield blocks arrows, I create an CheckShield system and place it between HandleCollision and ApplyArrowDamage. CheckShield works with ApplyArrowDamage, checks whenether the reciever (Link in this case) has a shield equiped and removes ArrowDamage component if so.
This way, my old code doesn't need to account for new code to work properly and vice versa.

For the 'ABC' situation I do the same: If I want C to erase B, I write a new system that works with C and fires off before the system that works with B.
The only sane way to solve this problems with event raising is to keep rethrowing the event whenether it's state changed, and keep rethrowing it until it doesn't changed in the last iteration.


texts: How to handle two players playing on one keyboard with Box2D (LibGDX)?

texts:
I'm making a racing game with LibGDX and Box2D. I've been using this tutorial to implement the basic physics, and it works properly.

My main problem is to implement two different sets of keys (UP-DOWN-LEFT-RIGHT and ASDW) to control two different instances of a Car class on a same screen.

The code I have yet for handling one set of input (for KeyDown):

@Override
public boolean keyDown(int keycode) {
    if (keycode == Input.Keys.UP) {
        if (!pressedKeys.contains(Key.Up)) {
            pressedKeys.add(Key.Up);
        }
    } else if (keycode == Input.Keys.DOWN) {
        if (!pressedKeys.contains(Key.Down)) {
            pressedKeys.add(Key.Down);
        }
    } else if (keycode == Input.Keys.LEFT) {
        if (!pressedKeys.contains(Key.Left)) {
            pressedKeys.add(Key.Left);
        }
    } else if (keycode == Input.Keys.RIGHT) {
        if (!pressedKeys.contains(Key.Right)) {
            pressedKeys.add(Key.Right);
        }
    }
    return false;
}

(KeyUp):

    @Override
public boolean keyUp(int keycode) {
    if (keycode == Input.Keys.UP) {
        if (pressedKeys.contains(Key.Up)) {
            pressedKeys.remove(Key.Up);
        }
    } else if (keycode == Input.Keys.DOWN) {
        if (pressedKeys.contains(Key.Down)) {
            pressedKeys.remove(Key.Down);
        }
    } else if (keycode == Input.Keys.LEFT) {
        if (pressedKeys.contains(Key.Left)) {
            pressedKeys.remove(Key.Left);
        }
    } else if (keycode == Input.Keys.RIGHT) {
        if (pressedKeys.contains(Key.Right)) {
            pressedKeys.remove(Key.Right);
        }
    }

    return false;
}

How should I do to be able to handle UP-DOWN-LEFT-RIGHT and ASDW keys simultaneously?

Note: A Car is instantiated in the main class.

I can always add more code if needed.


texts: Confusion about Sprite Size in World Space (Unity)

texts:
I have a Sprite with 1080x1920 resolution. And I set the Game View Resolution also to 1080x1920. What I was thinking is that the sprite (1080x1920) should fit correctly within the Camera View.

But when I drag that sprite, the sprite is enlarged and goes out of the camera view.

What adjustments do I need to do to make sure this sprite is 100% fit within the camera view.
I could have changed the Sprite Transform Scale. But that will cause problems because I've a lot of other sprites to deal with and they should be proportional.


texts: Spine runtime for libgdx clipped rendering issue

texts:
I've started to play with the Spine for libgdx runtime in Java.

But I can't seem to render without some sort triangular clipping.

The code is based on the Spine examples:

public class AnimalTest extends ApplicationAdapter {

   OrthographicCamera camera;
   PolygonSpriteBatch batch;
   SkeletonRenderer renderer;

   TextureAtlas atlas;
   Skeleton skeleton;
   AnimationState state;

   public void create () {

      camera = new OrthographicCamera();

      batch = new PolygonSpriteBatch();

      renderer = new SkeletonRenderer();

      atlas = new TextureAtlas(Gdx.files.internal("animals/Animals.atlas"));
      SkeletonJson json = new SkeletonJson(atlas); // This loads skeleton JSON data, which is stateless.

      SkeletonData skeletonData = json.readSkeletonData(Gdx.files.internal("animals/Animals.json"));

      skeleton = new Skeleton(skeletonData); // Skeleton holds skeleton state (bone positions, slot attachments, etc).
      skeleton.setSkin("5");

      skeleton.setX(1000);
      skeleton.setY(-400);

      AnimationStateData stateData = new AnimationStateData(skeletonData); // Defines mixing (crossfading) between animations.

      state = new AnimationState(stateData); // Holds the animation state for a skeleton (current animation, time, etc).

      state.setAnimation(0, "idle", true);
   }

   public void render () {

      state.update(Gdx.graphics.getDeltaTime()); // Update the animation time.

      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

      state.apply(skeleton); // Poses skeleton using current animations. This sets the bones' local SRT.
      skeleton.updateWorldTransform(); // Uses the bones' local SRT to compute their world SRT.

      // Configure the camera, SpriteBatch, and SkeletonRendererDebug.
      camera.update();
      batch.setProjectionMatrix(camera.combined);

      batch.begin();
      renderer.draw(batch, skeleton); // Draw the skeleton images.
      batch.end();

   }

   public void resize (int width, int height) {
      camera.setToOrtho(false);
   }

   public void dispose () {
      atlas.dispose();
   }

}


texts: Error: Cannot create FMOD::Sound instance for resource sharedassets0.resource when splitting application binary in Unity

texts:
I'm trying to publish an Unity app to the PlayStore. Since the size of the app is over the limit of 100MB, I need to split the binary. So I selected the option Split Application Binary in Unity.

However, when I try to launch this application (either by downloading it on the Playstore or putting the .apk and the .obb directly on my device from my computer), I get the following errors on Android SDK monitor:

01-24 11:38:52.442: E/Unity(25004): Error: Cannot create FMOD::Sound instance for resource
sharedassets0.resource, (File not found. )
01-24 11:38:52.442: E/Unity(25004):
01-24 11:38:52.442: E/Unity(25004): (Filename:  Line: 882)
01-24 11:38:52.442: E/Unity(25004): Function SoundHandle::Instance::~Instance() may only be
called from main thread!
01-24 11:38:52.442: E/Unity(25004):
01-24 11:38:52.442: E/Unity(25004): (Filename:  Line: 25)

The application freezes at the "Made with Unity" splash screen.

This is not happening when I don't use the Split Application Binary option and put the .apk directly on my device from my computer.

I'm using Unity 5.4.0.


texts: how to use vehicles in a sandbox with gamepad

texts:
hello I have a game prototype in unity about a local multiplayer sandbox game with gamepad.

The game tries to use vehicles and perform an activity x and I want it to be for 2 people.

At this moment I have a car, a limousine, a tank, a fire truck and an ambulance.

I use Rewired for the input of the gamepad, but the problem I have is that what is already programmed is wrong, that is, everything works in its own scene. In CarScene I have my car and when I move the sticks of the gamepad it moves as it should, so in TankScene my tank moves because it inherits from car and a method of shooting is added, and so on, the ambulance only sounds its siren and the firefighter's cabin shoots water with a shader. But when the players in a scene all move at the same time. Because basically I program in the Update () that takes the movement of the left stick and the movement is applied.

What I need and it is not clear to me is how I can make it possible to select only one vehicle, similar to GTA, a character walks through the city, approaches a vehicle, enters it with a button, at this moment all the Vehicle operations, the player presses a button to exit the vehicle and the control now reprocesses the character.

In fact I already have my modified version of ThirdPersonControl using REWIRED.

The first idea that I have is that in the player's component, a reference to which vehicle is being used is added and it is left null when walking, and add the reference when the button is pressed near a vehicle.

The second idea I had was to create a vehicle-level variable, turn it on and off with the same logic that I require

Vehicle {
Update () {
if (IsInUse)
    ProcessInput ()

And the last thing that occurred to me was to add a Player object in each vehicle, leave it in null when the vehicle is not in use and activate it

Vehicle{ //car inherits from here
Update () {
if (player! = null)
    ProcessInput ()

But I feel that with these approaches at some point I am going to have a bug when two vehicles are very close to the command to enter, activate both and cause bad behavior. Or worse, that at some point you lose the reference of which vehicle is active and nothing moves or the character.

I hope you can help me, and that is that I already thought a lot about it in my head, but I feel that I do not have the right solution for the problem


texts:
I am trying to convert a 3d point into a 2d point using a perspective projection. I'm new to OpenGL and may not have fully understood how this works. How exactly do I calculate the near and far values?

The vertex values I want to consider are between 1, 1, 1 and 16, 16, 16.
So if I consider a output texture of size 16 x 16. Will my near and far be 0 and 16 respectively?

Does this transformation take care of scaling my vertex values between 0 and 1 as well?


texts: How to create a custom set of coordinates based on two points in Unity?

texts:
As the title says, I am having problems finding a way to create a new set of local coordinates based on two points. Here is an example:

Consider that the two gameObjects are not one parent of another, therefore I cannot use something like transform.localPosition, furthermore I tried using transform.TransformPoint(), however the latter works only if if I want to create it with respect to a single point.
I think it is a silly question, yet I am not finding a way to solve it, so any help is greatly appreciated!


texts:
This is not a question but a confirmation if I'm correct about the behavior of HLSL arrays.

I'm working with a standard lighting vertex shader, HLSL plus C++, DirectX11.1 API. For storing my lights data I've setup a simple declaration, padded accordingly to match the packing requeriments of constant buffers:

  // C++ side
struct LightBase {
            DirectX::XMFLOAT3   pos, color;
            DirectX::XMFLOAT3   color;
            float               intensity;
            float               isOn;
    };
    struct CBUFFER_LIGHT {
        LightBase   light[MAX_LIGHTS];
        float       numActiveLights;
        float       _padding[3];
    };

The shader declares a "matching" cbuffer as:

// HLSL vertex shader
    struct LightBase {
        float3 pos;
        float3 color;
        float  intensity;
        float  isOn;
    };
    cbuffer lights : register (b3) {
        LightBase light[MAX_LIGHTS];
        float numActiveLights;
    }

Now, as I expected, it didnt work due to the HLSL memory organization policy regarding arrays. e.g; if I set the buffer from C++ with the following data:

I get the following data when accessing struct members of light[0] from shader:

See how light[0].color and other struct members  got messed up?  Seems that HLSL will organize your arrays in Vector4 elements regardless of the real type of the array element.

So the array data passed from C++ which is { -7, -1, -100, 0.44, 0.66, 0.88, 1.0, 1.0 } will be organized by HLSL as follows:

A[0] = { -7, -1, -100, 0.44 }
A[1] = { 0.66, 0.88, 1.0, 1.0 }
A[2] = { ...}

So A[0] contains .xyz for position and .x for color struct member. A[1] contains .gb for color member, intensity and isOn data.

But calling light[0].color from the shader will still try to address &light + sizeof(float3)+sizeof(float3) as defined in the cbuffer, but you will get incorrect results due to array organization policy of HLSL.

If HLSL and DirectX are so fond of FLOAT4 values, it's not better to use all float4 variables and access members (.xyzw)  as needed?
Thanks.


texts:
Processing is a Java library for working with computer graphics, providing methods by which to draw primitive objects, custom meshes, etc., as well as mathematical methods (such as Simple Harmonic Motion) by which to animate and control them.

p5.js is an equivalent library for JavaScript and working with graphics on the web. You also have openFramworks which is similar but for C++.

How can you achieve similar graphics capabilities in the Unity Game Engine?

Suppose, for example, I wanted to build a game like Duet. I can imagine how I might go about creating those graphics in Processing or p5.js, but not in Unity and C#. How can you have that kind of creative freedom to build and draw in Unity?

Thanks.


texts: Common way to store model transformations

texts:
I ask myself what's the best way to store the transformations in a model class.
What I came up with is to store the translation and scaling in a Vector3 and the rotation in a Matrix4.

On each update (frame) I multiply the 3 matrices (first build a Translation and Scaling Matrix) to get the world matrix. In this way I have no accumulated error.

world = translation * scaling * rotation

Another way would be to store the rotation in a quaternion but then I would have a high cost to convert to a matrix every time step. If I lerp the model I convert the rotation matrix to quaternion and then back to matrix.

For speed optimization I have a global dirty flag and one for each transformation so that I only do a matrix multiplication if necessary.

if (isDirty) {
    world = translation
    if (isScaled) {
        world *= scaling
    }
    if (isRotated) {
        world *= rotation
    }
}

Is this a common way or is it more common to have only one Matrix4 for all transformations?
And is it better to store the rotation only as quaternion? For info: Currently I'm building a CSS3D engine in Javascript but these questions are relevant for every 3D engine.


texts: How do I find the downward sliding direction of a plane?

texts:
first time poster.

I'm curious as to how I can obtain a vector that defines the downward slope of a 3D plane. The goal is to apply this to a player as a force to achieve a sliding mechanic, like in Mario 64 (for steep floors and slide levels).

My attempts at this used variations of this equation, but it's not quite what I'm looking for.

b * ( -2*(V dot N)*N + V )
where
v is the vector that you want to reflect,
n is the normal of the plane,
b is the amount of momentum preserved (0.0 - 1.0).

this gives a reflected vector

I also have means to calculate the plane normal and get the intersection point of the player

Any other ideas to solve this are also appreciated


texts: How can I launch a GameObject at a target if I am given everything except for its launch angle?

texts:
I am trying to launch an object at a target, given its position, its target position, the launch speed, and the gravity.  I am following this formula from Wikipedia:

$$ \theta = arctan \bigg( \frac{v^2 \pm \sqrt{v^4-g(gx^2 + 2yv^2)}}{gx} \bigg) $$

I have simplified the code to the best of my ability, but I still cannot consistently hit the target.  I am only considering the taller trajectory, of the two available from the +- choice in the formula.

Does anyone know what I am doing wrong?

using UnityEngine;

public class Launcher : MonoBehaviour
{
    public float speed = 10.0f;

    void Start()
    {
        Launch(GameObject.Find("Target").transform);
    }

    public void Launch(Transform target)
    {
        float angle = GetAngle(transform.position, target.position, speed, -Physics2D.gravity.y);
        var forceToAdd = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * speed;
        GetComponent<Rigidbody2D>().AddForce(forceToAdd, ForceMode2D.Impulse);
    }

    private float GetAngle(Vector2 origin, Vector2 destination, float speed, float gravity)
    {
        float angle = 0.0f;

        //Labeling variables to match formula
        float x = Mathf.Abs(destination.x - origin.x);
        float y = Mathf.Abs(destination.y - origin.y);
        float v = speed;
        float g = gravity;

        //Formula seen above
        float valueToBeSquareRooted = Mathf.Pow(v, 4) - g * (g * Mathf.Pow(x, 2) + 2 * y * Mathf.Pow(v, 2));
        if (valueToBeSquareRooted >= 0)
        {
            angle = Mathf.Atan((Mathf.Pow(v, 2) + Mathf.Sqrt(valueToBeSquareRooted)) / g * x);
        }
        else
        {
            //Destination is out of range
        }

        return angle;
    }
}


texts:
I have created a control scheme identical to the UDK Jazz Jackrabbit tutorial.

Everything works as it should except I would like the Left Stick to control the character rotation when the Right Stick is not being pressed.

I'm terribly stumped here as don't know whether I should be comparing the vector output or the active/inactive input... nor do I honestly know how do this in Kismet :)

Any help would be greatly appreciated!

EDIT:
I want the left stick to do both the movement and rotation... until the right stick is pressed. In Kismet, how do I override the left stick's input with the right stick when it is pressed? (for the rotation that is)


texts: How can I create the graphical concept for a game?

texts:
I don't even know the right formulation for this, but basically, I have got a gameplay idea for a mobile game and now I need to create/develop/decide:

The theme of my game (e.g is it space, fantasy, abstract)
Color palette for my game.
The overall graphical style.

What could be the creative process to figure this out?

p.s. Is the stuff that I've described called graphical concept or art concept or something else?


texts: How to get a job in the game industry if you live in a country where there are no game companies?

texts:
You know not everyone of us is living in the US/Europe where there is potentially many more employers/opportunities than other countries, I live in a country where there is literally zero game companies (aside from a couple of companies that make HTML games), but I am sure there are many other people with the same situation, I am making some prototype games that will/might help.

But the real question is there any better way to get noticed (at least get an interview) by international companies, or given you are living far away will diminish their interest in hiring you?

-This question might be considered subjective or even a duplicate, but I feel am addressing an issue that might not have been addressed.


texts:
I'm rendering just a really small amount of polygons for my UI but however I still tried to increase the FPS. In the end I removed redundant calls which increased the FPS. I really don't want to lose FPS for nothing so I keep looking for more improvements.

The first thing I noticed is the "huge" time where no calls are made before SwapBuffer (the black one). Well I know that OpenGL works asynchronous so SwapBuffer has to wait until everything is done. But shouldn't PerfStudio mark this time also as black ? Correct me If I am wrong.

The second thing I noticed is that some glUniform2f calls just take longer (the brown ones). I mean they should all upload 2floats to the GPU how can the time be so different from call to call. The program isn't even changed or something like that.

I also tried to look at other programs like gDebugger or CodeXL but they often crashed and they show less statistics (only # of calls or redundant calls etc.)

EDIT: I also realized that the draw calls also have different durations, which was obvious for me but sometimes drawing more vertices is faster than drawing less vertices.


texts: What do colleges such as Rocky Mountain College of Art and Design look for in a portfolio?

texts:
I really want to get into Rocky Mountain College of Art and Design (RMCAD), but I don't know if my skills are up to par. A representative came down today and she told me the requirements for the Game Art degree. Turns out I don't need a portfolio, but I know it would definitely help me out with scholarships, acknowledgement of skill and so on. I want one for myself anyway.

I have a few 'good' sketches and some other 'eh' sketches I don't think are anywhere near my best. I have some life drawings I've been working on as well. To improve my skill I decided to start over and I'm currently learning the human anatomy to draw better skeletons for my characters and such.

I want to be a concept artist with characters and levels/buildings, but... I'm not the best at levels or buildings since I've never really drawn them before. My characters aren't the best, but I am improving. if anyone could help me, I'd greatly appreciate knowing what I should put in my portfolio, how to prepare for college, and etc.

Note: The college is an actual college which is a plus because I can learn my major (game art) plus a minor like business or something else. Maybe architecture...


texts:
I am trying to make a health system where hearts display how much health you have. On each heart, I have an Image component. I am trying to control what source image the Image component uses from a script, but it is not letting me. I read the documentation for the Image component here and it has no sprite property. This is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class HeartScript : MonoBehaviour
{
    public GameObject heart1;
    public GameObject heart2;
    public GameObject heart3;
    public Sprite halfHeart;
    public Sprite fullHeart;
    public Sprite emptyHeart;
    private double playerHealth = 3;

    // Update is called once per frame
    void Update()
    {
        if(playerHealth == 2.5)
        {
            heart1.GetComponent<Image>().image = fullHeart;
            heart2.GetComponent<Image>().image = fullHeart;
            heart3.GetComponent<Image>().image = halfHeart;
        }
        else if(playerHealth == 2)
        {
            heart1.GetComponent<Image>().image = fullHeart;
            heart2.GetComponent<Image>().image = fullHeart;
            heart3.GetComponent<Image>().image = emptyHeart;
        }
        else if(playerHealth == 1.5)
        {
            heart3.GetComponent<Image>().image = emptyHeart;
            heart2.GetComponent<Image>().image = halfHeart;
            heart1.GetComponent<Image>().image = fullHeart;
        }
        else if(playerHealth == 1)
        {
            heart3.GetComponent<Image>().image = emptyHeart;
            heart2.GetComponent<Image>().image = emptyHeart;
            heart1.GetComponent<Image>().image = fullHeart;
        }
        else if(playerHealth == .5)
        {
            heart3.GetComponent<Image>().image = emptyHeart;
            heart2.GetComponent<Image>().image = emptyHeart;
            heart1.GetComponent<Image>().image = halfHeart;
        }
        else if(playerHealth == 0)
        {
            heart3.GetComponent<Image>().image = emptyHeart;
            heart2.GetComponent<Image>().image = emptyHeart;
            heart1.GetComponent<Image>().image = emptyHeart;
        }
    }

    public void RemoveHealth()
    {
        playerHealth = playerHealth - 0.5;
    }
}

How do I change the sprite the heart uses from a script?


texts: Using an iPhone as a controller for a flash game

texts: How can I use an iPhone as a controller for a flash game, as described here?


texts:
I am currently working in C++ with SDL2. I plan on making a game that utilizes character visual customization. More specifically, equipping clothes and items changes the appearance of characters. However I don't know how to approach this situation. With that being said, how would I achieve this character customization in SDL2?

Right now I have two ideas...

Create a sprite sheet for every possible combination.( Way too much
time).
Break the sprite into different rects to draw each article of clothing or item. (Not sure if this is efficient)


texts: For character animation, is it better to use sprite sheets or animating "pieces" with keyframes?

texts:
First I want to say that I am not an artist, and I intend to work with an artist to complete my project. I'm looking for the solution that makes it the easiest to work with the artist and create the best final product.

I also want to clarify what my two choices are, in case I've used imprecise language.

1) Sprite sheets. By this, I mean that each frame of animation is a complete picture, as shown on the right-hand side of this image.

2) Animating pieces with keyframes. By this I mean each piece of the character is a separate sprite as shown on the left-hand side of the same image. In this case, the developer must specify keyframes and the engine interpolates between them to create a smooth animation.

Here are some pros and cons of each as I see it.

1 Pros

Each frame looks better, more connected and whole
Less work for the developer, just drop it in as a new animation

1 Cons

Potentially choppy animations (an artist isn't likely to draw 60 frames per second of animation)
A lot of work for the artist if the character has to move in lots of different ways
Difficult to communicate ideas about exactly how the character should move

2 Pros

Smooth animation
Very dynamic, the character can move in an infinite number of ways without requiring more assets to be produced
Less work for the artist (this is good for the developer too because you can have faster iteration and create new assets easier)

2 Cons

Potential for wonky looking characters (joints moving in weird ways or not looking fully connected)
More work for the developer (must animate everything themselves)

If it helps, I have two main use-cases. The first game that I want to make is an infinite runner style game which should be pretty simple, the character only moves in one direction with limited actions. The second is a more complex story-based platformer. Here the characters will move in all four directions, jump, shoot, shoot while jumping, shoot forward while running backwards, etc.

However in either case, I can see these questions being relevant. Even when there is very little animation, is it better to go for flexibility and smoothness, or for good detail?

I think Mark of the Ninja showcases what I'm looking for very well, even knowing that I probably can't hit that level of production quality with one developer and one artist. For that game, it looks like each animation frame is completely drawn, but it's so smooth and dynamic that it's hard to tell.

So which method is better given the output that I'd like? Or would it be better to do a hybrid in some way?


texts: How do I view a Source engine (Left 4 Dead 2) VTF?

texts:
I used to use Source a lot, but it's been a long time. Now I want to look up some Left 4 Dead 2 textures for reference (Hard Rain's water particles, mainly), but the tools I used to use don't seem to have the same functionality as they used to, are broken or are new and seemingly broken.

I literally just want to look at VTFs I've exported from VPK's with GCFScape in the manner of a normal image viewer, as if they were .pngs instead of VTFs.

This seems like the best candidate, but I couldn't get it to open a viewer. Perhaps you can provide some documentation? Hammer might have been a useful texture inspector for me, except its thumbnails are restricted to 512x512 or lower viewing size.

Can anybody help me view these images in a vaguely straight-forward non-console GUI-ish manner? Like I used to be able to? Thank you in advance. =)


texts: Objective C and C++ for Game Development

texts:
I'm trying to figure out which language I should begin learning. I've only been programming for about 6 months, with languages like PHP, Java, and C#. I want to learn how to dev games, and while I know in most cases the answer to this would be through C++ (at least, I would think), though I'm still curious about what Objective C can offer in the sense of long term benefit.

It seems like there's a chance that Objective-C may actually become more popular than C++ in a few years, and for all I know, it may become the de facto standard development language for games. Still, despite all of this, I really don't know anything, and this is all speculation.

Both languages seem very interesting, and obviously can pull a lot of out of themselves.

What do you think?

Note: despite what some might say, I really don't want to end up using prebuilt engines, and would rather just learn how to make my own. I'm well aware that it takes a lot more time, but I'm quite ok with that.


texts: How can I extend this graphics code to draw more vectors of vertices?

texts:
I want to include the drawing of other vectors of vertices in the following code, in a number of places it seems easy enough to simply add or multiply size()s of the two vectors, for instance in the first check. But then it gets a bit fuzzy simply because of a lack of understanding.

Should I add them together to create a bigger buffer description and copy everything together? Or should I do it all separately?

Basically how would I extend this code to include more vectors of vertices?

if (temporary2DVerts.size() > 0)
{
    // create the vertex buffer and store the pointer into pBuffer, which is created globally
    D3D10_BUFFER_DESC bd;
    bd.Usage = D3D10_USAGE_DYNAMIC;
    bd.ByteWidth = sizeof(VERTEX) * temporary2DVerts.size();// this breaks the create buffer line : temp2DVerts.size();
    bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
    bd.MiscFlags = 0;

    device->CreateBuffer(&bd, NULL, &pBuffer);

    void* pVoid;    // the void pointer

    pBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pVoid);    // map the vertex buffer
    memcpy(pVoid, &temporary2DVerts[0], sizeof(temporary2DVerts[0]) * temporary2DVerts.size());
    pBuffer->Unmap();

    // select which input layout we are using
    device->IASetInputLayout(screenVertexLayout);

    // select which primtive type we are using
    device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_LINELIST);

    // select which vertex buffer to display
    UINT stride = sizeof(VERTEX);
    UINT offset = 0;
    device->IASetVertexBuffers(0, 1, &pBuffer, &stride, &offset);

    // apply the appropriate pass
    screenPass->Apply(0);

    // draw the vertex buffer to the back buffer
    device->Draw(temporary2DVerts.size(), 0);

    temporary2DVerts.clear();
}

EDIT - just to be clearer - there are 4 vectors of vertices. two that don't change and two that constantly change. permanent 2D and permanent 3D and a temporary version of both. This is so the permanent ones can just be loaded in and are always drawn, and the temporary ones  only get drawn for a frame. This way I can create moving lines for debugging, like line of sight cones etc.

EDIT - the naive approach would be to duplicate this code 4 times for each vector, but surely there is a better way? I don't think this is a hard thing to do, but trying to do it has exposed a basic gap in my knowledge about what some of these lines of code do. should I just populate one big list from all the vectors and push that through?

some need to be drawn with different passes, and some don't need to be changed each frame. for example, the permanent ones can just stay on the gpu. right?


texts: How much a game can borrows from a franchise before becoming a fangame/infringing the copyright

texts:
Let's say you like the theme/world of a franchise, for example SpongeBob SquarePants, and you want to make it into maybe a business game where you hold an underwater restaurant. Make burgers, invent recipes, have fishes as customers etc. How much can you borrow from the original franchise before crossing the red line ? I know that the names are the first to be copyrighted, but if for example your cook looks like a yellow square sponge, is that an infringement ? Even more, if you want to implement the concept of "Special Formula" as in the anime (without naming it in the same way), is that an infringement ?

Thanks.


texts: How can I store a large amount of items in a space-efficient manner?

texts:
How can I store a large amount of items inside my game?

Are each of the items default data be loaded from a file into an item class and then stored in a giant array/list/dictionary?

For a point of reference, I'm talking about something like Skyrim where there are hundreds of items that the player is able to touch and pickup. And at any point the player can debug and add an item to their inventory.

I feel like the game would store everything is some kind of list but I also feel like this could consume a lot of memory, but maybe I am overthinking the size of each individual items data.


texts:
I am trying to implement field of view (FOV) in a hex grid. I am using the cube coordinate system from here. Then, I am using shadow casting to find FOV as from here.

I have a system like in the image, below. The numbers at the corners are coordinates. The numbers in the center are formatted as [Ring index],[Hex Index].

I need to used both ring index and hex index to calculate angles used for shadow casting. I spent several days on it, but I still cannot find a way to make these two sets of numbers convertible.

How do I calculate hex coordinates from a ring and index?


texts: Trying to understand light on Opengl, how to simulate a realistic sun light?

texts:
I don't know if I'm doing something wrong or missing anything but I want to simulate sun light, like in a sunny day.

When the object is facing the directional light, it's well lit and there's no problems there. If I go around the object and look at it's back, it's dark. It's not too much dark because I'm using GL_AMBIENT but it's still too dark for a sunny day. If I increase the value, it will never look better because the side of the object facing the light will be too bright.

And there's another annoying issue with the ambient light, when looking at the back of the object, I can't see any shape, only a plain color. Hard to explain, here's some pictures:

Object Front: http://i.stack.imgur.com/YW53X.png
Object Back: http://i.stack.imgur.com/Qufha.png

As you can easily see, the front side looks nice, you can see the shape of that red thing. On the back side, it's plain, you can't see the same shape.

Now, I know that I'm looking at the back of an object and I'm looking in the direction of the light and it should be darker than the front side. But it shouldn't look so plain like this. That's not what we see when going against the sun light looking at some object, we see that the objects form some shape.

How can I have the same (or similar) effect on OpenGL?

My light is currently defined like this:

float posLight0[4] = {-1.0f, 1.0f, 1.0f, 0.0f};
float ambLight0[4] = {0.5f, 0.5f, 0.5f, 0.5f};

glLightfv(GL_LIGHT0, GL_POSITION, posLight0);
glLightfv(GL_LIGHT0, GL_AMBIENT, ambLight0);


texts: "Industry Standard" JSON formats for game assets

texts:
This question is inspired by my venture into the Phaser game engine but seems to apply to any engine that uses JSON for its asset format.

Phaser relies on PhysicsEditor to export and create the JSON data for its physics bodies and TexturePacker for its sprite atlases. When I learned this I found some free alternatives that look like they might do the job.

So here's the problem. These JSON creators claim their output works for a slew of different engines, but how can I be certain of that when there can't possibly be such universal collaboration between the creators of these engines? It's especially dubious considering I can't find a standard anywhere. I don't want to rely on a solution only to encounter a glitch I don't understand. I want certainty.

After a lot of searching I finally found this thread, in which a couple of posters also expressed these frustrations. The final post appears to come from the horse's mouth, explaining that there's some "industry standard" that everyone uses, but the poster doesn't seem to know where the industry standard comes from either.

So I'd really like to know, is this specification actually documented anywhere? Does it have an origin or did it just... accrete?

If there's no good answer to this question, can I at least trust the claims of, say, Physics Body Editor and Shoebox, that their exports will work anywhere?


texts: Collision prediction of 2 moving objects

texts: I have to 2 objects with Collider2D. Both objects are moving, in the very next frame they will either overlap each other or not. How to predict if they would collide on the next frame? I'm thinking of instantiating a temporary object then use collider.Overlap(). But maybe there are better ways to do this.


texts: So I couldn't find anything online for this, but I want to make my text render actor clickable for my main menu. For example, when "New Game" is clicked it starts a new game. If you have any answers, please leave them for me! Tysm! :>


texts: How do I draw a full resolution texture to a window of the same resolution?

texts:
My image is 1280x800, and my screen size is 1280x800. It should draw perfectly. I'm creating a quad the size of the screen, and setting the texture to fit the quad. But right now it draws a square texture on my upper left corner of my screen that's out of scale and not large enough.

I don't know why it doesn't work, I've tried writing the size of the texture larger when drawing and it seems to work sort-of, but I don't know why it didn't work when drawing on a 1280x800 quad.

How do I create a fullscreen quad?

Here's how I'm currently doing it:

This is my OPENGL and display setup code:

    DisplayMode displayMode = null;
    DisplayMode[] modes = Display.getAvailableDisplayModes();

    for (int i = 0; i < modes.length; i++) {
        if (modes[i].getWidth() == World.SCREEN_WIDTH && modes[i].getHeight() == World.SCREEN_HEIGHT && modes[i].isFullscreenCapable()) {
            displayMode = modes[i];
        }
    }

    Display.setDisplayMode(displayMode);
    Display.setFullscreen(false);
    Display.create();

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, World.SCREEN_WIDTH, World.SCREEN_HEIGHT, 0, 1, -1);
    glMatrixMode(GL_MODELVIEW);
    glEnable(GL_TEXTURE_2D);

This is my code for drawing the textured quad:

    background = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/menu/background.png")));

    glBindTexture(GL_TEXTURE_2D, background.getTextureID());
    glPushMatrix();
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex2f(0, 0); // Upper left

    glTexCoord2f(1, 0);
    glVertex2f(World.SCREEN_WIDTH, 0); // Upper right

    glTexCoord2f(1, 1);
    glVertex2f(World.SCREEN_WIDTH, World.SCREEN_HEIGHT); // Lower right

    glTexCoord2f(0, 1);
    glVertex2f(0, World.SCREEN_HEIGHT); // Lower left
    glEnd();
    glPopMatrix();


texts: GLSL Motion blur on mobile.. possible at acceptable framerates?

texts:
I have been struggling to implement a simple linear motion blur effect on mobile (Android, OpenGLES 2.0) but it just seems to destroy my framerate.

I'm rendering to texture (FBO) then applying a fragment shader with a blur function that looks like this (with just some hard coded values for testing):

vec4 motionBlur(sampler2D color, vec2 uv, float intensity)
{
    vec2 speed = vec2(0.05, 0.0);
    vec2 offset = intensity * speed;
    vec3 c = vec3(0.);
    float inc = 0.1;
    float weight = 0.;
    for (float i = 0.; i <= 1.; i += inc)
    {
        c += texture2D(color, uv + i * offset).rgb;
        weight += 1.;
    }
    c /= weight;
    return vec4(c, 1.);
}

Called with (for example):

gl_FragColor = motionBlur(u_Texture, v_TexCoordinate.xy, 0.2);

This sends my frame rate from 60fps to 5fps.

Is this even plausible on a mobile device?  I have a 2012 Galaxy Nexus (PowerVR SGX540 GPU).

I'm wondering if it's just too much for a little mobile, or whether I'm doing something stupidly wrong in the shader.

Any ideas?  Anyone successfully implemented a motion blur on mobile?


texts: Unity - Display array of Objects in inspector

texts:
I have an array of ScritableObject's, which should only be displayed in the inspector if a boolean is true. How would I do this? With my current code, I get an error saying:

  Cannot implicitly convert type Tile to `Tile[]

This is my current code:

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

[CreateAssetMenu (fileName="Data", menuName="Tiles/Map", order=1)]
public class Tile : ScriptableObject {

    public ETile eTile;
    public Sprite sprite;

    [Space(5), Header("Variety")]
    public bool variety;

    [Range(0f, 1f)]
    public float varietyChance;
    public Tile[] varietyTiles; <---- This should be hidden if variety is true
}

public enum ETile {
    Water,
    Grass
}

[CustomEditor(typeof(Tile))]
public class MyScriptEditor : Editor {

    override public void OnInspectorGUI() {
        var tile = target as Tile;

        tile.variety = EditorGUILayout.Toggle("Hide Fields", tile.variety);

        if (tile.variety) {
            tile.varietyTiles = (Tile)EditorGUILayout.ObjectField("Tile", tile, typeof(Tile), allowSceneObjects: true);         }
        }
    }
}


texts: How can I get the palette of an 8-bit surface in SDL.NET/Tao.SDL?

texts:
I'm looking to get the palette of an 8-bit surface in SDL.NET if possible, or (more than likely) using Tao.SDL. This is because I want to do palette swapping with the palette directly, instead of blitting surfaces together to replace colours like how you would do it with a 32-bit surface.

I've gotten the SDL_Surface and the SDL_PixelFormat, however when I go to get the palette in the same way, I get a System.ExecutionEngineException:

private Tao.Sdl.Sdl.SDL_Palette GetPalette(Surface surf)
{

// Get surface.
Tao.Sdl.Sdl.SDL_Surface sdlSurface = (Tao.Sdl.Sdl.SDL_Surface)System.Runtime.InteropServices.Marshal.PtrToStructure(surf.Handle,
    typeof(Tao.Sdl.Sdl.SDL_Surface));

// Get pixel format.
Tao.Sdl.Sdl.SDL_PixelFormat pixelFormat = (Tao.Sdl.Sdl.SDL_PixelFormat)System.Runtime.InteropServices.Marshal.PtrToStructure(sdlSurface.format,
    typeof(Tao.Sdl.Sdl.SDL_PixelFormat));

// Execution exception here.
Tao.Sdl.Sdl.SDL_Palette palette = (Tao.Sdl.Sdl.SDL_Palette)System.Runtime.InteropServices.Marshal.PtrToStructure(pixelFormat.palette,
    typeof(Tao.Sdl.Sdl.SDL_Palette));

return palette;
}

When I used unsafe code to get the palette, I got a compile time error: "Cannot take the address of, get the size of, or declare a pointer to a managed type ('Tao.Sdl.Sdl.SDL_Palette')".

My unsafe code to get the palette was this:

unsafe
{
    Tao.Sdl.Sdl.SDL_Palette* pal = (Tao.Sdl.Sdl.SDL_Palette*)pixelFormat.palette;
}

From what I've read, a managed type in this case is when a structure has some sort of reference inside it as a field. The SDL_Palette structure happens to have an array of SDL_Color's, so I'm assuming that's the reference type that is causing issues. However I'm still not sure how to work around that to get the underlying palette.

So if anyone knows how to get the palette from an 8-bit surface, whether it's through safe or unsafe code, the help would be greatly appreciated.


texts: What is transmitted over the network during multiplayer first person shooter games?

texts:
In games like Half-Life 2, Team Fortress 2 etc, when you play against other players online, your local game communicates with a game server.
If you've built one of these games, what sort of information is sent by your local game to the game server, and what sort of information is sent to you by the game server?
I recall reading that in Team Fortress 2, the computer tracks the trajectory of every projectile including every bullet, rocket. It seems like that would generate a tsunami of messages, yet my game works reasonably well over distinctly average broadband.
I've noticed gaps in the magician's curtain when severe lag occurs. Sometimes other players "teleport"; they're not where I think they are. Other times, I can peer around a corner and be killed when there's no-one there; except shortly after I see the other victorious player.
So roughly, what is being communicated over the network to create the illusion of real time?
I'm generally interested in simulation games but have never built one. I'm just trying to get a feel for how it's done.
Let's start with

The position x, y, z, speed, and direction of every player.
Player switches weapon
Player fires/stop firing.


texts: Need help with simple octree implementation

texts:
Hello I'm trying to implement an octree, but when I query the centre positions they all return zero, but these should be offset from zero. Here is my code:

class Octree:

def __init__( self, _centre, _size ):
    '''
    Class to create an Octree

    @param: _centre: [float,float,float], position in world space for centre of octree
    @param: _size: float, length of one edge of the first cube, should be big enough to fit all data
    '''

    self.centre = _centre
    self.size = _size
    self.octreeNodes = []

def subdivideOctree( self, _subdivisions ):
    '''
    subdivides octree

    @param: _subdivisions: int, number of times to subdivide octree
    '''

    for i in range(8):
        newCentre = self.centre

        if ((i&2) == 2):
                newCentre[0] += self.size * 0.25
        else:
                newCentre[0] -= self.size * 0.25

        if ((i&4) == 4):
                newCentre[1] += self.size * 0.25
        else:
                newCentre[1] -= self.size * 0.25

        if ((i&1) == 1):
                newCentre[2] += self.size * 0.25
        else:
                newCentre[2] -= self.size * 0.25

        print newCentre

        self.octreeNodes.append(Octree( newCentre, self.size * 0.5 ))

        if( _subdivisions > 0 ):
                self.octreeNodes[i].subdivideOctree( _subdivisions - 1 )

def isLeaf( self ):
    return self.octreeNodes == None

def getCentre( self ):
    return self.centre

def getSize( self ):
    return self.size

a = Octree([0,0,0], 2.0)
a.subdivideOctree(2)

print a.getCentre()
print a.octreeNodes[0].getCentre()
print a.octreeNodes[0]

for n in a.octreeNodes:
    for b in n.octreeNodes:
        print b.getCentre()


texts: 3D format or software that stores a vertex normal

texts:
At the moment i'm using .obj file format to store 3D models. It's popular, easy to read and parse. The issue is that it stores sufrace normals for each face. This isn't an issue for me yet, but i'm keeping in mind that i have to deal with lights once i'm done with the basics of my engine. This will require vertex normals and not surface normals. I want to avoid vertex multiplication and i want nice, curved surfaces. Blender seems to be unable to store vertex normals, only sufrace normals, is this typical of 3D rendering software and file formats?

Now i'm still kind of bad at profiling and i lack experience of what's "standard", but still i want to write effective code and i can't benchmark my ideas, so please excuse me asking weird questions here.

Is it "normal" to load surface normals from the .obj file and then for each vertex do an average of all the surface normals of surfaces that use this vertex (f.e. a plane "f " in .obj says vertex of index "i" has some normal "n", so i averate this normal "n" with the one already stored for this vertex)? This seems like such an expensive calculation to do when loading a model, is this the right way to think about it? Or is there a better way (or a file format/3D editor) to deal with this issue. Having multiple normals per vertex means that i have to duplicate vertices which is out of the question, not to mention that i'd get flat shading.

I'm mostly asking this because it seems illogical that a 3D model would be stored with surface normals that are very easy to calculate and not vertex normals which aren't easy to calculate and which are required for realistic lighting. Maybe it's a "legacy" thing?

Also, while we're on the subject, how do people deal with surfaces that have to be flat planes like a brick? For light calculations these models need vertices normals to be surface normals. but if i had a model like a knife that would consist of the blade that needs to be flat and the handle that i want round i would have to have the blade with duplicate vertices and the handle with not duplicate vertices which seems like a weird thing to request from my 3D softare (if it's even possible).

How do people deal with it, the only "smart" idea i can think of is to do separate models for flat objects (that would be stored in an innefficient way with vertex copies instead of indices) and separate models for round objets that would use the averating described above. The other idea is to have a program with a geometry shader in case i want to render a flat surface that would calculate a surface normal and set each vertex's normal to the one calculated and pass that to the fragment shader (though the extent of my geometry shader knowledge is a short article, haven't used them yet, is this even possible in OpenGL?).

I feel like i'm trying to brute force the issue, maybe there's a "magic" math trick that could help me or am i just stuck with more models or shader programs to manage.


texts: How much of a game can be protected by law?

texts:
I want to remake an old multiplayer game in commercial way and I wonder how different my game has to be not to violate some IP rights. I know so far that name and logo are registered trademarks of the company that still exists so I cannot use it. But ...
How about other things such as maps or mechanics of the game? Can this be somehow protected?
If I make a new map that will NOT use a single asset from that old map (like textures, sounds or models) but will mimic the old map as much as possible, can this be problem from legal point of view?
By mimic I mean for example putting tree in excactly same position as on the old map, but the tree would be completely different model; buildings would have same plans but all the models and walls textures would be different.
Also this game has some certain amount of features (players classes, mission scenarios, types of weapons) that are being used in other games commonly so this cannot be patented.
But how about given set of these features? For example having given types of classes connected with given missions scnarios and types of weapons can be protected even though seperately they cannot be???
Is that possible?


texts: Storing few values in an int - small gain

texts:
This might be a bit hard-to-answer question, but... I had a DirectX::XMFLOAT3 as a vertex attribute. I have changed it to just an int by placing the 3 floats into int (using only 8 bits per float). In the vertex shader I am extracting the bits like this:

// example int bits: 00000000 10011000 00011101 11111111

input.weight.x =   ( input.w >> 16 )               / 255.0f; // 10011000 / 255.0f
input.weight.y = ( ( input.w & 0x0000FF00 ) >> 8 ) / 255.0f; // 00011101 / 255.0f
input.weight.z =   ( input.w & 0x000000FF )        / 255.0f; // 11111111 / 255.0f

But with this manner I've only gained like 1-5 fps (from ~130 to ~135), how is that possible that the fps boost is that small? What's the culprit here? Is the extracting bits on GPU that heavy?


texts: How to make animation in unity Dots hybrid?

texts: I'm working on isometric game in 2D but didn't find any good tutorial in how to handle animation...any help?


texts: Rendering PhysX Primitive Geometry in DirectX 12

texts:
I created a scene with two primitive geometries (Sphere and Box). Now I want to  recreate what I see in the scene (PhysX Visual Debugger) in my game engine window, but I can't find any functions that could help me create a vertex buffer.

How do I render PhysX items using DirectX 12?
How can I get vertices from geometries in PhysX?

Code used to create a sphere using PhysX:

auto geometry = physx::PxSphereGeometry(1);
auto transform = physx::PxTransform(physx::PxVec3(0, 0, 0));
physx::PxRigidDynamic* dynamic = physx::PxCreateDynamic(*mPhysics, transform, geometry, *mMaterial, 10.0f);
mScene->addActor(*dynamic);


texts: How to clear the content of a Rendertexture?

texts:
I want to clear the content of a RenderTexture in runtime.

Basically I have this script:

   void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        RenderTexture TempRT = new RenderTexture(cam.pixelWidth, cam.pixelHeight, 24);
        RenderTexture whiteRT = new RenderTexture(TempRT.width, TempRT.height, TempRT.depth);

        Graphics.Blit(source, whiteRT, WhiteColorisation);
        if (Gauss)
        {
            Graphics.Blit(whiteRT, TempRT, PostOutline);
            Graphics.Blit(TempRT, destination, GaussianBlur);
        }
        else
        {
            Graphics.Blit(whiteRT, destination, PostOutline);
        }
    }

the problem here is: The 2 newly created Rendertextures' Memory is not released anymore.

So I changed it like:

void OnRenderImage(RenderTexture source, RenderTexture destination)
{
    RenderTexture _tempRT = RenderTexture.GetTemporary(cam.pixelWidth, cam.pixelHeight);
    RenderTexture _whiteRT = RenderTexture.GetTemporary(cam.pixelWidth, cam.pixelHeight);

    Graphics.Blit(source, _whiteRT, WhiteColorisation);
    if (Gauss)
    {
        Graphics.Blit(_whiteRT, _tempRT, PostOutline);
        Graphics.Blit(_tempRT, destination, GaussianBlur);
    }
    else
    {
        Graphics.Blit(_whiteRT, destination, PostOutline);
    }

    RenderTexture.ReleaseTemporary(_whiteRT);
    RenderTexture.ReleaseTemporary(_tempRT);
}

Now I dont get "new" Rendertextures anymore, but used ones.
It just draws something over a existing Texture, instead over a new "white" page.

The only thing i want is... that "_whiteRT" and "_tempRT" to be "new" ones, and the memory free.

The Obvious solution does not work:

void OnRenderImage(RenderTexture source, RenderTexture destination)
{
    RenderTexture tempRT = new RenderTexture(cam.pixelWidth, cam.pixelHeight, 16);
    RenderTexture whiteRT = new RenderTexture(cam.pixelWidth, cam.pixelHeight, 16);

    Graphics.Blit(source, whiteRT, WhiteColorisation);
    if (Gauss)
    {
        Graphics.Blit(whiteRT, tempRT, PostOutline);
        Graphics.Blit(tempRT, destination, GaussianBlur);
    }
    else
    {
        Graphics.Blit(whiteRT, destination, PostOutline);
    }
    tempRT.Release();
    whiteRT.Release();
}

If I use the code above, in the profiler my object count rises and rises (until i get a crash)

How can I solve this problem?


texts: I am building a 2D game in Java in which I use trig operations for rotation. I know Java offers an excellent graphics library but I intend to make my own code just for learning purposes. Now the problem is, I do not understand image interpolation. I do know it tracks the unmapped pixels on rotation and there are various techniques to do it etc. But one thing that Im still confused about even after referring to several tutorials, is - how to find the pixels that are not mapped ?? Once I know it, I can easily implement it in code. Im using PixelGrabber to get pixels and then perform rotation. So could someone just explain how to find unmapped pixels in the array during the rotation operation please?


texts: Elevation model for hexagonal game grids

texts:
TL;DR:

Where should elevation be anchored on a civ-style hexagonal grid? Center, side or vertex? (Or more complex?)

Question proper:

Consider for a moment a classic game we all know and love (maybe?), Sid Meier's Alpha Centauri. The map model introduced the brand new concept of visible terrain elevation to the classic Civ formula. In SMAC, every vertex of the game board had an elevation, allowing the map beautiful rolling hills, a complete necessity, considering the mind worm boils waiting around every corner.

Would a vertex-only elevation map translate neatly to a hexagonal grid?

The obvious alternatives are side-based elevation mapping and center-based elevation mapping; as well as inner-vertex elevation mapping (giving the opportunity for cliffs! Yay!)

The last option is applying a triangular lattice to the game grid encompassing centers and vertices, and having vertex-only or inner-vertex elevation.

Which of these options is likely to work well? Which are likely to suck all the juice out of the CPU and RAM in a hurry?


texts: Windows Phone 8.1 Monogame Content.Load exception

texts:
need some help, just trying to load compiled .fx (.xnb) file by monogame (version 3.4.0.456) in Windows Phone 8.1 enviroment by this code

MainEffect = Game.Content.Load<Effect>("chessboard");

there is a some delay, about 3-4 seconds, and then i get

  SharpDX.SharpDXException
  "Additional information: HRESULT: [0x80070057], Module: [General], ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect."

Tried different files, but seems no matter how complex the are, behaviour is the same.
Even this simple effect gives an error:

float4x4 World;

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

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

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

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    return input.Color;
}

technique Specular
{
    pass Pass1
    {
        VertexShader = compile  vs_4_0 VertexShaderFunction();
        PixelShader = compile ps_4_0 PixelShaderFunction();
    }
}

But for Windows 7/8/10 its works well. Any ideas ?


texts: How to compute tangent and bitangent vectors

texts:
I have a texture loaded in three.js, then passed to the shaders. In the vertex shader I compute the normal, and I save into a variable the uv vector.

<script id="vertexShader" type="x-shader/x-vertex">

                varying vec3 N,P;
                varying vec2 UV;

                void main() {
                    gl_Position= projectionMatrix * modelViewMatrix * vec4(position,1.0);
                    P= position;
                    N= normalMatrix * vec3(normal);
                    UV= uv;
                }
            </script>
            <script id="fragmentShader" type="x-shader/x-fragment">

                varying vec3 N,P;
                varying vec2 UV;
                uniform sampler2D texture;

                void main() {
                    gl_FragColor= texture2D(texture,UV);
                }

            </script>

How do I compute the T and B vectors?


texts: What is a good rule for blocking projectiles on a square grid?

texts:
Suppose we have a square grid, and each tile may or may not be occupied by an object. Some of those objects can be a unit that can launch a projectile at another unit. However, that projectile should be blocked if a third unit is "in the way" of the projectile path.

What I want is a rule for whether a projectile path is "blocked" from one tile to another, based on possible intermediate tiles blocked by an object. The blocking rule should satisfy the following criteria:

1) It should be based only on the information about the relative position on the grid of the two tiles, and the occupation of tiles by objects. Details such as which object is occupying a tile should not matter. Imagine the same rules would apply with placing stones on a Go board

2) It should be as obvious to the player as possible what the projectile blocking rules are. Imagine they could move a ranged unit to a tile to get a shot, and that movement is irreversible. If they later find out that the shot they wanted to make is blocked, they essentially got screwed over by a game mechanic. I don't want people to lose a game because of opaque mechanics. It should be as obvious as possible to the player that the shot they want to make form a tile is blocked before moving to that tile.

3) The rule should be generally applicable, not just a heuristic for a non-general set of possible scenarios. Given any two integer coordinates, {X1, Y1} and {X2, Y2} we should automatically be able to name the coordinates of all tiles that block those two coordinates.

4) The rule should be invariant to 4-way rotation, translation, and reflection along either axis.

Some rules would be obvious. For example, if your shot is completely horizontal/vertical (rook movement) or completely diagonal (bishop movement) and something is directly in that path, it should be blocked.

But there are cases that are not completely obvious to me, and different rules have been followed in different games. For example, what if the projectile launcher and target are separated by a knight's path? Is an object blocking the projectile if it lies on one of the two tiles that sit between the launcher and target along the long axis of separation? I have seen that being a valid block in the game Hero Academy, though it's not obvious to me that it should be.

EDIT: I realize that point #2 can be addressed with a nice UI that can inform the player of whether a path is blocked before they commit to their move. However, even if the UI does that, I still want it to be obvious to the player, independent of the UI. (If the player has to play a few games to learn how it works, that's fine, as long as it's easy to learn.) This aligns with my general philosophy that one should maximize the proportion of cognitive effort that goes towards strategic decision making, and minimize the proportion of cognitive effort that goes towards figuring out game mechanics on the spot.


texts: Keep game name after complete rebuild, engine migration and change from 2D to 3D?

texts:
I have published an Alpha version of a game with XNA in 2D, but I am now learning Unreal with full intention of porting the game to 3D there. I expect that in 3 months time, or less with a little luck, I will have a comparable version of the game in 3D, but I am already really close to the point where I can release some early footage.

With this in mind, I am also beginning to think about the game's promotion, its IndieDB page has it listed as a 2D XNA game, but there's two considerations:

a) Should I change the engine, given that earlier images and uploads are still there and I haven't got a release to replace them with?

b) Should I keep the name, considering that, 1) it is associated with the 2D game, and 2) search results bring up Fallout content, and the abbreviation SW is already fully associated with Star Wars?

I am, in the meantime, going to try to contact IndieDB and see if I am even allowed to change the game's listing (in terms of game engine and type) and will edit the post when I have an answer.