2013-03-14

$w(css,parentNode) as WidgetList (NodeList on steroids)

Story in development, the post will be modified as ongoing design changed.

The CSS selector for widget's content has been used for a while by dojoplay2012/lib/TemplatedWidget. It allows the query to scope by widget's content and handy for group operations given by NodeList:

this.$(".classInChild").html("");

This interface has been extended to get sub-child widget

this.$w(".classInChild").resize();


At the moment $w() returns only first widget but it would be handy to operate with all widgets with same call. So the expression above will resize() all matching children rather first only.

Following the NodeList chaining concept, would be nice to have calls chained.

this.$w(".classInChild").update().resize();

WidgetList will be returned on each call to support the chainig. That could be achieved by wrapping returned widgets into object which will simulate each method call invoking each widget one and returning WidgetList.

To access results of last call :
this.$w(".classInChild")
    .resize(maxDimentions)
    .getSize()
    .forEachResult(function(sz){ total.x+=s.x; });

COST

When WidgetList is created there is no way to define ahead which method will be called as a first in the chain. Which will have an overhead of wrapper creation for each method name in each returned object.
Each call could potentially change widget set and it's  interface and as result WidgetList and methods map need to be updated. While API changing of widgets could be ignored assuming no changes during WidgetList existence, DOM changes are little trickier to guess.

WAYS AROUND
The chaining by member method name could be substituted with explicitly set function name set in first parameter:

this.$w(".classInChild")
    .call( "resize", maxDimentions )
    .call(  "getSize"  )
    .forEachResult( function(sz){ total.x+=s.x; } );

Another short version of above using return the function instead of object:

this.$w(".classInChild")
    ( "resize", maxDimentions )
    (  "getSize"  )
    .forEachResult( function(sz){ total.x+=s.x; } );


Such call convention will prevent creation of mappings hence could help with extra memory and CPU during execution. But it makes code less elegant and readable. The simple string substitution during compilation could convert original "nice" syntax to "efficient" one.

Comments and suggestions are welcome.

2013-02-12

Stateful object history vs change journal DB patterns

During creation of retail sales module I have come over 2 different patterns dealing with history of object.
On one side each atomic operation need to be preserved for audit reasons. Which makes a patter of journalling of change records. The current object state in such pattern is a sequential combination of journal records. In the best case it is just a last record.  In worst it is a set of business rules applied over the sequence. In order to keep track of current state all records should be preserved.

As alternative instead of keeping change records as primary source for current state the object's state itself could serve as historical record. That would eliminate the need for extra table per entity(change one).

As the history is still is requirement, each change should have a matched record in HISTORY namespace. This namespace could reside as in another DB as in same but under another high-availability profile(partition, etc.)

There is another frequently used pattern which goes along with history track. Comments. The comment often accompanied the change but on another hand comment could be just a verbal instruction. While the 1st fits into change content, the comment without a change looks as overkill as it wasting the object state for "no reason". But if we look from the data integrity prospective the object state is a part of comment. I.e. without object state as whole comment has no track value.

The interesting side effect of history pattern is that schema will be preserved as on current objects snapshot as in history namespace. I.e. there is no need to increase DB schema complexity to add history track.

Having the state embedded into object rather using journal assumes the data from change will embedded into object. Normalized schema will allow to preserve minimal data footprint ( the change will have only changed fields and reference to obj ). Fusing the change and other object fields will preserve. Could the increase of db table size be justifiable? And what are the criteria?

1. DB schema simplicity. As stateful object itself comprise all potential changesets there is no need for keeping relations between change and object. During prototyping phase it is a strong argument. As well as in  conditions of stressed development resources.

2. DB performance effect.
The journalling allows to insulate change operations and avoid affecting of other object properties. Here the current object state is not simple extraction: query or complex procedure are giving the cumulative result. The optimization of such cases leads to creating the cached (either withing object or aside) "current" state. Which in fact is same pattern as stateful object except of some complexity on top of it. As stateful object reflects all kind of changes, tuning of each use case still in place(indexing, partitioning,etc). But it gives ability to separate statistics and troubleshooting( history review) optimizations within dedicated environment(HISTORY namespace). The most real-time namespace is "current" state is extracted from way larger volume of historical data and as result could be held in high-available profile.

The sync with history for stateful object could be done over generic queue-ing. Which will allow to decouple
RT and HISTORY namespaces. Obviously sync need to be in place when looking on RT data withing HISTORY. But that is a rare case as most of HISTORY operations(troubleshooting or reports) are done way beyond of queue flush time( days vs minutes)

3. DB integrity. While journalling permits to use strictly normalized schema, it is also subject for DB corruption or cost of transactional lock. Unlike that, operations over stateful object are atomic by definition(no object references) and do not require any locks.

4. For stateful pattern the State flow implementation gain simplest implementation. Either service which does the change initiates next step in the flow. Or it could be done natively by DB triggers (not my case but DB-centric apps will value it a lot).

5. Security. Stateful approach also given ability to create extra DB user profiles which in case of ShoppingCart could be a business/audit requirement. More discreet access to historical vs current state data, excluding any changes in HISTORY namespace are shaping true multi-tiered security.
Conclusion. If the project is stable and size + performance dominate the  development cost, journal records pattern could win. In other cases (including mine) Stateful pattern is the way to go. Hooray to conscious simplicity!

2013-02-01

The internal combustion engine without batteries, generator and starter

There was a news article on ability to ignite ICE using its own chambers for the first push. No details, but in a week later the whole chain of relative ideas came over.

It looks like modern gasoline cars could loose the weight(and read the cost) of batteries, generator and starter(which sometimes combined with generator). The heavy weight of those three components along with additional load on engine to spin the generator is good reason to improve the efficiency/performance.

The diesel engines are ignited by compressed fuel which requires quite more energy to start in comparison with simple fuel injection and spark in gasoline one. I will set diesel aside for now, lets see what could be done in gasoline car.

Complete removal of electrical storage does not seem possible as fuel ignition requires a spark (gasoline engine) not only for initial start but also during work cycle. But for this purpose the amount of energy will be significantly less than carried in current car batteries.

Most of us have more than sufficient energy to produce the spark with a twist of thumb. The piezoelectric gas lighter is a prove. The last peace in this puzzle is fuel injection. Could it use same energy from car keys twist? Hmm... possibly. As a last resort, gas pedal could serve as additional starting energy source. Perhaps it recall the time when initial fuel injection was controlled manually in carburetor :)

The small amount of electricity to support the work cycle could be stored in small capacitor. I remember the times where it was used instead of dead batteries. But at such situations spinning of generator was a pain - the classic engine required full spin by starter. Or as in 100 years ago, make a starter from your own hands.

How the generator could disappear? It could not. But classic generator is not required anymore. Instead few wire rings making an electromagnetic coil fused into ceramic cap of engine plus magnetized plunger will render enough energy to keep the cycle of gas pump, injector and ignition. As motor gain enough RPM, amount of generated electricity should fulfill whole car's needs.

Reduction of batteries volume will affect on ability to use the car lights and say stereo without engine on. Seems bad... But if you think of the gasoline as a electricity source it will be justifiable. Obviously the engine should be working as efficient generator.

I love the car without gears, transmission, all-wheel powered with independent torque (and even spin direction) control. More light-weight and efficient.

Which come to the next generation: fusion of ICE with generator.
Details for that idea are following...

2013-01-30

The pattern of using fake functions parameters instead of var declaration in JavaScript

Many JS geeks making bazaar tricks to shrink the code as much as possible. While it makes the code readability worse and as result less reliable, it pays back with saving a byte or two making them proud.

There is my attempt to recover the damage by balancing it with some benefits.

sample 1 function(par1, par2, var1, var2, var3,i,j,x,y,z,k,w,n,m)

par1, par2, - Using parameters is out of scope of this article, just a note on the good habit to keep them read-only.

var1, var2, var3 - the local variables which are usually declared with var:

sample 2 var var1, var2, var3;
The good thing about such kind of declaration that along with declaring the variable it could be initialized.
IMO it is bad to have any uninitialized variable. Which means no ahead-declaration. The variable should be declared in place where it used and all initialization data are available:

sample 3 for( var x=0...)
for( var y=x ... )

But scripting guys do that all over thinking of saving bytes for "var " string and replacing with list of variables(as in #2, #4):
sample 4 var x,y;
for( x=0...)
for( y=0 ... )

5 more bytes ('var ' and ';')could be taken away by having local variable declared as function parameters:

sample 5 function (x,y)
for( x=0...)
for( y=0 ... )
The list of useful side effect will appear:
  1. shrinking the code footprint
  2. no global scope variables mistakenly assigned(#6)
    sample 6 function ()// no x is declared in the function
    for( x=0...) // here the global scope 'x' assigned
  3. questionable but will be loved by scripters(yuck) - declaring of all variables in single comma-separated list.

To prevent potentially missing declaration variables usually used in local scope (i,j,o,r,d,x,y,z,k,w,n,m) could be listed in complex functions as the safeguard.
The compilers could do the optimization quite well. Not sure whether relocation of variable declaration into function parameters is an option there.

2012-12-20

Images embedding into HTML

Currently known image use in HTML do not have a support of reusing:
  • IMG tag do not refetch the file, but still issues http request
  • CSS background-image keeps the image in backround. Still it is the most powerful since it allows to reuse the image, pick the tiles, associate with CSS rule switch animation.
  • SVG embedding allow to reuse the image only by reusing its source text. Each image will have own instance in browser.
JS has a powerful gears for image reusing. The cloning image node will keep the same image reference. Unfortunately this optimization did not sneaked into JS libraries I am using.

Q. How to make image reusing convenient and still efficient on browser side?

Will be the preprocessor of HTML template the proper answer?
  1. It could strip off the URLs from IMG tags. Say by renaming src attribute.
  2. Load the image say in hidden node, keep it in global url to img map
  3. Upon image load and when widget dom is ready, roll over all IMG-es in DOM and swap with clone of cached one; apply all original attributes and CSS.
This method should work as compiler layer + runtime patch to DTK templated widgets;

PS. This note is just a response on multiple attempts around on image use optimization. As plain idea it is not worth anything, so bug me if you see the need for code or help there.

2012-12-05

ASSERT in JS

Usually asserts are not destructive. I.e. even if condition false-d, the code still working. Your evaluations throw-ing exceptions and changing the logic. Also there is a some additional logic resides in assert call:
  • in release build the code is disabled, ideally removed by compiler
  • log output with caller function
  • log evaluated value
  • log comment string
  • breakpoint call
Extra things I do in C++ and could potentially port to JS:
  • modal dialog with assert info(above)
  • ability to ignore further( do not display dialog), retry(repeat the condition call)
  • counter for particular assert failures
  • log not just to comsole but also to external target like FS or server.
There are some related patterns applied in debug mode
  • automatic parameters and return value check against type and permitted values. That should have the type definition and values/validators be available in run-time. Used Annotation for that. The call traps need enumeration of object's methods and wrapping by aspect.
  • Profiler( call counts+timing, call graph, etc) is not a hot topic anymore since most of browsers have them implemented. But in many cases like mobile, it worth to have the profiler be implemented by JS and hooked into server-side logger.
Final assert call I envision as such:

while( assert && assert( isDomNode(param1), "should be a valid dom node") );

or simpler form:

assert && assert( isDomNode(param1), "should be a valid dom node");

assert && assert(...) gives ability to disable assert for release build on AMD module switch level. It also could be used for individual module tuning.
while( assert(...) ) needed for "Retry" option. Handy for debugging. When problem found, the same condition could be reevaluated for step-through debugging.

Annotations and aspects are the gears for such functionality. 25% of above I have done earlier but not made a shippable tool. It is too big effort to be justified by projects I was working on at the time. If anyone interested we could talk further.

2012-07-18

Use of dynamic css as HTML5 game play engine


CSS transforms are neat and powerful effects engine in HTML. Besides of HTML it could be used for SVG graphics on same page.
And what has been only web page with SVG became serious gaming platform.
For JS developer it would be straight to implement most of gameplay and scene control using JS+canvas leaving some effects to CSS.

But when a kid asked me to help with building the game, functional/aspect programming appeared to be easier. It is quite simple to explain that by adding class name to character's dom node its appearance and behavior changed accordingly.
To add little attraction to this approach, CSS-driven effects are way more efficient than same with JS. Less CPU, easier development.
Not to mention more reliable code: no memory leaks, JS closures, etc.

Obviously CSS is not much designed to change the DOM, hence the gameplay could not be completely covered by this approach (see disclaimer on active CSS)
So what are the layers and what benefits to chose technology for each?
1. DOM as model
For simple arcade the visual and business object model have a 1:1 match. In this case there is no need to separate game and UI objects. Implemented as DOM subtree character or scene will be able to preserve and manipulate own data utilizing as JS as native browser capabilities.
  • Having screen coordinates matching the game scene will fuse native rendering, motion and colorspace/transparency/fog/shadow effects supported by browser.
  • Zoom could be applied by changing the default font size and defining the model in em units. To make it even more attractive, the focus subscene or object could have dynamic font-size allowing to zoon-in or grow the character without affecting other model parts. Achievable by class name.
  • DOM subtree as scene component/character. It is hard to enumerate what adwantages could be gained. Some of them:
    • Design and develop as independent module (HTML, CSS, transformations, behavior). From HTML space SVG for vector graphics, GIF animation(see disclaimer), etc.
    • Event-driven interaction. Native declaration and handling. Native events( mouse, swipe,etc) support along with no model parameters conversion( this is reference to node which is same as in UI as in model, model coordinates == screen coordinates). Event propagation interface and handling.
    • Ow, forgot about tons of docs and help on HTML and CSS.

2. Behavior definition.
Primarily defines reaction of the system and its parts on various kinds of events. Literally event-driven engine.
There are multiple implementations I could think of. At the moment could not make any preference.

  • JS. By picking the library with artificial + native event support and transform/effect most of the needs are covered. Other features are depend of project complexity and personal view. Such things as modularity, compilation, documentation, etc. really could be skipped.
    JS itself is not oriented for the task and only libraries could give enough abstraction for event-driven behavior definition.
  • Event definition and transformations chaining is native part of SVG. While the language is not perfect itself, it gives native (read most efficient) support and prevents such mistakes as hanging event chain(when broken in the middle of execution), memory leaks, object and timing conflicts. Need to check cross-browser capabilities.
3. Support and low-level functionality.
Many app sides like saving to database, communication with server(s) belong to "support" or "service" layer. So far I see only 1 choice: JS. Better with sufficient featureset library. DTK for example.

The game is not only about visual interaction but also about sound. Not just background music but rather interactive and event-driven. While HTML5 has support for such, it is possible to utilize multiple sound player widgets with events and sound level control.
Unlike visual the sound sources count need to be more limited to avoid unrecognizable mash-up. The proper join of sound source with associated scene component(s) and ability to switch the vocal focus requires separate implementation of sound players stack and visual game model.

Voice or/and video communication creates another dimension for gameplay. Those have own set of requirements and definitely should be dedicated in own layer. Quite often dominating for resources consumption. This part is not necessary need to be embedded into game scene. For resources distribution reasons it worth to keep it even in separate frame or even window. Multiple monitors are not exception novadays.

Disclaimer.
Active CSS assumes to associate behavioral patterns with class names. Some browsers have sufficient support for such( lovely HTC, or poor Mozilla ones), but there is no good unified native cross-browser solution.
This gap has been closed by jQuery.live approach on JS level, but in this case we have poor JS performance. Being purist on my own, I do not see the benefit for gameplay logic completely covered by CSS class names manipulation.
3D rendering and stereo. Unfortunately it is somewhere in the future for cross-browser development. But if you have in mind customized WebKit(?) environment, than many principles of this article could be applied now.
GIF animation. While it seems familiar and simple solution, it is quite inefficient in terms of control and resources. On one side it is raster graphics and needs pre-scale(saved in larger than usual use dimensions) to support acceptable quality. On another side consolidation of GIFs into single tiles file seems to be heavy for resources and should have synch animation effect. Never tried thought :) Alternatives with SVG transform- or CSS-transform driven animations given way more control and flexibility along with smaller memory and CPU footprint. Forgot to mention "skinning" of characters which is difficult to achieve in GIF and so easy by SVG. Skinning is applying for same element coloring by team, incremental details upgrade, etc. The goal should be skinning control by the node class name changing as most memory(same node and image) and CPU(native transformations) saving .

Happy coding!