GX Rigid Body Dragging
 Volume Number: 12 Issue Number: 8 Column Tag: New Technologies

# Dragging and Rigid-Body Transformations

## QD GX can make your Mac a swinging place

By Lawrence D’Oliveiro

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

QuickDraw GX offers some interesting new possibilities for interactive graphics. This article is a note on one of them: the idea of dragging an object about, and having it rotate to follow the drag, just like real objects tend to do when you pull or push them.

The code I’m presenting here is by no means finished; think of it as a rough sketch, a demonstration of the concept. It is written in Modula-2, and makes heavy use of my standard libraries, which you can find at ftp://ftphost.waikato.ac.nz/pub/ldo/MyModLib.hqx.

Feel free to use my code as a starting point for your own experiments.

## Transformations in QuickDraw GX

QuickDraw GX supports 3-by-3 mappings, which are capable of applying any kind of linear transformation to the geometry of a GX shape. (A linear transformation is one that preserves the straightness of lines. Thus, a GX mapping cannot transform a straight line to a curve, or vice versa.)

Linear transformations can be broken down into various simple types: translations (changes of position), rotations, scaling, skewing and perspective. In fact, any arbitrary linear transformation can be considered to be built from components of these types.

There are various useful subsets of linear transformations: an affine transformation is one where any pair of parallel lines remains parallel after the transformation. GX’s perspective transformations clearly are not affine; thus, an affine transformation is one that has no perspective component.

An important subset of affine transformations is the set of rigid-body transformations: these are ones that preserve the distance between any two given points. Rigid-body transformations consist only of translations and rotations; this corresponds intuitively to our notions of real rigid bodies, which cannot be scaled or stretched in any way, though you can usually move them around and reorient them any way you like (unless they’re a lot bigger or heavier than you are).

Figure 1. As the cursor pulls the arrow to the right, the arrow swings into line with the direction of motion. These are successive screen shots from my program; the upper-left corner of each shot is the upper-left corner of the window.

## Dragging a Rigid Body

Consider what happens when you try to move a real rigid body. The body has a center of mass; if you orient the direction of your force so that it passes exactly through this point, the object will change its position without rotating. But if you offset your force by any amount, you will produce a torque, and the object will change both its position and its orientation. (For example, place a book on a smooth surface such a desk, grasp it by just one corner, and pull in a straight line; the book, as it starts to move, also swings around to line up its center of mass with the direction of travel.)

Figure 1 shows this happening in my program.

In the following analysis, I’ll follow the rules of Aristotelian, rather than Newtonian, physics: objects have no inertia, but they are subject to friction, which acts through their center of mass. Thus, they stop moving as soon as you stop pushing them.

Consider a body with its center of mass at a point C. Say you apply a small force on it at a point F, sufficient to displace that point to a new position G close to F. The center of mass is in turn moved to a new position D (Figure 2).

Figure 2. Movements... Figure 3. ...and analysis

The force you apply can be split into two components: the component parallel to CF moves the object without rotating it (hence the new position of the center of mass, D, lies on this line), while the component perpendicular to this line exerts a pure rotational force on the object without moving the center of mass.

In Figure 2, q is the angle CFG and can have any value, while f is the angle of rotation FCG, and is assumed to be small (you’ll see why shortly).

Now draw a line P1P2 parallel to CF, and project the points C, D, F and G onto this line at the points Cp, Dp, Fp and Gp (Figure 3). Gt is the intersection between FFp and CG. In this case, q is greater than 90°, so the angle GFGt is q - 90° (I’ll leave the analysis of the case where q is less than 90° as an “exercise for the reader”, as they say). Since f is small, FGtG is close to 90°, so the ratio FGtFG is approximately cos q - 90°, which equals sin q. Now, since GFGt is a right angle, sin f equals FGtCF which becomes FG sin qCF when you apply the above approximation.

For larger movements, where the angle f might not be small, simply split the movement into lots of small steps with correspondingly small f. If you want a fancy-sounding term for this mathematical trick, it’s called differential calculus.

## Translating This Into Code

The next step is to write some actual code based on this analysis. In the following, I’ll intermingle declarations and statements to suit the exposition, rather than the requirements of strict language syntax (in other words, I’ll be following the order in which code is usually written).

```VAR
LastMouse, ThisMouse : Point;
ThisDelta : gxPoint;
ShapeCenter : gxPoint;

```

LastMouse is the point F, while ThisMouse is the point G. ThisDelta is the displacement FG, computed as follows:

``` ThisDelta.x := IntToFixed(ThisMouse.h - LastMouse.h);
ThisDelta.y := IntToFixed(ThisMouse.v - LastMouse.v);

```

ShapeCenter is supposed to be the center of mass, or center of geometry, of the shape. GX provides a call, GXGetShapeCenter, that is supposed to return this in the coordinate system of the shape geometry itself. You could then put this through the shape mapping to get the center in “local coordinates”. Unfortunately, when I tried this, I got incorrect results for a complex picture shape (a QuickDraw GX bug?). So, to avoid this problem, my code takes ShapeCenter as the center of the shape’s bounding rectangle, rather than of its actual geometry:

```GXGetShapeLocalBounds(TheShape, Bounds);
ShapeCenter.x := (Bounds.right + Bounds.left) DIV 2;
ShapeCenter.y := (Bounds.bottom + Bounds.top) DIV 2;

```

Next we perform the computation of the actual rotation angle, using good old floating-point numbers instead of fixed-point ones:

```VAR
DeltaX, DeltaY, Delta : LongReal;
DragAngle, RotationAngleSin : LongReal;
RotationAngle : LongReal;

```

DeltaX and DeltaY are the x- and y-components of the displacement FG, while Delta is the magnitude of this displacement.

```DeltaX := Fix2Double(ThisDelta.x);
DeltaY := Fix2Double(ThisDelta.y);
Delta := Sqrt(Squared(DeltaX) + Squared(DeltaY));

```

Similarly, RadiusX and RadiusY are the x- and y-components of thedistance CF, while Radius is the magnitude of this distance.

```RadiusX := Fix2Double(IntToFixed(LastMouse.h) - ShapeCenter.x);
```

DragAngle is the angle q. I compute it here from the difference between the angles of the lines FG and CF (ArcTan2(x, y) returns the angle with tangent y/x in the appropriate quadrant, taking account of the signs of x and y):

```DragAngle := ArcTan2(DeltaX, DeltaY) - ArcTan2(RadiusX, RadiusY);

```

RotationAngleSin is the sine of the angle f. DLimit is just a routine that constrains its first argument to within the specified limits (in this case, between -1 and 1). The need for this constraint will become apparent later.

```RotationAngleSin := DLimit
(
FLOATD(-1),
FLOATD(1)
);

```

And finally, we compute the angle f itself, converting from the floating-point radians that SANE operates in, to the fixed-point degrees that QuickDraw GX uses:

```RotationAngle :=
Double2Fix(ArcSin(RotationAngleSin) * FLOATD(180) / Pi())

```

Applying the transformation to the shape is pretty straightforward. Simply obtain the shape’s existing mapping:

```VAR
ShapeMapping : gxMapping;
...
GXGetShapeMapping(TheShape, ShapeMapping);

```

then apply the appropriate movement and rotation:

```MoveMapping
(
(*@target :=*) ShapeMapping,
(*hOffset :=*) ThisDelta.x,
(*vOffset :=*) ThisDelta.y
);
RotateMapping
(
(*@target :=*) ShapeMapping,
(*angle :=*) RotationAngle,
(*xCenter :=*) IntToFixed(ThisMouse.h),
(*yCenter :=*) IntToFixed(ThisMouse.v)
);
GXSetShapeMapping(TheShape, ShapeMapping)

```

Note that the center of rotation used in the RotateMapping call is the point G rather than C. This is all right, because the direction of rotation calculated by the code is actually the opposite of that in the analysis; thus the effect is the same.

## Other Matters

There are several other aspects of the example code that I’ve glossed over so far.

To keep the size of the source code down, the program itself has absolutely the minimum user interface I felt I could get away with. It doesn’t even have any menus! When you start it up, it already has a shape loaded that you can try dragging about. You can bring in a different shape by dragging it into the window, from a Finder clipping file or another drag-aware application (I’ve provided a few sample clippings you can try). To quit the program, click the close box in the window.

An important issue is how to do off-screen rendering, so that your on-screen drawing doesn’t flicker. There is no direct equivalent to QuickDraw GWorlds in QuickDraw GX, but the GX SDK library code shows you how to create a much more powerful alternative: an offscreen graphics context that can optimize drawing simultaneously for multiple screens, rather than just the deepest one that your window happens to cross.

My actual program uses a routine I wrote called MoveSprite, which creates temporary offscreen structures every time you call it to move an object. It automatically sizes these structures to cover only the affected on-screen area (and doesn’t bother doing off-screen drawing if the old and new positions of the object don’t overlap). Thus, this routine is simpler to use than explicitly creating separate off-screen structures and reusing them for the duration of the drag, though it may be slower.

One feature of the code is that it doesn’t rotate the shape if you drag it at a point close to its center, or if you hold the command-key down. I figure this sort of feature could be useful in a “real” program, where the user might not always want the object to rotate.

One pitfall you always have to keep in mind when doing calculations on a computer is rounding error. In this case, repeated calls to RotateMapping can accumulate distortions in the shape geometry, since the mapping elements cannot be computed exactly. To get around this, you should keep separate track of the shape position and rotation angle, and recompute the shape mapping from these values each time, instead of applying an incremental rotation to the previous mapping. This will keep the distortion within fixed bounds, instead of letting it accumulate. My code doesn’t do this, though I must admit I have yet to notice any distortions in shapes after repeated drags.

Finally, I should own up to one important liberty I have taken with the mathematical analysis. Remember how I kept saying that the displacement and rotation angle were assumed to be small? In fact, the code will happily compute arbitrarily large values for the FG displacement, depending on how quickly you can move the mouse, and how long it takes your machine to redraw the shape in between checking the mouse position. This means that, for large mouse movements, the code is no longer strictly MC (Mathematically Correct). It’s also why I put in the DLimit call.

But then, I figure this is part of the fun of programming. For instance, I have found that I can drag a shape to a corner of the window, and leave the mouse absolutely stationary outside the window, while the shape continues to spin round and round in the corner. Is this a consequence of the code hitting a non-MC situation? I don’t know - you tell me!

Community Search:
MacTech Search:

Ableton Live 11.3.11 - Record music usin...
Ableton Live lets you create and record music on your Mac. Use digital instruments, pre-recorded sounds, and sampled loops to arrange, produce, and perform your music like never before. Ableton Live... Read more
Affinity Photo 2.2.0 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
SpamSieve 3.0 - Robust spam filter for m...
SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering. SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more
WhatsApp 2.2338.12 - Desktop client for...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
Fantastical 3.8.2 - Create calendar even...
Fantastical is the Mac calendar you'll actually enjoy using. Creating an event with Fantastical is quick, easy, and fun: Open Fantastical with a single click or keystroke Type in your event details... Read more
iShowU Instant 1.4.14 - Full-featured sc...
iShowU Instant gives you real-time screen recording like you've never seen before! It is the fastest, most feature-filled real-time screen capture tool from shinywhitebox yet. All of the features you... Read more
Geekbench 6.2.0 - Measure processor and...
Geekbench provides a comprehensive set of benchmarks engineered to quickly and accurately measure processor and memory performance. Designed to make benchmarks easy to run and easy to understand,... Read more
Quicken 7.2.3 - Complete personal financ...
Quicken makes managing your money easier than ever. Whether paying bills, upgrading from Windows, enjoying more reliable downloads, or getting expert product help, Quicken's new and improved features... Read more
EtreCheckPro 6.8.2 - For troubleshooting...
EtreCheck is an app that displays the important details of your system configuration and allow you to copy that information to the Clipboard. It is meant to be used with Apple Support Communities to... Read more
iMazing 2.17.7 - Complete iOS device man...
iMazing is the world’s favourite iOS device manager for Mac and PC. Millions of users every year leverage its powerful capabilities to make the most of their personal or business iPhone and iPad.... Read more

## Latest Forum Discussions

Motorsport legends NASCAR announce an up...
NASCAR often gets a bad reputation outside of America, but there is a certain charm to it with its close side-by-side action and its focus on pure speed, but it never managed to really massively break out internationally. Now, there's a chance... | Read more »
Skullgirls Mobile Version 6.0 Update Rel...
I’ve been covering Marie’s upcoming release from Hidden Variable in Skullgirls Mobile (Free) for a while now across the announcement, gameplay | Read more »
Amanita Design Is Hosting a 20th Anniver...
Amanita Design is celebrating its 20th anniversary (wow I’m old!) with a massive discount across its catalogue on iOS, Android, and Steam for two weeks. The announcement mentions up to 85% off on the games, and it looks like the mobile games that... | Read more »
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 21st, 2023. I got back from the Tokyo Game Show at 8 PM, got to the office here at 9:30 PM, and it is presently 11:30 PM. I’ve done what I can today, and I hope you enjoy... | Read more »
Massive “Dark Rebirth” Update Launches f...
It’s been a couple of months since we last checked in on Diablo Immortal and in that time the game has been doing what it’s been doing since its release in June of last year: Bringing out new seasons with new content and features. | Read more »
‘Samba De Amigo Party-To-Go’ Apple Arcad...
SEGA recently released Samba de Amigo: Party-To-Go () on Apple Arcade and Samba de Amigo: Party Central on Nintendo Switch worldwide as the first new entries in the series in ages. | Read more »
The “Clan of the Eagle” DLC Now Availabl...
Following the last paid DLC and free updates for the game, Playdigious just released a new DLC pack for Northgard (\$5.99) on mobile. Today’s new DLC is the “Clan of the Eagle" pack that is available on both iOS and Android for \$2.99. | Read more »
Let fly the birds of war as a new Clan d...
Name the most Norse bird you can think of, then give it a twist because Playdigious is introducing not the Raven clan, mostly because they already exist, but the Clan of the Eagle in Northgard’s latest DLC. If you find gathering resources a... | Read more »
Out Now: ‘Ghost Detective’, ‘Thunder Ray...
Each and every day new mobile games are hitting the App Store, and so each week we put together a big old list of all the best new releases of the past seven days. Back in the day the App Store would showcase the same games for a week, and then... | Read more »
Urban Open-World RPG ‘Project Mugen’ Fro...
Last month, NetEase Games revealed a new free to play open world RPG tentatively titled Project Mugen for mobile, PC, and consoles. I’ve liked the setting and aesthetic since its first trailer, and today’s new video has the Game Designer and... | Read more »

## Price Scanner via MacPrices.net

Apple AirPods 2 with USB-C now in stock and o...
Amazon has Apple’s 2023 AirPods Pro with USB-C now in stock and on sale for \$199.99 including free shipping. Their price is \$50 off MSRP, and it’s currently the lowest price available for new AirPods... Read more
New low prices: Apple’s 15″ M2 MacBook Airs w...
Amazon has 15″ MacBook Airs with M2 CPUs and 512GB of storage in stock and on sale for \$1249 shipped. That’s \$250 off Apple’s MSRP, and it’s the lowest price available for these M2-powered MacBook... Read more
New low price: Clearance 16″ Apple MacBook Pr...
B&H Photo has clearance 16″ M1 Max MacBook Pros, 10-core CPU/32-core GPU/1TB SSD/Space Gray or Silver, in stock today for \$2399 including free 1-2 day delivery to most US addresses. Their price... Read more
Switch to Red Pocket Mobile and get a new iPh...
Red Pocket Mobile has new Apple iPhone 15 and 15 Pro models on sale for \$300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide service using all the major... Read more
Apple continues to offer a \$350 discount on 2...
Apple has Studio Display models available in their Certified Refurbished store for up to \$350 off MSRP. Each display comes with Apple’s one-year warranty, with new glass and a case, and ships free.... Read more
Apple’s 16-inch MacBook Pros with M2 Pro CPUs...
Amazon is offering a \$250 discount on new Apple 16-inch M2 Pro MacBook Pros for a limited time. Their prices are currently the lowest available for these models from any Apple retailer: – 16″ MacBook... Read more
Closeout Sale: Apple Watch Ultra with Green A...
Adorama haș the Apple Watch Ultra with a Green Alpine Loop on clearance sale for \$699 including free shipping. Their price is \$100 off original MSRP, and it’s the lowest price we’ve seen for an Apple... Read more
Use this promo code at Verizon to take \$150 o...
Verizon is offering a \$150 discount on cellular-capable Apple Watch Series 9 and Ultra 2 models for a limited time. Use code WATCH150 at checkout to take advantage of this offer. The fine print: “Up... Read more
New low price: Apple’s 10th generation iPads...
B&H Photo has the 10th generation 64GB WiFi iPad (Blue and Silver colors) in stock and on sale for \$379 for a limited time. B&H’s price is \$70 off Apple’s MSRP, and it’s the lowest price... Read more
14″ M1 Pro MacBook Pros still available at Ap...
Apple continues to stock Certified Refurbished standard-configuration 14″ MacBook Pros with M1 Pro CPUs for as much as \$570 off original MSRP, with models available starting at \$1539. Each model... Read more

## Jobs Board

Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Retail Key Holder- *Apple* Blossom Mall - Ba...
Retail Key Holder- APPLE BLOSSOM MALL Brand: Bath & Body Works Location: Winchester, VA, US Location Type: On-site Job ID: 03YM1 Job Area: Store: Sales and Support Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more