How does Qt animate the QProgressBar? - animation

In some Qt 5 styles (such as Breeze), progress bars which are in indefinite state (minimum == maximum) show an animation.
I want to create my own progress widget which has less visual footprint for use in a status bar, so I looked at the source code of QProgressBar to understand how the animation is implemented.
To my surprise, I didn’t find any animation code in there. There are no timers. There is no event filter.
How is this animation implemented?

The magic dust is the QStyle::polish method. It is invoked on widgets, including the QProgressBar instances.
The breeze style sets up its own animation logic. The progress bars are handled by Breeze::BusyIndicatorEngine. It uses a QPropertyAnimation to advance its own internal value.
Its registerWidget method is invoked from the polish implementation of the Breeze style. This in turn saves the widget in an internal map.
When the internal value is updated by the animation, the map is iterated and update is invoked on all widgets which are currently being animated (using indirection via QMetaObject).

Related

d3.js Saved Transition Error

I am working in d3.js, making a chart object. My chart has an update() method that refreshes the data, using a transition to animate the change. Because I have several different objects to animate within one chart, I wanted to store the transition as a member of the Chart's prototype, then use transition.each wrapped around my transitions to allow all the transitions to inherit the settings of the outer one. I am using setTimeout to schedule updates to the chart over time, so it becomes an animation.
The chart is supposed to show the distribution of means of a skew population, as more and more means are taken. Here's a working version, where the transition is not saved as a member of the chart prototype: http://jsfiddle.net/pmwxcpz7/
Now, I try to modify the above code to store the transition during the constructor of the Chart. When I fetch the saved transition object and call transition.each() in the chart's update method, it works for the first several hundred calls, then stops working. Here's the above code, with the creation of the transition moved to the constructor: http://jsfiddle.net/whtfny15/1/
When I run the second version of the code, the chart stops animating part of the way through, and the console shows many errors saying
TypeError: t.__transition__[e] is undefined (d3.v3.min.js:5)
I have reduced the code to the minimum needed to generate the error here: http://jsfiddle.net/bw1e2vLo/1/ (note that the error shows in the console, but this script doesn't produce any visual output.)
When I run the code (in Firefox), watching the console, I get 200 errors, all of which say
TypeError: t.__transition__[e] is undefined (d3.v3.min.js:5)
I'm not sure what's going on. I would like to be able to save the transition object into my chart's prototype, so I can reuse the delay and duration settings for future animations.
Thanks for the help!
It's not a good idea to store D3 transitions because they are stateful -- what happens when you operate on them depends on whether they are scheduled, running, or finished. If they are finished you can't in fact do a lot with them at all, as you've discovered. In general, you should only ever manipulate a transition when creating it.
The D3 way to do multiple transitions is to re-select the elements to operate on and initialise a new transition. You can store the parameters (delay and duration) in separate variables if you want to reuse them. If you're using a custom function for the transition itself, you can also save that separately and "assign" it to the transition using .attrTween().
I thought I would add that I opened an issue for this question on the d3 GitHub, and Mr. Bostock suggested using transition.call() to apply the settings in a callback right before using the transition.
The code would look something like this:
function myTransitionSettings(transition) {
transition
.duration(100)
.delay(0);
}
// Then later…
d3.transition().call(myTransitionSettings)…
The callback has access to the current transition object, so it can apply the same settings to each new transition that invokes it.

Windows Phone Visibility Behaviours in CPU

I'd like to ask how objects behave in our phone when we program our applications.
Assume that we have some ellipses, squares rotating around a point, that is, there is a graphic animations where all animation is supposed to be an object as XAML.
If we make this animation Visibility="Collapsed"; what will phone CPU do? Does it still work in CPU without displaying on the screen, or it throws into suspended state into harddrive or something, or in other words, any visibility collapsed object including button, webpage, animations etc. consume the CPU and hence, the battery just as it does while visibility="visible"?
Thanks for your enlightening me in advance.
There are two ways to hide objects on the screen
Visibility Property
When the Visibility property is set to Collapsed, XAML does not hold any visual data for the element in visual memory and does not do any processing related to the element.
Setting Visibility to Visible, will draw the contents of the visual tree and the element is completely.
Opacity
You can improve performance in your app by manipulating the Opacity property of elements when you are using bitmap caching. Bitmap caching allows visual elements to be stored as bitmaps after the first render pass. After the element is cached, the app bypasses the render phase for the cached visual element and displays the stored bitmap instead. When you set the Opacity for a cached element to 0, a bitmap representation of the element is saved in memory. It's recommanded to use BitmapCaching (set CacheMode property to BitmapCache) in scenarios where you are blending, transforming (translating, stretching, rotating).
WP supports a composition thread in addition to the UI thread. UI thread will parse and create objects from XAML, Draw all visuals the first time they are drawn and Process per-frame callbacks and execute other user code. Composition thread combines graphics textures and passes them to the GPU for drawing. There are also some optimisatins forstoryboard-driven animations.
Maintaining a lightweight UI thread is the key to writing a responsive app.

EaselJS and multi layered canvas system: performance tuning, game developing, event handling

I'm an engineer and we are currently porting our Red5 + Flash game into a Node.js + Easeljs html5 application.
Basicly: it's a board game, not an rpg. The layer system means we have multiple canvasses, based on functionally. For example there is a static background stage, with images. There is a layer for just the timers.
At default, all canvas size is 1920x1080, if needed we downscale to fit to the resolution.
The first approach used kinetic.js, but the performance fallen when the game got complex. Then we switched to easel, because it's abstraction level is lower, so we can decide how to implement some more function, not just use the provided robust one.
I was optimistic, but now it's starting to show slowness again, that's why I want to look deeper inside and do fine performance tuning. (Of course everything is fine in Chrome, Firefox is the problem, but the game must run smoothly on all modern browser).
The main layer (stage) is the map, contains ~30 containers, in each there is a complex custom shape, ~10 images. The containers are listening to mouse events, like mouseover, out, click. Currently, for example on mouseover I refill the shape with gradient.
Somehow, when I use cache, like the way in the tuts the performance get even worse, so I assume I'm messing up something.
I collected some advanced questions:
In the described situation when can I use cache and how? I've already tried cache on init, cacheUpdate after fill with other color or gradient, then stage.update(). No impact.
If I have a static, never changing stage cache doesn't make sense on that layer, right?
What stage.update() exactly do? Triggering the full layer redraw? The doc mentions some kind of intelligent if changed then redraw effect.
If I want to refill a custom shape with new color or gradient I have to completely redraw its graphics, not just use a setFill method, right?
In easel there is no possibility to redraw just a container for example, so how can I manage to not update the whole stage, but just the one container that changed? I thought I can achieve this with caching, cache all containers the just update the one that changed, but this way didn't work at all for me.
Does it make sense to cache bitmap images? If there are custom shapes and images in a container what is better? Cache the container or just the shape in container.
I found a strange bug, or at least an interesting clue. My canvas layers totally overlapping. On the inferior layers the mouseover listening is working well, but the click isn't on the very same container/object.
How can I produce a click event propagation to overlapped layers those have click listeners? I've tried it with simple DOM, jquery, but the event objects were far away from what canvas listeners wanted to get.
In brief, methods and props I've already played with bare success when tried tuning: cache(), updateCache(), update(), mouseEnabled, snapToPixel, clear(), autoClear, enableMouseOver, useRAF, setFPS().
Any answer, suggestion, starting point appreciated.
UPDATE:
This free board game is a strategy game, so you are facing a world map, with ~30 territories. The custom shapes are the territories and a container holds a territory shape and the icons that should be over the territory. This container overlapping is minimal.
An example mouse event is a hover effect. The player navigate over the territory shape then the shape is getting recolored, resized, etc and a bubble showing up with details about the place.
Basically, maximum amount of 1-3 container could change at once (except the init phase -> all at this time). Not just the animations and recoloring slow in FF, but the listener delay is high too.
I wrote a change handler, so I only stage.update() up on tick the modified stages and the stages where an animation is running (tweenjs).
In my first approach I put every image to the container that could be needed at least once during the game, so I only set visible flags on images (not vectors).
Regarding caching:
There are some strange caching-issues, somehow the performance can drop with certain sizes of the caching rectangle: CreateJS / EaselJS Strange Performance with certain size shapes
(2) Depending on how often you call stage.update();
(3)
Each time the update method is called, the stage will tick any
descendants exposing a tick method (ex. BitmapAnimation) and render
its entire display list to the canvas. Any parameters passed to update
will be passed on to any onTick handlers.
=> Afaik it rerenders everything if not cached
(4) Yes.
(5) No. (I don't know of any)
(6) If the content's of the container don't change often, I'd cache the whole container, otherwise the container will be reconstructed every frame.
I have a question though: Why do you use multiple canvases? How many do you use? I could imagine that using multiple canvases might slow down the game.
How many sprites do you use in total?
2: if your layer or stage doesn't change, don't call stage.update() for that layer (so it doesn't gets rerendered, gives me a much lower cpu!)
For example, keep a global "stagechanged" variable and set this to true when something has changed:
createjs.Ticker.addEventListener("tick",
function() {
if (stagechanged)
{
stagechanged = false;
stage.update();
}
});
(or do you already use this, as stated in your "update"?)
4: I found a way to update for example the fill color :)
contaier1.shape1.graphics._fillInstructions[0].params[1] = '#FFFFFF';
(use chrome debugger to look at the _fillInstructions array to see which array position contains your color)
5: I found a way to just paint one container :)
//manual draw 1 component (!)
var a = stage.canvas.getContext("2d");
a.save();
container1.updateContext(a); //set position(x,y) on context
container1.draw(a);
a.restore();

How to implement a timeline custom control with cocoa?

My Cocoa application collects events (instances of NSManagedObject) that need to be displayed in a timeline. My initial approach was to use an existing Javascript based widget (I tried using Simile Timeline and Timeglider) and display the timeline using a WebView control. This works in principle, however unfortunately both these widgets do not handle BC dates very well, which is an important requirement for my app.
The events in my app have date ranges from 500.000BC up to recent dates. Event dates are only expressed with a year. Their day, month and time attributes are irrelevant.
After discarding the Javascript approach, I remain with the option to display the timeline using a custom Cocoa control. As I found none suitable, I will have to develop that myself.
This would be my first custom Cocoa control and after thinking about this for a while I've come up with the following rough design:
I need a custom control to render the actual time line. This control is probably based on an NSView. This control should calculate its size based on the number of tick marks on the time line multiplied by the width (pixels) between each mark. For example the timeline is made up of centuries, each century 100 pixels wide. A time line of events between 10.000BC and 5.000BC would then be 5000 pixels wide (10000 - 5000 = 5000 years, equals 50 centuries).
I need a ScrollView to wrap the timeline to allow it to support scrolling behaviour. There's only need for scrolling horizontally.
I need something to represent an actual event. I'm thinking of using existing controls for this, probably the standard round button and a label wrapped together as a single control.
I need a custom control to render a tick mark on the time line.
Taking this as the basic design for my time line component in Cocoa, would that work or am I completely missing the point?
The basic approach sounds fine.
Apple has a good example of creating a custom NSView called "TreeView". It's a good sample to understand.
https://developer.apple.com/library/mac/#samplecode/TreeView/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010131
“TreeView” presents an example of a creating an entirely new custom
view from scratch (by directly subclassing NSView). Its implementation
illustrates many of the considerations involved in creating a custom
view, including issues of content layout, drawing, handling user
interaction, and providing Accessibility support.
Another thing you may want to consider is zoom in and out. If you have a long timeline, I imagine you may want to zoom out and then zoom in on a cluster of activity. If you have one event in 10k BC and then a cluster of events much later, the user could scroll through tons of empty space trying to find events. Another approach would be to have a mini timeline above that's fit to/static size which is sort of like an index with lines showing activity points - then clicking on that would auto scroll to that point. That may be a nice to have depending on your data.
Some thoughts:
For something this custom drawn, you'll want to override drawRect to draw your lines and layout your subControls.
If you're drawing your background or any part of the views, ensure you enable layer backed views:
[self setWantsLayer:YES];
If you can, as you noted, try leverage existing controls that you add and layout. In my custom controls, I maintained data structures independent of the views/controls that represented the state of all the objects. The in drawRect, I detected the view changing and I called my layoutSubviews function. My layoutSubViews function would do the math from my data structures and create or move the frame of existing controls. That worked well for resize and zooming. If you zoom, your labels ad markers will need to react well to being zoomed really small - perhaps text drops out at some point etc...
if ([self dataSource] &&
!NSEqualRects(_prevRect, [self bounds]))
{
// layoutViews is my custom function that worked over the data structures
// and moved the frame
[self layoutViews];
}
_prevRect = [self bounds];
Hope that helps.

How do I perform my own redraw in the Paint event of a VB6 PictureBox?

A coworker is encountering an error when he tries to run a VB6 app we're working on. The error is, "480: Can't create AutoRedraw image". Microsoft's documentation says this is because "There isn't enough available memory for the AutoRedraw property to be set to True. Set the AutoRedraw property to False and perform your own redraw in the Paint event procedure or make the PictureBox control or Form object smaller..."
Making the PictureBox smaller isn't an option. I'd be glad to "...perform my own redraw in the Paint event procedure...", but I'm not sure how to go about it. Can someone show me the way?
Without details this will be a simplistic answer. In general most beginning VB6 programmers use AutoRedraw=True draw in responds to some input. Fill out some data, click draw, and it appears in the picture box.
The click event in the Draw Button is linked do your drawing code. The first step is move the call to the drawing code to the paint event of the picture. The second step is to replace all calls to the drawing code with MyPictureBox.Refresh. Refresh forces the paint event of that picture box to fire.
The main problem you will have to be concerned with is that the paint event is going to be fired everytime the form needs refreshed. Like if a window covering it is moved. This means that any speed issue in your drawing code will be exposed. AutoRedraw=True takes what you drew and puts in a hidden bitmap that the PictureBox uses to display what you drew.
The Paint event will execute each step of your drawing process so you have to make sure you are as fast as possible. Depending on how dynamic your application is the worse slowdown issues will become. If you are displaying a static image then the problem isn't as bad.
Making the PictureBox smaller isn't an option. I'd be glad to "...perform my own redraw in the Paint event procedure...", but I'm not sure how to go about it. Can someone show me the way?
That is easy. You just implement the _Paint()-Event of your Form or PictureBox and draw.
Because you are asking, i think i should clarify what the AutoRedraw-Propeprty does. If it is set to true, you can "just draw your image" any way you want. In multiple steps. Whatever. If it needs to be redrawn, for example, because another windows was on top it, it will be magically done. The down site is, that is slow, for the drawing part.
If AutoRedraw is false, no magic will happen. The Paint()-Event will be fired and you are responsible to draw your image again. This will be much faster, if your window is not "invalidated" (e.g. "covered") often. Or you are doing a lot of drawing.
Or you are running out of memory for the "magic space" ;-)
If you don't mind rewriting your graphics code to use the GDI API - this could be a fairly big task - I found this thread from 2006 in the VB6 discussion group, where Mike Sutton said in answer to a similar problem:
VB's back-buffer implementation uses a
Device Dependant Bitmap (DDB) to store
the image data, which is quite limited
in how large it can be made. On older
OS' this used to be ~16mb uncompressed
data size, on later OS this has been
expanded but is still quite
restrictive.
A workaround for this is to use a
Device Independent Bitmap (DIB) and
manage the GDI resources yourself,
have a look at the DIB article on my
site for an example of how to work
with them.
I haven't tried it myself.
There's usually a drop-down box of events for your control in the forms code window. You need to pick the paint event:
Private Sub object_Paint()
and fill in your your code for drawing on the PictureBox.

Resources