Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
guenter
Dec 24, 2003
All I want out of life is to be a monkey of moderate intelligence who wears a suit. That's why I've decided to transfer to business school!
I have a question about splines. Catmull-Rom splines, though I don't think it matters.

So far I've only been using the spline to animate objects at some constant speed. So I have a spline parameterized by arc length. That is, at creation I evaluate the spline at small intervals and cache the total length of the spline thus far on each control point. So if I want to evaluate the position of the spline at a given distance along it then I just figure out which control points that distance falls between and what value t as a ratio of the distances at the two neighboring control points.

Now I'm trying to allow the time at each control point to be specified so an animation can be keyframed. Now here's where I'm clearly doing something wrong. I thought since I already have the time at each control point that I can just ignore the arc length and all of the work I do on creation to cache the distance and just evaluate it on time directly.

So instead of this:

code:
vec3 getPositionFromDistance(float distance)
{
  // Binary search over list of control points. Find the control points that neighbor that bound the given distance.
  cp1, cp2, cp3, cp4 = FindNeighboringControlPointsFromDistance(distance)

  // Map distance to [0..1]
  t = LinearMap(distance, cp2->getCachedDistance(), cp3->getCachedDistance(), 0, 1)

  return catmullRom(t, cp1->getPosition(), cp2->getPosition(), cp3->getPosition(), cp4->getPosition());
}
Which works fine. I can move through the spline with constant speed. But now I'm doing this:

code:
vec3 getPositionFromDistance(float time)
{
  // Binary search over list of control points. Find the control points that bound the given time.
  cp1, cp2, cp3, cp4 = FindNeighboringControlPointsFromTime(time)

  // Map time to [0..1]
  t = LinearMap(time, cp2->Time(), cp3->Time(), 0, 1)

  return catmullRom(t, cp1->getPosition(), cp2->getPosition(), cp3->getPosition(), cp4->getPosition());
}
Which does not work. There's huge changes in velocity whenever the animation moves moves through a control point. And I'm having some trouble wrapping my head around why.

Any suggestions? Or some search terms? I've been trying variations of "parameterizing spline time" and "keyframing spline" without much luck.

Adbot
ADBOT LOVES YOU

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

dupersaurus posted:

Scaleform 3+ may have changed some things, but in 2 all you need to do is tell scaleform that there's a method it can call through an fscommand or ExternalInterface.

It's been a long time since I used the API, but I recall it being a real pain to handle structured data (objects with methods, life cycle management) through ExternalInterface. It's really a pretty terrible FFI through which to project the primary function of a UI: representing the state of a system, and manipulating it in response to user action. Maybe Scaleform's ExternalInterface is somehow better, though, and admits to something more effective and efficient than the XML encoding for marshaling.

Paniolo
Oct 9, 2007

Heads will roll.
The other problem with Scaleform is that it's yet another abstraction over game state; you're probably already exposing a lot of that information to a scripting VM, also exposing it to a UI VM is conceptually redundant. I think it's just a tradeoff of what you would consider a better engineered solution versus UI designer productivity; but with the pool of designers who are fluent in Flash diminishing due to its reduced web presence, and that large bucket of perf and memory taken by Scaleform looking more and more attractive as you run out of other things to cannibalize, ditching it becomes more and more attractive. (I'm on a project with a bespoke UI solution entirely due to perf requirements, for example.)

I am expecting to start seeing engines that use Javascript as their scripting language and HTML for their user interface. I believe that JS is implicitly more memory hungry than Lua but the difference between the two is less relevant on the new console generations, and the perf of JS VMs is quite good, especially if you use something like asm.js. HTML will never be an optimal solution for UI rendering but it has the same tradeoffs as Scaleform.

xgalaxy
Jan 27, 2004
i write code

Paniolo posted:

The other problem with Scaleform is that it's yet another abstraction over game state; you're probably already exposing a lot of that information to a scripting VM, also exposing it to a UI VM is conceptually redundant. I think it's just a tradeoff of what you would consider a better engineered solution versus UI designer productivity; but with the pool of designers who are fluent in Flash diminishing due to its reduced web presence, and that large bucket of perf and memory taken by Scaleform looking more and more attractive as you run out of other things to cannibalize, ditching it becomes more and more attractive. (I'm on a project with a bespoke UI solution entirely due to perf requirements, for example.)

I am expecting to start seeing engines that use Javascript as their scripting language and HTML for their user interface. I believe that JS is implicitly more memory hungry than Lua but the difference between the two is less relevant on the new console generations, and the perf of JS VMs is quite good, especially if you use something like asm.js. HTML will never be an optimal solution for UI rendering but it has the same tradeoffs as Scaleform.

I'd rather have lua / some subset of html / css for UI than javascript.
You could support all of the apple extensions to CSS for transform manipulation and animation (it wast part of the standard last I looked).
I don't think including a full fledged HTML rendering engine should be the goal though, eg things like chromiumembedded.

aerique
Jul 16, 2008

Paniolo posted:

I am expecting to start seeing engines that use Javascript as their scripting language and HTML for their user interface.

It's been a good couple of years since I played with Ogre3D but didn't Awesomium do that already?: http://labs.awesomium.com/the-rationale-for-awesomium/

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

xgalaxy posted:

I'd rather have lua / some subset of html / css for UI than javascript.
You could support all of the apple extensions to CSS for transform manipulation and animation (it wast part of the standard last I looked).
I don't think including a full fledged HTML rendering engine should be the goal though, eg things like chromiumembedded.

I have an emotional attachment to JS and web tech, so grain of salt, but.

JS + canvas/webgl should be able to improve on the memory profile of Scaleform at least, and with good use of shadow dom you could probably go there as well. Modern JS JITs have GCs optimized for pause time, and the rendering runtimes in web engines have all the asynchrony and composition tricks you want for keeping the UI responsive even if the game is chugging. JS is also designed for isolation and asynchronous/event-based flow, meaning that it's easier to make safe for extending. Mozilla has FirefoxOS running on 128MB, $25 phones with responsive UI and such, so fitting into even a mobile game memory budget should be fine. (Less so on iOS where you can't bring along a JIT, but for UI stuff you might not actually need it, and then ever better memory savings.) There is definitely also a code-footprint issue, in that it can be 20MB to bundle it along without version-fragile build hackery.

I would strongly caution against trying to do a CSS implementation for a random UI toolkit; the cascade alone is surprisingly tricky to get right, and uncanny valley APIs are pretty tricky, and a bunch of things really only make sense with the CSS flow and box model.

There's so much out there for JS devs, and using web tech lets UI development use the powerful browser tools and edit/reload model, that I think it's really a much better choice than Lua these days. Futures!

Edit:

aerique posted:

It's been a good couple of years since I played with Ogre3D but didn't Awesomium do that already?: http://labs.awesomium.com/the-rationale-for-awesomium/

I think EQN also uses Awesomium, though I'm not sure if they do so for UI.

xgalaxy
Jan 27, 2004
i write code
You make a great argument for leveraging existing experience for web development. I still think a full fledged embedded browser is the wrong way to go about it.
Last I heard Awesomium was pretty much abandoned.

Flownerous
Apr 16, 2012

guenter posted:

code:
  return catmullRom(t, cp1->getPosition(), cp2->getPosition(), cp3->getPosition(), cp4->getPosition());
Which does not work. There's huge changes in velocity whenever the animation moves moves through a control point. And I'm having some trouble wrapping my head around why.

The choice of spline is actually a big deal. Some splines are designed to look good as paths rather than to feel smooth when moving along them. Catmull Rom is one used for smooth motion between keyframes.

But you need to use a time-parameterized version of Catmull Rom. The standard version which it appears you are using assumes that the time between each pair of control points is the same. That's why you only need to pass in the t value within [0,1], it assumes that the t = -1 at cp1, and t = 2 at cp4.

See http://en.wikipedia.org/wiki/Cubic_Hermite_spline#Catmull.E2.80.93Rom_spline for how to calculate the tangent at each point based on the positions and times of its neighbours.

Paniolo
Oct 9, 2007

Heads will roll.

xgalaxy posted:

You make a great argument for leveraging existing experience for web development. I still think a full fledged embedded browser is the wrong way to go about it.
Last I heard Awesomium was pretty much abandoned.

I agree, I think the more likely solution is a stripped down HTML renderer + JavaScript VM. Awesomium took the approach of embedding an entire browser, which was okay for applications that actually wanted to have a full featured browser inside pulling content from the web (I think Guild Wars 2 auction house worked like this) but was not really appropriate for being a general purpose UI.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Paniolo posted:

I agree, I think the more likely solution is a stripped down HTML renderer + JavaScript VM. Awesomium took the approach of embedding an entire browser, which was okay for applications that actually wanted to have a full featured browser inside pulling content from the web (I think Guild Wars 2 auction house worked like this) but was not really appropriate for being a general purpose UI.

That would be ok, if you get the stripping at the right place (hard). I don't think you get much that's different functionally, though. With HTML you want and get the DOM and event flow (though you want flexbox, really truly), and most layout engines are a little hard to bring up without the networking layer intact. Just use the parts you want, and figure out a way to not pay for a full document context for each UI window if it causes memory woes. The rest of the browser stuff (like history and cache and plugin hosting and save dialogs and so forth) is usually easy enough to disable or just not trigger.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
I don't really see game menus being done by HTML, really.

A lot of them want fancy animated effects, and those were really easy to hook up in the Flash authoring environment. Edge is really the only replacement for that, but it would basically turn the HTML layout engine into something just using position: absolute;

I mean, there's really no good replacement authoring tool for Flash, even though it's just maintained by a team of three people from India. And that's the really strong part about using Flash.

I wish Adobe would just sell the Flash authoring environment to a company who cares, or open-source the drat thing. It's a really good tool.

guenter
Dec 24, 2003
All I want out of life is to be a monkey of moderate intelligence who wears a suit. That's why I've decided to transfer to business school!

Flownerous posted:

The choice of spline is actually a big deal. Some splines are designed to look good as paths rather than to feel smooth when moving along them. Catmull Rom is one used for smooth motion between keyframes.

But you need to use a time-parameterized version of Catmull Rom. The standard version which it appears you are using assumes that the time between each pair of control points is the same. That's why you only need to pass in the t value within [0,1], it assumes that the t = -1 at cp1, and t = 2 at cp4.

See http://en.wikipedia.org/wiki/Cubic_Hermite_spline#Catmull.E2.80.93Rom_spline for how to calculate the tangent at each point based on the positions and times of its neighbours.

I definitely did not realize that time between keyframes was expected to be uniform, though it makes perfect sense with your explanation. Thanks!

pseudopresence
Mar 3, 2005

I want to get online...
I need a computer!
I've played around with libRocket a little; it's an HTML/CSS based UI library designed for games. It pretty much does what it says on the tin; unfortunately I think I've found doing my layout with HTML and CSS pretty frustrating.

OneEightHundred
Feb 28, 2008

Soon, we will be unstoppable!

Paniolo posted:

The other problem with Scaleform is that it's yet another abstraction over game state; you're probably already exposing a lot of that information to a scripting VM, also exposing it to a UI VM is conceptually redundant. I think it's just a tradeoff of what you would consider a better engineered solution versus UI designer productivity; but with the pool of designers who are fluent in Flash diminishing due to its reduced web presence, and that large bucket of perf and memory taken by Scaleform looking more and more attractive as you run out of other things to cannibalize, ditching it becomes more and more attractive. (I'm on a project with a bespoke UI solution entirely due to perf requirements, for example.)

I am expecting to start seeing engines that use Javascript as their scripting language and HTML for their user interface. I believe that JS is implicitly more memory hungry than Lua but the difference between the two is less relevant on the new console generations, and the perf of JS VMs is quite good, especially if you use something like asm.js. HTML will never be an optimal solution for UI rendering but it has the same tradeoffs as Scaleform.
I think that what makes the most sense long-term is to treat UI as a presentation of the game state in the same way that sound and graphics are already. There's an ongoing demand for easier ways to do things like cinematics and game scripting that have a lot of commonality with the type of control needed in a UI system, so once the tools for better scene control start existing, it's not a huge leap from there to treating the UI as a scene and controlling it that way.

Baldbeard
Mar 26, 2011

What's a good way to hook up with a more experienced programmer and get advice on a a project? I don't mean asking a simple question that can be quoted here, but broader stuff like a good way to handle a certain event in this part of my code etc....

I've been starting and scrapping projects endlessly, and while I get a little farther and more organized each time, I can't help but think how beneficial it would be to work with somebody who knows what the gently caress they are doing. My local college doesn't have any clubs relating to programming at all, and I even went so far as to call up some professional tutors -- who all seemed to be 65 year old middle-eastern-guys-that-speak-poor-english.

Basically, I want to be able to show someone my design document for my game -- have them "get it" -- and then give me pointers on how to make it happen in an organized matter. I can code and design my game how I want it right now, but I'm plagued with the feeling of "This is so jerry-rigged, I know there is a better way to do this." the whole way through. Should I just put an ad on SA mart? Is there a better way?

Obsurveyor
Jan 10, 2003

Baldbeard posted:

What's a good way to hook up with a more experienced programmer and get advice on a a project? I don't mean asking a simple question that can be quoted here, but broader stuff like a good way to handle a certain event in this part of my code etc....

Join the IRC channel and ask questions.

#SAGameDev on irc.synirc.net

Boz0r
Sep 7, 2006
The Rocketship in action.
If I implement a fluid algorithm or something based on a research paper and sell it on Unity Asset Store, do I have to give credit or pay royalties or anything to the authors of that paper?

coffeetable
Feb 5, 2006

TELL ME AGAIN HOW GREAT BRITAIN WOULD BE IF IT WAS RULED BY THE MERCILESS JACKBOOT OF PRINCE CHARLES

YES I DO TALK TO PLANTS ACTUALLY

Boz0r posted:

If I implement a fluid algorithm or something based on a research paper and sell it on Unity Asset Store, do I have to give credit or pay royalties or anything to the authors of that paper?

Depends if they patented it. Either way though, you should give them a credit. If they're a lesser-known researcher, maybe even email them saying "Hey you did a cool thing and I made something with it".

Bob Morales
Aug 18, 2006


Just wear the fucking mask, Bob

I don't care how many people I probably infected with COVID-19 while refusing to wear a mask, my comfort is far more important than the health and safety of everyone around me!

Baldbeard posted:

What's a good way to hook up with a more experienced programmer and get advice on a a project? I don't mean asking a simple question that can be quoted here, but broader stuff like a good way to handle a certain event in this part of my code etc....

I've been starting and scrapping projects endlessly, and while I get a little farther and more organized each time, I can't help but think how beneficial it would be to work with somebody who knows what the gently caress they are doing. My local college doesn't have any clubs relating to programming at all, and I even went so far as to call up some professional tutors -- who all seemed to be 65 year old middle-eastern-guys-that-speak-poor-english.

Basically, I want to be able to show someone my design document for my game -- have them "get it" -- and then give me pointers on how to make it happen in an organized matter. I can code and design my game how I want it right now, but I'm plagued with the feeling of "This is so jerry-rigged, I know there is a better way to do this." the whole way through. Should I just put an ad on SA mart? Is there a better way?

It's better to just get it done than to plan it perfectly. Write it and fix it later. Sometimes you learn a better way while you're implementing your original idea, or if you put the game out there and someone says "xxx is slow as gently caress how come you're not using a b-tree filter hash?"

Unormal
Nov 16, 2004

Mod sass? This evening?! But the cakes aren't ready! THE CAKES!
Fun Shoe

Boz0r posted:

If I implement a fluid algorithm or something based on a research paper and sell it on Unity Asset Store, do I have to give credit or pay royalties or anything to the authors of that paper?

quote:

Depends if they patented it. Either way though, you should give them a credit. If they're a lesser-known researcher, maybe even email them saying "Hey you did a cool thing and I made something with it".

Yeah, I'd certainly do this; you'll not only find out if they care and what the requirements are, you might make a new friend! :hfive:

Seashell Salesman
Aug 4, 2005

Holy wow! That "Literally A Person" sure is a cool and good poster. He's smart and witty and he smells like a pure mountain stream. I posted in his thread and I got a FANCY NEW AVATAR!!!!
Is there any way to not have Unity networkview state synchronization send to peers always? If my server is authoritative then all the peer to peer syncs are ignored and a big waste. RPC lets you do this but it doesn't have the fixed sync schedule and, more importantly, doesn't support variable length sync data.

e: I think, in answer to my own question, the intended way to do this is to only ever state sync from the server (ie. server owns all objects) and then the clients communicate with the server purely through RPC. I think I can live with that. My chief fear now is how the Unity data compression (some kind of deltas) will interact with whatever data compression I'm using myself. I guess in theory there shouldn't be any way it breaks my data.

Seashell Salesman fucked around with this message at 04:02 on Mar 28, 2014

Wordicuffs
Jun 14, 2011

Baldbeard posted:

What's a good way to hook up with a more experienced programmer and get advice on a a project? I don't mean asking a simple question that can be quoted here, but broader stuff like a good way to handle a certain event in this part of my code etc....

I've been starting and scrapping projects endlessly, and while I get a little farther and more organized each time, I can't help but think how beneficial it would be to work with somebody who knows what the gently caress they are doing. My local college doesn't have any clubs relating to programming at all, and I even went so far as to call up some professional tutors -- who all seemed to be 65 year old middle-eastern-guys-that-speak-poor-english.

Basically, I want to be able to show someone my design document for my game -- have them "get it" -- and then give me pointers on how to make it happen in an organized matter. I can code and design my game how I want it right now, but I'm plagued with the feeling of "This is so jerry-rigged, I know there is a better way to do this." the whole way through. Should I just put an ad on SA mart? Is there a better way?

My advice is to let those insecurities go and finish. Just keep trucking along until there actually is a problem and then go back and fix that problem. While fixing it make sure you understand what went wrong, why it went wrong, and why your fix works. Then repeat until you die (just hopefully not on the same problem)

Code isn't language. Making code beautiful does not (usually) make the end user's experience any better like making language beautiful does. It doesn't matter how amazingly easy your code is to extend or how easy it is for others to read and understand quickly if others never read it and you never extend it. If an algorithm isn't efficient enough to run properly then do some research on the problem, get some help, and fix it. If some objects are strongly coupled and you need to change the functionality to add a feature? Spend a few hours redesigning and fix it. Learn why the original was bad and why the new is good and start from there in your next game.

Knowing that there is a better way is almost meaningless if you don't understand what that way is. There is always a better way to do anything we do ever. Imagine if there was a way sexy dude lying naked in your bed ready to bump uglies but you couldn't make it to the bed because you couldn't figure out the most efficient path there. You'd never get to feel the warmth of his manly, hairy chest against your cheek, or his supple caressing of your buttocks, or his strong forearms around your body as he cradles you gently. Are those things you want to miss because you were afraid of being judged by some meaningless metric? I didn't think so. So go, Baldbeard. Cast off the shackles of self doubt and show that man meat you're not afraid anymore.

Baldbeard
Mar 26, 2011

Wordicuffs posted:

My advice is to let those insecurities go and finish. Just keep trucking along until there actually is a problem and then go back and fix that problem. While fixing it make sure you understand what went wrong, why it went wrong, and why your fix works. Then repeat until you die (just hopefully not on the same problem)

Code isn't language. Making code beautiful does not (usually) make the end user's experience any better like making language beautiful does. It doesn't matter how amazingly easy your code is to extend or how easy it is for others to read and understand quickly if others never read it and you never extend it. If an algorithm isn't efficient enough to run properly then do some research on the problem, get some help, and fix it. If some objects are strongly coupled and you need to change the functionality to add a feature? Spend a few hours redesigning and fix it. Learn why the original was bad and why the new is good and start from there in your next game.

Knowing that there is a better way is almost meaningless if you don't understand what that way is. There is always a better way to do anything we do ever. Imagine if there was a way sexy dude lying naked in your bed ready to bump uglies but you couldn't make it to the bed because you couldn't figure out the most efficient path there. You'd never get to feel the warmth of his manly, hairy chest against your cheek, or his supple caressing of your buttocks, or his strong forearms around your body as he cradles you gently. Are those things you want to miss because you were afraid of being judged by some meaningless metric? I didn't think so. So go, Baldbeard. Cast off the shackles of self doubt and show that man meat you're not afraid anymore.

Thank you. I will continue forward and embrace the man meat.

dupersaurus
Aug 1, 2012

Futurism was an art movement where dudes were all 'CARS ARE COOL AND THE PAST IS FOR CHUMPS. LET'S DRAW SOME CARS.'
As they say, don't let perfect be the enemy of good (enough)

Bob Morales
Aug 18, 2006


Just wear the fucking mask, Bob

I don't care how many people I probably infected with COVID-19 while refusing to wear a mask, my comfort is far more important than the health and safety of everyone around me!

I have some bullet code that works, but I'm sure it's not optimal. Basically I have an array of bullets[50], and every time you hit 'fire' jmanShoot() gets called. When a bullet has a successful hit detection, or goes off screen the state gets cleared on the bullet and it goes away.

What are some better ways to do this? 50 objects (really there are only 4-6 on the screen at any time) isn't really a deal-breaker when it comes to memory, I'm just wondering if another data type or algorithm would be more well-suited.

code:
      jmanShoot = function () {
        console.log('jman.lastFired = ' + jman.lastFired + ' other = ' + guns[0].repeatRate);
        if (jman.lastFired + (1000 * guns[jman.gun].repeatRate) < Date.now()) {
          console.log('Pow!');
          bulletFired = 0;

          for (i = 0; i < 50 && bulletFired == 0; i++) {
            if (bullets[i] == undefined || bullets[i].state == '') {
              // make a bullet
              console.log('Loading slot ' + i);
              bullets[i] = { x: jman.x + XSIZE/2, y: jman.y - YSIZE/2, dir: jman.facing, state: 'live',
                              speed:guns[jman.gun].bulletSpeed, strength: guns[jman.gun].gunStrength };
              bulletFired = 1;
              jman.lastFired = Date.now();
            }
          }
        }
      };

      doBullets = function () {
        // move all bullets that aren't dead
        for (i = 0; i < 50; i++) {
          if (bullets[i] !== undefined && bullets[i].state == 'live') {
            //console.log("Doing bullet " + i);
            b = bullets[i];
            if (b.x < 0 || b.x > SCREEN_X) {
              // offscreen
              b.state = '';
            }

            b.x += b.speed * (b.dir == 'left' ? -1 : 1);

            // hit detect
            for (e = 0; e < MAX_ENEMIES; e++) {
              if (enemies[e] != undefined) {
                if (enemies[e].state != 'dead') {
                  if (b.y >= enemies[e].y &&
                      (b.y+2) <= enemies[e].y+19) {  // pre-calc these?
                    if (b.x >= enemies[e].x &&
                        (b.x+2) <= enemies[e].x+19) {
                      console.log('HIT!');
                      enemies[e].state = 'dead';
                      b.state = '';
                    }
                  }
                }
              }
            }
          }
        }
      };

      drawBullets = function () {
        for (i = 0; i < 50; i++) {
          if (bullets[i] !== undefined && bullets[i].state == 'live') {
            //console.log("DRAWing bullet " + i + " x = " + b.x + " y = " + b.y);
            b = bullets[i];

            context.fillStyle = "#000000";
            context.fillRect(b.x,b.y,3,3);
          }
        }
      };

Flownerous
Apr 16, 2012

Bob Morales posted:

What are some better ways to do this? 50 objects (really there are only 4-6 on the screen at any time) isn't really a deal-breaker when it comes to memory, I'm just wondering if another data type or algorithm would be more well-suited.

This is basic pooling and from your description you're on the right track. You allocate the maximum number you expect simultaneously and when one is deactivated you put it back on the <container> of free objects.

The only tricky thing is what to do if the pool is exhausted. This comes up a lot in sound effects. Usually you just choose a policy depending on the use case. Reuse the oldest living item, reuse the least-visible living item, etc.

G-Prime
Apr 30, 2003

Baby, when it's love,
if it's not rough it isn't fun.

Bob Morales posted:

I have some bullet code that works, but I'm sure it's not optimal. Basically I have an array of bullets[50], and every time you hit 'fire' jmanShoot() gets called. When a bullet has a successful hit detection, or goes off screen the state gets cleared on the bullet and it goes away.

What are some better ways to do this? 50 objects (really there are only 4-6 on the screen at any time) isn't really a deal-breaker when it comes to memory, I'm just wondering if another data type or algorithm would be more well-suited.

I'm far from the most experienced at this but, when I ran into almost exactly this same scenario, I found my big killer was looping through all the bullets every frame to make sure they were active and update their positions and such. At least, it felt that way to me. What I ended up doing was using the STL Vector class in C++ and looping through it. Dynamic resizing kept the loop sizes small. Instead of keeping an active state on each bullet, I just looked at everything that was in the Vector and when a bullet "died", I'd just rip it out, and append a new one to the end each time the player fired.

Now, in fairness, I had a lot of other optimization issues, but that was an easy one to knock out, and it put the overhead on the creating and destroying of bullets, which was far less frequently than once per frame.

HiriseSoftware
Dec 3, 2004

Two tips for the wise:
1. Buy an AK-97 assault rifle.
2. If there's someone hanging around your neighborhood you don't know, shoot him.
One of the things I implemented I called a "packed array" where you'd still have a maximum number of objects (i.e. you allocate space beforehand), if you remove an object from the middle of the array, you replace it with the last item in the array. That way when you iterate, all of the items are contiguous and you don't have to check if an item is "active" or not. It works well with iteration but not for random access, since a pointer to an object (i.e. its place in the array) could change during its lifetime. Also if you remove an item during an iteration loop, make sure you don't move the index forward or else you'll miss the item you just moved into the removed item's spot.

I've also used a linked list of pre-allocated objects - the linked list at first is the "free list". When I need an object, I pull it from the end of the free list where I can add it to an active list of objects if I want. When I want to get rid of it, I place it back at the end of the free list. Even though the linkage of objects in the "free list" changes a lot, the pointer to the object stays the same. You have to be careful with iteration as you remove objects from an active list though - I get around that by "marking" an object for removal and then actually do the removal in bulk after the iteration loop is over.

Paniolo
Oct 9, 2007

Heads will roll.

G-Prime posted:

I'm far from the most experienced at this but, when I ran into almost exactly this same scenario, I found my big killer was looping through all the bullets every frame to make sure they were active and update their positions and such. At least, it felt that way to me. What I ended up doing was using the STL Vector class in C++ and looping through it. Dynamic resizing kept the loop sizes small. Instead of keeping an active state on each bullet, I just looked at everything that was in the Vector and when a bullet "died", I'd just rip it out, and append a new one to the end each time the player fired.

Now, in fairness, I had a lot of other optimization issues, but that was an easy one to knock out, and it put the overhead on the creating and destroying of bullets, which was far less frequently than once per frame.

Overhead from resizing the vector - particularly removing objects from the middle of it - was probably orders of magnitude more expensive that looping through a contiguous array of objects and skipping over most of them. Good example of why optimizing is dangerous.

The packad array with a second array of indices allowing persistent handle access is the best solution I'm aware of. The index array allow you to give an ID to an object, and no matter where that object ends up living in the actual pool, you can access it with that ID. So random access is two dereferences, and iteration is as fast as possible.

Paniolo fucked around with this message at 16:15 on Mar 28, 2014

G-Prime
Apr 30, 2003

Baby, when it's love,
if it's not rough it isn't fun.
Like I said, far from an expert. But if I'm looping through 50 elements 60 times per second, and I can reduce that to looping through an average of 5 elements 60 times, and occasionally (1-3 times per second) incur overhead from adding to or removing from that list, while simultaneously simplifying my code, it seems like a worthwhile tradeoff in situations that aren't performance critical. If my game's CPU bound and struggling to keep up with my expected framerate, I would totally agree that it's not worth doing. (And, in fact, it WAS struggling on a lower end machine at the time, because my collision detection code was a steaming pile of poo poo that I wrote through sheer guesswork. But once I fixed that problem, there was a ton more breathing room.)

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
You need to measure more. Reallocation can be thousands of times more expensive than iteration. Looping through 50 elements 60 times per second is absolutely nothing, and I'd actually expect it to be considerably less expensive than reallocating three times a second.

That said, that's my outdated intuition based on what I know about how memory allocation at the OS level. Computers are rapidly improving, so always, always profile and measure before doing any guesswork.

Obsurveyor
Jan 10, 2003

This is why you abstract all that away into a manager that deals with specifics. You can bench it separately from the game loop if it comes up in profiling and easily change out/tweak the pooling strategy as needed without changing anything anywhere else.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Suspicious Dish posted:

You need to measure more. Reallocation can be thousands of times more expensive than iteration. Looping through 50 elements 60 times per second is absolutely nothing, and I'd actually expect it to be considerably less expensive than reallocating three times a second.

That said, that's my outdated intuition based on what I know about how memory allocation at the OS level. Computers are rapidly improving, so always, always profile and measure before doing any guesswork.

All reasonable container implementations amortize reallocation to reduce that cost. Does your favorite STL implementation actually reallocate here other than when growing to a new maximum size?

Removing an item from a vector should result in a copy for each one following in the vector, but I don't believe it'll reallocate. If it did, erase could fail due to out of memory errors, which is pretty bad ergonomics even for C++, and it would be sort of an odd fit with reserve's semantics. You typically have to explicitly trim to get containers to reduce their underlying allocations (shrink_to_fit in C++11) -- and if you do, watch out for hysteresis. This also means that a subsequent emplace_back will use the existing storage, meaning it's again just a copy operation for the new element. I don't think this is an issue requiring measurement, given the guarantees of the STL.

But if what you're doing is front-to-back iteration and removal from the middle, maybe use a forward_list?

(erase can throw for removals that don't include the last element, because copy constructors can throw, but if you're removing a proper tail then it provides a no-throw guarantee. I haven't looked for spec text explicitly about it, but that definitely seems to rule out reallocation on erase.)

Paniolo
Oct 9, 2007

Heads will roll.
It will only reallocate on the high water mark rising. Otherwise, it will compile down to memmove assuming the types are POD.

taqueso
Mar 8, 2004


:911:
:wookie: :thermidor: :wookie:
:dehumanize:

:pirate::hf::tinfoil:

I've been programming for something like 25 years and I've played around with making some games, but all of it was more than 10 years ago. I got an itch and installed Unity last night. I've been going through some of the tutorials and playing around with them afterwards. Holy poo poo does Unity make things easy. I'm blown away by how smooth and integrated the whole system is. So many batteries are included.

This post doesn't really have a point, I am just floored and had to share.

Seashell Salesman
Aug 4, 2005

Holy wow! That "Literally A Person" sure is a cool and good poster. He's smart and witty and he smells like a pure mountain stream. I posted in his thread and I got a FANCY NEW AVATAR!!!!

taqueso posted:

I've been programming for something like 25 years and I've played around with making some games, but all of it was more than 10 years ago. I got an itch and installed Unity last night. I've been going through some of the tutorials and playing around with them afterwards. Holy poo poo does Unity make things easy. I'm blown away by how smooth and integrated the whole system is. So many batteries are included.

This post doesn't really have a point, I am just floored and had to share.

Yeah I had a similar experience with Unity. It's made me even more excited to play with UE4 for my next project.

Stick100
Mar 18, 2003

taqueso posted:

I've been programming for something like 25 years and I've played around with making some games, but all of it was more than 10 years ago. I got an itch and installed Unity last night. I've been going through some of the tutorials and playing around with them afterwards. Holy poo poo does Unity make things easy. I'm blown away by how smooth and integrated the whole system is. So many batteries are included.

This post doesn't really have a point, I am just floored and had to share.

If you like Javascript or C# go ahead and just jump all the way into Unity. It's totally free to use for Mac, PC, Linux, Webplayer, Android, iOS, Windows 8 Metro, and Windows Phone 8.

You'll be required to buy the Pro versions once you make 100k.

If you're a C++ dev, then pay the $19 for one month and grab Unreal Engine 4 and cancel the plan.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Stick100 posted:

If you're a C++ dev, then pay the $19 for one month and grab Unreal Engine 4 and cancel the plan.

Note, though, that you're still obligated to pay the 5%-of-gross royalty when you ship.

taqueso
Mar 8, 2004


:911:
:wookie: :thermidor: :wookie:
:dehumanize:

:pirate::hf::tinfoil:

Stick100 posted:

If you like Javascript or C# go ahead and just jump all the way into Unity. It's totally free to use for Mac, PC, Linux, Webplayer, Android, iOS, Windows 8 Metro, and Windows Phone 8.

You'll be required to buy the Pro versions once you make 100k.

If you're a C++ dev, then pay the $19 for one month and grab Unreal Engine 4 and cancel the plan.

I'm an embedded developer and am most comfortable with C, but I've dabbled with JS, C++, and C#. I don't ever want to do anything with C++, at least for things that are just for my amusement, so I guess UE is out. Is there any practical difference between JS and C# for Unity? I would prefer C#, but if there is some kind of limitation, I would rather start using javscript right away.

I'm the opposite of concerned about the $100k pro requirement. I have no plans to sell anything, and if I did make $100k I would be incredibly happy to pay someone $1500.

Adbot
ADBOT LOVES YOU

ephphatha
Dec 18, 2009




All the limitations are on the JS side, you're better off using C# for the bulk of the codebase from what I understand. Don't let that stop you getting a basic understanding of JS though since it's used in a whole host of other areas you might encounter in the future.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply