Hi first time posting here. I searched and found how re-implementing the QSpinBox class allows for custom uses. However I am not sure if my needs are addressed in as much as what I found by re-implementing the validate method.
I need a custom range that excludes a zero value in the range of values. The spinner is used for selecting zoom ratio for a loaded image. The initial range at design time is -25 to 10. That range could change depending on the dimensions of the image. Nevertheless, I have to be able to "skip" zero for a desired zoom factor. For example, the range would have to always be going from -1 to 1 or vice-versa.
I assume you're listening to QSpinbox::valueChanged(int i) signal, there you can do something like this:
void zoomImage(int i) {
if (i == 0) {
if (lastValue < 0) //if sliding from negative values
spinBox->setValue(1);
else
spinBox->setValue(-1);
return; //skip processing for 0
}
else
lastValue = i; //save last state to a class variable
//processing...
}
EDIT: int lastValue is used for storing the position of slider before it hits 0 in order to determine if the user slides to negative or positive values
What seems to have worked:
void MainWindow::zoomImage(int ctlValue)
{
if(ctlValue == 0)
{
if(zoomLastValue < 0)
ui->sbScaleImage->stepBy(1);
else
ui->sbScaleImage->stepBy(-1);
}
zoomLastValue = ui->sbScaleImage->value();
}
Apologies if I screwed up the formatting.
Related
#include <stdio.h>
#include <cs50.h>
void draw(int n);
int main(void)
{
int height = get_int("number:");
draw(height);
}
void draw(int n)
{
if(n <= 0)
{
return;
}
draw(n - 1);
for(int i = 0 ; i < n ; i++)
{
printf("#");
}
printf("\n");
}
Iam learing recursion topic, suppose the user input 4 when the compiler completes the if part the value of n is '0' and returning when i debug , but then the for loop starts the value of 'n' becomes '1' and also 'i' doesn't change it constantly 0 why is that iam expected n becomes 0 after the if draw(n - 1) completes.
I will try to make this explanation as simple as I can. First things first, To begin with, when using recursion, you would be noticing the calling of a method within itself with a different argument. In your case it is the draw method.
Now each time, a draw method is called inside another draw method, the outer method(in this case the draw that is called first) stops its flow of execution till the completion of the inner draw.
So when you called draw(4), it ran all the code till it reached line 5 in draw method, and called draw(3). Your for loop of draw(4) is not executed yet. This will continue till draw(1) calls a draw(0). At this stage, draw(0) will return out and the draw(1) will continue its for loop from where it left. So you would find that here n=1, leading to the first print of # and then a new line after it. Once the operation completes in here, it continues with where it left for draw(2). Which is the for loop in draw(2) where the value of n=2. And here it does two print of # and then a new line. This continues.
Now for the question why i is always 0, it is to do with what we call scopes in programming, you can see that each time the i is declared fresh in the loop and assigned a value 0. This means, each time a for loop is hit, the value of i is reinitialised to 0. If you had a global var i out side of your draw method, you would have had the value of i being retained.
I did try my best to put things in as simple form as possible but feel free to let me know if you needed more clarity.
I need QSpinBox for unsigned int. Therefore I have wrote simple class:
class UnsignedSpinBox : public QAbstractSpinBox {
private:
uint32_t value = 0;
uint32_t minimum = 0;
uint32_t maximum = 100;
private:
void stepBy(int steps) {
if (steps < 0 && (uint32_t)(-1 * steps) > value - minimum)
value = minimum;
else if (steps > 0 && maximum - value < (uint32_t)steps)
value = maximum;
else
value += steps;
lineEdit()->setText(QString::number(value));
}
StepEnabled stepEnabled() const {
if (value < maximum && value > minimum)
return QAbstractSpinBox::StepUpEnabled | QAbstractSpinBox::StepDownEnabled;
else if (value < maximum)
return QAbstractSpinBox::StepUpEnabled;
else if (value > minimum)
return QAbstractSpinBox::StepDownEnabled;
else
return QAbstractSpinBox::StepNone;
}
QValidator::State validate(QString &input, int &) const {
if (input.isEmpty())
return QValidator::Intermediate;
bool ok = false;
uint32_t validateValue = input.toUInt(&ok);
if (!ok || validateValue > maximum || validateValue < minimum)
return QValidator::Invalid;
else
return QValidator::Acceptable;
}
public:
UnsignedSpinBox(QWidget* parent = 0) : QAbstractSpinBox(parent) {
lineEdit()->setText(QString::number(value));
}
virtual ~UnsignedSpinBox() { }
};
In gerenal it works fine but it has one shortcoming. Step buttons are refreshed only after mouse moving (althouth function stepEnabled is called every second). As a result if I hold Page Up, my spin box gets maximum value and these step buttons don't change their state until I move my mouse. Or if value is 0, one pressing of Page Up or up arrow key on a keyboard changes value and text, but doesn't change buttons' state (down button is still disabled). Moreover, when value == maximum both buttons are disabled although function stepEnabled returnes QAbstractSpinBox::StepDownEnabled (I've checked it). What am I doing wrong? How can I enforce QAbstractSpinBox to draw these buttons correctly?
P.S. I use Debian. But I don't think it does matter since QSpinBox works fine
I think the Qt on your platform is either too old or otherwise broken. It works fine on OS X, on both Qt 4.8.5 and Qt 5.2.0.
There are two other solutions:
If you don't care about full range of unsigned integer, simply use QSpinBox and set non-negative minimum and maximum. That's all. On platforms with 32 bit int, maximum int value is 2^31-1, that's about half of the maximum uint value of 2^32-1.
You can use QDoubleSpinBox. On sane platforms you care about, double has more than 32 bits of mantissa, so you can convert it to a quint32 without loss of precision.
If you want to be sure, just add static_assert(sizeof(double)>4) anywhere in your code.
If one worries about performance, then it really doesn't matter. The calculations are performed at the rate of user input events: that's a couple dozen double operations per second. It doesn't matter.
I am using a cosine curve to apply a force on an object between the range [0, pi]. By my calculations, that should give me a sine curve for the velocity which, at t=pi/2 should have a velocity of 1.0f
However, for the simplest of examples, I get a top speed of 0.753.
Now if this is a floating point issue, that is fine, but that is a very significant error so I am having trouble accepting that it is (and if it is, why is there such a huge error computing these values).
Some code:
// the function that gives the force to apply (totalTime = pi, maxForce = 1.0 in this example)
return ((Mathf.Cos(time * (Mathf.PI / totalTime)) * maxForce));
// the engine stores this value and in the next fixed update applies it to the rigidbody
// the mass is 1 so isn't affecting the result
engine.ApplyAccelerateForce(applyingForce * ship.rigidbody2D.mass);
Update
There is no gravity being applied to the object, no other objects in the world for it to interact with and no drag. I'm also using a RigidBody2D so the object is only moving on the plane.
Update 2
Ok have tried a super simple example and I get the result I am expecting so there must be something in my code. Will update once I have isolated what is different.
For the record, super simple code:
float forceThisFrame;
float startTime;
// Use this for initialization
void Start () {
forceThisFrame = 0.0f;
startTime = Time.fixedTime;
}
// Update is called once per frame
void Update () {
float time = Time.fixedTime - startTime;
if(time <= Mathf.PI)
{
forceThisFrame = Mathf.Cos (time);
if(time >= (Mathf.PI /2.0f)- 0.01f && time <= (Mathf.PI /2.0f) + 0.01f)
{
print ("Speed: " + rigidbody2D.velocity);
}
}
else
{
forceThisFrame = 0.0f;
}
}
void FixedUpdate()
{
rigidbody2D.AddForce(forceThisFrame * Vector2.up);
}
Update 3
I have changed my original code to match the above example as near as I can (remaining differences listed below) and I still get the discrepancy.
Here are my results of velocity against time. Neither of them make sense to me, with a constant force of 1N, that should result in a linear velocity function v(t) = t but that isn't quite what is produced by either example.
Remaining differences:
The code that is "calculating" the force (now just returning 1) is being run via a non-unity DLL, though the code itself resides within a Unity DLL (can explain more but can't believe this is relevant!)
The behaviour that is applying the force to the rigid body is a separate behaviour.
One is moving a cube in an empty enviroment, the other is moving a Model3D and there is a plane nearby - tried a cube with same code in broken project, same problem
Other than that, I can't see any difference and I certainly can't see why any of those things would affect it. They both apply a force of 1 on an object every fixed update.
For the cosine case this isn't a floating point issue, per se, it's an integration issue.
[In your 'fixed' acceleration case there are clearly also minor floating point issues].
Obviously acceleration is proportional to force (F = ma) but you can't just simply add the acceleration to get the velocity, especially if the time interval between frames is not constant.
Simplifying things by assuming that the inter-frame acceleration is constant, and therefore following v = u + at (or alternately ∂v = a.∂t) you need to scale the effect of the acceleration in proportion to the time elapsed since the last frame. It follows that the smaller ∂t is, the more accurate your integration.
This was a multi-part problem that started with me not fully understanding Update vs. FixedUpdate in Unity, see this question on GameDev.SE for more info on that part.
My "fix" from that was advancing a timer that went with the fixed update so as to not apply the force wrong. The problem, as demonstrated by Eric Postpischil was because the FixedUpdate, despite its name, is not called every 0.02s but instead at most every 0.02s. The fix for this was, in my update to apply some scaling to the force to apply to accomodate for missed fixed updates. My code ended up looking something like:
Called From Update
float oldTime = time;
time = Time.fixedTime - startTime;
float variableFixedDeltaTime = time - oldTime;
float fixedRatio = variableFixedDeltaTime / Time.fixedDeltaTime;
if(time <= totalTime)
{
applyingForce = forceFunction.GetValue(time) * fixedRatio;
Vector2 currentVelocity = ship.rigidbody2D.velocity;
Vector2 direction = new Vector2(ship.transform.right.x, ship.transform.right.y);
float velocityAlongDir = Vector2.Dot(currentVelocity, direction);
float velocityPrediction = velocityAlongDir + (applyingForce * lDeltaTime);
if(time > 0.0f && // we are not interested if we are just starting
((velocityPrediction < 0.0f && velocityAlongDir > 0.0f ) ||
(velocityPrediction > 0.0f && velocityAlongDir < 0.0f ) ))
{
float ratio = Mathf.Abs((velocityAlongDir / (applyingForce * lDeltaTime)));
applyingForce = applyingForce * ratio;
// We have reversed the direction so we must have arrived
Deactivate();
}
engine.ApplyAccelerateForce(applyingForce);
}
Where ApplyAccelerateForce does:
public void ApplyAccelerateForce(float requestedForce)
{
forceToApply += requestedForce;
}
Called from FixedUpdate
rigidbody2D.AddForce(forceToApply * new Vector2(transform.right.x, transform.right.y));
forceToApply = 0.0f;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying to make a 2D tile-based top-down game in XNA. It is 16 x 16 tiles, and each tile is 25 pixels.
I have a character sprite starting at (0, 0) first tile, and I'm trying to make it movable using the keyboard from tile to tile. So in the Update method, when the arrow key is pressed, I tried adding or subtracting 25 to x or y of the position vector. It seems to be aligned in the tiles when moving, but it's moving about 4-5 tiles instead of just 1 tile at a time. I have tried multiplying it with gameTime.TotalGameTime.TotalSeconds, but it doesn't seem to help.
I'm kind of new to using XNA. Does anyone have any tutorials or can help with how to calculate the movement? Thanks in advance.
If you just check IsKeyDown every frame, it will say it is down on each frame that it is held down. At 60 frames-per-second, pressing a key will result in it being in the down state for several frames. Hence on each frame you are moving your character! By the time you let go of the key - he'll have moved several squares.
If you want to detect each key press (the key entering the "down" state), you need something like this:
KeyboardState keyboardState, lastKeyboardState;
bool KeyPressed(Keys key)
{
return keyboardState.IsKeyDown(key) && lastKeyboardState.IsKeyUp(key);
}
override void Update(GameTime gameTime)
{
lastKeyboardState = keyboardState;
keyboardState = Keyboard.GetState();
if(KeyPressed(Keys.Right)) { /* do stuff... */ }
}
However if you want to add a "repeat" effect when holding down the key (like what happens in typing), you need to count the time - something like this:
float keyRepeatTime;
const float keyRepeatDelay = 0.5f; // repeat rate
override void Update(GameTime gameTime)
{
lastKeyboardState = keyboardState;
keyboardState = Keyboard.GetState();
float seconds = (float)gameTime.ElapsedGameTime.TotalSeconds;
if(keyboardState.IsKeyDown(Keys.Right))
{
if(lastKeyboardState.IsKeyUp(Keys.Right) || keyRepeatTime < 0)
{
keyRepeatTime = keyRepeatDelay;
// do stuff...
}
else
keyRepeatTime -= seconds;
}
}
When you use IsKeyDown, you don't have to use timers.
public void HandleInput(KeyboardState keyState)
{
if (keyState.IsKeyDown(Keys.Left))
{
//go left...
}
}
I want to write an FSM which starts with an idle state and moves from one state to another based on some event. I am not familiar with coding of FSM and google didn't help.
Appreciate if someone could post the C data structure that could be used for the same.
Thanks,
syuga2012
We've implemented finite state machine for Telcos in the past and always used an array of structures, pre-populated like:
/* States */
#define ST_ANY 0
#define ST_START 1
: : : : :
/* Events */
#define EV_INIT 0
#define EV_ERROR 1
: : : : :
/* Rule functions */
int initialize(void) {
/* Initialize FSM here */
return ST_INIT_DONE
}
: : : : :
/* Structures for transition rules */
typedef struct {
int state;
int event;
(int)(*fn)();
} rule;
rule ruleset[] = {
{ST_START, EV_INIT, initialize},
: : : : :
{ST_ANY, EV_ERROR, error},
{ST_ANY, EV_ANY, fatal_fsm_error}
};
I may have the function pointer fn declared wrong since this is from memory. Basically the state machine searched the array for a relevant state and event and called the function which did what had to be done then returned the new state.
The specific states were put first and the ST_ANY entries last since priority of the rules depended on their position in the array. The first rule that was found was the one used.
In addition, I remember we had an array of indexes to the first rule for each state to speed up the searches (all rules with the same starting state were grouped).
Also keep in mind that this was pure C - there may well be a better way to do it with C++.
A finite state machine consists of a finite number discrete of states (I know pedantic, but still), which can generally be represented as integer values. In c or c++ using an enumeration is very common.
The machine responds to a finite number of inputs which can often be represented with another integer valued variable. In more complicated cases you can use a structure to represent the input state.
Each combination of internal state and external input will cause the machine to:
possibly transition to another state
possibly generate some output
A simple case in c might look like this
enum state_val {
IDLE_STATE,
SOME_STATE,
...
STOP_STATE
}
//...
state_val state = IDLE_STATE
while (state != STOP_STATE){
int input = GetInput();
switch (state) {
case IDLE_STATE:
switch (input) {
case 0:
case 3: // note the fall-though here to handle multiple states
write(input); // no change of state
break;
case 1:
state = SOME_STATE;
break
case 2:
// ...
};
break;
case SOME_STATE:
switch (input) {
case 7:
// ...
};
break;
//...
};
};
// handle final output, clean up, whatever
though this is hard to read and more easily split into multiple function by something like:
while (state != STOP_STATE){
int input = GetInput();
switch (state) {
case IDLE_STATE:
state = DoIdleState(input);
break;
// ..
};
};
with the complexities of each state held in it's own function.
As m3rLinEz says, you can hold transitions in an array for quick indexing. You can also hold function pointer in an array to efficiently handle the action phase. This is especially useful for automatic generation of large and complex state machines.
The answers here seem really complex (but accurate, nonetheless.) So here are my thoughts.
First, I like dmckee's (operational) definition of an FSM and how they apply to programming.
A finite state machine consists of a
finite number discrete of states (I
know pedantic, but still), which can
generally be represented as integer
values. In c or c++ using an
enumeration is very common.
The machine responds to a finite
number of inputs which can often be
represented with another integer
valued variable. In more complicated
cases you can use a structure to
represent the input state.
Each combination of internal state and
external input will cause the machine
to:
possibly transition to another state
possibly generate some output
So you have a program. It has states, and there is a finite number of them. ("the light bulb is bright" or "the light bulb is dim" or "the light bulb is off." 3 states. finite.) Your program can only be in one state at a time.
So, say you want your program to change states. Usually, you'll want something to happen to trigger a state change. In this example, how about we take user input to determine the state - say, a key press.
You might want logic like this. When the user presses a key:
If the bulb is "off" then make the bulb "dim".
If the bulb is "dim", make the bulb "bright".
If the bulb is "bright", make the bulb "off".
Obviously, instead of "changing a bulb", you might be "changing the text color" or whatever it is you program needs to do. Before you start, you'll want to define your states.
So looking at some pseudoish C code:
/* We have 3 states. We can use constants to represent those states */
#define BULB_OFF 0
#define BULB_DIM 1
#define BULB_BRIGHT 2
/* And now we set the default state */
int currentState = BULB_OFF;
/* now we want to wait for the user's input. While we're waiting, we are "idle" */
while(1) {
waitForUserKeystroke(); /* Waiting for something to happen... */
/* Okay, the user has pressed a key. Now for our state machine */
switch(currentState) {
case BULB_OFF:
currentState = BULB_DIM;
break;
case BULB_DIM:
currentState = BULB_BRIGHT;
doCoolBulbStuff();
break;
case BULB_BRIGHT:
currentState = BULB_OFF;
break;
}
}
And, voila. A simple program which changes the state.
This code executes only a small part of the switch statement - depending on the current state. Then it updates that state. That's how FSMs work.
Now here are some things you can do:
Obviously, this program just changes the currentState variable. You'll want your code to do something more interesting on a state change. The doCoolBulbStuff() function might, i dunno, actually put a picture of a lightbulb on a screen. Or something.
This code only looks for a keypress. But your FSM (and thus your switch statement) can choose state based on what the user inputted (eg, "O" means "go to off" rather than just going to whatever is next in the sequence.)
Part of your question asked for a data structure.
One person suggested using an enum to keep track of states. This is a good alternative to the #defines that I used in my example. People have also been suggesting arrays - and these arrays keep track of the transitions between states. This is also a fine structure to use.
Given the above, well, you could use any sort of structure (something tree-like, an array, anything) to keep track of the individual states and define what to do in each state (hence some of the suggestions to use "function pointers" - have a state map to a function pointer which indicates what to do at that state.)
Hope that helps!
See Wikipedia for the formal definition. You need to decide on your set of states S, your input alphabet Σ and your transition function δ. The simplest representation is to have S be the set of integers 0, 1, 2, ..., N-1, where N is the number of states, and for Σ be the set of integers 0, 1, 2, ..., M-1, where M is the number of inputs, and then δ is just a big N by M matrix. Finally, you can store the set of accepting states by storing an array of N bits, where the ith bit is 1 if the ith state is an accepting state, or 0 if it is not an accepting state.
For example, here is the FSM in Figure 3 of the Wikipedia article:
#define NSTATES 2
#define NINPUTS 2
const int transition_function[NSTATES][NINPUTS] = {{1, 0}, {0, 1}};
const int is_accepting_state[NSTATES] = {1, 0};
int main(void)
{
int current_state = 0; // initial state
while(has_more_input())
{
// advance to next state based on input
int input = get_next_input();
current_state = transition_function[current_state][input];
}
int accepted = is_accepting_state[current_state];
// do stuff
}
You can basically use "if" conditional and a variable to store the current state of FSM.
For example (just a concept):
int state = 0;
while((ch = getch()) != 'q'){
if(state == 0)
if(ch == '0')
state = 1;
else if(ch == '1')
state = 0;
else if(state == 1)
if(ch == '0')
state = 2;
else if(ch == '1')
state = 0;
else if(state == 2)
{
printf("detected two 0s\n");
break;
}
}
For more sophisticated implementation, you may consider store state transition in two dimension array:
int t[][] = {{1,0},{2,0},{2,2}};
int state = 0;
while((ch = getch()) != 'q'){
state = t[state][ch - '0'];
if(state == 2){
...
}
}
A few guys from AT&T, now at Google, wrote one of the best FSM libraries available for general use. Check it out here, it's called OpenFST.
It's fast, efficient, and they created a very clear set of operations you can perform on the FSMs to do things like minimize them or determinize them to make them even more useful for real world problems.
if by FSM you mean finite state machine,
and you like it simple, use enums to name your states
and switch betweem them.
Otherwise use functors. you can look the
fancy definition up in the stl or boost docs.
They are more or less objects, that have a
method e.g. called run(), that executes
everything that should be done in that state,
with the advantage that each state has it's own
scope.