Recommended Posts

Hi, I came across this udk article:

https://docs.unrealengine.com/udk/Three/VolumetricLightbeamTutorial.html

that somewhat teaches you how to make the volumetric light beam using a cone. I'm not using unreal engine so I just wanted to understand how the technique works.

What I'm having problems is with how they calculate the X position of the uv coordinate, they mention the use of a "reflection vector" that according to the documentation (https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/ExpressionReference/Vector/#reflectionvectorws ) it just reflects the camera direction across the surface normal in world space (I assume from the WS initials) .

So in my pixel shader I tried doing something like this:

float3 reflected_view = reflect(view_dir, vertex_normal);
tex2D(falloff_texture, float2(reflected_view.x * 0.5 + 0.5, uv.y))

view_dir is the direction that points from the camera to the point in world space. vertex normal is also in world space. But unfortunately it's not working as expected probably because the calculations are being made in world space. I moved them to view space but there is a problem when you move the camera horizontally that makes the coordinates "move" as well. The problem can be seen below:

Screenshot_4.png.9f80ef66237b81e7a53db583f1b3591c.pngScreenshot_5.png.9c801ecfb2d4515c81394eb04921bb13.png

Notice the white part in the second image, coming from the left side.

Surprisingly I couldn't find as much information about this technique on the internet as I would have liked to, so I decided to come here for help!

Edited by ramirofages

Share this post


Link to post
Share on other sites

I am interested in this as well. 

I tried to create hlsl by what is going on in their "material node graph" image:

void main_ps(in VERTEX_OUT IN, out PIXEL_OUT OUT)
{
    static const float AddR = 8.0f;
    static const float MulR = 0.8f;

	float3 vvec = camPos.xyz - IN.WorldPos;
	float3 v = normalize(vvec);
	float3 n = normalize(IN.Normal);
	float3 rvec = reflect(v, n);
	float3 rx = rvec.x;
	float rz = sqrt((rvec.z + AddR) * MulR);
	float xcoord = (rx / rz) + 0.5f;
	float2 coord = float2(xcoord, IN.TexCoord0.y);
	float3 lightFalloff = tex2D(lightSamp, coord);

	float3 lightCol = float3(1.0f, 1.0f, 1.0f);
	OUT.Color = float4(lightCol, lightFalloff.r);
}

but wrong result:

KF5WUyg.png

I copied their image to use as light texture

If you got it solved please share.

Share this post


Link to post
Share on other sites

I kinda made some progress. Found their original material and inspect it, i was missing transform ReflectionVector to tangent space.

In Unreal :

z5baTJW.png

gZyNSG8.png

 

In my test program:

xio5vwR.png

i have seam error somehow (might be problems with my mesh exporter). And could not get correct result with CLAMP addressing (above image is WRAP)

tpm2drH.png

void main_ps(in VERTEX_OUT IN, out PIXEL_OUT OUT)
{
    float3x3 tangentBasis = float3x3(normalize(IN.Tangent), normalize(IN.Binormal), normalize(IN.Normal));

	float2 uv = IN.TexCoord0;
	
    static const float AddR = 8.0f;
    static const float MulR = 0.6f;

	float3 toEye = camPos.xyz - IN.WorldPos.xyz;

	float3 v = normalize(toEye);
	float3 n = normalize(IN.Normal);
	
	float3 R = reflect(v, n);
	float3 rvec = mul(R, tangentBasis);

	float rx = rvec.x;
	float rz = sqrt( (rvec.z + AddR) * MulR );
	float xcoord = (rx / rz) + 0.5f;
	float2 coord = float2(xcoord, uv.y);

	float3 lightFalloff = tex2D(lightSamp, coord);

	float3 lightCol = float3(1.0f, 1.0f, 1.0f);
	OUT.Color = float4(lightCol, lightFalloff.r);
}

 

Edited by belfegor

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Forum Statistics

    • Total Topics
      627719
    • Total Posts
      2978790
  • Similar Content

    • By gdarchive
      Over the past few years I have had a growing feeling that videogame storytelling is not what it could be. And the core issue is not in the writing, themes, characters or anything like that; instead, the main problem is with the overall delivery. There is always something that hinders me from truly feeling like I am playing a story. After pondering this on and off for quite some time I have come up with a list of five elements that I think are crucial to get the best kind of interactive narrative.
      The following is my personal view on the subject, and is much more of a manifesto than an attempt at a rigorous scientific theory. That said, I do not think these are just some flimsy rules or the summary of a niche aesthetic. I truly believe that this is the best foundational framework to progress videogame storytelling and a summary of what most people would like out of an interactive narrative.
      Also, it's important to note that all of the elements below are needed. Drop one and the narrative experience will suffer.
      With that out of the way, here goes:
      1) Focus on Storytelling
      This is a really simple point: the game must be, from the ground up, designed to tell a story. It must not be a game about puzzles, stacking gems or shooting moving targets. The game can contain all of these features, but they cannot be the core focus of the experience. The reason for the game to exist must be the wish to immerse the player inside a narrative; no other feature must take precedence over this.
      The reason for this is pretty self-evident. A game that intends to deliver the best possible storytelling must of course focus on this. Several of the problems outlined below directly stem from this element not being taken seriously enough.
      A key aspect to this element is that the story must be somewhat tangible. It must contain characters and settings that can be identified with and there must be some sort of drama. The game's narrative cannot be extremely abstract, too simplistic or lack any interesting, story-related, happenings.
      2) Most of the time is spent playing
      Videogames are an interactive medium and therefore the bulk of the experience must involve some form of interaction. The core of the game should not be about reading or watching cutscenes, it should be about playing. This does not mean that there needs to be continual interaction; there is still room for downtime and it might even be crucial to not be playing constantly.
      The above sounds pretty basic, almost a fundamental part of game design, but it is not that obvious. A common "wisdom" in game design is that choice is king, which Sid Meier's quote "a game is a series of interesting choices" neatly encapsulates. However, I do not think this holds true at all for interactive storytelling. If choices were all that mattered, choose your own adventure books should be the ultimate interaction fiction - they are not. Most celebrated and narrative-focused videogames do not even have any story-related choices at all (The Last of Us is a recent example). Given this, is interaction really that important?
      It sure is, but not for making choices. My view is that the main point of interaction in storytelling is to create a sense of presence, the feeling of being inside the game's world. In order to achieve this, there needs to be a steady flow of active play. If the player remains inactive for longer periods, they will distance themselves from the experience. This is especially true during sections when players feel they ought to be in control. The game must always strive to maintain and strengthen the experience of "being there".
      3) Interactions must make narrative sense
      In order to claim that the player is immersed in a narrative, their actions must be somehow connected to the important happenings. The gameplay must not be of irrelevant, or even marginal, value to the story. There are two major reasons for this.
      First, players must feel as though they are an active part of the story and not just an observer. If none of the important story moments include agency from the player, they become passive participants. If the gameplay is all about matching gems then it does not matter if players spend 99% of their time interacting; they are not part of any important happenings and their actions are thus irrelevant. Gameplay must be foundational to the narrative, not just a side activity while waiting for the next cutscene.
      Second, players must be able to understand their role from their actions. If the player is supposed to be a detective, then this must be evident from the gameplay. A game that requires cutscenes or similar to explain the player's part has failed to tell its story properly.
      4) No repetitive actions
      The core engagement from many games come from mastering a system. The longer time players spend with the game, the better they become at it. In order for this process to work, the player's actions must be repeated over and over. But repetition is not something we want in a well-formed story. Instead, we want activities to only last as long as the pacing requires. The players are not playing to become good at some mechanics, they are playing to be part of an engrossing story. When an activity has played out its role, a game that wants to do proper storytelling must move on.
      Another problem with repetition is that it breaks down the player's imagination. Other media rely on the audience's mind to fill out the blanks for a lot of the story's occurrences. Movies and novels are vague enough to support these kinds of personal interpretations. But if the same actions are repeated over and over, the room for imagination becomes a lot slimmer. Players lose much of the ability to fill gaps and instead get a mechanical view of the narrative.
      This does not mean that the core mechanics must constantly change, it just means that there must be variation on how they are used. Both Limbo and Braid are great examples of this. The basic gameplay can be learned in a minute, but the games still provide constant variation throughout the experience.
      5) No major progression blocks
      In order to keep players inside a narrative, their focus must constantly be on the story happenings. This does not rule out challenges, but it needs to be made sure that an obstacle never consumes all focus. It must be remembered that the players are playing in order to experience a story. If they get stuck at some point, focus fades away from the story, and is instead put on simply progressing. In turn, this leads to the unraveling of the game's underlying mechanics and for players to try and optimize systems. Both of these are problems that can seriously degrade the narrative experience.
      There are three common culprits for this: complex or obscure puzzles, mastery-demanding sections and maze-like environments. All of these are common in games and make it really easy for players to get stuck. Either by not being sure what to do next, or by not having the skills required to continue. Puzzles, mazes and skill-based challenges are not banned, but it is imperative to make sure that they do not hamper the experience. If some section is pulling players away from the story, it needs to go.
      Games that do this
      These five elements all sound pretty obvious. When writing the above I often felt I was pointing out things that were already widespread knowledge. But despite this, very few games incorporate all of the above. This is quite astonishing when you think about it. The elements by themselves are quite common, but the combination of all is incredibly rare.
      The best case for games of pure storytelling seems to be visual novels. But these all fail at element 2; they simply are not very interactive in nature and the player is mostly just a reader. They often also fail at element 3 as they do not give the player much actions related to the story (most are simply played out in a passive manner).
      Action games like Last of Us and Bioshock infinite all fail on elements 4 and 5 (repetition and progression blocks). For larger portions of the game they often do not meet the requirements of element 3 (story related actions) either. It is also frequently the case that much of the story content is delivered in long cutscenes, which means that some do not even manage to fulfill element 2 (that most of the game is played). RPGs do not fare much better as they often contain very repetitive elements. They often also have way too much downtime because of lengthy cutscenes and dialogue.
      Games like Heavy Rain and The Walking Dead come close to feeling like an interactive narrative, but fall flat at element 2. These games are basically just films with interactions slapped on to them. While interaction plays an integral part in the experience it cannot be said to be a driving force. Also, apart from a few instances the gameplay is all about reacting, it does not have have the sort of deliberate planning that other games do. This removes a lot of the engagement that otherwise comes naturally from videogames.
      So what games do fulfill all of these elements? As the requirements of each element are not super specific, fulfillment depends on how one chooses to evaluate. The one that I find that comes closest is Thirty Flights of Loving, but it is slightly problematic because the narrative is so strange and fragmentary. Still, it is by far the game that comes closest to incorporating all elements. Another close one is To The Moon, but it relies way too much on dialog and cutscenes to meet the requirements. Gone Home is also pretty close to fulfilling the elements. However, your actions have little relevance to the core narrative and much of the game is spent reading rather than playing.
      Whether one chooses to see these games as fulfilling the requirements or not, I think they show the path forward. If we want to improve interactive storytelling, these are the sort of places to draw inspiration from. Also, I think it is quite telling that all of these games have gotten both critical and (as far as I know) commercial success. There is clearly a demand and appreciation for these sort of experiences.
      Final Thoughts
      It should be obvious, but I might as well say it: these elements say nothing of the quality of a game. One that meets none of the requirements can still be excellent, but it cannot claim to have fully playable, interactive storytelling as its main concern. Likewise, a game that fulfills all can still be crap. These elements just outline the foundation of a certain kind of experience. An experience that I think is almost non-existent in videogames today.
      I hope that these five simple rules will be helpful for people to evaluate and structure their projects. The sort of videogames that can come out of this thinking is an open question as there is very little done so far. But the games that are close to having all these elements hint at a very wide range of experiences indeed. I have no doubts that this path will be very fruitful to explore.
      Notes
      Another important aspects of interaction that I left out is the ability to plan. I mention it a bit when discussing Walking Dead and Heavy Rain, but it is a worth digging into a little bit deeper. What we want from good gameplay interaction is not just that the player presses a lot of buttons. We want these actions to have some meaning for the future state of the game. When making an input players should be simulating in their minds how they see it turning out. Even if it just happens on a very short time span (eg "need to turn now to get a shot at the incoming asteroid") it makes all the difference as now the player has adapted the input in way that never happens in a purely reactionary game. The question of what is deemed repetitive is quite interesting to discuss. For instance, a game like Dear Esther only has the player walking or looking, which does not offer much variety. But since the scenery is constantly changing, few would call the game repetitive. Some games can also offer really complex and varied range of actions, but if the player is tasked to perform these constantly in similar situations, they quickly get repetitive. I think is fair to say that repetition is mostly an asset problem. Making a non-repetitive game using limited asset counts is probably not possible. This also means that a proper storytelling game is bound to be asset heavy. Here are some other games that I feel are close to fulfilling all elements: The Path, Journey, Everyday the Same Dream, Dinner Date, Imortall and Kentucky Route Zero. Whether they succeed or not is a bit up to interpretation, as all are a bit borderline. Still all of these are well worth one's attention. This also concludes the list of all games I can think of that have, or at least are close to having, all five of these elements. Links
      http://frictionalgames.blogspot.se/2012/08/the-self-presence-and-storytelling.html Here is some more information on how repetition and challenge destroy the imaginative parts of games and make them seem more mechanical.
      http://blog.ihobo.com/2013/08/the-interactivity-of-non-interactive-media.html This is a nice overview on how many storytelling games give the player no meaningful choices at all.
      http://frictionalgames.blogspot.se/2013/07/thoughts-on-last-of-us.html The Last of Us is the big storytelling game of 2013. Here is a collection of thoughts on what can be learned from it.
      http://en.wikipedia.org/wiki/Visual_novel Visual Novels are not to be confused with Interactive Fiction, which is another name for text adventure games.
      Thirty Flights of Loving This game is played from start to finish and has a very interesting usages of scenes and cuts.
      To The Moon This is basically an rpg but with all of the fighting taken out. It is interesting how much emotion that can be gotten from simple pixel graphics.
      Gone Home This game is actually a bit similar to To The Moon in that it takes an established genre and cuts away anything not to do with telling a story. A narrative emerge by simply exploring an environment.
       
      This article was originally published on the Frictional Games blog and is republished with kind permission from the original author Thomas Grip.
    • By varton
      In Chess, there are many options for starting and answering. The Sicilian defense is one of them, but not the last, but, on the contrary, one of the most popular and successful. So, the goal of the presented game is to open and study all variants of the Sicilian defense in chess in a game form. The game develops concentration and attention, so necessary in chess. This game can be useful not only for chess players, experienced or beginners, but also for people who are just beginning to get acquainted with the ancient art of chess. And also to those who are quite far away from chess (smile).
      iTunes Store: https://itunes.apple.com/us/app/chess-match-sicilian-defense/id12… ls=1&mt=8 
      iTunes Store iPad: https://itunes.apple.com/us/app/chess-match-sicilian-defense/id12… ls=1&mt=8



    • By durianodour
      I am just a newbie game developer, I am trying to create a frame independent game loop.
      I am currently using the following code
      private class MainGameThread extends Thread { public static final int PAUSE_SLEEP_TIME = 10; long previous = getCurrentTimeInMillis(); long totalElapsed = 0; long gameTimeStart = 0; long currentTime = getCurrentTimeInMillis(); long accumulatorTime = 0; @Override public void run() { gameTimeStart = getCurrentTimeInMillis(); while (mIsRunning) { // Pause game while (mIsPaused) { try { Thread.sleep(PAUSE_SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } long current = getCurrentTimeInMillis(); long elapsed = current - previous; previous = current; processGameInput(); updateGameState(elapsed); totalElapsed += elapsed; if (totalElapsed > MainGame.MS_PER_FRAME) { drawGame(); totalElapsed -= MainGame.MS_PER_FRAME; if (totalElapsed > MainGame.MS_PER_FRAME) { Log.e("GAME", "Performance warning, rendering or update took too long"); } } checkIfGameShouldStop(gameTimeStart); } shutdownGracefully(); } private void shutdownGracefully() { } } It works, how ever it performs differently on different devices
      In my game models update method I am performing the following actions
      mCenterX += (mVelocityVector.x * timeElapsed); mCenterY += (mVelocityVector.y * timeElapsed + gameSpeed.getValue()) I have read this article https://gafferongames.com/post/fix_your_timestep/
      But I can't understand the final example
      double t = 0.0; double dt = 0.01; double currentTime = hires_time_in_seconds(); double accumulator = 0.0; State previous; State current; while ( !quit ) { double newTime = time(); double frameTime = newTime - currentTime; if ( frameTime > 0.25 ) frameTime = 0.25; currentTime = newTime; accumulator += frameTime; while ( accumulator >= dt ) { previousState = currentState; integrate( currentState, t, dt ); t += dt; accumulator -= dt; } const double alpha = accumulator / dt; State state = currentState * alpha + previousState * ( 1.0 - alpha ); render( state ); } What does the State class object mean in this case.
      Could someone please help to adapt this example to my case or explain the example from the article and how I could update my loop to be frame independent ?
      Thanks
    • By tgobbens
      Introduction 
      The architecture of software design is a much-debated subject. Every developer has his own opinion about what is good software design and what is not. Most developers agree on what is bad design, on what is good design there are a wide variety of opinions. Unfortunately, due to the nature of software development, there is no silver bullet; there is no one design strategy that always works.
      There are a couple of strategies that have proofed to be successful. These strategies have known strengths and weaknesses. The advantage of using such a strategy is allowing you to focus on building your game, instead of worrying if your codebase will implode after someone decided the game should function a bit different than how the code was originally written.
      Architecture
      In game development, the entity-component-system is an architectural pattern that is used successfully in small, medium and large games. The main strength of this strategy is the usage of the composition over inheritance pattern. This pattern prevents the build-up of complex object inheritance tree’s, that will make your code impossible to refactor without a lot of side-effects.
      So how does this pattern work, at its core, there are three elements; entity, components, and systems guess you didn’t see that coming. Let’s describe these one by one, I’m starting with the smallest and most simple one the “component”:
      Component
       The component represents a single attribute of an entity. Some examples of entities can be:
      Position Rotation Scale Physics body Texture Health Entity
       Entities are the “game-object” some examples:
      Ball Camera Player Enemy Bullet An entity can have multiple components, for example, a ball entity can have the following components: position, rotation, scale, texture and physics body. A camera entity might only have a position. Usually, all entities have a unique-id for fast access, but there can also be other ways of accessing entities.
      System
      The system is responsible for one aspect of the game, a simple game has can, for example, have the following systems:
      Rendering Physics GUI Sound AI What a system does is iterating over all entities that have components of the types defined by the system. For example, the physics system will act only on entities with a physics-component and a position-component. The rendering system will only act on entities that have a position and texture component. 
      For example, if a ball entity has a position and physics and texture component. The physics system will pick up the ball entity, as it has a physics and position component. The physics-system control a physics-engine, that will do its magic and calculate a new position for the ball. The physics system will set this new position on the position component.
      The rendering-system will also pick up the ball entity, as it acts on all entities that have a position and a texture component. The rendering system can render the ball using the texture and the position found with the ball entity (yes, the same component that was just updated by the physics-system).
      Now imagine you spend some time implementing the architecture described above, and you after, running it, realize the ball is not really moving very realistic. That might be because you forgot to take rotation into account.
      To fix it you now only have to create a rotation-component and add it to the ball entity. Now add in the physics system a check if the entity has a rotation component and if so just set the rotation on this component. In the rendering-system also add some code to check if there is a rotation component and if so render with this rotation.
      This is where the power of this architecture emerges, imagine you have not one ball entity but have a lot of entities like the ball, wall, player, ground, etc. and you forgot about the rotation. You only have to modify the rendering system and the physics system. Then by simple adding a rotation component to the entities you want to have rotation on, magically all those objects have a rotation. Now adding rotation seems like a trivial thing to do, but what does this architecture enforces is the separation of concerns (e.g. rendering and physics) while still allows adding new functionality. And important; It does this without the usage of inheritance but rather by composition.
      Possible features
      The architecture described above is in itself quite powerful. But there are some more interesting possibilities with this architecture. I will describe some of them below.
      Game-mechanic tweaking
      Creating a generic mechanic-tuning-utilities; as there are a limit number of component types, you can create a (developer) GUI-overlay that allows you to modify the values of a component. This will allow you to in real-time modify the values, e.g. the position, size, texture, acceleration, the weight of a certain entity his components. This will help you tremendously in fine-tuning game mechanics without the need to keep recompiling and reloading your game.
      Level-editor
      Taking this even a step further you could use the above system to load all entities and relevant components from a file, e.g. XML. This will also help you decrease compile and loading time, letting you focus more one tuning game mechanics. This could then be a very good start for creating a level-editor, letting a none technical team member (game-designers) tweak game mechanics.
      Dynamic loading
      Something else that can be managed using this system, is implementing an entity loading/unloading mechanism. You can define an interface with functions like initializing, loading, starting, stopping, unloading, destructing. Now you can implement a loading mechanism that guarantees the loading and initializing always happen asynchronously. This will allow you to load and unload entities in a uniform and controlled manner. You could also choose to run all the systems in a different thread you need to take some more care about modifying components, but this could allow you to do a lot of performance enhancements, as for example, the AI needs less frequent updates then a renderer.
      Real-world example
      Note this implementation is done in Java, as I’m using libGDX as the platform, but the architecture is certainly not limited to Java and can also be implemented in other languages like C++.
      Enough of the theory, now for a real implementation. As a hobby project, I have been creating a small iOS/Android game, my first implementation of this game was naïve, with one source file containing all logic. No need to explain this is a bad implementation, but this did allow me to check if my idea was fun and create a quick prototype and do some fast iterations from there.
      For reference, the “bad” implementation can still be found here:  https://github.com/tgobbens/fluffybalance/blob/master/core/src/com/balanceball/Balanceball.java  
      After I created this implementation I decided I wanted to implement the same game using a better manageable implementation.
      The “main” entry file can be found here: https://github.com/tgobbens/fluffybalance/blob/master/core/src/com/balanceball/BalanceBallSec.java.
      So, I’ve created my own entity-component-system. If you want to create your own game using an entity-component-system, and want the game to be ready as soon as possible then I wouldn’t recommend writing one yourself. However, if you want to learn about programming or just create something for fun, implementing such a system is easy, and you will learn a lot from doing this. Another reason to implement this yourself is you get a lot of freedom allowing you to add specific tricks and features that can help you improve your codebase.
      The entity component system can be found under https://github.com/tgobbens/fluffybalance/tree/master/core/src/com/sec and yes there are some optimisation and improvements opportunities in this code base. But it does show an easy to understand implementation. When trying to understand make sure you know what Java generic types are. It’s quite common you need to find a certain entity to update or get some info from. As there are a lot of components you know there will be only one instance from. I’ve added a method to get the first entity of a certain type. For example, give me the camera entity, or give me the first “game-world” entity. But there are also helper functions to get all entities of a certain type. The same trick is used for getting components of an entity.
      You will also find a basic type called “engine”, used for binding everything together. This will trigger the updates and holding references to all systems and entities. If you look for a “starting” point for the architecture this is where to start looking.
    • By Geometrian
      Hi all,
      More than a decade ago, a problem came up on this forum for computing a fast transpose of a 3x3 matrix using SSE. The most sensible implementation stores the matrix internally as a 3x4 matrix (so, one row stores 4 elements, aligned in a vector). A version, which I believe to be the fastest currently known, was presented:
      I am pleased to report that I have been able to come up with a version which should be faster:
      inline void transpose(__m128& A, __m128& B, __m128& C) { //Input rows in __m128& A, B, and C. Output in same. __m128 T0 = _mm_unpacklo_ps(A,B); __m128 T1 = _mm_unpackhi_ps(A,B); A = _mm_movelh_ps(T0,C); B = _mm_shuffle_ps( T0,C, _MM_SHUFFLE(3,1,3,2) ); C = _mm_shuffle_ps( T1,C, _MM_SHUFFLE(3,2,1,0) ); } This should be 5 instructions instead of ajas95's 8 instructions. Of course, to get that level of performance with either version, you need to inline everything, or else you spend tons of time on moving floating point arguments to/from input registers.
      The other thing that is crucial is that the instruction set be VEX encoded. This allows generating instructions that take three arguments, like `vunpcklps`, instead of instructions like `unpcklps` that take only two. VEX is only available in AVX and higher (usually passing e.g. `-mavx` is sufficient to get the compiler to generate VEX instructions).
      -G
  • Popular Now