Sunday, January 08, 2012

iOS: search bar with table view

// assuming table view is done
VC .h

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
{
    // ADDED
    NSMutableArray *tableData;
    NSArray *array;
    NSMutableArray *searchResults;
    
    IBOutlet UITableView *tableView;
}

@property (nonatomic, retain) NSArray *array;

@end


// assuming table view is done
VC .m
// ADDED: to search
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"searching: %@", searchText);
    searchText = [searchText lowercaseString];
    // search for text in array
    if(searchText.length > 0)
    {
        [tableData removeAllObjects];// clear all data
        [searchResults removeAllObjects];
        for (NSString *ostr in array)
        {
            //NSLog(@"looping: %@", str);
            NSString *str = [ostr lowercaseString];
            NSRange range = [str rangeOfString:searchText];
            if(range.location != NSNotFound)
            {
                NSLog(@"matched: %@", searchText);
                [searchResults addObject:ostr];
            }
        }
        //[tableData removeAllObjects];
        [tableData addObjectsFromArray:searchResults];
        [tableView reloadData];
    }
    else
    {
        [tableData removeAllObjects];// clear all data
        [tableData addObjectsFromArray:array];
        [tableView reloadData];
    }
}


- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"Cancel Button Clicked");
    [searchBar resignFirstResponder]; // close keyboard
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"Search Button Clicked");
    [searchBar resignFirstResponder]; // close keyboard

}

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    tableView.delegate = self;
    tableView.dataSource = self;
    
    // ADDED
    self.array = [NSArray arrayWithObjects:@"Beng", @"Seng", @"Lian", @"Beng2", @"Seng2", @"Lian2", nil];
    // must alloc and init. strange. cannot use arrayWithArray
    tableData = [[NSMutableArray alloc] init]; //[NSMutableArray arrayWithArray:self.array];
    searchResults = [[NSMutableArray alloc] init];//[NSMutableArray arrayWithArray:self.array];
    [tableData addObjectsFromArray:self.array];
    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width0)];
    [searchBar sizeToFit];
    searchBar.delegate = self;
    [searchBar setShowsCancelButton:YES animated:YES];
    //[searchBar showsSearchResultsButton];
    [self.view addSubview:searchBar];
    
    // place tableview just below search bar. else, the first row of the table view will be hidden behind search bar
    // hence adjust the y and height in the (x,y,w,h) of the table view's frame
    [tableView setFrame:CGRectMake(0, searchBar.frame.size.height, tableView.frame.size.width, tableView.frame.size.height - searchBar.frame.size.height)];
}



Saturday, January 07, 2012

iOS: Table View

// in table view controller .h

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
    // ADDED
    NSArray *array;
    IBOutlet UITableView *tableView;
}

@property (nonatomic, retain) NSArray *array;

@end

// in table view controller .m
@implementation ViewController
@synthesize array;

// ADDED: method to handle table cell click
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"click cell: %i", indexPath.row);
    // show another VC
    AboutVC *avc = [[AboutVC alloc] initWithNibName:@"AboutVC" bundle:nil];
    [self.view addSubview:avc.view];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
    }
    // ADDED
    cell.textLabel.text = [self.array objectAtIndex:indexPath.row]; // text label of the cell
    cell.imageView.image = [UIImage imageNamed:@"myimage.gif"]; // image on the left
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; // show a '>' button
    // end 
    
    return cell;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    tableView.delegate = self;
    tableView.dataSource = self;
    
    // ADDED
    self.array = [NSArray arrayWithObjects:@"Beng", @"Seng", @"Lian", nil];
}







iOS: UITabBarController


// in root view controller .m

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    UITabBarController *tbc = [[UITabBarController alloc] init];
    
    // create VC instances
    AboutVC *avc = [[AboutVC alloc] initWithNibName:@"AboutVC" bundle:nil];
    ContactVC *cvc = [[ContactVC alloc] initWithNibName:@"ContactVC" bundle:nil];
    
    // set tab bar properties if necessary. use system defined tab if necessary
    UITabBarItem *tbitem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:1];
    // link VC to this tab bar item
    [cvc setTabBarItem:tbitem];
    
    // interesting that if title is set in VC, it overrides the title here
    UITabBarItem *tbitem2 = [[UITabBarItem alloc] initWithTitle:@"Hmm" image:[UIImage imageNamed:@"myimage.gif"] tag:2];
    // link VC to this tab bar item
    [avc setTabBarItem:tbitem2];
    
    // create array storing all the VCs
    NSArray *arr = [NSArray arrayWithObjects:avc, cvc, nil] ;
    
    // link array to tab bar controller. if title is set in VC, it will show in tab bar
    [tbc setViewControllers:arr];
    
    // set the view bounds of tab bar
    [tbc.view setFrame:self.view.bounds];
    
    // add tab bar to current view
    [self.view addSubview:tbc.view];
}

iOS: UINavigationController


// in app delegate .m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    
    //NEW - start
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:self.viewController];
    self.window.rootViewController = nc;
    [nc release];
    // end

    [self.window makeKeyAndVisible];
    return YES;
}

// in viewcontroller .m ; assume IBAction to a button to click to go to another VC
-(IBAction) m1:(id)sender
{
    NSLog(@"about us");
    // NEW: create VC instance and push into nav controller
    AboutVC *about = [[AboutVC alloc] initWithNibName:@"AboutVC" bundle:nil];
    [self.navigationController pushViewController:about animated:YES];
}

// in AboutVC.m
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // NEW: set title on title bar of nav controller
    [self setTitle:@"About Us"];
}

iOS: Delegates

it works like an interface
Example:

@interface myVC:UIViewController <UIWebViewDelegate>
{
}
@end

// assume webViewToLoad IBOutlet
[webViewToLoad setDelegate:self];

// implement methods of delegate
-void webViewDidStartLoad: (UIWebView *) webview
{
  NSLog(@"started loading...");
}

-void webViewDidFinishLoad: (UIWebView *) webview
{
  NSLog(@"finished loading...");
}


iOS: Memory management

retain - increment reference count by 1
release - decrement by 1
retainCount - reference count
autorelease

tool
xcode > product > analyze

iOS: UIWebView

Assuming that IBOutlet urlTxtField and webViewToLoad
NSString *urlToLoad = [NSString stringWithString : @"http://www.google.com"];
[self.webViewToLoad loadRequest : [NSURLRequest requestWithURL : [NSURL URLWithString : urlToLoad]]];
[urlTxtField setText : urlToLoad];

// assume button IBAction
[urlTxtField resignFirstResponder]; //dismiss keyboard
[self.webViewToLoad loadRequest : [NSURLRequest requestWithURL : [NSURL URLWithString : urlTxtField.text]]];

iOS: View Programming


Eg.:
UILabel *label = [[UILabel alloc] init];
CGRect bounds = CGRectMake(10, 20, 300, 200);
[label setText:@"This is a label"]; // put some text, if not, nothing seen on screen
[label setFrame:bounds];
[self.view addSubview:label];

// loading image
UIImage *img = [UIImage imageNamed:@"image.jpg"];    
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
// add to view with the same steps as above
...
// set color
[self.view setBackgroundColor:[UIColor colorWithRed:0.1 green:0.7 blue:0.3 alpha:1]];
Note:
UIButton has a class method to create a button. [UIButton buttonWithType:UIButtonTypeRoundedRect]

To programmatically add an action to a button, use addTarget:action:forControlEvents: of the UIControl
Example:
[button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
...
-(void) btnPressed:(id) sender
{
   UIButton *btn = (UIButton *) sender;
   if([btn.titleLabel.text isEqual:@"button label"])
   {
      // code to do something
   }
}

// to remove
[self.view removeFromSuperview];

To load and display a ViewController from XIB file

Screen01ViewController.m
Screen02ViewController *next = [[Screen02ViewController alloc] initWithNibName:@"Screen02ViewController" bundle:nil];    
[self.view addSubview:next.view]; // will put the new view on top of this current view
...

Screen02ViewController.m
[self.view removeFromSuperview]; // if you are done with this view and wants to close it

iOS: more basics

Random numbers
random() // gives you 0-(2^31-1)
to generate random number from 0 to 9: random() % 10
3 to 18: random() % ( 18-3 +1) + 3

if need numeric pad for textfield, interface builder > text input trait > num pad

Timer
NSTimer
[NSTimer timerWithTimeInterval:0.5 /* seconds */ invocation: invocation repeats:YES]

NSDate
NSDate *now = [[NSDate alloc] init];
[date2 timeIntervalSinceDate:date1]; returns seconds
[date1 release];

iOS basics

- Variables: int, float, double
- Operators: +, -, *, /, %
- Conditional statements: if-else, switch-case
- Loops: for, while, do-while
- printf() function
- viewDidLoad event


Example:
int i = 1;
float f = 2.3;
printf("This is a string with integer: %d and a floating point number: %f", i, f);
NSLog(@"This is a string with integer: %d and a floating point number: %f", i, f);



Constants:
.h
extern const int MY_NUMBER;
.m
const int MY_NUMBER = 123;



Outlets
in .h
UITextField *tf;
@property (nonatomic, retain) IBOutlet UITextField *tf;

in .m
@synthesize tf;
tf.text = @"Hello textfield";

in .xib
Reload class files, if necessary
File's Owner > Ctrl+Click and drag to textfield in "View" > New reference (outlet)

Actions
in .h
-(IBAction) whatToDoWhenButtonClicked:(id)sender;

in .m
-(IBAction) whatToDoWhenButtonClicked:(id)sender {
// do what ever
tf.text = @"button clicked";
}

in .xib
Reload class files, if necessary
Ctrl+click button in "View" and drag to "File's Owner" > "whatToDoWhenButtonClicked" (Action) TouchUpInside

NSString
NSString *str = [NSString stringWithFormat: @"string %@ with %d and %f", someWords, i, f]
float f = [str floatValue]
int i = [str intValue]



Object-Oriented Programming (OOP)
@interface
@property
@implementation
@synchronise
@end
methods








Creating a custom class, MyClass

  1. MyClass.h
    @interface MyClass : NSObject {
       float myfloat;
       int myint;
    }
    @property float myfloat;
    @property int myint;
    -(void) myMethodWithParameter:(float) param1
    @end
  2. MyClass.m
    #import "MyClass.m"
    @implementation MyClass
    @synthesize myfloat;
    @synthesize myint;
    -(void) myMethodWithParameter:(float) param1
    {
       NSLog(@"this is my method with %f", param1);
    }
    @end

Instantiation of an object and using the object

MyClass *myObject = [MyClass alloc];
[myObject init]; // or [[MyClass alloc] init];
[myObject myMethodWithParameter:4.5];
[myObject release];






NSNumber
NSNumber *fNum = [NSNumber numberWithFloat:12.3];
float f = [fNum floatValue];
NSString *str = [fNum stringValue];
NSNumber reference

NSArray & NSMutableArray
NSArray *names01 = [NSArray arrayWithObjects: @"Beng", @"Siti", @"Dinesh"];
NSMutableArray *names02 = [NSMutableArray arrayWithObjects: @"Beng", @"Siti", @"Dinesh"];
int number = [names01 count];
NSString *firstName = [names01 objectAtIndex:0];
OR for fast enumeration
for(NSString *n in names01)
{
NSLog(@"The name is %@", n);
}

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>