Pseudo 3D tricks from old computer games for all your Canvas needs

It is quite interesting to see how technology moves in circles. With canvas being the new fun toy to play with for creating browser-based games we have to find solutions to fake a 3D environment to be really fast (sure there is Canvas 3D but it is overkill for most games). The trick is to dig into the tricks arsenal of old-school game development on machines full of win like the Commodore 64 or Amiga.

Louis Gorenfeld some very detailed explanations on how to fake 3D including some of the formulas used in the days of 8 bit.

He is also working on some demo code which you can help him with by providing some JS/Canvas demos:

Fake 3D

CODE:
  1. current_x = 160 // Half of a 320 width screen
  2. dx = 0 // Curve amount, constant per segment
  3. ddx = 0 // Curve amount, changes per line
  4.  
  5. for each line of the screen from the bottom to the top:
  6.   if line of screen's Z Map position is below segment.position:
  7.     dx = bottom_segment.dx
  8.   else if line of screen's Z Map position is above segment.position:
  9.     dx = segment.dx
  10.   end if
  11.   ddx += dx
  12.   current_x += ddx
  13.   this_line.x = current_x
  14. end for
  15.  
  16. // Move segments
  17. segment_y += constant * speed // Constant makes sure the segment doesn't move too fast
  18. if segment.position <0 // 0 is nearest
  19.   bottom_segment = segment
  20.   segment.position = zmap.length - 1 // Send segment position to farthest distance
  21.   segment.dx = GetNextDxFromTrack() // Fetch next curve amount from track data
  22. end if

Román Cortés and Ajaxian make up with amazing CSS demos

We have been long term fans of Román and the fantastic demos and samples that he puts together, usually involving CSS goodness. We messed up the other week though when we linked to his work on a scrolling coke can. I do these postings as a labor of love, and since Ajaxian isn't my day job, that means that the labor often happens at 2am. In this case I made the rookie mistake of grabbing an iframe to his demo so it would run inline. Román then looked up to see his servers getting pummeled and a bill is associated with that traffic. He quickly rick rolled us (thank you for not going for something much worse ;) and Christian Heilman (who is in Europe along with Román) saw it and kindly switched in an image of the code can effect.

I woke up the next morning to learn about this all and see a post that Román did talking about our hot linking. I immediately responded saying how sorry I am. I aim to highlight the great work that is done, not cause an issue.

Román is a great guy and kindly offered to collaborate and show friendship with Ajaxian (and myself) by putting together more amazing demos to share on the blog. Inline. Not hot-linking. :)

Here they are

These effects are CSS level 1 and 2.1 only. There is no javascript, css3 or whatever, just html and css.

They are all based on the CSS 2D displacement map technique that Román Cortés discovered when he created the infamous CSS Coke Can effect. Since displacement maps are very versatile, Román Cortés wanted to show us more and different applications of these.

The Ajaxian Prism

This is simple displacement map usage to distort the borders of the prism, with a transparent .png image on top to add the shadows, orange semi-transparent bg and the Ajaxian's "a" logo. The background painting is an original artwork by Román Cortés. Move the area around to see the effect the prism has on the underlying painting.

ajaxianprism

Van Gogh's Starry Night

Van Gogh's Starry Night separated in 3 layers and displacement map sinusoidal distortions applied to two of them.

starrynight

Sliding and Slicing

A really simple displacement map + rearranged image makes this effect possible. Watch the window blinds do their thing as you move the scollbar.

romajaxian

The Coke Can spinning in the opposite direction of the original

There some comments in the original code can posting that the spinning direction was unnatural. So, here he did spin as the commenters wanted it. To make it possible, he had to mirror the label texture and adapt the source code.

The smashed can

By using several cylindrical displacement map layers with a growing radius and png transparent textures, it is possible to do voxel surface rotations like this one.

crashedcokecan

Thanks for Román for being so reasonable, and for creating such fun examples for us all. We hope to go deeper on the implementation of some of these examples in the future.

Built-in Charting Controls (VS 2010 and .NET 4 Series)

[In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

This is the fifteenth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release.  Today’s post covers a nice addition to ASP.NET and Windows Forms with .NET 4 - built-in charting control support.

ASP.NET and Windows Forms Charting Controls

A little over 14 months ago I blogged about how Microsoft was making available a free download of charting controls for both ASP.NET 3.5 and Windows Forms 3.5. 

You can download and use these runtime controls for free within your web and client applications today.  You can also download VS 2008 tooling support for them.  They provide a rich set of charting capabilities that is easy to use.  To get a sense of what all you can do with them, I recommend downloading the ASP.NET and Windows Forms sample projects which provide more than 200 samples within them.  Below is a screen-shot of some pie and doughnut chart samples from the ASP.NET sample application:

image

Charting Controls Now Built-into .NET 4

With .NET 3.5 you had to separately download the chart controls and add them into your application.  With .NET 4 these controls are now built-into ASP.NET 4 and Windows Forms 4 – which means you can immediately take advantage of them out of the box (no separate download or registration required). 

Within ASP.NET 4 applications you’ll find that there is now a new built-in <asp:chart> control within the “Data” tab of the Toolbox:

image

You can use this control without having to register or wire-up any configuration file entries.  All of the charting control configuration is now pre-registered with ASP.NET 4 (meaning nothing has to be added to an application’s web.config file for them to work).  This enables you to maintain very clean and minimal Web.config files.

Learning more about the <asp:chart> control

Scott Mitchell has written a great series of articles on the www.4guysfromrolla.com site on how to take advantage of the <asp:chart> control:

  1. Getting Started - walks through getting started using the Chart Controls, from version requirements to downloading and installing the Chart Controls, to displaying a simple chart in an ASP.NET page.
  2. Plotting Chart Data - examines the multitude of ways by which data can be plotted on a chart, from databinding to manually adding the points one at a time.
  3. Rendering the Chart - the Chart Controls offer a variety of ways to render the chart data into an image. This article explores these options.
  4. Sorting and Filtering Chart Data - this article shows how to programmatically sort and filter the chart's data prior to display.
  5. Programmatically Generating Chart Images - learn how to programmatically create and alter the chart image file.
  6. Creating Drill Down Reports - see how to build drill down reports using the Chart control.
  7. Adding Statistical Formulas - learn how to add statistical formulas, such as mean, median, variance, and forecasts, to your charts.
  8. Enhancing Charts With Ajax - improve the user experience for dynamic and interactive charts using Ajax.

His articles are written using .NET 3.5 and the separate ASP.NET charting controls download – but all of the concepts and syntax work out of the box exactly the same with ASP.NET 4.

Michael Ceranski has also written a blog post demonstrating how to use the ASP.NET Chart control within an ASP.NET MVC application.  I’m hoping someone will create some nice ASP.NET MVC Html.Chart() helper methods soon that will make this even easier to do in the future.

Hope this helps,

Scott

Mozilla Labs’ Weave can become a platform for us

weaveitup

Mozilla Labs has released the magical 1.0 version of Weave and the doors are now open for developers.

When I was a part of Mozilla Labs day to day, I always loved the vision and team behind Weave. I kept wanting the implementation to match the vision, but it is a tough problem and it takes time to bake. Well, it is getting there now.

Weave is special because it offers a series of back-end services (more than just sync) that are build with users (and their privacy) in mind, rather than business models. I have talked to a couple of entrepreneurs recently and thought that there ideas could be implemented nicely on top of Weave.

It is still early days, but I am jazzed to see the platform getting opened up. I am hoping to get clients for Safari, Chrome, and IE…. and look forward to a webOS client too :)

AT AT Walking with CSS

Anthony Calzadilla has a fun Friday example for us. He has a tutorial on how he animated an AT AT using CSS.

He goes over the different areas and how he uses animation and transforms.

For example, the head of the beast:

CSS:
  1.  
  2. @-webkit-keyframes rotate-head{
  3.   0% {-webkit-transform:rotate(0deg) translate(0px,0px);}
  4.   40% {-webkit-transform:rotate(10deg) translate(15px,5px);}
  5.   80% {-webkit-transform:rotate(-5deg) translate(8px,5px);}
  6.   100% {-webkit-transform:rotate(0deg) translate(0px,0px);}
  7. }
  8. #atat #head {
  9.   -webkit-animation-name: rotate-head;
  10.   -webkit-animation-duration: 7s;
  11.   -webkit-animation-iteration-count: infinite;
  12.   -webkit-transform-origin: 0 50%;
  13. }
  14.  

ASP.NET MVC 2 (Release Candidate 2) Now Available

[In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

Earlier this evening the ASP.NET team shipped ASP.NET MVC (Release Candidate 2) for VS 2008/.NET 3.5.  You can download it here.

The RC2 release of ASP.NET MVC 2 is a follow-up to the first ASP.NET MVC 2 RC build that we shipped in December.  It includes a bunch of bug fixes, performance work, and some final API and behavior additions/changes.  Below are a few of the changes between the RC1 and RC2 release (read the release notes for even more details):

  • The new ASP.NET MVC 2 validation feature now performs model-validation instead of input-validation (this means that when you use model binding all model properties are validated instead of just validations on changed values of a model).  This behavior change was based on extensive feedback from the community.
  • The new strongly-typed HTML input helpers now support lambda expressions which reference array or collection indexes.  This means you can now write code like Html.EditorFor(m=>m.Orders[i]) and have it correctly output an HTML <input> element whose “name” attribute contains the index (e.g. Orders[0] for the first element), and whose “value” contains the appropriate value.
  • The new templated Html.EditorFor() and Html.DisplayFor() helper methods now auto-scaffold simple properties (and do not render complex sub-properties by default).  This makes it easier to generate automatic scaffolded forms.  I’ll be covering this support in a future blog post.
  • The “id” attribute of client-script validation message elements is now cleaner.  With RC1 they had a form0_ prefix.  Now the id value is simply the input form element name postfixed with a validationMessage string (e.g. unitPrice_validationMessage).
  • The Html.ValidationSummary() helper method now takes an optional boolean parameter which enables you to control whether only model-level validation messages are rendered by it, or whether property level validation messages are rendered as well.  This provides you with more UI customization options for how validation messages are displayed within your UI.
  • The AccountController class created with the default ASP.NET MVC Web Application project template is cleaner.
  • Visual Studio now includes scaffolding support for Delete action methods within Controllers, as well as Delete views (I always found it odd that the default T4 templates didn’t support this before).
  • jQuery 1.4.1 is now included by default with new ASP.NET MVC 2 projects, along with a –vsdoc file that provides Visual Studio documentation intellisense for it.
  • The RC2 release has some significant performance tuning improvements (for example: the lambda based strongly-typed HTML helpers are now much faster).

Today’s RC2 release only work with VS 2008 and .NET 3.5.  We’ll shortly be releasing the VS 2010 RC (which will be available for everyone to download). It will include ASP. NET MVC 2 support built-in (no separate download required).

Hope this helps,

Scott

P.S. The source code for the ASP.NET MVC RC2 release (along with a MVC futures library that goes with it) can be downloaded here. You can learn even more about ASP.NET MVC 2 by reading the ASP.NET MVC 2 blog series I’m working on.

jsContract: Design by Contract library

Fan of Eiffel or the design by contract pattern that it espouses?

Øyvind Kinsey is, and he just created jsContract an alpha library to give you some pre and post condition abilities.

Here is an example:

JAVASCRIPT:
  1.  
  2. function _internalMethod(a, b){
  3.     Contract.expectNumber(a);
  4.     Contract.expectNumber(b);
  5.     Contract.expectWhen(config.mode === "divide", b> 0, "Divisor cannot be 0");
  6.     Contract.expectWhen(config.mode === "multiply", a> 0 && b> 0, "The multiplicands cannot be 0");
  7.     Contract.guaranteesNumber();
  8.     Contract.guarantees(function(result){
  9.         return result> 0;
  10.     }, "Result must be> 0");
  11.  
  12.     if (config.mode == "divide") {
  13.         return a / b;
  14.     }
  15.     // At this point config.mode must be "multiply"
  16.     return a * b;
  17. }
  18.  

A lot of contract code for little functionality.... good old contracts ;)

It is interesting to read how Øyvind instruments the code. Run a test through the translator tool and you get:

JAVASCRIPT:
  1.  
  2. function _internalMethod(a, b){
  3.     arguments.callee.isInstrumented = true;
  4.     /*preconditions*/
  5.     Contract.expectNumber(a);
  6.     Contract.expectNumber(b);
  7.     Contract.expectWhen(config.mode === "divide", b> 0, "Divisor cannot be 0");
  8.     Contract.expectWhen(config.mode === "multiply", a> 0 && b> 0, "The multiplicands cannot be 0");
  9.     var __return = (function(a, b){
  10.         if (config.mode == "divide") {
  11.             return a / b;
  12.         }
  13.         // At this point config.mode must be "multiply"
  14.         return a * b;
  15.     }(a, b));
  16.     /*postconditions*/
  17.     Contract.guaranteesNumber(__return);
  18.     Contract.guarantees(__return, function(result){
  19.         return result> 0;
  20.     }, "Result must be> 0");
  21.     return __return;
  22. }
  23.  

User scripts becoming more portable with Greasemonkey support in Chrome

Aaron Boodman created Greasemonkey back in the day. He also worked on Gears. And most recently he created Chrome Extensions. I have a funny feeling that folks were pinging him daily “hey, when ya gunna give me Greasemonkey on Chrome” and he just delivered:

One thing that got lost in the commotion of the extensions launch is a feature that is near and dear to my heart: Google Chrome 4 now natively supports Greasemonkey user scripts. Greasemonkey is a Firefox extension I wrote in 2004 that allows developers to customize web pages using simple JavaScript and it was the inspiration for some important parts of our extension system.

Ever since the beginning of the Chromium project, friends and coworkers have been asking me to add support for user scripts in Google Chrome. I’m happy to report that as of the last Google Chrome release, you can install any user script with a single click. So, now you can use emoticons on blogger. Or, you can browse Google Image Search with a fancy lightbox. In fact, there’s over 40,000 scripts on userscripts.org alone.

Not all of the scripts will work. The deeper the integration, the less chance of success. We now have user scripts supported in a variety of browsers, and hopefully they get more and more portable.

If browsers could surface the functionality to mainstream users, good things could happen beyond us power users.

LunaScript: A new language and platform to take your Web 2.0 apps to the moon?

A Googler and a Facebooker were in a pub discussing the complexities of building out a rich modern Web application. There are a ton of dependencies, and you need to be proficient in multiple languages and tools (JavaScript, HTML, CSS, SQL/NoSQL, backend languages, build tools, etc).

Well, they may not have been in a pub.... but a deadly duo did get together to try to solve this problem.

Dustin Moskovitz (Facebook co-founder and former CTO) and former-Googler/Facebooker Justin Rosenstein decided to try something different when they started to implement a Collaborative Information Manager tool at their new startup . They have created a new high level language that is part JavaScript, part Protocol Buffers. The language is LunaScript.

What was their motivation?

All of us on the Asana team have deep backgrounds writing rich web applications at companies like Google and Facebook. We've been continually frustrated by how long it takes to write software, and by a nagging feeling that in some deep sense we've been writing the same code over and over. Even when using the latest and greatest frameworks and disciplines, writing fast, highly interacting web applications involves a lot of accidental complexity:

First you need server code to figure out what data the browser needs. Hopefully you have an ORM layer, but you still need to carefully structure your code to minimize your backend dispatches, and you need to carefully keep that in sync with your front-end code lest you don't fetch enough data or hurt performance by fetching too much. If it's a Web 2.0-style app, you re-implement a ton of that server-side code in JavaScript, once for creating the page and then again as controller code for keeping it up to date and consistent. And when the user changes something, you bottle that up -- typically in a custom over-the-wire format -- and send it as an XHR to the server. The server has to de-serialize it into different data structures in a different language, notify the persistence store, figure out what other clients care about the change, and send them a notification over your Comet pipe, which is handled by yet more JavaScript controller code. Offline support? More code.

This is not a one-off task: it's rote work that adds complexity to every feature that you build in every application. By the time that you are done with all this, the important and novel parts of your application are only around 10% of your code. We wondered whether we could build a programming system in which we just wrote that 10% -- the essential complexity -- and a compiler handled the other 90%.

And this lead them to their solution:

Inspired by incremental computing, we're building Lunascript as a simple way to write modern web applications. Lunascript has a syntax and easy of use reminiscent of JavaScript, but a powerful pure-functional lazily-evaluated semantics historically confined to academic languages.

A Lunascript application specifes a data model and a function from the model to the view or user interface, annotated with handler functions from user inputs to model mutations. From this the Lunascript compiler produces a functioning Web2.0 application -- the client-side JavaScript, the server-side SQL, and everything in between -- complete with real-time bidirectional data synchronization. There's no need to write separate code to help the server figure out which values need to be sent to the client: the server can do this by simulating the UI. Because a LunaScript application only specifies how the UI should look given the current data (rather than how the UI should be updated as changes happen) it's impossible to write a UI that loads correctly but does not stay correct as changes are made.

"What does it look like?" I hear you cry. Time for a hello world, and since Comet is in the mix, that means a chat server:

JAVASCRIPT:
  1.  
  2. // Some of our currently implemented syntax isn't quite this clean, but it's
  3. // fairly close and this is the direction we're going.
  4.  
  5. class World {
  6.   // "1." serves the same purpose as "= 1" does in Google protocol buffer syntax.
  7.   1. ChatMessage[] messages;
  8. };
  9.  
  10. class ChatMessage {
  11.   1. User user;
  12.   2. string text;
  13. };
  14.  
  15. class Session {
  16.   1. User user;
  17.   2. String new_comment;
  18. };
  19.  
  20. return fn(world, browser, session) {
  21.   var renderMessage = fn(message) {
  22.     // Most style information omitted to improve readability.
  23.     var bubble_style = { background: '#b7e0ff', padding: 7, ... };
  24.  
  25.     return <div>   // XML literals are first-class primitives.
  26.       <img src=message.user.small_pic_url />
  27.       <div style=bubble_style>
  28.         <b> message.user.name, ': ' </b>
  29.         <div> message.text </div>
  30.       </div>
  31.     </div>;
  32.   };
  33.  
  34.   var postMessage = fn() {
  35.     // Only handler functions can request data mutations.
  36.     messages += ChatMessage {
  37.       user: session.user,
  38.       text: session.new_comment
  39.     };
  40.     session.new_comment := '';
  41.   };
  42.  
  43.   return <table>
  44.     <tr><td>
  45.       messages.map(renderMessage)
  46.     </td></tr>
  47.     <tr><td>
  48.       <img src=(session.user.small_pic_url) />
  49.       <div>
  50.         <input data=session.user.name /> <b>' (your nickname)'</b>
  51.         <form onsubmit=postMessage>
  52.           <input data=session.new_comment hasFocus=true />
  53.         </form>
  54.       </div>
  55.     </td></tr>
  56.   </table>;
  57. };
  58.  

You will notice the protobufferness at the top, and the fn of less characters, and E4X-like.

To learn more, let's listen in to Dustin as he gives us a walk through the world of LunaScript:

I talked to the guys and asked a few questions which they answered..... what questions do you have for them though? Are you excited about what a higher level abstraction could give you? Or do you like to be close to the metal?

New Version of SVG-Edit

SVG-Edit is a nifty open source editing web app that uses SVG and doesn’t need a server-side:

svg-edit-screenshot1

The SVG-Edit team recently announced SVG-Edit 2.4, code named Arbelos. New features include:

- Raster Images
- Group/Ungroup
- Zoom
- Layers
- Curved Paths
- UI Localization
- Wireframe Mode
- Change Background
- Draggable Dialogs
- Resizable UI (SVG icons)
- Convert Shapes to Path

Try out the demo here:
http://svg-edit.googlecode.com/svn/branches/2.4/editor/svg-editor.html

Check out the project page:
http://svg-edit.googlecode.com

Read the release notes:
http://code.google.com/p/svg-edit/wiki/VersionHistory