Dark Bit Factory & Gravity
PROGRAMMING => Coding tutorials => Topic started by: benny! on November 20, 2011
-
How to get started with TinyC5
Introduction
Welcome to this small tutorial about how to get started with TinyC5 development. This tutorial assumes that you ...:
- have basic coding knowledge
- have heard about TinyPTC/Pixeltoaster and/or framebuffer stuff
- have some basic knowledge about HTML and javascript
Before we start, just another short list of what this tutorial is not/not about:
- complete
- bug-free ;-)
- advanced
- producing great graphic effects
All files of this tutorial are attached.
Step 01
Let's start off with the most minimal example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/TinyC5-0.6.js"></script>
<script type="text/javascript">
function main() {
new TinyC5().start();
}
</script>
</head>
<body onload="main()">
</body>
</html>
Assuming that you know the basic structure of a standrad HTML page, let's focus on the important bits, actually only 2 lines.
With the followin line we include the TinyC5 library code:
<script type="text/javascript" src="js/TinyC5-0.6.js"></script>
Within the main-function, which is called after the page is successfully loaded, we create a new instance of TinyC5 and immediately call the start method.
new TinyC5().start();
Result
We see a black square on the screen with the dimensions of 320x200 pixels, which are the default values. The black square is actually our drawing buffer, ie. canvas (http://en.wikipedia.org/wiki/Canvas_element) which is appended by default to the body element.
(http://www.dbfinteractive.com/adminteam/benny/TinyC5/tutorial/step01-02.JPG) (http://www.dbfinteractive.com/adminteam/benny/TinyC5/tutorial/step01.html)
Step 02
In the second step we restructure our code. This will show us the different parts of how to setup a TinyC5 instnace. The important bits are as follows. We replace the code of the main funciton with the following lines:
var tinyC5;
tinyC5 = new TinyC5();
tinyC5.init();
tinyC5.update = function() {};
tinyC5.start();
Line 1: Declare a variable that will refer to our TinyC5 instance.
Line 2: Assign to our tinyC5 varibale a new instance of TinyC5.
Line 3: Initialize out TinyC5 instance.
Line 4: Overwrite the update property of our instance with a new function, which we leave is empty for now.
Line 5: Start the animation of our tinyC5 instance.
Result
The outcome is the same as in Step 01. But this time we have created a detailed setup of our TinyC5 instance we can build on in future steps.
(http://www.dbfinteractive.com/adminteam/benny/TinyC5/tutorial/step01-02.JPG) (http://www.dbfinteractive.com/adminteam/benny/TinyC5/tutorial/step02.html)
Step 03
In this step we beautify our application while adding some more CSS/HTML to our code. In addition, we define some arguments which we pass to the TinyC5.init() function to overwrite certain default values.
New CSS/HTML code. No magic in here really.
Include some styles...
<link rel="stylesheet" type="text/css" href="css/styles.css" />
Add some more HTML to our body...
<div id="container">
<div id="tinyC5_container">
</div>
</div>
<div id="footer">
Tutorial | Created with <a href="http://www.dbfinteractive.com/forum/index.php?topic=5397.0">TinyC5</a>
</div>
Then we define a new variable that we pass as argumennt to TinyC5.init(). The argument is a simple proterty object which values will configure the TinyC5 instance.
Lines we modified:
var tinyC5, args;
tinyC5 = new TinyC5();
args = {
width: 160,
height: 100,
scale: 2,
title: 'Tutorial | TinyC5',
bgColor: tinyC5.color( 155, 255, 100, 255 ),
container: document.getElementById( 'tinyC5_container' )
};
tinyC5.init( args );
Line 01: Added delcaration for args.
Line 03: Assigned property-object to args. Most properties should be pretty self-explanary.
Line 06: The scale property will scale the canvas tag by the given value. In this example the resulting canvas will have a dimension of 320x200 pixels.
Line 07: The title will be set to the windows browser tab.
Line 08: We define a nice background color and overwrite the default value (which is solid black).
Line 09: In the previous steps the output canvas was appended directly beneath the body tag. If we pass another HTML element via the container property we can determine to which HTML node the canvas element is inserted in.
Line 11: We pass the created args as parameter to the TinyC5.init() funciton.
Result
Now the layout changed mostly due to the CSS. Our output should now be in the centre of the screen showing a green square.
(http://www.dbfinteractive.com/adminteam/benny/TinyC5/tutorial/step03.JPG) (http://www.dbfinteractive.com/adminteam/benny/TinyC5/tutorial/step03.html)
Step 04
Alright, let's draw something. Since we calculate the color of each pixel new on each loop, we do not need to set the initial background color anymore.
That's why we drop it:
bgColor: tinyC5.color( 155, 255, 100, 255 ),
The main addition in this step is that we actually create some logic in our update method - in this case we draw a sinple checkerboard:
tinyC5.update = function() {
var p, color, index;
index = 0;
p = tinyC5.pixels;
for( var y = 0; y < tinyC5.HEIGHT; y++ ) {
for( var x=0; x < tinyC5.WIDTH; x++ ) {
color = 255 * ( ( ( x >> 4 ) & 1 ) ^ ( ( y >> 4 ) & 1 ) );
p[index++] = color;
p[index++] = color;
p[index++] = color;
p[index++] = 255;
}
}
};
This should look actually a bit familiar to you if you have ever worked with tinyPTC/PixelToaster. Some quick notes:
Line 04: We make a local reference to the TinyC5.pixels array. The array holds all the pixel data in the following format [ Red, Green, Blue, Alpha, Red, Green, Blue, Alpha, Red, ... ]
Line 05: TinyC5.HEIGHT is the height value of the pixel buffer. In this case 100.
Line 06: Same with TinyC5.WIDTH. It's 160 pixel in our example.
Result
The result is a simple black/white checkerboard. Guess the FX itself does not require any explanation.
(http://www.dbfinteractive.com/adminteam/benny/TinyC5/tutorial/step04.JPG) (http://www.dbfinteractive.com/adminteam/benny/TinyC5/tutorial/step04.html)
Step 05
This step already indicates the end of the tutorial. In this step we added some movement to our small effect as well as some cracker-colors. Only one TinyC5 related function needs to be explained here.
tinyC5.getTime()
This returns the elapsed time in milliseconds since the TinyC5.start() function was called. Use this for timed animation.
Result
Since this is the last step, the code contains detailed comments for further details. Please have a look at the code.
(http://www.dbfinteractive.com/adminteam/benny/TinyC5/tutorial/step05.JPG) (http://www.dbfinteractive.com/adminteam/benny/TinyC5/tutorial/step05.html)
Please feel free to post any comments, thoughts or questions about this tutorial in this thread.
Thanks for reading.
P.S.: You need to be logged in in order to download the tutorial files.
Additional Stuff
ImageLoading with TinyC5 (http://www.dbfinteractive.com/forum/index.php?topic=5455.msg73321#msg73321)
-
Thanks for this tutorial Benny, K+
-
Thanks for this tutorial Benny, K+
Thanks for the "K" ... guess most of the coders here don't need that tutorial - but maybe its useful for one or the other. In addition, I hope to pull some non-forum members into this forum (tutorial is also linked from google code). Will see ...
-
Awesome tute dude!
-
Awesome tute dude!
Thanks a lot, mate!
-
Good stuff Benny. It would be nice to have something about texture loading covered as a lot of people will probably like to use that functionality.
-
Good stuff Benny. It would be nice to have something about texture loading covered as a lot of people will probably like to use that functionality.
Good call, I will add this topic!
-
Is there an input functionality? I wanna maek gmaes!
:goodpost:
-
Is there an input functionality? I wanna maek gmaes!
:goodpost:
Hey relsoft,
"natively" the library supports mouse events. Refer to Example 06 (http://www.dbfinteractive.com/adminteam/benny/TinyC5/examples/Example06.html). Getting the output canvas with TinyC5.getCanvas() you should be able to bind any event you want to the canvas and use it.
Let me know if you need any help here.
Best,
benny!
-
Ah, it's an HTML5 demo ... hum ... will be harder to start my framework :D
I hope to play with it :)
-
Introduction
This tutorial was done on request. It explains briefly how to load and use image data with TinyC5. This tutorial shows just one possible way. There are other ways to achieve the same, I guess.
Step 01
To avoid security issues which might arise when loading external images, let's do it the oldschool way and embed the imagedata in our product ;-). So first, we need to convert our image data to base64 format. There are numerous converters around, let's try the following:
http://www.greywyvern.com/code/php/binary2base64 (http://www.greywyvern.com/code/php/binary2base64)
Just point to the image to convert it, e.g. http://www.dbfinteractive.com/forum/Themes/nocturno205/images/img/logo.png (http://www.dbfinteractive.com/forum/Themes/nocturno205/images/img/logo.png).
After it was successful created, let's copy and paste the image data in an asset javascript object:
var Assets = {
dbflogo: "...ENCODED_DATA..."
};
Ok, now you have the imagedata embedded into your javascript code.
Step 02
So, to actually use the encoded data, we creaete an Image object in javascript and assign our encoded data to its source property. The Image object knows how to decode/handle that data ;-)
// Declare a var for our image
var dbfLogo;
// We wrap the image creation into a load function
function load() {
dbfLogo = new Image();
dbfLogo.src = Assets.dbfLogo;
dbfLogo.onload = function(e) { main(); };
}
Note
This might look a bit too complex you might think. We added an onload-event-handler to the Image, although we are not really loading an image. Nevertheless, javascript is asynchronous and assigning the data to the src property, decoding it takes a while.
Unlike other languages, the programm execution does not stop. That's why it is necessary to add that handler to make sure we does not make use the dbgLogo image before it is not fully initnialized.
Step 03
First, let's include the Utils library of the TinyC5 package:
<script type="text/javascript" src="js/TinyC5Utils-0.7.js"></script>
Then, we actually can get the pure image data from our Image with the following line:
// Get imageData
var logoImageData = TinyC5Utils.getImagedataFromImage( dbfLogo );
Result
I wrapped this in a small TinyC5 example. The result is as follows:
(http://www.dbfinteractive.com/adminteam/benny/TinyC5/tutorial/ImageLoading-scr.JPG)
(http://www.dbfinteractive.com/adminteam/benny/TinyC5/tutorial/ImageLoading.html)
-
Is it possible to draw a line with one command, similar to
canvas.strokeStyle="#ff7f00";
canvas.moveTo(x,y);
canvas.lineTo(xx,yy)
canvas.stroke();
Or should each pixel along the line be set individually? It seems as though using the above four commands would be faster from a programming point of view, but if this is outside of the spirit of TinyC5, then I will work on making my code conform.
-
What IDE's would you recommend?
-
Is it possible to draw a line with one command, similar to
canvas.strokeStyle="#ff7f00";
canvas.moveTo(x,y);
canvas.lineTo(xx,yy)
canvas.stroke();
Or should each pixel along the line be set individually? It seems as though using the above four commands would be faster from a programming point of view, but if this is outside of the spirit of TinyC5, then I will work on making my code conform.
Well, the library itself is focussing on pushing pixels and that's it. TinyC5 is just an really low-level abstraction layer of the canvas element to have direct pixel access. So, I guess the main FX should be based on a pixel-by-pixel basis. But if you are doing general Canvas programming I would recommend using the inbuild canvas stuff, like the commands you mentioned.
Nevertheless, it is still possible to additionally add normal canvas operation on the resulting output canvas. Refer to Example 06 (http://www.dbfinteractive.com/adminteam/benny/TinyC5/examples/Example06.html) and have a look how the text is drawn on the canvas. It's all handled in the tinyC5.postUpdate().
What IDE's would you recommend?
Good question. Personally I am currently using Netbeans (http://netbeans.org/) since the Intellisense is comparably good for javascript. I also liked working with Eclipse (http://www.eclipse.org/) - but since the most tools comes with the browser (e.g. debugging, network trace, console...) it is really a matter of taste, what you prefer.
What kind of tools do other use?
-
What kind of tools do other use?
Notepad++ at the moment. I think it's pretty cool.
-
Notepad++ is really great. I use it all the time for 100% of my web stuff.
-
To avoid security issues which might arise when loading external images, let's do it the oldschool way and embed the imagedata in our product ;-). So first, we need to convert our image data to base64 format. There are numerous converters around, let's try the following:
http://www.greywyvern.com/code/php/binary2base64 (http://www.greywyvern.com/code/php/binary2base64)
pfewwww hopefully yhere is this technique... I'm getting mad with this!
-
To avoid security issues which might arise when loading external images, let's do it the oldschool way and embed the imagedata in our product ;-). So first, we need to convert our image data to base64 format. There are numerous converters around, let's try the following:
http://www.greywyvern.com/code/php/binary2base64 (http://www.greywyvern.com/code/php/binary2base64)
pfewwww hopefully yhere is this technique... I'm getting mad with this!
Ehm? Doesn't this work for you ?
-
Yep it runs fine! I have tried to read pixel from context.getImageData and got the famous security error! With this technique of including binary data in the javascript var lets you work without problems :D
(Already made tunnel, plasma, zoomer effects ;D)
Huhu back to my code... Hum at the end, I will produce a mega demo :bfuck2:
-
Nevertheless, it is still possible to additionally add normal canvas operation on the resulting output canvas. Refer to Example 06 (http://www.dbfinteractive.com/adminteam/benny/TinyC5/examples/Example06.html) and have a look how the text is drawn on the canvas. It's all handled in the tinyC5.postUpdate().
Thanks Benny,
I will make the effect I was thinking of alongside a genuine TinyC5 pixel effect.
-
Nevertheless, it is still possible to additionally add normal canvas operation on the resulting output canvas. Refer to Example 06 (http://www.dbfinteractive.com/adminteam/benny/TinyC5/examples/Example06.html) and have a look how the text is drawn on the canvas. It's all handled in the tinyC5.postUpdate().
Thanks Benny,
I will make the effect I was thinking of alongside a genuine TinyC5 pixel effect.
Yep I've made a heavy use of the two way :D
I've also merged CODEF with TinyC5, but it will be for a next compo ;D
-
...
Thanks Benny,
I will make the effect I was thinking of alongside a genuine TinyC5 pixel effect.
Cool! Looking forward to see it!
...
(Already made tunnel, plasma, zoomer effects ;D)
Huhu back to my code... Hum at the end, I will produce a mega demo :bfuck2:
Woot ... wow .. that sounds awesome. O0
-
The problem is that all my effects are "common". I hope to find a original one up to the 24th of december :P
Guys like Raizor, Shockwave, Padman, Combatking0, Hellfire, Rbz, and so on (and even you ;) ) will do!
Have to work hard if I don't want to make up the numbers here! ;)
-
I got a few questions, sorry if they seem obvious or weird...
- Where can I find a command list or something, the docs only contain a todo list and changelog?
- How do I get or set specific pixel color values?
- This is prolly my animation brain talking but where is the framrate determined? For my old js games I used an interval timer which called a redraw function, what is making it tick here and at what speed?
PS I find the code bits in the examples quite elegant, some clever coding there! :cheers:
-
...
- Where can I find a command list or something, the docs only contain a todo list and changelog?
Unfortunately, I havent had the time to research a good javascript documentator. Please refer to the public functions descriptions within the TinyC5 code (all functions declared like this:
this.functionName = function( .. ) {
}
are publically available. I tried to do my best to added as explicit comments to their headers. Nevertheless, you are write I should provide a better docs for the functions. I will work on that!
- How do I get or set specific pixel color values?
For example to set a pixel at point (100,10) here is the equivalent code:
var destY = 10, destX=100, pixelIndex;
pixelIndex = ( destX * 4 ) + ( tinyC5.WIDTH * destY * 4);
tinyC5.pixels[ pixelIndex ] = 0; // Red color value (0-255)
tinyC5.pixels[ pixelIndex+1 ] = 255; // Green color value (0-255)
tinyC5.pixels[ pixelIndex+2 ] = 0; // Blue color value (0-255)
tinyC5.pixels[ pixelIndex+3 ] = 255; // Alhpa value (0-255)
I multiply with 4 because each pixel contains of the following single values: Red, Green, Blue, Alpha.
- This is prolly my animation brain talking but where is the framrate determined? For my old js games I used an interval timer which called a redraw function, what is making it tick here and at what speed?
Framerate is set to constant 60fps. Nothing to do about this, because some browsers already implement natively a function called requestAnimationFrame() which is also set to 60fps.
PS I find the code bits in the examples quite elegant, some clever coding there! :cheers:
Thanks ;-)
-
I have worked out how to draw a line in individual pixels. Now I can add a TinyC5 effect to the lines themselves :)
-
I have worked out how to draw a line in individual pixels. Now I can add a TinyC5 effect to the lines themselves :)
Sounds cool. Good news!
-
- Where can I find a command list or something, the docs only contain a todo list and changelog?
I use the following site as a javascript reference:
http://www.w3schools.com/js/default.asp
It won't contain anything specific to TinyC5, but it will help anyone who is new to JS in general.
-
Thanks for the help benny, I'm up and running now! :)
w3schools is a great resource I haven't checked in a while, thanks CK!
-
Does anybody have an easy solution for a performance indicator like an fps counter?
-
Does anybody have an easy solution for a performance indicator like an fps counter?
Definately. I would recommend:
https://github.com/mrdoob/stats.js?utm_source=javascriptweekly&utm_medium=email (https://github.com/mrdoob/stats.js?utm_source=javascriptweekly&utm_medium=email)
It's simple easy to get them working. Pseudocode:
var stats = new Stats();
// Align top-left
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
document.getElementsByTagName('body')[0].appendChild( stats.domElement );
tinyC5.update = function() {
stats.update();
}
-
:clap: my favorite :updance:
-
A question for Benny!
when I use the script ( http://www.greywyvern.com/code/php/binary2base64 ) to encode binary (music), if I want to decode it to plain/text (base64 decode) with the atob() javascript function I have to remove the start and the end of the text
"data:text/plain;base64,IQYtbGg1LWsRAADfJQIAAgD9EiAAC1NZTlRIRDUuQklOk... .... %3D" in bold
Have you got a technique or a function that auto-remove this? thanx
-
Hmm ... would it be enough if you simply remove the header and trailing part with some string manipulation functions. Something like:
base64String.replace( "data:text/plain;base64,", "" );
base64String.replace( "%3D", "" );
Would this work for you?
-
Or doing something similar with slice/subsring.
-
Huhu yep I know this, but I thought about a special function that remove this "header" :D It will works for everything :P Hmmm I think there nothing :D
-
Nice tutorial, thanks !
Thanks for the "K" ... guess most of the coders here don't need that tutorial - but maybe its useful for one or the other. In addition, I hope to pull some non-forum members into this forum (tutorial is also linked from google code). Will see ...
And you where right about pulling some non-forum members here ; )
-
Nice tutorial, thanks !
Thanks ;-)
Thanks for the "K" ... guess most of the coders here don't need that tutorial - but maybe its useful for one or the other. In addition, I hope to pull some non-forum members into this forum (tutorial is also linked from google code). Will see ...
And you where right about pulling some non-forum members here ; )
Hehe ... cool to know, that my tactics work ;-)
So, :hi: to the forum!