Sunday, November 13, 2011

HTML5 + Javascript

few lessons learnt:
  1. <script /> is not valid. must use closing tag </script>
  2. made a simple mistake and debug like crazy:
    canvas = document.getElementById("test");
    context = canvas.getContext("2d");
    context.fillStyle("#FF0000"); //SHOULD have been context.fillStyle = "#FF0000";
    context.fillRect( 10, 20, 100, 50);

    More canvas reference: http://www.w3schools.com/html5/html5_ref_canvas.asp
  3. must use addEventListener for mouse input: canvas.addEventListener("mousedown", mDown, false);
  4. cannot get mouse (x,y) relative to canvas top left (0,0) so must manually calculate:
    var mouseX = (e.pageX -canvas.offsetLeft );
    var mouseY = (e.pageY -canvas.offsetTop);
  5. OOP
    function A() // create a class
    {
    this.v = 1; // fields or variables
    this.name = "haha";
    }
    A.prototype.constructor = A;
    A.prototype.m1 = function(){ // methods
    this.v++;
    }
    A.prototype.m2 = function(){
    this.v+=10;
    }
    // new class
B.prototype = new A();
B.prototype.constructor = B;

function B(){

  A.call(this); // call super class constructor if necessary

  this.x = 2;
}
B.prototype.m2 = function()
{
  A.prototype.m2.call(this); // call super class method if necessary
  // do additional stuff
}

var b = new B(); // create instance. BUT instantiation MUST be after the class declaration. debugged for a long time.

Tuesday, October 18, 2011

Flash player 11 + Flash builder 4.5 + Flash CS5

Finally managed to get flash builder 4.5 to publish SWF for flash player 11. 
specifically using Stage3D
  1. Download the PlayerGlobal SWC and debugger player from http://www.adobe.com/support/flashplayer/downloads.html
  2. go to flash builder installation path: "Adobe Flash Builder 4.5\sdks\4.5.1\frameworks\libs\player"
  3. create a new folder "11.0"
  4. copy the SWC into this folder. 
  5. install the debugger player for your browser
  6. Create a new ActionScript project
  7. Go to project properties > Flash Player version > 11.0.0
  8. Add "-swf-version=13" under Compiler Arguments
  9. Add code. eg.: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display3D/Context3D.html#drawTriangles() 
  10. Run the application. 
should work now.

for Flash CS5
  1. Do the same as above for step 1
  2. go to flash cs5 installation path: "\Adobe Flash CS5\Common\Configuration\ActionScript 3.0"
  3. create a new folder "FP11"
  4. copy the SWC into this new folder
  5. go to: "Adobe Flash CS5\Common\Configuration\Players" folder
  6. copy the old "FlashPlayer10_1.xml" to paste as a new "FlashPlayer11.xml"
  7. Edit the XML using NotePad
    Change the following:
    'player id="FlashPlayer11" version="13" asversion="3"'
    '<name>Flash Player 11</name>'
    'as3="$(AppConfig)/ActionScript 3.0/FP11/playerglobal.swc" '
  8. Save and close the XML. 
  9. Go to folder: "Adobe Flash CS5\Players\Debug"
  10. copy the debugger EXE into this folder. change the original FlashPlayerDebugger.exe to  FlashPlayerDebugger_OLD.exe and change the name of the copied EXE to  FlashPlayerDebugger.exe 
  11. Close Flash CS5 and restart. 
  12. Create a new Actionscript 3 FLA.
  13. In Profiles > Version > Flash Player 11
  14. Change rendering to "Direct"
  15. Run the movie by using the Debug movie. Ctrl+shift+enter

Monday, August 22, 2011

Android phone: cannot send sms & make outgoing call

What an experience i have with an Android phone. Samsung Nexus S in particular.
1) cannot charge to 100%. had switched batt and sent to change motherboard. known problem in forums
2) found out later that this is different from Google Nexus S with AMOLED display
3) battery drains pretty fast, comparing to previous experience with iPhone 3G
4) recent encounters: SMS cannot be sent out and cannot make outgoing call when 3G data network is switched on. when switched to GPRS, it's ok. changed SIM card, sent phone for change of motherboard, still same problem. finally saw one suggestion in forums, clear data for the stock "Dialler" and "Messaging" apps. been working well so far.
Steps: Settings > Applications > Manage applications > All > "Dialler" AND "Messaging" > Clear Data

Afternote: the above does not solve the problem with 3G and SMS and voice calls (item 4). in the end, have to wait til M1 and Samsung to resolve this issue from their side. I'm just glad this saga is over and hope that it is the last of this phone. enough of bad experience.

Wednesday, May 11, 2011

BitmapData: histogram

public function histogram(hRect:Rectangle = null):Vector.<Vector.<Number>>

Computes a 256-value binary number histogram of a BitmapData object. This method returns a Vector object containing four Vector. instances (four Vector objects that contain Number objects). The four Vector instances represent the red, green, blue and alpha components in order. Each Vector instance contains 256 values that represent the population count of an individual component value, from 0 to 255.

var hist:Vector.<Vector.<Number>> = bmpData.histogram();
// RGBA order
hist[0][9] = number of pixels having the red color component 9. eg.: 0x093366
total of hist[0][0-255] = total number of pixels in hRect region of bmpData.

flash + webcam + color tracking

Created pixel bender shaders to convert RGB to HSV
Used probability densities to back project histogram
using camshift algorithm

http://psalmhundred.net/experiment/webcam/webcam_demo_color_detect.html

Wednesday, April 06, 2011

Android AVD error

after installing eclipse, JDK, ADT, created AVD
created project
run and experience the following error

emulator: ERROR: unknown virtual device name

gotta add environment variable "ANDROID_SDK_HOME"
and set it to "D:\Users\{username}"
or where the ".android" is.

restart eclipse
and run again.
should be ok now.

Friday, March 11, 2011

render 2011: ddm & dmat graduation show





finally website done (Oct 2010 - Mar 2011). for Dip in Digital Media & Dip in Music and Audio Tech
www.render.sg

mobile site: http://2011.render.sg


Thanks to the following DDM IA students:
Shihui (actionscript), Meixian (backend), Bryan (flash), Mira (design)

& colleagues: Leon Lim (music), Leon Chua (graphic)

Monday, February 07, 2011

Ctrl Fre@k website completed on 5 Jan

finally finished the website on 5 Jan. Used wordpress and customised the theme for Ctrl Fre@k.
Visit Ctrl Fre@k at http://ctrlfreak.sg

Wednesday, December 29, 2010

Flash: Inverse kinematics in external AS class

realised the following in IKManager reference: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/fl/ik/IKManager.html?filter_flash=cs5&filter_flashplayer=10.1&filter_air=2#eventSummary

Note: When referencing IKArmature objects within a document class, be sure to first check the frameConstructed event to ensure that all objects have been populated.

else IKManager.numArmatures = 0 and IKManager.trackAllArmatures(false) will not work.

the bad thing is frameConstructed runs every frame. so one way is to use a boolean variable to track and run the code once.

can also use ENTER_FRAME

eg.:

public function IK_MC() // constructor
{
trace("start ik");

IKManager.trackAllArmatures(false); // will not work
this.addEventListener(Event.ENTER_FRAME, constructed);
}
function constructed(e:Event):void
{
//trace(IKManager.numArmatures);
if(IKManager.numArmatures > 0 && !init)
{
IKManager.trackAllArmatures(false);

var arm:IKArmature = IKManager.getArmatureByName("Armature_2");
trace(arm);
var arm2:IKArmature = IKManager.getArmatureAt(0);
trace(arm2);
init = true;
}
}

Friday, December 24, 2010

OpenGL: intro program

first program from red book chapter 1

create a new empty project in VS C++
download the GLUT headers + binaries. http://www.xmission.com/~nate/glut.html


#include <Windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "glut.h"
#include <stdlib.h>

static GLfloat spin = 0.0;

void init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_FLAT);
}

void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glRotatef(spin, 0.0, 0.0, 1.0);
glColor3f(1.0, 1.0, 1.0);
glRectf(-25.0, -25.0, 25.0, 25.0);
glPopMatrix();
glutSwapBuffers();
}

void spinDisplay(void)
{
spin = spin + 2.0;
if (spin > 360.0)
spin = spin - 360.0;
glutPostRedisplay();
}

void reshape(int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

void mouse(int button, int state, int x, int y)
{
switch (button) {
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc(spinDisplay);
break;
case GLUT_MIDDLE_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc(NULL);
break;
default:
break;
}
}

/*
* Request double buffer display mode.
* Register mouse input callback functions
*/
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize (400, 400);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}

Sunday, November 28, 2010

python: lists

to use data structures
list
http://docs.python.org/tutorial/introduction.html#lists
a = [1, 3,4,2]
names = ['BY', 'jon']
#access individual items
eg.: a[2]
cannot use index beyond list range
so gotta use
methods: append, insert
(http://docs.python.org/tutorial/datastructures.html)
eg.: a.append(1000)
to find size of list: len(a)

iphone + flash cs4 + AIR 2.5 SDK

1) downloaded AIR 2.5 SDK
2) followed instructions on forum: http://forums.adobe.com/thread/745398
/******************************
Quit Flash CS4 Professional if it is open.
Navigate to the Flash CS4 installation folder. The default location on Windows is "C:\Program Files\Adobe\Adobe Flash CS4\" and on Mac OS "/Applications/Adobe Flash CS4/"
Within the "Adobe Flash CS4" folder you should see a folder called "AIK1.5". If this folder is not present repeat step #1.
Rename the folder "AIK1.5" to "AIK1.5 OLD" or delete it if you do not need to save a copy of it.
Make a new folder called "AIK1.5"
Download the Adobe AIR 2 SDK from the labs website and uncompress the contents of the folder to the new "AIK1.5" folder you just created.
Copy the "airglobal.swc" file located within the "Adobe Flash CS4/AIK1.5/frameworks/libs/air/" folder into the "Adobe Flash CS4/Common/Configuration/ActionScript 3.0/AIR1.5/" folder.
**************************************/
3) File > New > Actionscript 3 (AIR)
4) Save and Ctrl + Enter
5) Properties > AIR settings > Use custom application descriptor file. point to generated app.xml in folder where FLA is saved
6) modify app.xml:
namespace 1.5 to 2
<application xmlns="http://ns.adobe.com/air/application/2.0">
add "autoOrients", "icons" tags, etc
7) Ctrl + Enter again to run the application
8) use PFI to create IPA.
9) Install on iphone and test.

tested working.

Saturday, November 27, 2010

iphone + air 2.5 sdk + Flash Builder

File > New > Flex Project
Next > Next > last dialog
Main application file > replace .mxml with .as
Finish
.as created. class extends Sprite
open app.xml
set visible to true:
<application><initialWindow><visible>true</visible></initialWindow></application>
F11 to debug
empty window should appear
Project > Properties > Flex Compiler > options/arguments: -default-size 320 480

Sunday, November 21, 2010

3dsmax: COM classes

create .NET classes
register assembly (DLL) to COM

Python:
reference:
http://techarttiki.blogspot.com/2008/03/calling-python-from-maxscript.html
http://oreilly.com/catalog/pythonwin32/chapter/ch12.html

python COM server

class PythonUtilities:
_public_methods_ = [ 'AreaOfCircle' ]
_reg_progid_ = "PythonDemos.Utilities"
# NEVER copy the following ID
# Use "print pythoncom.CreateGuid()" to make a new one.
_reg_clsid_ = "{968B74C1-5B12-47CE-93DF-EE2C1418A542}"


def AreaOfCircle(self, radius):
return 3.14159 * radius * radius


# Add code so that when this script is run by
# Python.exe, it self-registers.
if __name__=='__main__':
print "Registering COM server..."
import win32com.server.register
win32com.server.register.UseCommandLine(PythonUtilities)



then compile and run this class...

in 3DS max > MAXScript Listener:

comObj = createOLEObject "PythonDemos.Utilities"
a = comObj.AreaOfCircle(10)


but have to reload 3DS max whenever the COM class is changed

Saturday, November 20, 2010

3dsmax: UI


-- UI
rollout addition "Addition of two numbers"
(
-- UI elements
edittext text1 "First number"
edittext text2 "Second number"
button b "Add"
label lbl "Result"
-- event handlers
on b pressed do
(
a1 = text1.text as float
a2 = text2.text as float
c = a1 + a2
lbl.text = c as string
)
)


in MAXScript listener:

-- create a dialog 320 x 240
createDialog addition 320 240


math operator: +, -, *, /
% = mod number1 to number 2
+=, -=, *=, /=

3dsmax: loops, array, struct, as


-- do-while loop
i = 0
do
(
b = box()
b.pos.x = i * 10
--print i
i = i +1
)while (i <a)

-- while loop
i = 0
while(i < a) do
(
print i
i = i+1
)

-- array
arr = #(1, 2, 3, 4)
-- one-based index
print arr[3]

-- struct
struct Fan
(
-- member variables
speed,
radius,
isOn,
-- member function
function setSpeed spd=
(
speed = spd
),
function getSpeed=
(
return speed
),
-- special: calling function when object is constructed
-- can only call function AFTER it is created. eg.: setSpeed()
speed = setSpeed(1)
)
-- initiating structure
f = Fan()
f.radius = 10
f.setSpeed(3)

-- using "as" command
str = "The fan speed is " + fan.getSpeed() as string

Friday, November 19, 2010

3ds max: MAXScript basics

comments:
-- single line comment
/* multi-line comment */

variables. simple. no need to declare. eg.: a = 3

F11 - Script listener. something like Output panel in flash. but it allows u to key in scripts directly

(.) dot operator = object properties
($) superscript = can use it to reference an object using pathname. eg.: $Sphere01.

point3 data type
eg.:


newpos = point3 10 0 0
b.pos = newpos
function parameter in any order
FunctionName keyword1:value1 keyword2:value2

5 /9 = 0. so if need decimal place, must use 5.0/9 or 5 / 9.0 or 5.0 / 9.0

custom function:
function celsiusToFahrenheit celsius =
(
fah = 5.0/9 * (celsius - 32)
return fah
)

returns fah automatically if without 'return fah'

pass by value default
pass by reference using (&) symbol

if-then-else
eg.:
if(zz > 100) then messagebox "hot"


example 2
function testIF a=
(
if(a > 0) then
(
messagebox "more than zero"
)
else if(a == 0) then
(
messagebox "equal to zero"
)
else
(
messagebox "less than zero"
)
)
and, or operator. literally use "and" and "or"

for loop
eg.:
function testFor a=
(
for i=1 to a do
(
b = box()
b.pos.x = i * 10
)
)


do-while loop
do
(
statements(s)
)
while(conditions)

while-do loop
while(conditions) do
(
statement(s)
)

Sunday, November 14, 2010

CSS: clear:both

assume using a container,
inside it a header,
then a left content, right side bar
then a footer

"
Clearing Method

Because all the columns are floated, this layout uses a clear:both declaration in the .footer rule. This clearing technique forces the .container to understand where the columns end in order to show any borders or background colors you place on the .container. If your design requires you to remove the .footer from the .container, you'll need to use a different clearing method. The most reliable will be to add a <br class="clearfloat" /> or <div class="clearfloat"></div> after your final floated column (but before the .container closes). This will have the same clearing effect.
"


Sample:
with CLEAR:BOTH
container
header
left content

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
right sidebar

footer



without CLEAR:BOTH (Different browsers, eg.: IE, safari, chrome, firefox, will have different rendering)
container
header
left content

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
right sidebar

footer

Wednesday, October 13, 2010

Flash Builder 4 + iphone packager

1) create actionscript project
2) code AS
3) compile > test > SWF
3a) Create application.xml (refer to below)
4) PFI + .mobileprovision + .p12 + all necessary files > IPA
eg.:
pfi.bat -package -target ipa-test -provisioning-profile "MyApp.mobileprovision" -storetype pkcs12 -keystore "iphone_dev.p12" HelloWorld.ipa application.xml MyApp.swf
Default.png icons [and other files or folders]
5) install .mobileprovision in itunes if not done so. File > Add to library. sync iphone
6) add IPA to itunes. sync.

application.xml:
<?xml version="1.0" encoding="utf-8"?>
<application xmlns="http://ns.adobe.com/air/application/2.0">
<id>com.myDomain.MyApp</id>
<filename>HelloWorld</filename>
<name>HelloWorld</name>
<version>1.0</version>
<initialWindow>
<content>MyApp.swf</content>
<fullScreen>true</fullScreen>
<autoOrients>false</autoOrients>
<aspectRatio>portrait</aspectRatio>
<renderMode>cpu</renderMode>
</initialWindow>
<icon>
<image512x512>icons/icon512.png</image512x512>
<image57x57>icons/icon57.png</image57x57>
<image29x29>icons/icon29.png</image29x29>
</icon>
</application>

Tuesday, October 05, 2010

iPhone development: Objective C

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;

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

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

Sunday, July 25, 2010

Flash: Weather RSS feed











Flash & XML: namespace

sample RSS feed: http://weather.yahooapis.com/forecastrss?w=1062605&u=c

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:

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:

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

/**
* 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);

}

Wednesday, June 02, 2010

OpenGL: Stereoscopic rendering

Source: http://www.orthostereo.com/geometryopengl.html

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;

}

XNA: 3D and 2D

Gotta reset settings when mixing 3D and 2D content

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:


/*
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


sigh.. took the shots in a rush with a baby in the babybjorn tugging at the camera.
exposure inconsistent, horizon tilted, people moving and thus at different locations in different shots, etc.

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.

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.

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.

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"]

Monday, December 21, 2009

Sunday, December 13, 2009

Wiimote interactive art




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

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.


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

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.

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();
}

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:

<?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.

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' ) ;

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();

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' )



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


file(f=True, new=True); # new file
i=0
n = 10
while i< n:
size = random.uniform(0.1, 5)
names = polyCube(o=True, w=size, h=size, d=size)
cube = names[0]
move(random.uniform(-5, 5),
random.uniform(-5, 5),
random.uniform(-5, 5), cube, r=True)
i = i+1


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

Recertified Flash and Dreamweaver CS4 ACE

Yay! passed the recertification exam for Flash and Dreamweaver CS4 ACE

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
>>> 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]
*/

Monday, June 08, 2009

TBY appears on ST paper


ha. found this newspaper clipping while clearing my old office.
ST, Tech & Sci, H9, 28 Aug 2003

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)

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

Saturday, March 28, 2009

Mobile Assignment done during NTU course

Collection of images done for my mobile design assignment:


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.