hmm.. property has to be defined after interface
eg.:
@interface MyViewController : UIViewController {
UITextField *textField;
UILabel *label;
NSString *string;
}
@property (nonatomic, retain) IBOutlet UITextField *textField;
@property (nonatomic, retain) IBOutlet UILabel *label;
@property (nonatomic, copy) NSString *string;
- (IBAction) changeGreeting: (id) sender;
NOT
@property (nonatomic, retain) IBOutlet UITextField *textField;
@property (nonatomic, retain) IBOutlet UILabel *label;
@property (nonatomic, copy) NSString *string;
- (IBAction) changeGreeting: (id) sender;
@interface MyViewController : UIViewController {
UITextField *textField;
UILabel *label;
NSString *string;
}
to use these in the .m files
must use @synthesize
eg.:
@synthesize textField;
@synthesize label;
@synthesize string;
Tuesday, October 05, 2010
Sunday, August 22, 2010
Flash: RSS + spring model
RSS:
http://www.straitstimes.com/STI/STIFILES/rss/break_lifestyle.xml
http://feeds.feedburner.com/StraitsTimesInteractive-Lifestyle
Demo: http://psalmhundred.net/experiment/rss_elastic.html
http://www.straitstimes.com/STI/STIFILES/rss/break_lifestyle.xml
http://feeds.feedburner.com/StraitsTimesInteractive-Lifestyle
Demo: http://psalmhundred.net/experiment/rss_elastic.html
Monday, July 26, 2010
PHP: yahoo finance to xml
wrote a simple PHP script to get quotes data from yahoo finance and format it into XML format.
sample: http://psalmhundred.net/experiment/stocks.php?s=adbe,goog,aapl,msft
OR
references:
http://www.gummy-stuff.org/Yahoo-data.htm
sample: http://psalmhundred.net/experiment/stocks.php?s=adbe,goog,aapl,msft
OR
references:
http://www.gummy-stuff.org/Yahoo-data.htm
Sunday, July 25, 2010
Flash & XML: namespace
sample RSS feed: http://weather.yahooapis.com/forecastrss?w=1062605&u=c
to access elements that are using namespace.
eg.:
gotta use the Namespace class and the :: operator
eg.:
to access elements that are using namespace.
eg.:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
<channel>
...
<item>
...
<yweather:condition text="Partly Cloudy" code="30" temp="31" date="Sun, 25 Jul 2010 7:00 pm SGT" />
...
</item>
...
</channel>
</rss>
gotta use the Namespace class and the :: operator
eg.:
var xml:XML = new XML(loader.data);
var ns:Namespace = xml.namespace("yweather");
trace(xml.channel.item.ns::condition.@text);
Friday, July 23, 2010
Wednesday, July 21, 2010
Novint Falcon used in Flash
Getting x, y, z coordinates and buttons status:
Using Flash to output force feedback to haptic device:
Using Flash to output force feedback to haptic device:
Tuesday, July 20, 2010
winsock 2: recv with select
needed to use recv in synchronous mode. but it is a blocking call.
so google a bit and found select.
code segment:
so google a bit and found select.
code segment:
fd_set sockets;
TIMEVAL waitTime;
void Receive()
{
// gotta call select() to check if there is incoming packet
sockets.fd_count = 1;
sockets.fd_array[0] = ClientSocket;
// time to expire for select call. since it is blocking too.
waitTime.tv_sec = 0; // seconds
waitTime.tv_usec = 100; // micro seconds
// check if any of the listening sockets has incoming data
// returns number of sockets in fd_set that has incoming data
int result = select(NULL, &sockets, NULL, NULL, &waitTime);
int iResult = result;
if(result > 0)
{
// blocking call
iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if(iResult > 0)
{
printf("Bytes received: %d\n", iResult);
printf("Recv: %s\n", recvbuf);
}
else if(iResult == 0)
{
//printf("Nothing received\n");
}
else
{
printf("recv failed: %d\n", WSAGetLastError());
}
}
return iResult;
}
Saturday, July 17, 2010
libxml2: XML parsing using C/C++
http://www.xmlsoft.org/
require some modification:
xmlversion.h
iconv.dll required. got it at: http://www.gnupg.org/download/iconv.en.html
require some modification:
xmlversion.h
/**
* LIBXML_ICONV_ENABLED:
*
* Whether iconv support is available
*/
#if 0 // instead of 1
#define LIBXML_ICONV_ENABLED
#endif
iconv.dll required. got it at: http://www.gnupg.org/download/iconv.en.html
xmlTextReaderPtr reader;
char xml[200] = "<root><child1><child2 attr=\"123\" attr2=\"test\">hello world</child2></child1></root>";
printf("%s\n", xml);
cout << "Read XML from memory...\n";
reader = xmlReaderForMemory(xml, strlen(xml), "", NULL, 0);
if (reader != NULL) {
// loop to read nodes
int ret;
const xmlChar *name, *value;
ret = xmlTextReaderRead(reader);
while(ret == 1)
{
name = xmlTextReaderConstName(reader);
value = xmlTextReaderConstValue(reader);
printf("%s=%s\n", name, value);
// attributes
ret = xmlTextReaderHasAttributes(reader);
if(ret == 1)
{
// has attributes
attrName = xmlCharStrdup("attr");
attrValue = xmlTextReaderGetAttribute(reader, attrName);
int attr = atoi((const char *) attrValue);
printf("attr=%d\n", attr);
}
ret = xmlTextReaderRead(reader);
}
cout << "Freeing XML reader...\n";
xmlFreeTextReader(reader);
}
Monday, June 28, 2010
Wednesday, June 02, 2010
OpenGL: Stereoscopic rendering
Source: http://www.orthostereo.com/geometryopengl.html
Example:
Example:
GLvoid display(GLvoid)
{
glDrawBuffer(GL_BACK); //draw into both back buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear color and depth buffers
glDrawBuffer(GL_BACK_LEFT); //draw into back left buffer
glMatrixMode(GL_MODELVIEW);
glLoadIdentity(); //reset modelview matrix
gluLookAt(-IOD/2, //set camera position x=-IOD/2
0.0, // y=0.0
0.0, // z=0.0
0.0, //set camera "look at" x=0.0
0.0, // y=0.0
screenZ, // z=screenplane
0.0, //set camera up vector x=0.0
1.0, // y=1.0
0.0); // z=0.0
glPushMatrix();
{
glTranslatef(0.0, 0.0, depthZ); //translate to screenplane
drawscene();
}
glPopMatrix();
glDrawBuffer(GL_BACK_RIGHT); //draw into back right buffer
glMatrixMode(GL_MODELVIEW);
glLoadIdentity(); //reset modelview matrix
gluLookAt(IOD/2, 0.0, 0.0, 0.0, 0.0, screenZ, //as for left buffer with camera position at:
0.0, 1.0, 0.0); // (IOD/2, 0.0, 0.0)
glPushMatrix();
{
glTranslatef(0.0, 0.0, depthZ); //translate to screenplane
drawscene();
}
glPopMatrix();
glutSwapBuffers();
}
XNA: higher refresh rate
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
this.TargetElapsedTime = TimeSpan.FromMilliseconds(8);
this.IsFixedTimeStep = false;
graphics.SynchronizeWithVerticalRetrace = false;
this.IsMouseVisible = true;
}
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
this.TargetElapsedTime = TimeSpan.FromMilliseconds(8);
this.IsFixedTimeStep = false;
graphics.SynchronizeWithVerticalRetrace = false;
this.IsMouseVisible = true;
}
XNA: 3D and 2D
Gotta reset settings when mixing 3D and 2D content
http://forums.xna.com/forums/t/48583.aspx
eg.:
http://forums.xna.com/forums/t/48583.aspx
eg.:
// to reset settings for 3D drawing
graphics.GraphicsDevice.RenderState.DepthBufferEnable = true;
graphics.GraphicsDevice.RenderState.AlphaBlendEnable = false;
graphics.GraphicsDevice.RenderState.AlphaTestEnable = false;
DrawModel(gameShip);
spriteBatch.Begin();
// Draw Hello World
string output = "FPS: " + fps;
// Find the center of the string
//Vector2 FontOrigin = Font1.MeasureString(output) / 2;
Vector2 FontOrigin = FontPos;
// Draw the string
//spriteBatch.DrawString(Font1, output, FontPos, Color.LightGreen,
// 0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f);
spriteBatch.DrawString(Font1, output, FontPos, Color.LightGreen);
spriteBatch.End();
Wednesday, April 28, 2010
C++: cin & gets
hmmm.. couldn't get cin and gets to work together.
if cin is used before gets, gets will not wait for user input get the string, due to the "\n" character.
if it's the other way round, it will work. but this is not useful in the general sense if your program needs both string and number input.
so in general, use gets and then use "stdlib.h" data conversion functions, eg.: atoi, string -> int
Example:
if cin is used before gets, gets will not wait for user input get the string, due to the "\n" character.
if it's the other way round, it will work. but this is not useful in the general sense if your program needs both string and number input.
so in general, use gets and then use "stdlib.h" data conversion functions, eg.: atoi, string -> int
Example:
/*
simple C++ program
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stdlib.h>
using namespace std;
// a c++ program starts with main
int main()
{
int score;
int i;
char str[200];
char c;
c = 'c';
cout << "Enter a number from 1 to 10: " ;
gets_s(str);
score = atoi(str);
cout << "Enter your name: ";
gets_s( str);
for(i = 0; i<score; i++){
cout << c <<"++ is cool and so is " << str << "; score: " << score << "\n";
}
return 0;
}
Saturday, March 27, 2010
panoramic pic - 1st attempt
Sunday, February 07, 2010
3ds max plugin wizard with visual studio 2008 express
1a. Copy the 3ds "maxsdk" to D:\ drive or other location where there are no user permission issues.
1. Open the 3dsmaxPluginWizard.vsz file (in the 3dsmaxPluginWizard directory root) in a text editor and edit the ABSOLUTE PATH parameter to reflect the new location of the 3dsmaxPluginWizard root directory. Do not add a backslash after the directory name.
Param="ABSOLUTE_PATH = [Absolute Path Location of 3dsmaxPluginWizard Root Directory]"
1b. Edit 3dsmaxPluginWizard.vsz with a text editor, eg.: Notepad.
change line 2: Wizard=VsWizard.VsWizardEngine.9.0
2. Copy the following files from the 3dsmaxPluginWizard root to the 'VC\VCProjects' directory under your Visual Studio installation (e.g. C:\Program Files\Microsoft Visual Studio 9.0\VC\VCProjects):
3dsmaxPluginWizard.ico
3dsmaxPluginWizard.vsdir
3dsmaxPluginWizard.vsz
If you are using Visual Studio Express Edition, you need to copy the files listed above to the 'VC\Express\VCProjects' folder.
3. At this point the 3ds Max Plugin Wizard project should appear under File menu:New:Projects:Visual C++ Projects in Visual Studio.
1. Open the 3dsmaxPluginWizard.vsz file (in the 3dsmaxPluginWizard directory root) in a text editor and edit the ABSOLUTE PATH parameter to reflect the new location of the 3dsmaxPluginWizard root directory. Do not add a backslash after the directory name.
Param="ABSOLUTE_PATH = [Absolute Path Location of 3dsmaxPluginWizard Root Directory]"
1b. Edit 3dsmaxPluginWizard.vsz with a text editor, eg.: Notepad.
change line 2: Wizard=VsWizard.VsWizardEngine.9.0
2. Copy the following files from the 3dsmaxPluginWizard root to the 'VC\VCProjects' directory under your Visual Studio installation (e.g. C:\Program Files\Microsoft Visual Studio 9.0\VC\VCProjects):
3dsmaxPluginWizard.ico
3dsmaxPluginWizard.vsdir
3dsmaxPluginWizard.vsz
If you are using Visual Studio Express Edition, you need to copy the files listed above to the 'VC\Express\VCProjects' folder.
3. At this point the 3ds Max Plugin Wizard project should appear under File menu:New:Projects:Visual C++ Projects in Visual Studio.
CSS: rounded edge / corner box




CSS:
.mainbody {
border-right-width: 1px;
border-left-width: 1px;
border-right-style: solid;
border-left-style: solid;
border-right-color: #CCC;
border-left-color: #CCC;
padding-right: 10px;
padding-left: 10px;
}
.topcenter {
border-top-width: 1px;
border-top-style: solid;
border-top-color: #CCC;
}
.bottomcenter {
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #CCC;
height: 4px;
}
.topleft {
background-image: url(images/corners_topleft.gif);
background-repeat: no-repeat;
background-position: left top;
height: 5px;
width: 5px;
float: left;
}
.topright {
background-image: url(images/corners_topright.gif);
background-position: right top;
float: right;
background-repeat: no-repeat;
height: 5px;
width: 5px;
}
.bottomright {
background-image: url(images/corners_bottomright.gif);
background-repeat: no-repeat;
background-position: right top;
float: right;
height: 5px;
width: 5px;
}
.bottomleft {
background-image: url(images/corners_bottomleft.gif);
background-repeat: no-repeat;
background-position: left top;
height: 5px;
width: 5px;
float: left;
}
.topbottom {
height: 5px;
}
HTML:
<div>
<div class="topbottom">
<div class="topleft"></div>
<div class="topright"></div>
<div class="topcenter"></div>
</div>
<div class="mainbody">content</div>
<div class="topbottom">
<div class="bottomleft"></div>
<div class="bottomright"></div>
<div class="bottomcenter"></div>
</div>
</div>
Monday, January 25, 2010
Maya Plugin wizard for Visual C++ express edition 2008 setup
1. Unzip the MayaPluginWizard2.0.zip file in the maya installation folder, eg.: C:\Program Files\Autodesk\Maya2008\devkit\pluginwizard
2. Copy the following files to the "C:\Program Files\Microsoft Visual Studio 9.0\VC\Express\VCProjects" directory:
MayaPluginWizard.vsdir
MayaPluginWizard.vsz
MayaPluginWizard.ico
2b. Edit MayaPluginWizard.vsz with a text editor, eg.: Notepad.
change line 2: Wizard=VsWizard.VsWizardEngine.9.0
2c. create a folder "MayaPlugInWizard" in "C:\Program Files\Microsoft Visual Studio 9.0\VC\Express\VCProjects"
2d. move "MayaPluginWizard.vsdir" into this new folder.
3. Copy the "MayaPluginWizard" directory to "C:\Program Files\Microsoft Visual Studio 9.0\VC\VCWizards".
4. Start Microsoft Visual Studio 8 and invoke File -> New -> Project -> Visual C++ Projects and select MayaPluginWizard.
5. Enter a name and solution name and select the OK button.
6. Fill in the information for the "Plug-in setup" screen and then select the "Plug-in type" and "Included libraries" links to also enter the required information.
7. The project will be created and then the solution can updated and built.
2. Copy the following files to the "C:\Program Files\Microsoft Visual Studio 9.0\VC\Express\VCProjects" directory:
MayaPluginWizard.vsdir
MayaPluginWizard.vsz
MayaPluginWizard.ico
2b. Edit MayaPluginWizard.vsz with a text editor, eg.: Notepad.
change line 2: Wizard=VsWizard.VsWizardEngine.9.0
2c. create a folder "MayaPlugInWizard" in "C:\Program Files\Microsoft Visual Studio 9.0\VC\Express\VCProjects"
2d. move "MayaPluginWizard.vsdir" into this new folder.
3. Copy the "MayaPluginWizard" directory to "C:\Program Files\Microsoft Visual Studio 9.0\VC\VCWizards".
4. Start Microsoft Visual Studio 8 and invoke File -> New -> Project -> Visual C++ Projects and select MayaPluginWizard.
5. Enter a name and solution name and select the OK button.
6. Fill in the information for the "Plug-in setup" screen and then select the "Plug-in type" and "Included libraries" links to also enter the required information.
7. The project will be created and then the solution can updated and built.
Simple Stereo 3d Anaglpyh example
Download FLA
import flash.display.*;
import flash.events.*;
import flash.geom.*;
import flash.utils.*;
// Picture is a movie clip symbol in the Library
var loader:Picture = new Picture();
var loader2:Picture = new Picture();
var scene:Sprite = new Sprite();
// for drawing scene from left eye view
var left:Bitmap = new Bitmap();
// for drawing scene from right eye view
var right:Bitmap = new Bitmap();
// background for correct blending
var bg:Sprite = new Sprite();
var leftData:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);
var rightData:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);
var distance:Number = 4; // left-right eye distance
init();
prepareStereo();
function prepareStereo():void
{
left.blendMode = BlendMode.SCREEN;
// right eye = green and blue channel
right.transform.colorTransform = new ColorTransform(0, 1, 1, 1);
// left eye = red channel
left.transform.colorTransform = new ColorTransform(1, 0, 0, 1);
left.bitmapData = leftData;
right.bitmapData = rightData;
setBackground();
this.addChild(right);
this.addChild(left);
// set the UI textbox and label to the top
this.setChildIndex(ui_mc, this.numChildren-1);
}
function setBackground(color:int = 0):void{
bg.graphics.beginFill(color);
bg.graphics.drawRect(-2000, -2000, 4000, 4000);
}
function init():void{
loader.x = 200;
loader.y = 200;
loader2.y = 200;
loader2.z = 300;
stage.addEventListener(MouseEvent.MOUSE_MOVE, move);
this.addEventListener(Event.ENTER_FRAME, update);
scene.addChild(bg);
scene.addChild(loader2);
scene.addChild(loader);
ui_mc.distance_txt.text = String(distance);
}
function update(e:Event):void{
// clear screen
rightData.fillRect(rightData.rect, 0xFFFFFF);
leftData.fillRect(rightData.rect, 0xFFFFFF);
distance = Number(ui_mc.distance_txt.text);
loader.x -= distance / 2; // move scene to the left for right eye
loader2.x -= distance / 2;
rightData.draw(scene);
loader.x += distance; // move scene to the right for left eye
loader2.x += distance;
leftData.draw(scene);
loader.x -= distance / 2; // move scene back to original position
loader2.x -= distance / 2;
}
function move(e:MouseEvent):void
{
loader.rotationY = (mouseY*2/stage.stageHeight - 1) * 60;
loader2.rotationY = (1-mouseY*2/stage.stageHeight) * 60;
loader.x = stage.stageWidth - mouseX;
loader2.x = mouseX;
}
Saturday, January 16, 2010
EasyPHP issues with Windows 7
Thanks to Ryan for the following post:
http://ryan.rawswift.com/2009/09/20/easyphp-on-64-bit-windows-7-how-to-fix-apache-and-mysql-problem/
summary of the above post:
issue 1 for Apache:
Apache cannot be runned: another Web server use the Web port
or port is blocked by firewall.
solution:
- Click the EasyPHP icon beside “Apache” button.
- Click “Configure” then click “EasyPHP“.
- Uncheck “Check server’s TCP port before starting” then click “Apply” button and then “Close” button.
- Click “Apache” button and then click “Start“.
issue 2 for MySQL:
Unexpected end of MySql... See log file?
solution:
- Go to “Computer“, open/view Drive C, then double click “Program Files (x86)“.
- Right click on “EasyPHP5.3.0” folder then click “Properties“.
- On “Security” tab click “Edit…” button.
- Select the user that you are currently using.
- Under “Permissions for Users” box, tick “Full control” on “Allow” column.
- And then click “OK” button to apply the changes.
Thanks, Ryan. it works for me.
http://ryan.rawswift.com/2009/09/20/easyphp-on-64-bit-windows-7-how-to-fix-apache-and-mysql-problem/
summary of the above post:
issue 1 for Apache:
Apache cannot be runned: another Web server use the Web port
or port is blocked by firewall.
solution:
- Click the EasyPHP icon beside “Apache” button.
- Click “Configure” then click “EasyPHP“.
- Uncheck “Check server’s TCP port before starting” then click “Apply” button and then “Close” button.
- Click “Apache” button and then click “Start“.
issue 2 for MySQL:
Unexpected end of MySql... See log file?
solution:
- Go to “Computer“, open/view Drive C, then double click “Program Files (x86)“.
- Right click on “EasyPHP5.3.0” folder then click “Properties“.
- On “Security” tab click “Edit…” button.
- Select the user that you are currently using.
- Under “Permissions for Users” box, tick “Full control” on “Allow” column.
- And then click “OK” button to apply the changes.
Thanks, Ryan. it works for me.
Friday, January 08, 2010
Wednesday, January 06, 2010
FlashVars: sending variables into Flash from HTML/PHP
in HTML containing SWF:
...
AC_FL_RunContent(
...,
'flashVars','myVariable=<?php echo((isset($_GET['myVariable'])) ? $_GET['myVariable'] : ""); ?>'
); //end AC code
...
<param name="movie" value="live_stream.swf?myVariable=<?php echo((isset($_GET['myVariable'])) ? $_GET['myVariable'] : ""); ?>" />
<embed src="live_stream.swf?src=<?php echo((isset($_GET['myVariable'])) ? $_GET['myVariable'] : ""); ?>" ... >
in FLA/AS:
access variable thru:
this.loaderInfo.parameters["myVariable"]
...
AC_FL_RunContent(
...,
'flashVars','myVariable=<?php echo((isset($_GET['myVariable'])) ? $_GET['myVariable'] : ""); ?>'
); //end AC code
...
<param name="movie" value="live_stream.swf?myVariable=<?php echo((isset($_GET['myVariable'])) ? $_GET['myVariable'] : ""); ?>" />
<embed src="live_stream.swf?src=<?php echo((isset($_GET['myVariable'])) ? $_GET['myVariable'] : ""); ?>" ... >
in FLA/AS:
access variable thru:
this.loaderInfo.parameters["myVariable"]
Monday, December 21, 2009
Flash: Webcam motion detection
Using edge detection, thresholding, k-means clustering
http://psalmhundred.net/experiment/webcam/motion/
http://psalmhundred.net/experiment/webcam/motion/
Friday, December 18, 2009
Sunday, December 13, 2009
Plumbing experience - changing fill valve of toilet bowl
It all started with water leak from the back of the toilet bowl. then further investigation proved that the bottom inlet valve where the water enters to fill the toilet bowl after a flush is not functioning after 6 yrs of usage. somehow the water will seep in and water level will go beyond the drainage hole at the back hence the wet toilet floor at the back of the toilet bowl.
so gotta go spend $12 on the new valve to replace the original Fluidmaster. then realise need a bigger plier so spend another $18 to get the big big pliers to unscrew that white plastic nut at the bottom of the valve.
so the procedure can be found on youtube:
now to wait til next day to see if new valve is working fine
Monday, November 02, 2009
Flex: K-means algorithm in AS3
Move mouse within white canvas to collect mouse (x, y) data.
Enter the number of clusters to group the data.
Click "Cluster" to cluster mouse data
Click "Reset" to clear all previous data
url: http://psalmhundred.net/experiment/gesture/GestureApp.html
Enter the number of clusters to group the data.
Click "Cluster" to cluster mouse data
Click "Reset" to clear all previous data
url: http://psalmhundred.net/experiment/gesture/GestureApp.html
Sunday, November 01, 2009
Flash, AIR, ActionScript: File & FileStream
Cannot write to filesystem at File.applicationDirectory
But yet you can write using File.applicationDirectory.nativePath
To serialise an object of a custom class,
1) use flash.net.registerClassAlias( aliasName:String, classObject:Class)
to register the class before writing or reading
2) implement IExternalizable to your custom class
- readExternal(input:IDataInput):void
- writeExternal(output:IDataOutput):void
- Alternatively, you can use public fields in the custom class. But that is not entirely recommended for real world application.
But yet you can write using File.applicationDirectory.nativePath
To serialise an object of a custom class,
1) use flash.net.registerClassAlias( aliasName:String, classObject:Class)
to register the class before writing or reading
2) implement IExternalizable to your custom class
- readExternal(input:IDataInput):void
- writeExternal(output:IDataOutput):void
- Alternatively, you can use public fields in the custom class. But that is not entirely recommended for real world application.
import flash.filesystem.*;
import flash.net.*;
var a:A = new A();
...
...
function write():void{
registerClassAlias("A", A);
fileStream.open(file, FileMode.UPDATE);
fileStream.writeObject(a);
fileStream.close();
}
function read():void{
fileStream.open(file, FileMode.READ);
var o:A = fileStream.readObject() as A;
o.c();
fileStream.close();
}
/********************
class A
********************/
import flash.utils.*;
public class A implements IExternalizable
{
var b:int = 10;
public function c():void{
trace(b);
}
public function readExternal(input:IDataInput):void
{
b = input.readInt();
}
public function writeExternal(output:IDataOutput):void
{
output.writeInt(b);
}
}
Thursday, October 29, 2009
Wii remote libraries
Wiigee - A Java-based gesture recognition library for the Wii remote
Background Tech Info:
http://www.wiigee.org/development/background/background.html
wiiremotej
http://www.world-of-cha0s.hostrocket.com/WiiRemoteJ/
http://www.world-of-cha0s.hostrocket.com/WiiRemoteJ/docs.zip.gz
http://www.wiili.com/forum/wiiremotej-f68.html
Managed library for wii remote
http://www.codeplex.com/WiimoteLib
http://blogs.msdn.com/coding4fun/archive/2007/03/14/1879033.aspx
Background Tech Info:
http://www.wiigee.org/development/background/background.html
wiiremotej
http://www.world-of-cha0s.hostrocket.com/WiiRemoteJ/
http://www.world-of-cha0s.hostrocket.com/WiiRemoteJ/docs.zip.gz
http://www.wiili.com/forum/wiiremotej-f68.html
Managed library for wii remote
http://www.codeplex.com/WiimoteLib
http://blogs.msdn.com/coding4fun/archive/2007/03/14/1879033.aspx
Monday, October 12, 2009
Flash SWF in Flex
Interestingly, got stuck at an application domain issue.
Did a Flex SWC library using Flex builder.
Used the SWC in Flash CS4. no issue. SWF created.
Loaded SWF into a flex mxml app using Loader. the app domain of the loader is different from the app domain of the flex app. had used Application.currentDomain to format the LoaderContext. http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e07.html
it just doesn't work.
However, the LoaderContext works in Flash CS4. seems that the context is dependent on how the SWF is created. looks like that's the only way, and have to endure without code hinting in flash CS4.
Tried using Flex component library for CS4. still doesn't work.
Did a Flex SWC library using Flex builder.
Used the SWC in Flash CS4. no issue. SWF created.
Loaded SWF into a flex mxml app using Loader. the app domain of the loader is different from the app domain of the flex app. had used Application.currentDomain to format the LoaderContext. http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e07.html
it just doesn't work.
However, the LoaderContext works in Flash CS4. seems that the context is dependent on how the SWF is created. looks like that's the only way, and have to endure without code hinting in flash CS4.
Tried using Flex component library for CS4. still doesn't work.
Sunday, September 13, 2009
WPF: rendering & timer
strange that there's a 24fps limit even on DispatcherTimer
have to use a thread to force a fast refresh rate
partial code:
bool running = true;
public delegate void updateDelegate();
public Window1(){
Thread t = new Thread(new ThreadStart(Run));
t.Start();
}
void Run()
{
while (running)
{
this.Dispatcher.Invoke(new updateDelegate(update), DispatcherPriority.Normal);
Thread.Sleep(5);
}
Console.WriteLine("ended thread");
}
void Window1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
running = false;
}
void update()
{
this.InvalidateVisual();
}
have to use a thread to force a fast refresh rate
partial code:
bool running = true;
public delegate void updateDelegate();
public Window1(){
Thread t = new Thread(new ThreadStart(Run));
t.Start();
}
void Run()
{
while (running)
{
this.Dispatcher.Invoke(new updateDelegate(update), DispatcherPriority.Normal);
Thread.Sleep(5);
}
Console.WriteLine("ended thread");
}
void Window1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
running = false;
}
void update()
{
this.InvalidateVisual();
}
Tuesday, September 08, 2009
maya + python: UI
cubeHt = 2
rgb = [0.5, 0.5, 0.5]
# functions
def updateSlider(*args):
intSlider(slider, value = int(args[0]), e=True);
def updateTxt(*args):
intField(txt, value = int(args[0]), e=True);
def buttonPush(*args):
print(str(args))
n = intField(txt, q=True, value=True)
createCubes(n)
def createCubes(n):
i=0
while(i<n):
names = polyCube();
move((i-n/2)*2, cubeHt, 0, names[0]);
#apply material
sets( names[0], e=True, forceElement=shadingGroup[0] )
i= i+1
def newFile(*args):
init()
def colorUpdate(*args):
rgb = colorSliderGrp(color, q=True, rgb=True)
print(shadingGroup[1])
setAttr(shadingGroup[1]+".diffuse" , rgb[0], rgb[1], rgb[2], type='double3' ) ;
def createMaterials():
# set up ambient occlusion for mental ray
material = shadingNode('mib_illum_lambert', asShader=True)
texture = shadingNode('mib_amb_occlusion', asShader=True)
connectAttr(texture + '.outValue', material + '.ambient', f=True );
# set up shading group, connect material to this group and apply group to cube object
group = sets( renderable=True, empty=True )
connectAttr( material+".outValue", group+".miMaterialShader", force=True)
setAttr(material+".ambience", 0.5, 0.5, 0.5, type='double3' ) ;
setAttr(material+".diffuse" , 0.5, 0.5, 0.5, type='double3' ) ;
result = [group, material, texture]
return result
def createPlane():
names = polyPlane( w=20, h=20)
white = createMaterials()
sets( names[0], e=True, forceElement=white[0] )
def init():
# new file
file(new=True, force=True)
# create a plane
createPlane()
shadingGroup = createMaterials()
init()
result = promptDialog(
title='Welcome',
message='Enter Name:',
button=['OK', 'Cancel'],
defaultButton='OK',
cancelButton='Cancel',
dismissString='Cancel')
if (result == 'OK'):
name = promptDialog(query=True, text=True)
confirmDialog( title='Welcome', message='Welcome, ' + name, button=['OK'] )
# create a window
w = 400
h = 240
win = window( title="Boon's UI", iconName='TBY', widthHeight=(w, h) )
c1 = columnLayout( columnAttach=('both', 5), rowSpacing=5, adjustableColumn=True )
r1 = rowLayout( numberOfColumns=3, parent=c1)
text( label='Number of cubes')
txt = intField(value=1, changeCommand=updateSlider)
slider = intSlider(min=0, max=10, value=1, step=1, changeCommand=updateTxt)
color = colorSliderGrp( parent=c1, label='Color of cube', rgb=(1, 1, 1) ,changeCommand=colorUpdate)
button(parent=c1, label='Create cubes', command=buttonPush )
button(parent=c1, label='New File', command=newFile )
showWindow(win)


Monday, September 07, 2009
Flex: charting
MXML:
AS:
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script source="chart.as" />
<mx:LineChart x="62" y="78" id="linechart1" dataProvider="{expenses}">
<mx:horizontalAxis>
<mx:CategoryAxis
dataProvider="{expenses}"
categoryField="Month"
/>
</mx:horizontalAxis>
<mx:series>
<mx:LineSeries displayName="Series 1" yField="Expenses" xField="Month" sortOnXField="true"/>
</mx:series>
</mx:LineChart>
<mx:Legend dataProvider="{linechart1}"/>
</mx:WindowedApplication>
AS:
import mx.collections.*;
[Bindable]
private var expenses:ArrayCollection = new ArrayCollection([
{Month:"January", Profit:2000, Expenses:1500, Amount:450},
{Month:"February", Profit:1000, Expenses:200, Amount:600},
{Month:"March", Profit:1500, Expenses:500, Amount:300},
{Month:"April", Profit:500, Expenses:300, Amount:500},
{Month:"May", Profit:1000, Expenses:450, Amount:250},
{Month:"June", Profit:2000, Expenses:500, Amount:700}
]);
Blogger: CSS not loaded & image upload not working
been getting the following errors:
Message: 'Textbar' is undefined
Line: 202
Char: 5
Code: 0
URI: http://www.blogger.com/post-create.g?blogID=8001423862883592815
Message: Object doesn't support this property or method
Line: 385
Char: 7
Code: 0
URI: http://www.blogger.com/post-create.g?blogID=8001423862883592815
Message: Object expected
Line: 233
Char: 1
Code: 0
URI: http://www.blogger.com/post-create.g?blogID=8001423862883592815
Error: Detect is not defined
Source File: http://www.blogger.com/static/v1/v-app/scripts/2280349093-post.images.js
Line: 214
sigh. search the internet.
strange solution: clear all cache in browser, and add the proxy server setting in the browser.
Message: 'Textbar' is undefined
Line: 202
Char: 5
Code: 0
URI: http://www.blogger.com/post-create.g?blogID=8001423862883592815
Message: Object doesn't support this property or method
Line: 385
Char: 7
Code: 0
URI: http://www.blogger.com/post-create.g?blogID=8001423862883592815
Message: Object expected
Line: 233
Char: 1
Code: 0
URI: http://www.blogger.com/post-create.g?blogID=8001423862883592815
Error: Detect is not defined
Source File: http://www.blogger.com/static/v1/v-app/scripts/2280349093-post.images.js
Line: 214
sigh. search the internet.
strange solution: clear all cache in browser, and add the proxy server setting in the browser.
Sunday, September 06, 2009
maya + python: mental ray nodes
# set up ambient occlusion for mental ray
material = shadingNode('mib_illum_lambert', asShader=True)
texture = shadingNode('mib_amb_occlusion', asShader=True)
connectAttr(texture + '.outValue', material + '.ambient', f=True );
# set up shading group, connect material to this group and apply group to cube object
group = 'mibMaterialGroup'
sets( name=group, renderable=True, empty=True )
connectAttr( material+".outValue", group+".miMaterialShader", force=True)
sets( cube, e=True, forceElement=group )
setAttr(material+".ambience", 0.5, 0.5, 0.5, type='double3' ) ;
setAttr(material+".diffuse" , 0.5, 0.5, 0.5, type='double3' ) ;
material = shadingNode('mib_illum_lambert', asShader=True)
texture = shadingNode('mib_amb_occlusion', asShader=True)
connectAttr(texture + '.outValue', material + '.ambient', f=True );
# set up shading group, connect material to this group and apply group to cube object
group = 'mibMaterialGroup'
sets( name=group, renderable=True, empty=True )
connectAttr( material+".outValue", group+".miMaterialShader", force=True)
sets( cube, e=True, forceElement=group )
setAttr(material+".ambience", 0.5, 0.5, 0.5, type='double3' ) ;
setAttr(material+".diffuse" , 0.5, 0.5, 0.5, type='double3' ) ;
Friday, September 04, 2009
python+maya: animation
from maya.cmds import *
import random
import math
# Delete any existing scene
file(newFile=True, force=True)
names = sphere(r=10)
s = names[0] # object name
# call python script procedure haha() in anim.py module
expression(o=s, s='python("anim.haha()")', ae=True)
playbackOptions( minTime='0sec', maxTime='10sec', loop='continuous')
play( state=True )
viewFit()
# create a function to run every frame
def haha():
x = getAttr(s + ".translateX")
#print(x)
t = currentTime(query=True)
#print(t)
x = 50* math.cos(math.pi * t / 120)
# setAttr(s + ".translateX", x);
setAttr(s + ".translate", x, 0, 0);
Apparently, must Bake Simulation before rendering. no dynamic content when rendering
Edit > Keys > Bake Simulation
Strange. some bug. in Render option > Common > End Frame. if i key in 240, it will reset to 10. but if i key in 100 first, it will accept. and then 240, it will accept. ???
python + maya: lighting
# create ambient light
light = ambientLight(intensity=0.4, softShadow=True, useRayTraceShadows=True)
# Create a directional light
#lightDir = directionalLight(rotation=(45, 30, 15))
lightDir = directionalLight(intensity=0.9, softShadow=True, useRayTraceShadows=True)
rotate(-60, 45, 0, lightDir);
# fit scene in active camera
viewFit();
light = ambientLight(intensity=0.4, softShadow=True, useRayTraceShadows=True)
# Create a directional light
#lightDir = directionalLight(rotation=(45, 30, 15))
lightDir = directionalLight(intensity=0.9, softShadow=True, useRayTraceShadows=True)
rotate(-60, 45, 0, lightDir);
# fit scene in active camera
viewFit();

python + maya: shading
can also use the following commands:
cmds.sets( name='redMaterialGroup', renderable=True, empty=True )
cmds.shadingNode( 'phong', name='redShader', asShader=True )
cmds.setAttr( 'redShader.color', 1, 0, 0, type='double3' )
cmds.surfaceShaderList( 'redShader', add='redMaterialGroup' )
cmds.sets( 'plane1', e=True, forceElement='redMaterialGroup' )
cmds.sets( name='redMaterialGroup', renderable=True, empty=True )
cmds.shadingNode( 'phong', name='redShader', asShader=True )
cmds.setAttr( 'redShader.color', 1, 0, 0, type='double3' )
cmds.surfaceShaderList( 'redShader', add='redMaterialGroup' )
cmds.sets( 'plane1', e=True, forceElement='redMaterialGroup' )
i=0
n = 50
limit = 20
lamb = []
lambSG = []
while i< n:
size = random.uniform(0.1, 5)
names = polyCube(o=True, w=size, h=size, d=size)
k=0
for name in names:
print(str(k) + ": " + name)
k = k + 1
cube = names[0] # object name
node = names[1] # node name
lamb=lamb + [createNode('lambert', n=('lamb' + str(i)))]; # create lambert shader node
lambSG= lambSG + [sets(n='lambSG'+str(i), empty=True, r=True, nss=True )] # create an empty shading group
connectAttr( lamb[i]+".outColor", lambSG[i]+".surfaceShader", force=True) # connect attribute
r = random.uniform(0, 1)
g = random.uniform(0, 1)
b = random.uniform(0, 1)
setAttr(lamb[i]+".color", r, g, b, type='double3' ); # set to random colour
sets(cube, fe=lambSG[i]) # set cube to have the above shading group
move(random.uniform(-limit, limit),
random.uniform(-limit, limit),
random.uniform(-limit, limit), cube, r=True)
i = i+1

Thursday, September 03, 2009
randomise cubes
Wednesday, September 02, 2009
Maya and Python - 1st try
C:\Documents and Settings\{username}\My Documents\maya\{version}\Maya.env
PYTHONPATH="C:\Documents and Settings\{username}\My Documents\maya\scripts"
* for Mac OS, DON'T use double quotes "..."
instead eg.: PYTHONPATH = /Users/username/Documents/maya/scripts
default for Mac OSX: ~/Library/Preferences/Autodesk/maya//scripts
start new hello.py file
put into the "scripts" folder
start maya. open Script Editor window
import hello
(to reload, use reload(hello))
.pyc compiled python also works in the scripts folder
sample py code:
print("hello world");
from maya.cmds import *
file(f=True, new=True); # new file
#select(all=True) # select all objects
#delete(all=True) # delete all objects. not supported anymore. Use "file -f -new;" instead.
# create a polygon cube
# store all names
names = polyCube(ch=True, o=True,w=5.038671,h=3.648038,d=3.788829,cuv=4)
# use for loop to print out the object and node name
#for s in names:
# print(s);
cube = names[0]
print(cube)
move(10, 0, 0, cube, r=True) # move (10, 0, 0), note that the order of arguments is different from MEL
just realised from the maya help doc:
"Objects and arguments are passed to commands as they would be in MEL, but they must be passed in the following order:
command arguments object flags/named arguments
This is different from MEL where the ordering requires that objects appear at the end of the argument list. However, Python requires that named arguments come after all other arguments."
eg.: move(10, 0, 0, cube, r=True) # python
MEL: move -r 10 0 0 cube
&
"Maya Python implementation requires you to assign a boolean argument to those flags that do not normally take any arguments."
eg.: file(f=True, new=True); # python
MEL: file -f -new
save the following python script on shelf:
import hello
reload(hello)
Script Editor > File > Save Script to Shelf...
this will facilitate easier execution of the hello.py script
PYTHONPATH="C:\Documents and Settings\{username}\My Documents\maya\scripts"
* for Mac OS, DON'T use double quotes "..."
instead eg.: PYTHONPATH = /Users/username/Documents/maya/scripts
default for Mac OSX: ~/Library/Preferences/Autodesk/maya/
start new hello.py file
put into the "scripts" folder
start maya. open Script Editor window
import hello
(to reload, use reload(hello))
.pyc compiled python also works in the scripts folder
sample py code:
print("hello world");
from maya.cmds import *
file(f=True, new=True); # new file
#select(all=True) # select all objects
#delete(all=True) # delete all objects. not supported anymore. Use "file -f -new;" instead.
# create a polygon cube
# store all names
names = polyCube(ch=True, o=True,w=5.038671,h=3.648038,d=3.788829,cuv=4)
# use for loop to print out the object and node name
#for s in names:
# print(s);
cube = names[0]
print(cube)
move(10, 0, 0, cube, r=True) # move (10, 0, 0), note that the order of arguments is different from MEL
just realised from the maya help doc:
"Objects and arguments are passed to commands as they would be in MEL, but they must be passed in the following order:
command arguments object flags/named arguments
This is different from MEL where the ordering requires that objects appear at the end of the argument list. However, Python requires that named arguments come after all other arguments."
eg.: move(10, 0, 0, cube, r=True) # python
MEL: move -r 10 0 0 cube
&
"Maya Python implementation requires you to assign a boolean argument to those flags that do not normally take any arguments."
eg.: file(f=True, new=True); # python
MEL: file -f -new
save the following python script on shelf:
import hello
reload(hello)
Script Editor > File > Save Script to Shelf...
this will facilitate easier execution of the hello.py script
Tuesday, August 25, 2009
1st try at Python
# for comments
variables. easy.
concatenating strings a bit more troublesome.
eg.:
i = 1.23
s = "hello"
a = s + i
will give error
have to convert to string
a = s + str(i)
b = True
b = not b #store False. same as b = !b
if-else conditions
while loop still ok. but must get used to the : at the back
eg.:
for loop v different.
functions
eg.:
classes and objects
modules
save into separate .py files
and then import
using import hello (if module is hello.py)
or use from hello import *
variables. easy.
concatenating strings a bit more troublesome.
eg.:
i = 1.23
s = "hello"
a = s + i
will give error
have to convert to string
a = s + str(i)
b = True
b = not b #store False. same as b = !b
if-else conditions
>>> if x < 0: ... x = 0 ... print 'Negative changed to zero' ... elif x == 0: ... print 'Zero' ... elif x == 1: ... print 'Single' ... else: ... print 'More' ...
while loop still ok. but must get used to the : at the back
eg.:
i = 0 while i<= 10: # : is equivalent of starting a curly brace { print i # identation used to indicate within while loop i = i + 1 # what happened to ++, --?!
for loop v different.
>>> # Measure some strings: ... a = ['cat', 'window', 'defenestrate'] >>> for x in a: ... print x, len(x)
OR
for i in range(10): print i # print 0, 1, 2,..., 9
functions
eg.:
def functionName(): print "running in function"
classes and objects
class MyClass: property = 1 # static variable
self.myVar = "hello" # instance variable def __init__(self, p): # contructor, self = this self.property = p def method1(self): # note the need for self, even with no arguments/parameters print "running method"
@staticmethod def staticMethod2(args, arg2): print "call me by classname, eg.: MyClass.staticMethod2(1,2)" x = MyClass() # instantiate print x.property x.method1() class DerivedClass(MyClass): # inheritance newProperty = 2 class SubSubClass(Class1, Class2, Class3): # multiple inheritance supported # fields & methods
modules
save into separate .py files
and then import
using import hello (if module is hello.py)
or use from hello import *
Thursday, August 06, 2009
Flash 10: Matrix3D
rawData is set as column major order
hence, gotta transpose to row major
var v:Vector.<Number> = Vector.<Number>(
[1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16]);
var m:Matrix3D = new Matrix3D();
m.rawData = v;
/*
matrix is stored as
[1, 5, 9, 13]
[2, 6, 10, 14]
[3, 7, 11, 15]
[4, 8, 12, 16]
*/
m.transpose();
/*
matrix is stored as
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
[13, 14, 15, 16]
*/
hence, gotta transpose to row major
var v:Vector.<Number> = Vector.<Number>(
[1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16]);
var m:Matrix3D = new Matrix3D();
m.rawData = v;
/*
matrix is stored as
[1, 5, 9, 13]
[2, 6, 10, 14]
[3, 7, 11, 15]
[4, 8, 12, 16]
*/
m.transpose();
/*
matrix is stored as
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
[13, 14, 15, 16]
*/
Monday, June 08, 2009
Thursday, June 04, 2009
Using Flex Library SWC with Flash CS3 FLA
Useful link: http://www.timwalling.com/2007/10/22/compiling-flash-cs3-compatible-swcs-with-flex/
It works.
1) manifest.xml
eg.:
<?xml version="1.0" encoding="utf-8"?>
<componentPackage>
<component id="OOPMLibrary" class="com.boon.OOPM" />
</componentPackage>
1b) Flex Library Compiler > Fill in Namespace URL and Manifest File
2) Compiler arguments: -compute-digest=false
3) put in the folder (WinXP): C:\Documents and Settings\{username}\Local Settings\Application Data\Adobe\Flash CS3\en\Configuration\Components
4) Flash CS3 > Components Panel > Reload (Menu)
It works.
1) manifest.xml
eg.:
<?xml version="1.0" encoding="utf-8"?>
<componentPackage>
<component id="OOPMLibrary" class="com.boon.OOPM" />
</componentPackage>
1b) Flex Library Compiler > Fill in Namespace URL and Manifest File
2) Compiler arguments: -compute-digest=false
3) put in the folder (WinXP): C:\Documents and Settings\{username}\Local Settings\Application Data\Adobe\Flash CS3\en\Configuration\Components
4) Flash CS3 > Components Panel > Reload (Menu)
Wednesday, May 20, 2009
Fireworks effect
Created a fireworks effect component.
FLA: fireworks_cs3.fla
Drag the fireworks component from the library to the Stage.
Modify the component parameters from the Component Inspector Panel. play around with different values for different effect.
parameters:
- burstVelMin/Max : min and max speed of the particles when fireworks explode. randomise. higher, faster
- colour: colour of fireworks
- drag: how fast the particles will slow down. lower number, slow down faster
- gravity: how fast the particle will fall downward. higher number, faster the drop
- numFramesToBurst: number of frames before the fireworks explode
- numParticles: number of particles when the the fireworks explode
- particleLifeSpan: number of frames before particles will disappear
- particleSizeGrowth: how fast the size of the particle will grow. higher number, bigger the growth
- trailDecay: how fast the trail will disappear. higher number, faster
- vx / vy: starting speed in x and y direction
FLA: fireworks_cs3.fla
Drag the fireworks component from the library to the Stage.
Modify the component parameters from the Component Inspector Panel. play around with different values for different effect.
parameters:
- burstVelMin/Max : min and max speed of the particles when fireworks explode. randomise. higher, faster
- colour: colour of fireworks
- drag: how fast the particles will slow down. lower number, slow down faster
- gravity: how fast the particle will fall downward. higher number, faster the drop
- numFramesToBurst: number of frames before the fireworks explode
- numParticles: number of particles when the the fireworks explode
- particleLifeSpan: number of frames before particles will disappear
- particleSizeGrowth: how fast the size of the particle will grow. higher number, bigger the growth
- trailDecay: how fast the trail will disappear. higher number, faster
- vx / vy: starting speed in x and y direction
Saturday, March 28, 2009
Wednesday, March 18, 2009
Tuesday, February 17, 2009
Flash webcam tracking experiment
Used the same logic in Touchless SDK. port it into Flash. tracking using colour histogram.
Use the mouse to drag and select an object to track.
Use the mouse to drag and select an object to track.
Monday, January 26, 2009
Flash 10, 3D and BSP Tree
Used a Binary Space Partitioning (BSP) Tree to sort the order of the triangles to be drawn on the screen using Flash 10 3D API.
http://psalmhundred.net/experiment/flash3d/coffee_table_bsp/
BSP Tree Component: BSPTree.swc
Updated BSPTree.swc: 01 Feb 2009. Resolved some bugs.
02 Feb 2009. optimised code
24 Feb 2009. changed code. using timer-based instead of loops to add triangles to tree nodes. to avoid script timeout limit.
1) Import package
import dmp.*;
2) Create a BSPTree object
var tree:BSPTree = new BSPTree();
3) Add the vertices and uvt data of the model
tree.add(vertices, uvt);
4) Sort by model composite transform or by camera location
tree.sortByModelTransform(compositeM, outVertices, outUVT);
OR
tree.sortByCameraLoc(cameraLoc, outVertices, outUVT);
5) Transform & project outVertices and outUVT to draw model
Source:
BSP Tree library
BSP Tree sample program
http://psalmhundred.net/experiment/flash3d/coffee_table_bsp/
BSP Tree Component: BSPTree.swc
Updated BSPTree.swc: 01 Feb 2009. Resolved some bugs.
02 Feb 2009. optimised code
24 Feb 2009. changed code. using timer-based instead of loops to add triangles to tree nodes. to avoid script timeout limit.
1) Import package
import dmp.*;
2) Create a BSPTree object
var tree:BSPTree = new BSPTree();
3) Add the vertices and uvt data of the model
tree.add(vertices, uvt);
4) Sort by model composite transform or by camera location
tree.sortByModelTransform(compositeM, outVertices, outUVT);
OR
tree.sortByCameraLoc(cameraLoc, outVertices, outUVT);
5) Transform & project outVertices and outUVT to draw model
Source:
BSP Tree library
BSP Tree sample program
Tuesday, January 20, 2009
Security Error 2148: while loading XML
http://adobeflash.wordpress.com/2007/01/13/error-2148-loading-xml-with-flex2-security-error/
adding the "-use-network=false" argument works in Flex Builder.
hmmm. strange. sometimes, it works without adding the argument.
adding the "-use-network=false" argument works in Flex Builder.
hmmm. strange. sometimes, it works without adding the argument.
Monday, January 19, 2009
OBJ to DMP format
A convertor I wrote using Actionscript 3.0 and Flex to convert from OBJ to a custom XML format i used for my students' assignment
link to OBJ format: http://en.wikipedia.org/wiki/Obj
Export from 3D tools, eg.: Maya, to OBJ format
Open the OBJ file in a text editor, eg.: Notepad. Copy and paste the data into this application. Enter the texture filename. and click "Convert"
link to OBJ format: http://en.wikipedia.org/wiki/Obj
Export from 3D tools, eg.: Maya, to OBJ format
Open the OBJ file in a text editor, eg.: Notepad. Copy and paste the data into this application. Enter the texture filename. and click "Convert"
Tuesday, January 06, 2009
3D in Flash 10
Loaded a COLLADA model from an external DAE file.
Use cursor keys, W,A,S,D and the mouse to manipulate the model.
Flash 10 player required. http://get.adobe.com/flashplayer/
Applied simple clipping, sorting of triangles.
Frame rate will drop when number of triangles is about 1K+.
http://psalmhundred.net/experiment/flash3d/TrianglesApp.html
Use cursor keys, W,A,S,D and the mouse to manipulate the model.
Flash 10 player required. http://get.adobe.com/flashplayer/
Applied simple clipping, sorting of triangles.
Frame rate will drop when number of triangles is about 1K+.
http://psalmhundred.net/experiment/flash3d/TrianglesApp.html
Wednesday, November 26, 2008
Sunday, November 16, 2008
Flash AS3 Custom Component - parameters
If the parameters are modified during authoring time,
they are not ready til after the constructor is called.
package{
import flash.display.*;
import flash.events.*;
import flash.net.*;
public class Testing extends MovieClip{
[Inspectable]
public var id:Number = 0;
function Testing(){
this.addEventListener(MouseEvent.CLICK, mouseclick);
}
function mouseclick(e:MouseEvent):void{
trace("id" + id);
}
}
}
they are not ready til after the constructor is called.
package{
import flash.display.*;
import flash.events.*;
import flash.net.*;
public class Testing extends MovieClip{
[Inspectable]
public var id:Number = 0;
function Testing(){
this.addEventListener(MouseEvent.CLICK, mouseclick);
}
function mouseclick(e:MouseEvent):void{
trace("id" + id);
}
}
}
Tuesday, August 12, 2008
Elastic Flash Demo
Key in a number from 2-20 in the textbox and click the button to generate an elastic object. Use the mouse to drag the dots.
Tuesday, July 08, 2008
Microsoft.Win32.OpenFileDialog affect FileIO operation
Just found out that if I use the following code to retrieve a filename, the FileStream will be affected as the current directory will be set to where the filename was taken from, eg.: "My Documents", instead of the Application Path.
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "All files (*.*)|*.*";
if ((bool)dialog.ShowDialog())
{
// store filename
}
// and later in the code
FileStream stream = new FileStream(
"mydata.bin", FileMode.Create);
BinaryWriter writer = new BinaryWriter(stream);
// write some data
stream.Close();
// "mydata.bin" will be saved in the current directory of OpenFileDialog
One solution will be to use the application path and extract the directory:
String path = System.Reflection.Assembly.GetExecutingAssembly().Location;
another will be to use RestoreDirectory property of the OpenFileDialog. set it to true.
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "All files (*.*)|*.*";
if ((bool)dialog.ShowDialog())
{
// store filename
}
// and later in the code
FileStream stream = new FileStream(
"mydata.bin", FileMode.Create);
BinaryWriter writer = new BinaryWriter(stream);
// write some data
stream.Close();
// "mydata.bin" will be saved in the current directory of OpenFileDialog
One solution will be to use the application path and extract the directory:
String path = System.Reflection.Assembly.GetExecutingAssembly().Location;
another will be to use RestoreDirectory property of the OpenFileDialog. set it to true.
Thursday, June 19, 2008
Flash 10 3D Demo - partial cube
NOT working. Flash 10 player has been updated to official release.

Requires Flash 10 (currently beta)
http://labs.adobe.com/downloads/flashplayer10.html
Demo of rotating cube(partial to see culling effect):
http://psalmhundred.net/experiment/flash3d/Flash10App.html

Requires Flash 10 (currently beta)
http://labs.adobe.com/downloads/flashplayer10.html
Demo of rotating cube(partial to see culling effect):
http://psalmhundred.net/experiment/flash3d/Flash10App.html
Flash 10 3D API - Utils3D.projectVectors(...)
Utils3D.projectVectors(m:Matrix3D, verts:Vector, projectedVerts:Vector, uvts:Vector) causes Flash player 10 beta to crash currently.
so just a workaround, a custom method to do similar thing:
public function projectVectors(projMatrix:Matrix3D, vert:Vector.<Number>,
v2D:Vector.<Number>, uvt:Vector.<Number>):void{
var temp:Vector.<Number> = new Vector.<Number>(vert.length);
projMatrix.transformVectors(vert, temp);
var z:Number = 0;
for(var i:int = 0; i<temp.length/3; i++){
z = temp[i*3+2];
z = focalLength / (focalLength+z);
// x' = f*x/(f+z), y' = f*y/(f+z)
v2D[i*2] = temp[i*3]*z;
v2D[i*2+1] = temp[i*3+1]*z;
// t = f/(f+z)
uvt[i*3+2] = z;
}
}
so just a workaround, a custom method to do similar thing:
public function projectVectors(projMatrix:Matrix3D, vert:Vector.<Number>,
v2D:Vector.<Number>, uvt:Vector.<Number>):void{
var temp:Vector.<Number> = new Vector.<Number>(vert.length);
projMatrix.transformVectors(vert, temp);
var z:Number = 0;
for(var i:int = 0; i<temp.length/3; i++){
z = temp[i*3+2];
z = focalLength / (focalLength+z);
// x' = f*x/(f+z), y' = f*y/(f+z)
v2D[i*2] = temp[i*3]*z;
v2D[i*2+1] = temp[i*3+1]*z;
// t = f/(f+z)
uvt[i*3+2] = z;
}
}
Thursday, April 12, 2007
WPF: Media Player
MediaPlayer player;
Uri uri = new Uri("pack://siteoforigin:,,,/music.mp3");
player = new MediaPlayer();
player.Open(uri);
player.Play();
Uri uri = new Uri("pack://siteoforigin:,,,/music.mp3");
player = new MediaPlayer();
player.Open(uri);
player.Play();
Wednesday, April 11, 2007
WPF: setting cursor
eg:
void Page1_MouseMove(object sender, MouseEventArgs e)
{
e.MouseDevice.SetCursor(Cursors.Hand); //-- hand cursor
e.MouseDevice.SetCursor(Cursors.None); //-- none, invisible
}
void Page1_MouseMove(object sender, MouseEventArgs e)
{
e.MouseDevice.SetCursor(Cursors.Hand); //-- hand cursor
e.MouseDevice.SetCursor(Cursors.None); //-- none, invisible
}
WPF: Image Drawing
XAML:
<Image Name="image1" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top" Height="200" Width="200" />
C#:
DrawingGroup group = new DrawingGroup();
DrawingImage di = new DrawingImage(group);
//-- create clipping bound for drawing group
RectangleGeometry myRectangleGeometry = new RectangleGeometry();
myRectangleGeometry.Rect = new Rect(0,0,250,250);
group.ClipGeometry = myRectangleGeometry;
image1.Source = di;
//-- load image source (refer to prev post)
ImageSource img2 = ...
//-- to draw something
using (DrawingContext dc = group.Open())
{
dc.DrawImage(img2, new Rect(x, y, w, h));
//-- and other stuff
}
<Image Name="image1" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top" Height="200" Width="200" />
C#:
DrawingGroup group = new DrawingGroup();
DrawingImage di = new DrawingImage(group);
//-- create clipping bound for drawing group
RectangleGeometry myRectangleGeometry = new RectangleGeometry();
myRectangleGeometry.Rect = new Rect(0,0,250,250);
group.ClipGeometry = myRectangleGeometry;
image1.Source = di;
//-- load image source (refer to prev post)
ImageSource img2 = ...
//-- to draw something
using (DrawingContext dc = group.Open())
{
dc.DrawImage(img2, new Rect(x, y, w, h));
//-- and other stuff
}
Friday, March 30, 2007
C#: using the prev LinkList
LinkList<Dog> list = new LinkList<Dog>();
list.addLast(new Dog("Rocky", 16));
list.addLast(new Dog("Waggie", 6));
list.remove(0);
list.get(0).bark();
list.addLast(new Dog("Rocky", 16));
list.addLast(new Dog("Waggie", 6));
list.remove(0);
list.get(0).bark();
C#: reading text files
using System;
using System.IO;
namespace FileIOText
{
class ReadTextFile
{
public ReadTextFile()
{
try
{
//-- "using" also closes the file
using (StreamReader sr = new StreamReader("data.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch(Exception e){
Console.WriteLine("File could not be read");
Console.WriteLine(e.Message);
}
}
}
}
using System.IO;
namespace FileIOText
{
class ReadTextFile
{
public ReadTextFile()
{
try
{
//-- "using" also closes the file
using (StreamReader sr = new StreamReader("data.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch(Exception e){
Console.WriteLine("File could not be read");
Console.WriteLine(e.Message);
}
}
}
}
C#: reading binary file
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace FileIOText
{
class ReadBinaryFile
{
const String filename = "binfile.dat";
public ReadBinaryFile()
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
/*
//create reader
BinaryReader br = new BinaryReader(fs);
Console.WriteLine(br.ReadInt32());
Console.WriteLine(br.ReadDouble());
Console.WriteLine(br.ReadBoolean());
Console.WriteLine(br.ReadString());
Console.WriteLine(br.ReadChar());
br.Close();
*/
BinaryFormatter formatter = new BinaryFormatter();
Dog d = (Dog)formatter.Deserialize(fs);
Console.WriteLine(d.Name);
Console.WriteLine(d.Age);
fs.Close();
}
}
}
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace FileIOText
{
class ReadBinaryFile
{
const String filename = "binfile.dat";
public ReadBinaryFile()
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
/*
//create reader
BinaryReader br = new BinaryReader(fs);
Console.WriteLine(br.ReadInt32());
Console.WriteLine(br.ReadDouble());
Console.WriteLine(br.ReadBoolean());
Console.WriteLine(br.ReadString());
Console.WriteLine(br.ReadChar());
br.Close();
*/
BinaryFormatter formatter = new BinaryFormatter();
Dog d = (Dog)formatter.Deserialize(fs);
Console.WriteLine(d.Name);
Console.WriteLine(d.Age);
fs.Close();
}
}
}
C#: writing to text file
using System;
using System.IO;
namespace FileIOText
{
class WriteTextFile
{
public WriteTextFile()
{
try
{
//-- "using" also closes the file
using (StreamWriter sw = new StreamWriter("data.txt"))
{
sw.Write("Hello...");
sw.WriteLine("This is the start of the writing...");
sw.WriteLine("------------------");
//-- write arbitrary objects
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
}
}
catch (Exception e)
{
Console.WriteLine("File could not be written");
Console.WriteLine(e.Message);
}
}
}
}
using System.IO;
namespace FileIOText
{
class WriteTextFile
{
public WriteTextFile()
{
try
{
//-- "using" also closes the file
using (StreamWriter sw = new StreamWriter("data.txt"))
{
sw.Write("Hello...");
sw.WriteLine("This is the start of the writing...");
sw.WriteLine("------------------");
//-- write arbitrary objects
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
}
}
catch (Exception e)
{
Console.WriteLine("File could not be written");
Console.WriteLine(e.Message);
}
}
}
}
C#: Writing binary file
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace FileIOText
{
class WriteBinaryFile
{
const String filename = "binfile.dat";
public WriteBinaryFile()
{
if(File.Exists(filename)){
Console.WriteLine("{0} already exists!", filename);
return;
}
FileStream fs = new FileStream(filename, FileMode.CreateNew);
/*
//create writer
BinaryWriter bw = new BinaryWriter(fs);
//create test data to write to file
int i = 299;
double d = 2.5999;
bool b = false;
String s = "Haha";
char c = 'A';
bw.Write(i);
bw.Write(d);
bw.Write(b);
bw.Write(s);
bw.Write(c);
*/
Dog d = new Dog("Rocky", 16);
Dog e = new Dog("Waggie", 10);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, d);
formatter.Serialize(fs, e);
//bw.Close();
fs.Close();
}
}
}
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace FileIOText
{
class WriteBinaryFile
{
const String filename = "binfile.dat";
public WriteBinaryFile()
{
if(File.Exists(filename)){
Console.WriteLine("{0} already exists!", filename);
return;
}
FileStream fs = new FileStream(filename, FileMode.CreateNew);
/*
//create writer
BinaryWriter bw = new BinaryWriter(fs);
//create test data to write to file
int i = 299;
double d = 2.5999;
bool b = false;
String s = "Haha";
char c = 'A';
bw.Write(i);
bw.Write(d);
bw.Write(b);
bw.Write(s);
bw.Write(c);
*/
Dog d = new Dog("Rocky", 16);
Dog e = new Dog("Waggie", 10);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, d);
formatter.Serialize(fs, e);
//bw.Close();
fs.Close();
}
}
}
C#: LinkList
using System;
using System.Collections.Generic;
using System.Text;
namespace List
{
[Serializable]
class LinkList<T>
{
int numOfElements = 0;
ListNode<T> headNode = null;
public LinkList() { }
public LinkList(T data) {
headNode = new ListNode<T>(data);
}
public bool isEmpty()
{
return (numOfElements == 0);
}
public int getNumOfElements()
{
return numOfElements;
}
public ListNode<T> find(int index)
{
ListNode<T> node = headNode;
if(index < 0 || index >= numOfElements){
throw new IndexOutOfRangeException("Error! Out of List index bounds");
}
for (int i = 0; i < index; i++ )
{
node = node.Next;
}
return node;
}
public T get(int index)
{
/*
if (index >= 0 && index < numOfElements)
{
return find(index).Data;
}*/
return find(index).Data;
}
public void add(int index, T data)
{
if (index == 0)
{
ListNode<T> newNode = new ListNode<T>(data, headNode);
headNode = newNode;
}
else if (index > 0 && index <= numOfElements)
{
ListNode<T> prevNode = find(index - 1);
ListNode<T> newNode = new ListNode<T>(data, prevNode.Next);
prevNode.Next = newNode;
}else{
throw new IndexOutOfRangeException("Error! Out of List index bounds");
}
numOfElements++;
}
public void addLast(T data)
{
add(getNumOfElements(), data);
}
public void remove(int index)
{
if (index == 0)
{
headNode = headNode.Next;
}
else if (index > 0 && index < numOfElements)
{
ListNode<T> prev = find(index - 1);
ListNode<T> current = prev.Next;
prev.Next = current.Next;
}
else
{
throw new IndexOutOfRangeException("Error! Out of List index bounds");
}
numOfElements--;
}
public void removeLast()
{
remove(numOfElements - 1);
}
}
}
using System.Collections.Generic;
using System.Text;
namespace List
{
[Serializable]
class LinkList<T>
{
int numOfElements = 0;
ListNode<T> headNode = null;
public LinkList() { }
public LinkList(T data) {
headNode = new ListNode<T>(data);
}
public bool isEmpty()
{
return (numOfElements == 0);
}
public int getNumOfElements()
{
return numOfElements;
}
public ListNode<T> find(int index)
{
ListNode<T> node = headNode;
if(index < 0 || index >= numOfElements){
throw new IndexOutOfRangeException("Error! Out of List index bounds");
}
for (int i = 0; i < index; i++ )
{
node = node.Next;
}
return node;
}
public T get(int index)
{
/*
if (index >= 0 && index < numOfElements)
{
return find(index).Data;
}*/
return find(index).Data;
}
public void add(int index, T data)
{
if (index == 0)
{
ListNode<T> newNode = new ListNode<T>(data, headNode);
headNode = newNode;
}
else if (index > 0 && index <= numOfElements)
{
ListNode<T> prevNode = find(index - 1);
ListNode<T> newNode = new ListNode<T>(data, prevNode.Next);
prevNode.Next = newNode;
}else{
throw new IndexOutOfRangeException("Error! Out of List index bounds");
}
numOfElements++;
}
public void addLast(T data)
{
add(getNumOfElements(), data);
}
public void remove(int index)
{
if (index == 0)
{
headNode = headNode.Next;
}
else if (index > 0 && index < numOfElements)
{
ListNode<T> prev = find(index - 1);
ListNode<T> current = prev.Next;
prev.Next = current.Next;
}
else
{
throw new IndexOutOfRangeException("Error! Out of List index bounds");
}
numOfElements--;
}
public void removeLast()
{
remove(numOfElements - 1);
}
}
}
C#: ListNode
using System;
using System.Collections.Generic;
using System.Text;
namespace List
{
[Serializable]
class ListNode<T>
{
ListNode<T> next = null; //-- self referencing node
T data; //-- data segment
public ListNode(T t)
{
data = t;
}
public ListNode(T t, ListNode<T> n):this(t) //-- call the prev constructor 1st
{
//-- then proceed to following line
next = n;
}
public T Data{
get { return data; }
set { data = value; }
}
public ListNode<T> Next
{
get { return next; }
set { next = value; }
}
}
}
using System.Collections.Generic;
using System.Text;
namespace List
{
[Serializable]
class ListNode<T>
{
ListNode<T> next = null; //-- self referencing node
T data; //-- data segment
public ListNode(T t)
{
data = t;
}
public ListNode(T t, ListNode<T> n):this(t) //-- call the prev constructor 1st
{
//-- then proceed to following line
next = n;
}
public T Data{
get { return data; }
set { data = value; }
}
public ListNode<T> Next
{
get { return next; }
set { next = value; }
}
}
}
Thursday, March 29, 2007
NTU Assignment Demos
Inverse Kinematics using Flash
Fluid Simulation using Flash
http://psalmhundred.net/NTU/
My favourite: the fluid simulation one. : )
Fluid Simulation using Flash
http://psalmhundred.net/NTU/
My favourite: the fluid simulation one. : )
Saturday, February 10, 2007
WPF: loading images, audio, video
hmmm. strange that loading images more ma2 fan2 than loading video/audio
must set width/height. tried without and no image : (
loading images:
Image LoadImage(String imageFileName)
{
// Create source
BitmapImage myBitmapImage = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri("pack://siteoforigin:,,,/" + imageFileName);
// To save significant application memory, set the DecodePixelWidth or
// DecodePixelHeight of the BitmapImage value of the image source to the desired
// height or width of the rendered image. If you don't do this, the application will
// cache the image as though it were rendered as its normal size rather then just
// the size that is displayed.
// Note: In order to preserve aspect ratio, set DecodePixelWidth
// or DecodePixelHeight but not both.
myBitmapImage.EndInit();
Image i = new Image();
i.Source = myBitmapImage;
i.Width = myBitmapImage.Width;
i.Height = myBitmapImage.Height;
return i;
}
loading audio/video:
xaml:
<MediaElement Grid.Row="2" Name="myMedia" LoadedBehavior="Manual"/>
cs:
myMedia.Source = new Uri("mymediafile.wmv", UriKind.Relative);
myMedia.Play();
must set width/height. tried without and no image : (
loading images:
Image LoadImage(String imageFileName)
{
// Create source
BitmapImage myBitmapImage = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri("pack://siteoforigin:,,,/" + imageFileName);
// To save significant application memory, set the DecodePixelWidth or
// DecodePixelHeight of the BitmapImage value of the image source to the desired
// height or width of the rendered image. If you don't do this, the application will
// cache the image as though it were rendered as its normal size rather then just
// the size that is displayed.
// Note: In order to preserve aspect ratio, set DecodePixelWidth
// or DecodePixelHeight but not both.
myBitmapImage.EndInit();
Image i = new Image();
i.Source = myBitmapImage;
i.Width = myBitmapImage.Width;
i.Height = myBitmapImage.Height;
return i;
}
loading audio/video:
xaml:
cs:
myMedia.Source = new Uri("mymediafile.wmv", UriKind.Relative);
myMedia.Play();
Friday, February 09, 2007
What am i busy with?
Hmm...
switch(task){
case 1:
prepareFor1stBorn(); //-- baby coming
break;
case 2:
doASsignments(); //-- NTU modules
break;
case 3:
doResearch(); //-- NTU dissertation
break;
case 4:
mark(); //-- mark exam papers
break;
}
switch(task){
case 1:
prepareFor1stBorn(); //-- baby coming
break;
case 2:
doASsignments(); //-- NTU modules
break;
case 3:
doResearch(); //-- NTU dissertation
break;
case 4:
mark(); //-- mark exam papers
break;
}
How to teach programming???
am waiting for wifey at her office. still cracking my brain how to teach oopm more effectively... :(
//-- status now
boolean isFrustrated = true;
while(isFrustrated){
thinkSomeMoreIdeas();
}
//-- status now
boolean isFrustrated = true;
while(isFrustrated){
thinkSomeMoreIdeas();
}
Thursday, February 01, 2007
AS3: SoundMixer.computeSpectrum()
public static function computeSpectrum(outputArray:ByteArray, FFTMode:Boolean = false, stretchFactor:int = 0):void
Takes a snapshot of the current sound wave and places it into the specified ByteArray object. The values are formatted as normalized floating-point values, in the range -1.0 to 1.0. The ByteArray object passed to the outputArray parameter is overwritten with the new values. The size of the ByteArray object created is fixed to 512 floating-point values, where the first 256 values represent the left channel, and the second 256 values represent the right channel.
Takes a snapshot of the current sound wave and places it into the specified ByteArray object. The values are formatted as normalized floating-point values, in the range -1.0 to 1.0. The ByteArray object passed to the outputArray parameter is overwritten with the new values. The size of the ByteArray object created is fixed to 512 floating-point values, where the first 256 values represent the left channel, and the second 256 values represent the right channel.
Flash: BitmapData.draw
Draws a source image or movie clip onto a destination image, using the Flash Player vector renderer
draw(source:Object, [matrix:Matrix], [colorTransform:ColorTransform], [blendMode:Object], [clipRect:Rectangle], [smooth:Boolean])
draw(source:Object, [matrix:Matrix], [colorTransform:ColorTransform], [blendMode:Object], [clipRect:Rectangle], [smooth:Boolean])
Subscribe to:
Posts (Atom)