Sunday, December 30, 2012

WebGL: creating a plane


function initQuadBuffer(){
triangleVertexPositionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
    var vertices = initPlaneArray(1, 1, 10, 10);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
    triangleVertexPositionBuffer.itemSize = 3; // (x, y, z)
    triangleVertexPositionBuffer.numItems = 6*10*10; // number of vertices
}
function initPlaneArray(w, h, rows, cols){
var vertices = new Array();
var dx = w / cols;
var dy = h / rows;
var idx = 0;
var x = 0, y = 0;
for(var k = 0; k < rows; k++){
x = 0;
for(var i = 0; i<cols; i++){

vertices[idx] = x;  vertices[idx+1] = y;  vertices[idx+2] = 0.0;
vertices[idx+3] = x+dx;  vertices[idx+4] = y+dy;  vertices[idx+5] = 0.0;
vertices[idx+6] = x;  vertices[idx+7] = y+dy;  vertices[idx+8] = 0.0;

vertices[idx+9] = x;  vertices[idx+10] = y;  vertices[idx+11] = 0.0;
vertices[idx+12] = x+dx;  vertices[idx+13] = y;  vertices[idx+14] = 0.0;
vertices[idx+15] = x+dx;  vertices[idx+16] = y+dy;  vertices[idx+17] = 0.0;

idx += 18;
x += dx;
}
y += dy;
}

return vertices;
}

Friday, December 28, 2012

Mac OS X: pyglet


installed pyglet
tried a simple app and run, get the following error:

OSError: dlopen(/System/Library/Frameworks/QuickTime.framework/QuickTime, 6): no suitable image found.  Did find:
 /System/Library/Frameworks/QuickTime.framework/QuickTime: mach-o, but wrong architecture
 /System/Library/Frameworks/QuickTime.framework/QuickTime: mach-o, but wrong architecture

found a link: https://groups.google.com/forum/?fromgroups=#!topic/pyglet-users/mvvIo7NotBo

so run the command in Terminal: "defaults write com.apple.versioner.python Prefer-32-Bit -bool yes"
to set python to run in 32 bit mode
and then compile app again. no problem.

Monday, December 10, 2012

FlasCC: 1st experience

1) Download and extract FlasCC zip
2) try making the Hello sample. eg.: ..\..\sdk\usr\bin\make FLASCC="../../sdk" FLEX="../../../flex_sdk_4.6"
3) error
"-------- Sample 1 --------

First let's compile it as a projector:
"../../sdk/usr/bin/gcc" -Werror -Wno-write-strings -Wno-trigraphs hello.c -o hel
lo.exe
cc1: error in backend: Failed to run /cygdrive/c/Program Files/Git/bin/which wit
h args: java
Error:
/cygdrive/c/Program Files/Git/bin/which: line 7: $'\r': command not found

make: *** [T01] Error 1"

4) use dosunix on the "which" in Git\bin

5) then run again, another error
"LLVM ERROR: Error: Unable to launch the Java Virtual Machine.
This usually means you have a 32bit JVM installed or have set your Java heap siz
e too large.
Try lowering the Java heap size by passing "-jvmopt=-Xmx1G" to gcc/g++.
Stack dump: [blah blah ....]

make: *** [T01] Error 1"

6) added '-jvmopt="-Xmx1G"' to Makefile
"T01: check
@echo "-------- Sample 1 --------"
@echo && echo "First let's compile it as a projector:"
"$(FLASCC)/usr/bin/gcc" $(BASE_CFLAGS) -jvmopt="-Xmx1G" hello.c -o hello.exe

@echo && echo "Now lets compile it as a SWF:"
"$(FLASCC)/usr/bin/gcc" $(BASE_CFLAGS) -jvmopt="-Xmx1G" hello.c -emit-swf -swf-size=200x200 -o hello.swf

include ../Makefile.common

clean:
rm -f hello.swf hello *.bc *.exe"

7) finally no error and EXE and SWF generated.

Sunday, December 02, 2012

WebGL start

Reference: http://learningwebgl.com/blog/?p=28

download js matrix library: https://github.com/toji/gl-matrix/downloads

write the shader source code in a <script></script> tags

<script id="shader-fs" type="x-shader/x-fragment">
  precision mediump float;

  void main(void) {
    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
  }
</script>

<script id="shader-vs" type="x-shader/x-vertex">
  attribute vec3 aVertexPosition;

  uniform mat4 uMVMatrix;
  uniform mat4 uPMatrix;

  void main(void) {
    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
  }
</script>

variables needed in the javascript code

var triangleVertexPositionBuffer;
var squareVertexPositionBuffer;
var gl;
var shaderProgram;
var mvMatrix = mat4.create();
var pMatrix = mat4.create();

function webGLStart() {
    var canvas = document.getElementById("mycanvas");
    initGL(canvas);
    initShaders();
    initBuffers();

    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.enable(gl.DEPTH_TEST);

    drawScene();
}

function initGL(canvas) {
  try {
    gl = canvas.getContext("experimental-webgl");
    gl.viewportWidth = canvas.width;
    gl.viewportHeight = canvas.height;
  } catch(e) {
  }
  if (!gl) {
    alert("Could not initialise WebGL, sorry :-(");
  }
}

function initShaders() {
  var fragmentShader = getShader(gl, "shader-fs");
  var vertexShader = getShader(gl, "shader-vs");

  shaderProgram = gl.createProgram();
  gl.attachShader(shaderProgram, vertexShader);
  gl.attachShader(shaderProgram, fragmentShader);
  gl.linkProgram(shaderProgram);

  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
    alert("Could not initialise shaders");
  }

  gl.useProgram(shaderProgram);
  
  shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
  gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
  
  shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
  shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
}
function getShader(gl, id) {
    var shaderScript = document.getElementById(id);
    if (!shaderScript) {
        return null;
    }

    var str = "";
    var k = shaderScript.firstChild;
    while (k) {
        if (k.nodeType == 3)
            str += k.textContent;
        k = k.nextSibling;
    }

    var shader;
    if (shaderScript.type == "x-shader/x-fragment") {
        shader = gl.createShader(gl.FRAGMENT_SHADER);
    } else if (shaderScript.type == "x-shader/x-vertex") {
        shader = gl.createShader(gl.VERTEX_SHADER);
    } else {
        return null;
    }

    gl.shaderSource(shader, str);
    gl.compileShader(shader);

    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        alert(gl.getShaderInfoLog(shader));
        return null;
    }

    return shader;
}

function initBuffers() {
    triangleVertexPositionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
    var vertices = [
                    0.0,  1.0,  0.0,
                   -1.0, -1.0,  0.0,
                    1.0, -1.0,  0.0
               ];
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
    triangleVertexPositionBuffer.itemSize = 3; // number of component to represent a vertex = 3; (x, y, z)
    triangleVertexPositionBuffer.numItems = 3; // number of vertices
}

function drawScene() {
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0, pMatrix); mat4.identity(mvMatrix); mat4.translate(mvMatrix, [0, 0.0, -5.0]); gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer); gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, triangleVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0); setMatrixUniforms(); gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems);
}

function setMatrixUniforms() {
    gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
    gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
}

HTML
<body onload="webGLStart()">
<canvas id="mycanvas" style="border: none;" width="500" height="500"></canvas>
</body>


Saturday, December 01, 2012

PyQT - OpenGL - Timer


import sys
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtOpenGL import *
from PyQt4 import uic

class MyOGLWidget(QGLWidget):
    def __init__(self, parent=None):      
        QGLWidget.__init__(self, parent)
        self.spin = 0
             

    def initializeGL(self):
        print "init GL"
        glClearColor(0.0, 0.0, 0.0, 0.0);
        glShadeModel (GL_FLAT)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.spinDisplay)
        self.timer.start(40)
        print self.timer
     

    def resizeGL(self, w, h):
        print "resize: " + str(w ) + " x " +str(h)
        glViewport(0, 0, w, h);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0);

    def paintGL(self):
        print "paint GL"
        glClear (GL_COLOR_BUFFER_BIT );
        glPushMatrix()
        glRotatef(self.spin, 0, 0, 1)
        glColor3f (1.0, 1.0, 1.0);
        glRectf(-25.0, -25.0, 25.0, 25.0);
        glPopMatrix()
        glFlush();
     
    def spinDisplay(self):
        # print "spin display"
        self.spin = self.spin + 2
        self.spin = self.spin % 360
        # print self.spin
        #glutSwapBuffers()
        self.updateGL()
   
app = QApplication(sys.argv)
window = MyOGLWidget()
window.resize(300, 300)
window.setWindowTitle("Testing OpenGL in PyQT")
window.show()

sys.exit(app.exec_())


PyQt - OpenGL

install PyOpenGL - http://pyopengl.sourceforge.net/
install QT - http://qt-project.org/downloads
install PyQT- http://www.riverbankcomputing.com/software/pyqt/download
for Mac OS X, install PyQTX - http://sourceforge.net/projects/pyqtx/files/

import sys
from OpenGL.GL import *
from OpenGL.GLU import *
from PyQt4.QtGui import *
from PyQt4.QtOpenGL import *
from PyQt4 import uic

class MyOGLWidget(QGLWidget):
    def __init__(self, parent=None):
        QGLWidget.__init__(self, parent)      
 
    def initializeGL(self):
        print "init GL"
        glClearColor(0.0, 0.0, 0.0, 0.0);
        glShadeModel (GL_FLAT)
 
    def resizeGL(self, w, h):
        print "resize: " + str(w ) + " x " +str(h)
        glViewport(0, 0, w, h);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0);
 
    def paintGL(self):
        print "paint GL"
        glClear (GL_COLOR_BUFFER_BIT );
        glColor3f (1.0, 1.0, 1.0);
        glRectf(-25.0, -25.0, 25.0, 25.0);
        glFlush();
     
app = QApplication(sys.argv)
window = MyOGLWidget()
window.resize(300, 300)
window.setWindowTitle("Testing OpenGL in PyQT")
window.show()

sys.exit(app.exec_())



QT designer ui in python PyQT - event


import sys
from PyQt4.QtGui import QApplication, QDialog
from PyQt4 import uic

# a sample event listener
def handle():
    print "clicked"
    # get text in QTextEdit to display in QLabel
    ui.label.setText("hello " + ui.textEdit.toPlainText())

app = QApplication(sys.argv)
window = QDialog()
# dialog.ui is an xml file generated by QT designer
ui = uic.loadUi("dialog.ui")

# set text of QTextEdit
ui.textEdit.setText("hello")
# set text with HTML
ui.textEdit.setHtml("bolditalic")
# connect an event to a listener
ui.pushButton.clicked.connect(handle)

ui.show()

sys.exit(app.exec_())


QT .UI XML

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <widget class="QDialogButtonBox" name="buttonBox">
   <property name="geometry">
    <rect>
     <x>30</x>
     <y>240</y>
     <width>341</width>
     <height>32</height>
    </rect>
   </property>
   <property name="orientation">
    <enum>Qt::Horizontal</enum>
   </property>
   <property name="standardButtons">
    <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
   </property>
  </widget>
  <widget class="QLabel" name="label">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>10</y>
     <width>200</width>
     <height>13</height>
    </rect>
   </property>
   <property name="text">
    <string>TextLabel</string>
   </property>
  </widget>
  <widget class="QTextEdit" name="textEdit">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>30</y>
     <width>231</width>
     <height>50</height>
    </rect>
   </property>
  </widget>
  <widget class="QPushButton" name="pushButton">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>110</y>
     <width>75</width>
     <height>23</height>
    </rect>
   </property>
   <property name="text">
    <string>PushButton</string>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections>
  <connection>
   <sender>buttonBox</sender>
   <signal>accepted()</signal>
   <receiver>Dialog</receiver>
   <slot>accept()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>248</x>
     <y>254</y>
    </hint>
    <hint type="destinationlabel">
     <x>157</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
  <connection>
   <sender>buttonBox</sender>
   <signal>rejected()</signal>
   <receiver>Dialog</receiver>
   <slot>reject()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>316</x>
     <y>260</y>
    </hint>
    <hint type="destinationlabel">
     <x>286</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
 </connections>
</ui>



Friday, November 30, 2012

Loading QT Designer .ui file in PyQT

Create .ui in QT Designer (QT Creator > New File > QT Form)


import sys
from PyQt4.QtGui import QApplication, QDialog
from PyQt4 import uic

app = QApplication(sys.argv)

# returns a QWidget subclass

# assume that dialog.ui is created from QT designer
ui = uic.loadUi("dialog.ui")
ui.show()

sys.exit(app.exec_())


Thursday, October 18, 2012

C# PInvoke MDA error, stack imbalance

Issue with MDA PInvoke error, stack imbalance. even though had checked to make sure that the parameters match the DLL method signature.

Learnt from Mark that have to add an additional parameter.

[DllImport("somelibrary.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int methodName(string parameter);
 



Sunday, September 30, 2012

Installing Python libraries in Mac OS X

Thanks to the post in http://ashearer.com/blog/2011/xcode/ 
was trying to install Python Imaging Library (PIL), failed. 
basically from the post linked:
'enter the following command line once and the effect will last across multiple builds or installations for the remainder of the terminal session.'

export ARCHFLAGS="-arch i386 -arch x86_64"


Saturday, September 29, 2012

python + socket + xml

made a silly error:
xmldom = xml.dom.minidom.parseString(xml)
xml is a string containing the xml doc.
but its name clashes with the xml.dom.minidom package
xmldom = xml.dom.minidom.parseString(xml_string)

xml processing:
elements = xmldom.getElementsByTagName("mytag")
print elements.length                  # return number of elements
element.getAttribute("myattr")


using multiple line for code. use "\"
eg.: print "this, " + "that, " \
                + "those"

Dictionary
mydictionary = {"mykey":"hehe"}
mydictionary["newkey"] = "hello"       # can be number too
for k, v in mydictionary.iteritems():
   print k + "= " + v
if  "key" in mydictionary:
   print "key exists in dictionary"


Socket client:
import socket
socket = socket(AF_INET, SOCK_STREAM)
socket.connect(("127.0.0.1", 5000))   # address and port
data = socket.recv(4096)              # 4096 bytes buffer


binary data
data = bytearray(socket.recv(4096))
size = (data[3]<<24 | data[2]<<16 | data[1]<<8 | data[0] ) # to 32-bit or 4 byte integer


python imaging (PIL)

all thanks to the link: http://yufu.co/wordpress/?p=15

JPEG decoding from binary data using PIL. Documentation is lacking in official PIL site: http://www.pythonware.com/library/pil/handbook/image.htm

import Image
f = open("myimage.jpg", 'rb')
data = f.read()
im = Image.fromstring('RGB', (640,480), data, 'jpeg', 'RGB', '')



Tuesday, August 28, 2012

Android: Activity, View, onDraw, Canvas

Drawing on canvas overriding onDraw() method
Assuming using RelativeLayout in xml and with id "layout1"


public class SecondActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        //setContentView(new MyView(this));
        RelativeLayout layout = (RelativeLayout)(this.findViewById(R.id.layout1));
        layout.addView(new MyView(this));
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_second, menu);
        return true;
    }
    class MyView extends View{
   public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

// if required to add this custom view using xml or the graphical layout in eclipse. have to add this constructor
         public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

protected void onDraw(Canvas canvas){
    System.out.println("draw canvas");
    Paint paint = new Paint();
    paint.setColor(0xFFFF0000);
    Rect rect = new Rect();
    rect.set(100, 100, 200, 150);
    canvas.drawRect(rect, paint);
   }
    }
}


C#: Console


To capture key press, print at specific position of console window

class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            bool running = true;
            int pos = 0;
            int lengthOfLine = 1;
            int diff = 0;
            while (running)
            {
                //Console.Clear();
                if (Console.CursorTop - pos > diff)
                {
                    pos = Console.CursorTop;
                }
                else
                {
                    Console.CursorTop = pos;
                }
                Console.WriteLine("i = " + (i++));
                diff = Console.CursorTop - pos;
             
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo key = Console.ReadKey(true);
                    if (key.Key == ConsoleKey.I)
                    {
                        Console.WriteLine("I pressed");
                        //running = false;
                    }
                    else if (key.Key == ConsoleKey.X)
                    {
                        Console.WriteLine("Exit");
                        running = false;
                    }
                }
                Thread.Sleep(40);
            }

        }
    }

Tuesday, August 21, 2012

android: loading and displaying images on canvas


copy and paste image into res\drawable folder in project folder
R.java in "gen" should include this image with an id. Note: filename to be all lower-case

// loading, assuming written in a View class
Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.image_id); 
// displaying
canvas.drawBitmap(bmp, 50, 30, null);

Android: 2d drawing surface

To create a canvas for custom drawing, eg,: for 2d games without using opengl
Create a new class extending SurfaceView, add constructor with 2 arguments (so that it can be used in graphical editor in eclipse too), implement interface SurfaceHolder.Callback

import android.content.Context;
import android.util.AttributeSet;
import android.view.*;

public class MySurface extends SurfaceView implements SurfaceHolder.Callback{
SurfaceHolder holder;

public MySurface(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
holder = this.getHolder();
holder.addCallback(this);

}

public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
System.out.println("surface changed");
}

public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
System.out.println("surface created");
}

public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
System.out.println("surface destroyed");
}

}


This new custom UI will be available for the xml layout file in Eclipse

can create a draw() method to contain all drawing code in there. then call draw() when surfaceCreated(...)

void draw(){
canvas = holder.lockCanvas();
Paint paint = new Paint();
paint.setColor(0xFFFF0000); // ARGB, red
canvas.drawRect(new Rect(10, 20, 100, 50), paint);
holder.unlockCanvasAndPost(canvas);
}


Threading can be used if animation is needed, for example for games.

Sample code snippet:

public class MySurface extends SurfaceView implements SurfaceHolder.Callback, Runnable{
SurfaceHolder holder;
Canvas canvas;
MySprite s = new MySprite();
boolean isRunning = true;
long time = 0;

static final int DELAY = 10;

public MySurface(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
holder = this.getHolder();
holder.addCallback(this);

}

synchronized void draw(){
canvas = holder.lockCanvas();
canvas.drawColor(0xFFDDDDDD); // ARGB , fill whole canvas

// call draw in sprite
s.draw(canvas);

holder.unlockCanvasAndPost(canvas);
}

synchronized void update(){
s.update();
System.out.println((System.currentTimeMillis() - time) + " ms");
time = System.currentTimeMillis();
}

public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
System.out.println("surface changed");
}

public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
System.out.println("surface created");

isRunning = true;
Thread thread = new Thread(this);
thread.start();

time = System.currentTimeMillis();
}

public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
System.out.println("surface destroyed");
isRunning = false;
}

public void run() {
// TODO Auto-generated method stub
try{
while(isRunning){
update();
draw();
Thread.sleep(DELAY);
}
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}

MySprite is a custom class which contains x, y, width, height, its own draw(), update(), init(), cleanup() methods.


Monday, August 20, 2012

wxpython with new WebView

using version 2.9.4

import wx
import wx.html2

app = wx.App(False)
frame = wx.Frame(None, -1, 'A Simple Frame')
browser = wx.html2.WebView.New(frame)
browser.LoadURL("http://www.google.com")
frame.Show()
app.MainLoop()




tried loading local html file with some javascript.
worked so far. tested with jquery. ok too.

import os
browser.LoadURL(os.path.realpath("test.html"))


Tuesday, July 24, 2012

Panda3D & maya


Maya (+x, +y, +z) <=> Panda3D (+x, +z, -y)
Panda3D (+x, +y, +z) <=> Maya (+x, -z, +y)

Panda3D: camera face +Y by default; Maya: Model face +Z as Front

Sample code to add keyboard input:
        self.accept('arrow_up-up', self.moveForward ) # up cursor key released
def moveForward(self):
        self.pos = self.camera.getPos()
        self.pos.y = self.pos.y + 1
        self.camera.setPos(self.pos)
        print self.pos

Sample for mouse input:
self.accept('mouse1-up', self.click)
    
    def click(self):
        if self.mouseWatcherNode.hasMouse():
             print str(self.mouseWatcherNode.getMouseX()) + ", " + str(self.mouseWatcherNode.getMouseY()) # x and y = [-1,1], top left (-1,1), bottom right (1, -1)

Tuesday, May 22, 2012

Panda3D: Maya exporter

used maya2egg****.exe 
kept having error about "procedure entry point not located in some libmmd.dll", etc.

realised that have to copy the exe from panda/bin folder to maya/bin folder

maya2egg -a model -o "output.egg" "input.mb"


m = loader.loadModel("cube.egg")
m.reparentTo(base.render)
m.setPos(0,20,0)

EGG model loaded with texture.

couldn't get the COLLADA model to display textures.


Supported in Panda3d
Currently known scene file types are:
  Bam                             .bam
  Egg                             .egg
  MultiGen                        .flt
  Lightwave                       .lwo
  DXF                             .dxf
  VRML                            .wrl
  DirectX                         .x
  COLLADA                         .dae
  Also available: .ma .mb



Tuesday, May 15, 2012

Python & XML

how to parse XML file
using built-in xml.parsers.expat
steps:
  1. create handlers. eg.: def start_element(name, attrs):
  2. create parser. eg.: p = ParserCreate('utf-8')
  3. link handlers. eg.: p.StartElementHandler = start_element
  4. open file eg.: f = open(filename)
  5. ParseFile(file)
Python IDE summary: Netbeans 6.x looks like better choice than Eclipse in terms of code completion. however, netbeans 7 does not support python plugin. currently using netbeans 6.9.1
no problem in using Netbeans with Panda3D
discover a bug. cannot debug properly in Netbeans 6.9.1. cannot step into a method for multiple PY files. breakpoints do not work in multiple files. can be quite troublesome for debugging.
No issue with Eclipse.

converting from String to int or float using int() or float()
attributes in StartElementHandler is stored in Dictionary. eg.: to access an attribute called x , use attrs['x']

thing to note when using classes and methods, have to keep using 'self' keyword in methods when accessing object properties or methods. same as "this" in java but if you omit it in python, it will default to global variable. 

interesting note: cannot use ( ) parenthesis in "for" statement. eg.: for (x in a): 
instead use "for x in a:"

another interesting note: cannot use the same instance to re-parse another file or string. has to create a new instance of parser to do so. ie. Step 2