Game Development Community

Mod division

by WDDG · in Torque Game Builder · 02/18/2006 (11:11 am) · 6 replies

Weird bug,

365 % 360 = 5
-365 % 360 = 255 according to torque.

Is this a bug that's going to be fixed soon, or is there a work around for this bug?

#1
02/18/2006 (12:19 pm)
Looking at the code for the interpreter ...

The int stack is U32. Therefore, when doing any integer math it will treat both sides of the expression as unsigned. That probably explains why you're getting incorrect results.

If you look in compiledEval.cc, on roughly line 39 is the definition for intStack ... try changing that from a U32 to an S32. You will want to test very, very carefully if you do that. Note that this will affect everywhere that ints are used in the interpreter. That covers pretty much everything from jumps, comparisons, object IDs, and a lot of other things. You will get a lot of warnings about type conversion. There are likely other undesired knock on effects. From browsing the code, fixing that "properly" is a big job that would require a lot of very careful testing.

I suggest finding a work around.

T.
#2
02/18/2006 (12:49 pm)
Right now I have bunch of if statements, but if that's the only way then it's fine.
#3
02/18/2006 (2:34 pm)
I wouldnt say its the only way ... Another kludge would be to move that logic to a C++ console function, then you can cast to an S32 and get the correct result. Or write a quick s32mod() console function to do a mod on S32s.

Actually, thinking about it, an easier kludge is this:

In compiledEval.cc towards the end, you'll find the main interpreter loop. Its basically one huge switch/case. Look for the OP_MOD case. It should be easy to find. Where it does the %, change it so it looks something like intStack[UINT-1] = S32(intStack[UINT]) % S32(intStack[UINT-1]); (Note: That is from memory, I may have the -1s in the wrong place, check it but basically just cast each side of the expression)

Dont know why I didnt think of that earlier, it's pretty obvious really :/

T.
#4
02/18/2006 (10:34 pm)
I don't feel very comfortable recompiling the torque engine so this was the easiest route for me:

MAbs(%var) mod 360 * (%var / MAbs(%var))
365 % 360 = 5 * -1

Thank you though.
Also, do you think that your fix will be implimented in the main engine on an upcoming release.
#5
02/18/2006 (10:46 pm)
I don't feel very comfortable recompiling the torque engine so this was the easiest route for me:

function doMod(%var, %mod)
{
%AbsVar = MAbs(%var);
return %AbsVar % 360 * (%var / %AbsVar);
}

Thank you though.
Also, do you think that your fix will be implimented in the main engine on an upcoming release.
#6
02/19/2006 (3:59 am)
I doubt it would end up in the official engine since its more of a kludge for your particular situation then a workable general fix. The proper fix would be to handle signed and unsigned math correctly in all cases where it's currently problematic. That said, you never know :)

T.