iBeacons: distance between bluetooth devices in iOS - xcode

I am working on an app that displays notification when user enters a particular area and exits from the area.
I am using 3 beacons for my app. When user is in between second and third Beacon I need to notify the user that he is inside the premises and when user has crossed the first beacon I need to notify him that he is outside the premises.
Till some extent I am able to achieve this by using the beacons accuracy property as distance between the user's device and all three beacons, but the time to display an alert to the user is more about 30 sec to one minute, but it should be instant.

It is important to understand that the CLBeacon accuracy property, which gives you a distance estimate in meters, lags by up to 20 seconds behind a moving mobile device. The same is true with the proximity property, which is derived from accuracy. This lag may be causing the delays you describe.
Why does this lag exist? Distance estimates are based on the bluetooth signal strength (rssi property) which varies a lot with radio noise. In order to filter this noise, iOS uses a 20 second running average in calculating the distance estimate. As a result, it tells you how far a beacon was away (on average) during the last 20 second period.
For applications where you need less lag in your estimate, you can use the rssi property directly. But be aware that due to noise, you will get a much less accurate indication of your distance to a beacon from a single reading.
Read more here: http://developer.radiusnetworks.com/2014/12/04/fundamentals-of-beacon-ranging.html

There are 2 questions you are trying to ask here. Will try to address them seperately.
To notify when you are in between 2 beacons - This should be pretty straightforward to do using "accuracy" and/or the "proximity" property of both the beacons.
If you need a closer estimate, use distance. pseudo code -
beaconsRanged:(CLBeacon)beacon{
if(beacon==BEACON1 && beacon.accuracy > requiredDistanceForBkn1)
"BEACON 1 IN REQUIRED RANGE"
if(beacon==BEACON2 && beacon.accuracy > requiredDistanceForBkn2)
"BEACON 2 IN REQUIRED RANGE"
}
Whenever both the conditions are satisfied, you will be done. Use proximity if you don't want fine tuning.
Code tip - you can raise LocalNotifications when each of these conditions are satisfied and have a separate class which will observe the notifications and perform required operation.
Time taken to raise alert when condition is satisfied - Ensure that you are raising alert on the main thread. If you do so on any other thread it takes a lot of time. I have tried the same thing and it just takes around a second to raise a simple alert.
One way I know of to do this -
dispatch_async(dispatch_get_main_queue(), ^{
//code
}

Related

Xamarin iOS location with negative speed

The speed value which i get from the location object is always negative (-1). From Apples blog
A negative value indicates an invalid speed.
My code is
CLLocationManager iPhoneLocationManager = new CLLocationManager ();
iPhoneLocationManager.RequestAlwaysAuthorization ();
iPhoneLocationManager.PausesLocationUpdatesAutomatically = false;
iPhoneLocationManager.DesiredAccuracy = 100;
iPhoneLocationManager.DistanceFilter = 5;
if (CLLocationManager.LocationServicesEnabled) {
iPhoneLocationManager.StartUpdatingLocation ();
}
Even though it gives correct location, the speed is always negative.
Speed
This value reflects the instantaneous speed of the device in the
direction of its current heading. A negative value indicates an
invalid speed. Because the actual speed can change many times between
the delivery of subsequent location events, you should use this
property for informational purposes only.
Unless you are constantly moving at a fairly constant rate directly away from the last sampling point, i.e. a linear vector based calculation and not running around in a tight circle, instantaneous speed is somewhat worthless. Now riding a bike and driving in a car at a constant velocity, instantaneous speed can be fairly valid...
Most real-time mobile mapping systems use some type of a speed sampling algorithm; i.e. distance moved over X samples using a moving average calculation divided by your sampling time interval is one way to get your 'current' speed.
Each app has a different use-case, so your algorithm would need to be adjusted, like if you have a hiking application and are showing the user his avg. speed on a trail and how long it will take to complete the trail would have a different algorithm from a public transportation app that calculates your arrival time based on current speed of the bus but factoring in traffic conditions, time of day, passenger stops, red lights, etc...
A blog post showing a simple sampling technique (in obj-c, but easy to translate his idea to c#): http://www.perspecdev.com/blog/2012/02/22/using-corelocation-on-ios-to-track-a-users-distance-and-speed/

Tools to determine exact location when using ibeacons

We are working with a Retail client who would like to know if using multiple iBeacons throughout the store would help track a customer's exact location when they are inside the store (of course when they have the client's App installed).
I would like to know what software tools are already available for this purpose?
What is clear is that at the basic level the location of a device can be determined based on it's relative distance from multiple (at least 2) iBeacons. If so, aren't there tools that help with this?
Thanks
Obviously this is unlikely to work well due to the inconsistency of the RSSI value (bluetooth signal). However, this is the direction you may want to take it (adapted from lots of stackoverflow research):
Filter RSSI
I use a rolling filter with this whenever the beacons are ranged, using a kFilteringFactor of 0.1:
rollingRssi = (beacon.rssi * kFilteringFactor) + (rollingRssi * (1.0 - kFilteringFactor));
And I use this to get a rolling Accuracy value (in meters). (Thanks David!)
- (double)calculateAccuracyWithRSSI:(double)rssi {
//formula adapted from David Young's Radius Networks Android iBeacon Code
if (rssi == 0) {
return -1.0; // if we cannot determine accuracy, return -1.
}
double txPower = -70;
double ratio = rssi*1.0/txPower;
if (ratio < 1.0) {
return pow(ratio,10);
}
else {
double accuracy = (0.89976) * pow(ratio,7.7095) + 0.111;
return accuracy;
}
}
Calculate XY with Trilateration (Beacons 1, 2, and 3 are Beacon subclasses with pre-set X and Y values for location and distance is calculated as above).
float xa = beacon1.locationX;
float ya = beacon1.locationY;
float xb = beacon2.locationX;
float yb = beacon2.locationY;
float xc = beacon3.locationX;
float yc = beacon3.locationY;
float ra = beacon1.filteredDistance;
float rb = beacon2.filteredDistance;
float rc = beacon3.filteredDistance;
float S = (pow(xc, 2.) - pow(xb, 2.) + pow(yc, 2.) - pow(yb, 2.) + pow(rb, 2.) - pow(rc, 2.)) / 2.0;
float T = (pow(xa, 2.) - pow(xb, 2.) + pow(ya, 2.) - pow(yb, 2.) + pow(rb, 2.) - pow(ra, 2.)) / 2.0;
float y = ((T * (xb - xc)) - (S * (xb - xa))) / (((ya - yb) * (xb - xc)) - ((yc - yb) * (xb - xa)));
float x = ((y * (ya - yb)) - T) / (xb - xa);
CGPoint point = CGPointMake(x, y);
return point;
The easiest way to get an exact location is to put one iBeacons at each point you care about, then have an iBeacon-aware app compare the "accuracy" field (which actually gives you a rough distance estimate i meters), and assume the user is at the iBeacon point with the lowest "accuracy" reading. Clearly, this approach will require a large number of iBeacons to give a precise location over a large floorplan.
Lots of folks have proposed triangulation-like strategies for using only a few iBeacons. This is much more complex, and there is no pre-built software to do this. While I have read a lot about people wanting or trying to do this, I have not heard any reports of folks pulling it off yet.
If you want to try this yourself, then you should realize that you are undertaking a bit of a science project, and there may be a great deal of time and effort needed to make it happen with unknown results.
Exact location is something that is unlikely to be achievable, but something within some tolerance values is certainly possible. I've not done extensive testing of this yet, but in a small 3x4m area, with three Beacons, you can get good positioning in ideal situations, the problem is that we don't normally have ideal situations!
The hard part is getting an accurate distance from the receiver to the iBeacon, RSSI (the received signal strength) is the only information we have, to turn this into a distance we use a measurement based on known signal strengths at various distances from the transmitter e.g. Qiu, T, Zhou, Y, Xia, F, Jin, N, & Feng, L 2012. This bit works well (and is already implemented with an average accuracy in the iOS SDK), but unfortunately environmental conditions such as humidity and other objects (such as people) getting between the receiver and transmitter degrade the signal unpredictably.
You can read my initial research presentation on SlideShare, which covers some basic environmental effects and shows the effect on the accuracy of measurement, it also references articles that explain how RSSI is turned into distance, and some approaches to overcome the environmental factors. However in a retail situation the top tip, is to position the iBeacons on the ceiling as this reduces the number of Human obstructions.
Trilateration is basically the same whatever you do, I've been using Gema Megantara's version. To improve the positioning further a technique will be needed that takes environmental conditions into account e.g. Hyo-Sung & Wonpil 2009.
The solution is a technique called trilateration. There is a decent wiki article on it.
If you assume that all the beacons and the receiver are on the same plane you can ignore the Z dimension and it simplifies to circles.
The math is still kind of messy. You'd have to do some matrix math on the positions of the beacons to shift one beacon to the origin and put a second beacon on the x axis, and then apply the inverse of your matrix to the result to convert it back to "real" coordinates.
The big problem is that the "accuracy" (aka distance) value is anything but accurate. Even in a wide open space with no interference, the distance signals vary quite a bit. Add any interference (like from your body holding the phone even) and it gets worse. Add walls, furniture, metal surfaces, other people, etc, and it gets really wonky.
I have it on my list of things to do to write trilateration code, measure out a grid in my yard (when the weather warms up), take a tape measure, and do some testing.
The problem with all of this is that the RSSI signal you get back is extremely volatile. If you simply take the raw RSSI you will get very unreliable answers. You need to somehow process the data you get back before you run it through any triangulations, and that means either 1)averaging, or 2)filtering (or both). If you don't, you may get "IMMEDIATE" proximity response even though you are in fringe areas.
Bluetooth Low Energy (4.0) alone is not a robust indoor location and mapping technology, it will most likely become part of the fabric of indoor location technologies, in much the same way wi-fi signals are used to add fidelity to GPS signals in cities. Currently iBeacon can really only be used for fairly nebulous nodes indoors, like 'the shoe department' (assuming a large store)
I expect via the 'iBeacon' service (or something alternatively-named), Apple are working on high-resolution indoor location for app developers. You need look no further than their purchase of WifiSLAM, in mid 2013, for evidence. As yet, iBeacon and any other solely BLE technology is not going to give you precise indoor location. (Perhaps if you blanket the store with beacons, and combine a probabilistic model with a physical model, you could do it, but not with any practically-implementable beacon strategy.)
Also of note, is the discussion around Nokia's next-gen BLE HAIP (High-Accuracy Indoor Positioning) version http://conversations.nokia.com/2012/08/23/new-alliance-helps-you-find-needle-in-a-haystack/
Basically accurate indoor positioning doesn't exist in the wild yet, but it's about to...
We did use gimbal's ibeacons for indoor localization in a 6mx11m area. The RSSI fluctuation was a major issue that we handled through particle filtering. The code for the project can be found at https://github.com/ipapapa/IoT-MicroLocation/. The github repository contains the iOS application as well as a java based apache tomcat server. While we did get an accuracy as high as 0.97 meters, it is still very challenging to use beacons for micro-location purposes.Check the paper http://people.engr.ncsu.edu/ipapapa/Files/globecom2015.pdf which has been accepted for publication in IEEE Globecom conference.
To determine the user's position based on surrounding iBeacons, which have to stay at fixed positions, it is possible by signal strength triangulation. Take a look at this thesis about Bluetooth Indoor Positioning ;-)
Certainly if you can measure the exact position(lat/lon) of any individual iBeacon - that could be included in the beacons message. But assuming a stationary location - obviously this only need to be done once. Sort of an independent "calibration" exercise - which could itself be automated.
When discussing positioning, you need to first define your needs more concretely.
Computer/GPS geeks will assume you want accuracy down to the millimeter, if not finer, so they will either provide you with more information then you need - or tell you it can't be done[both viable answers].
However, in the REAL WORLD, most people are looking for accuracy of at most 3 feet[or 1 meter] - and most likely are willing to accept accuracy of within 10 feet[ie visual distance].
iOS already provides you with that level of accuracy - their api gives you the distance as "near, medium, far" - so within 10 feet all you need to check is that the distance is "near" or "medium".
If your needs go beyond that, then you can provide the custom functionality quite easily. You have 32 bits of information[major and minor codes] That is more then enough information to store the lattitude and longitude of each ibeacon IN the beacon itself using Morton Coding, http://www.spatial.maine.edu/~mark.a.plummer/Morton-GEOG664-Plummer.pdf
As long as altitude[height] is not a factor and no beacon will be deployed within 1 meter of another beacon - you can encode each lat/long pair into a single 32 bit integer and store it in the major and minor code.
Using just the major code, you can determine the location of the beacon[and hence the phone] to within 100 meters[conservatively]. This means that many beacons within the same 100 meter radius will have the SAME major code.
Using the minor code, you can determine the location of the beacon to within 1 meter, and the location of the phone to within 10 feet.
The code for this is already written and widely available - just look for code that demonstrates how it is "impossible" to do this, ignore what the comments about it not being possible since their focused on precision to a greater degree then you care about.
**Note: as mentioned in later posts, external factors will affect signal strength - but again this is likely not relevant for your needs. There are 3 'distances' provided by the iphone sdk, "close, near, far".
Far is the problematic one. Assume a beacon with a 150 foot range. Check with an iphone to determine what the 2 close distances are ideally... assume within 5 feet is "close" and 15 feet is "near".
If phone A is near to Beacon B[which has a known location] then you know the person is within 15 feet of point X. If there is a lot of interference, they may be 3 feet away, or they may be 15 feet, but in either case it is "within 15 feet". That's all you need.
By the same token, if you need to know if they are within 5 feet, then you use the "close" measurement.
I firmly believe that 80% of all positioning needs is provided by the current scheme - where it is not then you do your initial implementation with the limitation as a proof of concept and then contact one of the many ibeacon experts to provide the last bit of accuracy.
I have not done the extensive research that I believe went into Phil's above master's thesis, but...
There is another team that has claimed to have figured this out using various AI algorithms . See this linkedin post: https://www.linkedin.com/groups/6510475/6510475-5866674142035607552
As someone who develops beacons ( http://www.getgelo.com ) I can share first hand that pretty much any object will drastically change the consistency and accuracy of the RSSI which is going to make computing an exact position impossible. (Phil, I hope you prove me wrong, I haven't read your thesis yet).
If are the only person in a wide open space that has a grid of beacons then you can likely get this to work, but as soon as you add other people, walls, objects, etc, then you're SOL.
You can approximate location which is what iBeacons do and are pretty bad at, but it's directionless.
You could deploy enough beacons so that essentially wherever you are in a retail location you're standing very close to a beacon and you can have high confidence that you're in aisle 5 about 20 ft done (as opposed to being on the other side of aisle, aisle 6, and 20 ft down). Cost may become an issue here.
There are teams that are combining BLE with Wifi and other technologies to create a more accurate indoor positioning solution.
In short, and this will come as an echo of what's already been posted, BLE is not a good technology to be used solely for extremely accurate positioning.
The above problem can be solved using technology that combines Wi-Fi trilateration and a phone's sensor data. We get 1 meter accuracy in spaces that are properly outfitted when companies integrate our SDK with their app. The accuracy of these methods has improved dramatically over the last year.

Best practices for overall rating calculation

I have LAMP-based business application. SugarCRM to be more precise. There are 120+ active users at the moment. Every day each user generates some records that are used in complex calculation to get so called “individual rating”.
It takes for about 6 seconds to calculate one “individual rating” value. And there was not a big problem before: each user hits the link provided to start “individual rating” calculations, waits for 6-7 seconds, and get the value displayed.
But now I need to implement “overall rating” calculation. That means that additionally to “individual rating” I have to calculate and display to the user:
minimum individual rating among ALL the users of the application
maximum individual rating among ALL the users of the application
current user position in the range of all individual ratings.
Say, current user has individual rating equal to 220 points, minimum value of rating is 80, maximum is 235 and he is on 23rd position among all the users.
What are (imho) the main problems to be solved?
If one calculation lasts for 6 seconds, that overall calculations will take more than 10 minutes. I think it’s no good to make the application almost unaccessible for this period. And what if the quantity of users will rise in the nearest future 2-3 times?
Those calculations could be done as nightly job but all the users are in different timezones. In Russia difference between extreme timezones is 9 hours. So people in west part of Russia are still working in “today”. While people in eastern part is waking up to work in “tomorrow”. So what is the best time for nightly job in this case?
Are there any best practices|approaches|algorithms to build such rating system?
Given only the information provided, the only options I see:
The obvious one - reduce the time taken for a rating calculation (6 seconds to calculate 1 user's rating seems like a lot)
If possible, have intermediate values which you only recalculate some of, as required (for example, have 10 values that make up the rating, all based on different data, when some of the data changes, flag the appropriate values for recalcuation). Either do this recalculation:
During your daily recalculation or
When the update happens
Partial batch calculation - only recalculate x of the users' ratings at chosen intervals (where x is some chosen value) - has the disadvantage that, at all times, some of the ratings can be out of date
Calculate if not busy - either continuously recalculate ratings or only do so at a chosen interval, but instead of locking the system, have it run as a background process, only doing work if the system is idle
(Sorry, didn't manage with "long" comment posting; so decided to post as answer)
#Dukeling
SQL query that takes almost all the time for calculation mentioned above is just a replication of business logic that should be executed in PHP code. The logic was moved into SQL with the hope to reduce calculation time. OK, I’ll try both to optimize SQL query and play with executing logic in PHP code.
Suppose after that optimized application calculates individual rating for just 1 second. Great! But even in this case the first user logged into system should awaits for 120 seconds (120+ users * 1 sec = 120 sec) to calculate overall rating and gets its position in it.
I’m thinking of implementing the following approach:
Let’s have 2 “overall ratings” – “today” and “yesterday”.
For displaying purposes we’ll use “yesterday” overall rating represented as huge already sorted PHP array.
When user hits calculation link he started “today” calculation but application displays him “yesterday” value. Thus we have quickly accessible “yesterday” rating and each user randomly launches rating calculation that will be displayed for them tomorrow.
User list are partitioned by timezones. Each hour a cron job started to check if there’re any users in selected timezone that don’t have “today” individual rating calculated (e.g. user didn’t log into application). If so, application starts calculation of individual rating and puts its value in “today” (still invisible) ovarall rating array. Thus we have a cron job that runs nightly for each timezone-specific user group and fills the probable gaps in case users didn’t log into system.
After all users in all timezones had been worked out, application
sorts “today” array,
drops “yesterday” one,
rename “today” in “yesterday” and
initialize new “today”.
What do you think of it? Is it reasonable enough or not?

Algorithm for animating elements running across a scene

I'm not sure if the title is right but...
I want to animate (with html + canvas + javascript) a section of a road with a given density/flow/speed configuration. For that, I need to have a "source" of vehicles in one end, and a "sink" in the other end. Then, a certain parameter would determine how many vehicles per time unit are created, and their (constant) speed. Then, I guess I should have a "clock" loop, to increment the position of the vehicles at a given frame-rate. Preferrably, a user could change some values in a form, and the running animation would update accordingly.
The end result should be a (much more sophisticated, hopefully) variation of this (sorry for the blinking):
Actually this is a very common problem, there are thousands of screen-savers that use this effect, most notably the "star field", which has parameters for star generation and star movement. So, I believe there must be some "design pattern", or more widespread form (maybe even a name) for this algoritm. What would solve my problem would be some example or tutorial on how to achieve this with common control flows (loops, counters, ifs).
Any idea is much appreciated!
I'm not sure of your question, this doesn't seem an algorithm question, more like programming advice. I have a game which needs exactly this (for monsters not cars), this is what I did. It is in a sort of .Net psuedocode but similar stuff exists in other environments.
If you are running an animation by hand, you essentially need a "game-loop".
while (noinput):
timenow = getsystemtime();
timedelta = timenow - timeprevious;
update_object_positions(timedelta);
draw_stuff_to_screen();
timeprevious = timenow;
noinput = check_for_input()
The update_object_positions(timedelta) moves everything along timedelta, which is how long since this loop last executed. It will run flat-out redrawing every timedelta. If you want it to run at a constant speed, say once every 20 mS, you can stick in a thread.sleep(20-timedelta) to pad out the time to 20mS.
Returning to your question. I had a car class that included its speed, lane, type etc as well as the time it appears. I had a finite number of "cars" so these were pre-generated. I held these in a list which I sorted by the time they appeared. Then in the update_object_position(time) routine, I saw if the next car had a start time before the current time, and if so I popped cars off the list until the first (next) car had a start time in the future.
You want (I guess) an infinite number of cars. This requires only a slight variation. Generate the first car for each lane, record its start time. When you call update_object_position(), if you start a car, find the next car for that lane and its time and make that the next car. If you have patterns that you want to repeat, generate the whole pattern in one go into a list, and then generate a new pattern when that list is emptied. This would also work well in terms of letting users specify variable pattern flows.
Finally, have you looked at what happens in real traffic flows as the volume mounts? Random small braking activities cause cars behind to slightly over-react, and as the slight over-reactions accumulate it turns into cars completely stopping a kilometre back up the road. Its quite strange, and so might be a great effect in your wallpaper/screensaver whatever as well as being a proper simulation.

How do you separate game logic from display?

How can you make the display frames per second be independent from the game logic? That is so the game logic runs the same speed no matter how fast the video card can render.
I think the question reveals a bit of misunderstanding of how game engines should be designed. Which is perfectly ok, because they are damn complex things that are difficult to get right ;)
You are under the correct impression that you want what is called Frame Rate Independence. But this does not only refer to Rendering Frames.
A Frame in single threaded game engines is commonly referred to as a Tick. Every Tick you process input, process game logic, and render a frame based off of the results of the processing.
What you want to do is be able to process your game logic at any FPS (Frames Per Second) and have a deterministic result.
This becomes a problem in the following case:
Check input:
- Input is key: 'W' which means we move the player character forward 10 units:
playerPosition += 10;
Now since you are doing this every frame, if you are running at 30 FPS you will move 300 units per second.
But if you are instead running at 10 FPS, you will only move 100 units per second. And thus your game logic is not Frame Rate Independent.
Happily, to solve this problem and make your game play logic Frame Rate Independent is a rather simple task.
First, you need a timer which will count the time each frame takes to render. This number in terms of seconds (so 0.001 seconds to complete a Tick) is then multiplied by what ever it is that you want to be Frame Rate Independent. So in this case:
When holding 'W'
playerPosition += 10 * frameTimeDelta;
(Delta is a fancy word for "Change In Something")
So your player will move some fraction of 10 in a single Tick, and after a full second of Ticks, you will have moved the full 10 units.
However, this will fall down when it comes to properties where the rate of change also changes over time, for example an accelerating vehicle. This can be resolved by using a more advanced integrator, such as "Verlet".
Multithreaded Approach
If you are still interested in an answer to your question (since I didn't answer it but presented an alternative), here it is. Separating Game Logic and Rendering into different threads. It has it's draw backs though. Enough so that the vast majority of Game Engines remain single threaded.
That's not to say there is only ever one thread running in so called single threaded engines. But all significant tasks are usually in one central thread. Some things like Collision Detection may be multithreaded, but generally the Collision phase of a Tick blocks until all the threads have returned, and the engine is back to a single thread of execution.
Multithreading presents a whole, very large class of issues, even some performance ones since everything, even containers, must be thread safe. And Game Engines are very complex programs to begin with, so it is rarely worth the added complication of multithreading them.
Fixed Time Step Approach
Lastly, as another commenter noted, having a Fixed size time step, and controlling how often you "step" the game logic can also be a very effective way of handling this with many benefits.
Linked here for completeness, but the other commenter also links to it:
Fix Your Time Step
Koen Witters has a very detailed article about different game loop setups.
He covers:
FPS dependent on Constant Game Speed
Game Speed dependent on Variable FPS
Constant Game Speed with Maximum FPS
Constant Game Speed independent of Variable FPS
(These are the headings pulled from the article, in order of desirability.)
You could make your game loop look like:
int lastTime = GetCurrentTime();
while(1) {
// how long is it since we last updated?
int currentTime = GetCurrentTime();
int dt = currentTime - lastTime;
lastTime = currentTime;
// now do the game logic
Update(dt);
// and you can render
Draw();
}
Then you just have to write your Update() function to take into account the time differential; e.g., if you've got an object moving at some speed v, then update its position by v * dt every frame.
There was an excellent article on flipcode about this back in the day. I would like to dig it up and present it for you.
http://www.flipcode.com/archives/Main_Loop_with_Fixed_Time_Steps.shtml
It's a nicely thought out loop for running a game:
Single threaded
At a fixed game clock
With graphics as fast as possible using an interpolated clock
Well, at least that's what I think it is. :-) Too bad the discussion that pursued after this posting is harder to find. Perhaps the wayback machine can help there.
time0 = getTickCount();
do
{
time1 = getTickCount();
frameTime = 0;
int numLoops = 0;
while ((time1 - time0) TICK_TIME && numLoops < MAX_LOOPS)
{
GameTickRun();
time0 += TICK_TIME;
frameTime += TICK_TIME;
numLoops++;
// Could this be a good idea? We're not doing it, anyway.
// time1 = getTickCount();
}
IndependentTickRun(frameTime);
// If playing solo and game logic takes way too long, discard pending
time.
if (!bNetworkGame && (time1 - time0) TICK_TIME)
time0 = time1 - TICK_TIME;
if (canRender)
{
// Account for numLoops overflow causing percent 1.
float percentWithinTick = Min(1.f, float(time1 - time0)/TICK_TIME);
GameDrawWithInterpolation(percentWithinTick);
}
}
while (!bGameDone);
Enginuity has a slightly different, but interesting approach: the Task Pool.
Single-threaded solutions with time delays before displaying graphics are fine, but I think the progressive way is to run game logic in one thread, and displaying in other thread.
But you should synchronize threads right way ;) It'll take a long time to implement, so if your game is not too big, single-threaded solution will be fine.
Also, extracting GUI into separate thread seems to be great approach. Have you ever seen "Mission complete" pop-up message while units are moving around in RTS games? That's what I'm talking about :)
This doesn' cover the higher program abstraction stuff, i.e. state machines etc.
It's fine to control movement and acceleration by adjusting those with your frame time lapse.
But how about stuff like triggering a sound 2.55 seconds after this or that, or changing
game level 18.25 secs later, etc.
That can be tied up to an elapsed frame time accumulator (counter), BUT these timings can
get screwed up if your frame rate falls below your state script resolution
i.e if your higher logic needs 0.05 sec granularity and you fall below 20fps.
Determinism can be kept if the game logic is run on a separate "thread"
(at the software level, which I would prefer for this, or OS level) with a fixed time-slice, independent of fps.
The penalty might be that you might waste cpu time in-between frames if not much is happening,
but I think it's probably worth it.
From my experience (not much) Jesse and Adam's answers should put you on the right track.
If you are after further information and insight into how this works, i found that the sample applications for TrueVision 3D were very useful.

Resources