Resources on Learning Win32 API

Here are a set of online tutorials that helped me learn about Windows Programming , This is a short post – hoping that someone who happen to bump on to my blog finds it useful

(a) Forgers Win32 API programming tutorial  :  http://winprog.org/tutorial/

(b) Iczelion Win32 programming tutorials :- In assembly but the concepts remain the same.

http://win32assembly.programminghorizon.com/tutorials.html

http://www.woodmann.com/RCE-CD-SITES/Iczelion/

 

The best book on Windows Programming is by Charles Petzold , search on amazon.

 

 

 

Linux – bash ( commonly used commands )

I know no one really reads my blog , so here is again another note to myself on commonly used  linux commands for the heck of it ! . Hopefully someones finds it useful . Hoping that writing this down refreshes my frail memory

Getting help

[sourcecode language=”bash”]
$ # try –help with the command
$ man <command name>
$ info <command name>
$ apropos <command name>
[/sourcecode]

Listing Directories

[sourcecode language=”bash”]
$ls -a #lists all files
$ls -l #long listing
$ls -t # time
$ls -s # size
$ls -r # reverse
$ ls -ar # combination
[/sourcecode]

Changing Directories

[sourcecode language=”bash”]
$pwd # returns the current directory
$cd <dirname> # change directory to the given directory
[/sourcecode]

Copying files

[sourcecode language=”bash”]
$cp
$cp -r #recursive copy
$cp -i #interactive
[/sourcecode]

Creating/Removing directories

[sourcecode language=”bash”]
$mkdir #Creates
$rmdir #Removes
[/sourcecode]

Displaying file contents

[sourcecode language=”bash”]
$cat <file1> <file2> <file3>
$more <file1> <file2> <file3>
$less <file1> <file2> <file3> # you do more with less !
$head -n <file> # top n lines of the file
$tail -n <file> #bottom n lines of the file
[/sourcecode]

Pattern matching with grep

[sourcecode language=”bash”]
$grep <pattern> <files>
$grep -i <pattern> <files> #case insensitive

[/sourcecode]

Sorting

[sourcecode language=”bash”]
$sort <filename>
$sort -r <filename> #sort in reverse
[/sourcecode]

Sed

[sourcecode language=”bash”]
$# See : http://www.regular-expressions.info/ , sed can be used to parsing text and performing various transformations
$sed ‘s/<pattern>/<pattern to replace> <filename>
$#man sed
[/sourcecode]

Symbolic Links

[sourcecode language=”bash”]
$ln -s <filename> <link name> #soft link , omit -s for hard links
[/sourcecode]

Changing Permissions

[sourcecode language=”bash”]
$chmod <permissions> <files> # permissions – a,b,c = r*4+w*2+x

[/sourcecode]

Switch Users

[sourcecode language=”bash”]
$su (switch user)

[/sourcecode]

Tee send output to 2 devices

[sourcecode language=”bash”]
$tee [a] file

[/sourcecode]

Fill standard output with same thing

[sourcecode language=”bash”]
$yes <string> | <command>

[/sourcecode]

Useful process control commands

[sourcecode language=”bash”]
$jobs
$fg
$bg
$kill <pid>
$ps

[/sourcecode]

Environment Variables

[sourcecode language=”bash”]
$export varname = value

[/sourcecode]

Shortcuts with alias

[sourcecode language=”bash”]
$alias ls=’ls la’

[/sourcecode]

which is the executable

[sourcecode language=”bash”]
$which commandname

[/sourcecode]

Disk utilities

[sourcecode language=”bash”]
$du # disk usage
$df # disk free

[/sourcecode]

Compression utilities

[sourcecode language=”bash”]
$gzip / gunzip
$tar
$bunzip2
$lzma / unlzma

[/sourcecode]

Checking integrity

[sourcecode language=”bash”]
$md5sum

[/sourcecode]

File Comparison

[sourcecode language=”bash”]
$diff

[/sourcecode]

Location of files

[sourcecode language=”bash”]
$find <path> -name <name>
$locate <filename>

[/sourcecode]

Downloading websites offline

[sourcecode language=”bash”]
$wget
[/sourcecode]

Writing Real mode operating systems for fun , study and world domination

Writing real mode operating systems is not hard at all, in fact almost anyone with a little  knowledge of  x86 assembler will be able to create simple real mode operating systems. The idea of this post is to get you started with real mode operating system development. In this tutorial we will build a  simple yet functional real mode operating system.

Tools of  Trade

What we need to create a simple real mode operating system is just an assembler and a x86 emulator to test the operating system you wrote.  Another thing you can do is just  have  MS DOS running is one of the emulators and test your .COM files in the dos box before run in your operating system. Sounds fun ain’t  it ?  So what will we be using

  1. FASM as the assembler : http://www.flatassembler.net
  2. An emulator Microsoft Virtual PC : http://www.microsoft.com/downloads/en/details.aspx?FamilyID=04d26402-3199-48a3-afa2-2dc0b40a73b6&displaylang=en
  3. Dosbox for testing : www.dosbox.com

Learning real mode x86  assembly

Learning how to hack a few x86 instructions is a handy skill to have . There are plenty of resources available only to learn x86 assembly language programming .  My recommendations are as follows

  1. Emu8086 –  Emu8086 is a great platform to learn x86 assembly language , tutorials are simple and it even includes an os development tutorial.  See : http://ziplib.com/emu8086/
  2. Ketman’s utilites   – ketmans

What the heck is real mode and why is real mode OS development easier to get started ?

When an IBM x86 PC starts , it actually starts in real mode. You basically have access to only 1 MB of memory and you work with 16 bit registers.   The best part of real mode is that you can make use of BIOS services to get most of the work done, you need not write drivers display , keyboard and most of the other stuff. All you have to do  get most of hardware working is to invoke the appropriate real mode interrupt.

eg

[sourcecode language=”text”]

WAIT_FOR_KEY_PRESS:
XOR AX , AX
INT 16H

[/sourcecode]

Here 16h is a BIOS service that helps you to interact with the keyboard. For a details about BIOS services you may take look at the ralf brown interrupt list. Professor Ralf Brown’s Interrupt List ,

You work with 16 bit registers, you have access to 2^16 = 64kbytes of memory. However you can still access 1MB memory using 2 registers. This is called segment offset addressing or real mode segmentation. One of the segment registers act as a base address ( compare it to a page in a book ) and offset registers  ( like line within a page ) act as offset from the base, so the effective address really is  =  16 * SEGMENT_ADRESS + OFFSET_ADDRESS.  In many operations segment registers are implicitly  implied eg SS:SP , CS for IP , DS : DI , ES : SI  eg . However you can override the implied segment registers with an SEGMENT override prefix eg [ES:BX]  . This means you  treat ES as a segment and BX as the offset .

Starting Simple :- A simple boot loader

The first sector of the floppy is appended with the boot signature 0xaa55, then it will be executed by the computer and it will be able to use the bios services. That’s all you need to do to get a boot loader working. I am showing an example boot loader . I am just pasting an example bootloader from osdev.org. A more advanced boot loader would load a file  (kernel) into memory and jump to the first executable instruction. Take look at the freedos bootloader to see how it is done.

[sourcecode langauge=”text”]

mov ax, 0x07C0 ; set up segments
mov ds, ax
mov es, ax

mov si, welcome
call print_string

mainloop:
mov si, prompt
call print_string

mov di, buffer
call get_string

mov si, buffer
cmp byte [si], 0 ; blank line?
je mainloop ; yes, ignore it

mov si, buffer
mov di, cmd_hi ; "hi" command
call strcmp
jc .helloworld

mov si, buffer
mov di, cmd_help ; "help" command
call strcmp
jc .help

mov si,badcommand
call print_string
jmp mainloop

.helloworld:
mov si, msg_helloworld
call print_string

jmp mainloop

.help:
mov si, msg_help
call print_string

jmp mainloop

welcome db ‘Welcome to My OS!’, 0x0D, 0x0A, 0
msg_helloworld db ‘Hello OSDev World!’, 0x0D, 0x0A, 0
badcommand db ‘Bad command entered.’, 0x0D, 0x0A, 0
prompt db ‘>’, 0
cmd_hi db ‘hi’, 0
cmd_help db ‘help’, 0
msg_help db ‘My OS: Commands: hi, help’, 0x0D, 0x0A, 0
buffer times 64 db 0

; ================
; calls start here
; ================

print_string:
lodsb ; grab a byte from SI

or al, al ; logical or AL by itself
jz .done ; if the result is zero, get out

mov ah, 0x0E
int 0x10 ; otherwise, print out the character!

jmp print_string

.done:
ret

get_string:
xor cl, cl

.loop:
mov ah, 0
int 0x16 ; wait for keypress

cmp al, 0x08 ; backspace pressed?
je .backspace ; yes, handle it

cmp al, 0x0D ; enter pressed?
je .done ; yes, we’re done

cmp cl, 0x3F ; 63 chars inputted?
je .loop ; yes, only let in backspace and enter

mov ah, 0x0E
int 0x10 ; print out character

stosb ; put character in buffer
inc cl
jmp .loop

.backspace:
cmp cl, 0 ; beginning of string?
je .loop ; yes, ignore the key

dec di
mov byte [di], 0 ; delete character
dec cl ; decrement counter as well

mov ah, 0x0E
mov al, 0x08
int 10h ; backspace on the screen

mov al, ‘ ‘
int 10h ; blank character out

mov al, 0x08
int 10h ; backspace again

jmp .loop ; go to the main loop

.done:
mov al, 0 ; null terminator
stosb

mov ah, 0x0E
mov al, 0x0D
int 0x10
mov al, 0x0A
int 0x10 ; newline

ret

strcmp:
.loop:
mov al, [si] ; grab a byte from SI
mov bl, [di] ; grab a byte from DI
cmp al, bl ; are they equal?
jne .notequal ; nope, we’re done.

cmp al, 0 ; are both bytes (they were equal before) null?
je .done ; yes, we’re done.

inc di ; increment DI
inc si ; increment SI
jmp .loop ; loop!

.notequal:
clc ; not equal, clear the carry flag
ret

.done:
stc ; equal, set the carry flag
ret

times 510-($-$$) db 0
dw 0AA55h ; some BIOSes require this signature

[/sourcecode]

Understanding Fat File System

A fa12 file system looks like this.

BPB + Boot Code ] [ Fat Table 1] [ Fat Table 2] [Root Directory Area] [ Data]
Each file has an entry in the root directory area , One of the main fields of the root directory area is the
the first sector number. Fat table contains the next sector indexed by sector number . Fat Table2 is a
copy of Fat Table1 for recovery purposes. Fat Table1 [current_sector] = next sector. ( Note that fat12
does packs 2 12bit entries into a 24 bit entry to save space , but it’s explained easily as above.).

FAT12_overview

Implementing a simple shell

A shell accepts command from the user and takes appropriate actions. Below is a shell implementation

of my hobby operating system.

[sourcecode language=”text”]
#########################################################################################################
;# #
;# shell.asm #
;# This implements the shell . This is a really simple shell .It gets a string from the user #
;# and checks whether it is one of the commands known to shell ,if it is one them it just calls #
;# the corresponding functions , else it check that there exists an external file in the disk #
;# that has a same name as the input . If it exits , its loaded and executed #
;#########################################################################################################

;——————————————————————————-+
; procedure shell_initialize |
; performs various operations before starting the shell . |
; (1) print the Sandman Logo 🙂 |
; |
;——————————————————————————-+
shell_initialize:
mov [save_address],dx
mov [cs_save],ax
push cs
pop ds
push ds
pop es
cld

mov si , initial_msg
call print_string
cli
call install_interrupts
sti
shell_loop:
call print_prompt
mov di , cmd_buffer
mov cx , 13
call read_string
mov di , cmd_buffer
call to_upper
mov si , cmd_buffer
mov di , cmd_cls
stc
call string_equal
jnc .do_cls

mov si , cmd_buffer
mov di , cmd_help
stc
call string_equal
jnc .do_help

mov si , cmd_buffer
mov di , cmd_dir
stc
call string_equal
jnc .do_dir

.load_prog:

call ConvertFileName

stc
mov di , RootConvertedFileName
add di , 8
mov si , com_ext
call string_equal
jnc .file_extension_ok

stc
mov di , RootConvertedFileName
add di , 8
mov si , exe_ext
call string_equal
jnc .file_extension_ok

jmp shell_loop
.file_extension_ok:

mov ax,0x80
shl ax, 6
mov word[end_memory],ax
int 12h
shl ax,6
mov word[top_memory],ax

sub ax,512 / 16
mov es,ax
sub ax,2048 / 16
mov ss,ax
mov sp,2048

mov cx, 11
mov si, RootConvertedFileName
mov di,[save_address]
rep movsb

push es
mov bx,[cs_save]
push bx
xor bx,bx
retf
jmp $

.do_cls:
xor dx , dx
call set_cursor
call clear_screen
jmp shell_loop

.do_help:
mov si , help_msg
call print_string
jmp shell_loop
.do_dir:
call clear_screen
call DirPrintFile
jmp shell_loop

;——————————————————————————–+
; procedure print_prompt : |
; prints the prompt to the user . |
; input : none |
; output : prints the prompt |
;——————————————————————————–+
print_prompt:
mov si , prompt
call print_string
ret

cmd_cls db ‘CLS’,0
cmd_help db ‘HELP’,0
cmd_dir db ‘DIR’,0
prompt db ‘$’ ,0
cmd_buffer: times 14 db 0
com_ext db ‘COM’,0
exe_ext db ‘EXE’,0

initial_msg db ‘Welcome to 1K-DOS 🙂 ‘,13,10, ‘ ^ ^ ^’,13,10, ‘ ( *|* )’,13,10, ‘ / ~ \’,13,10, ‘ / \’,13,10, ‘ ———‘,13,10,’ | |’,13,10, ‘ _| _| by S@ndM@n ‘,13,10 ,0
help_msg db 13 , 10 ,’CLS – Clears the Screen ‘ ,13 , 10 , ‘HELP – Displays This Info ‘ , 13,10 , ‘<FILENAME> – Executes Given File’ ,13 , 10,’DIR -List Contents of Root Directory’ ,13 , 10, 0
save_address dw 0
cs_save dw 0

include ‘util.asm

[/sourcecode]

Executing programs

What you need to do is load the program into memory ( since it a fat12 file , we by now know how to load the file to memory ) and perform relocation if necessary . They jump to beginning of the first executable instruction. in the program. This is illustrated by the following code : ( taken from alexi a frounze , bootcode)

[sourcecode language=”text”]
;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Load entire a program ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;

ReadNextCluster:
call ReadCluster
cmp si, 0FF8h
jc ReadNextCluster ; if not End Of File

;;;;;;;;;;;;;;;;;;;
;; Type checking ;;
;;;;;;;;;;;;;;;;;;;

cli ; for stack adjustments

mov ax, ImageLoadSeg
mov es, ax

cmp word [es:0], 5A4Dh ; "MZ" signature?
je RelocateEXE ; yes, it’s an EXE program

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Setup and Run COM program ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

mov ax, es
sub ax, 10h ; "org 100h" stuff 🙂
mov es, ax
mov ds, ax
mov ss, ax
xor sp, sp
push es
push word 100h
jmp Run

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Relocate, setup and run EXE program ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

RelocateEXE:
mov ds, ax

add ax, [ds:08h] ; ax = image base
mov cx, [ds:06h] ; cx = reloc items
mov bx, [ds:18h] ; bx = reloc table pointer

jcxz RelocationDone

ReloCycle:
mov di, [ds:bx] ; di = item ofs
mov dx, [ds:bx+2] ; dx = item seg (rel)
add dx, ax ; dx = item seg (abs)

push ds
mov ds, dx ; ds = dx
add [ds:di], ax ; fixup
pop ds

add bx, 4 ; point to next entry
loop ReloCycle

RelocationDone:

mov bx, ax
add bx, [ds:0Eh]
mov ss, bx ; ss for EXE
mov sp, [ds:10h] ; sp for EXE

add ax, [ds:16h] ; cs
push ax
push word [ds:14h] ; ip
Run:
mov dl, [cs:bsDriveNumber] ; let program know boot drive
sti
retf

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Reads a FAT12 cluster ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Inout: ES:BX -> buffer ;;
;; SI = cluster no ;;
;; Output: SI = next cluster ;;
;; ES:BX -> next addr ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

ReadCluster:
mov bp, sp

lea ax, [si-2]
xor ch, ch
mov cl, [bpbSectorsPerCluster]
; cx = sector count
mul cx

add ax, [ss:bp+1*2]
adc dx, [ss:bp+2*2]
; dx:ax = LBA

call ReadSector

mov ax, [bpbBytesPerSector]
shr ax, 4 ; ax = paragraphs per sector
mul cx ; ax = paragraphs read

mov cx, es
add cx, ax
mov es, cx ; es:bx updated

mov ax, 3
mul si
shr ax, 1
xchg ax, si ; si = cluster * 3 / 2

push ds
mov ds, [ss:bp+3*2] ; ds = FAT segment
mov si, [ds:si] ; si = next cluster
pop ds

jnc ReadClusterEven

shr si, 4

ReadClusterEven:
and si, 0FFFh ; mask cluster value
ReadClusterDone:
ret

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Reads a sector using BIOS Int 13h fn 2 ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Input: DX:AX = LBA ;;
;; CX = sector count ;;
;; ES:BX -> buffer address ;;
;; Output: CF = 1 if error ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

ReadSector:
pusha

ReadSectorNext:
mov di, 5 ; attempts to read

ReadSectorRetry:
pusha

div word [bpbSectorsPerTrack]
; ax = LBA / SPT
; dx = LBA % SPT = sector – 1

mov cx, dx
inc cx
; cx = sector no.

xor dx, dx
div word [bpbHeadsPerCylinder]
; ax = (LBA / SPT) / HPC = cylinder
; dx = (LBA / SPT) % HPC = head

mov ch, al
; ch = LSB 0…7 of cylinder no.
shl ah, 6
or cl, ah
; cl = MSB 8…9 of cylinder no. + sector no.

mov dh, dl
; dh = head no.

mov dl, [bsDriveNumber]
; dl = drive no.

mov ax, 201h
; al = sector count
; ah = 2 = read function no.

int 13h ; read sectors
jnc ReadSectorDone ; CF = 0 if no error

xor ah, ah ; ah = 0 = reset function
int 13h ; reset drive

popa
dec di
jnz ReadSectorRetry ; extra attempt
jmp short ErrRead

ReadSectorDone:
popa
dec cx
jz ReadSectorDone2 ; last sector

add bx, [bpbBytesPerSector] ; adjust offset for next sector
add ax, 1
adc dx, 0 ; adjust LBA for next sector
jmp short ReadSectorNext

ReadSectorDone2:
popa
ret

[/sourcecode]

Implementing system calls or writing your own interrupt handler

Writing real mode interrupt handler is very easy, all you need to do is set the address of the of the interrupt routines in the real mode interrupt table. It is shown in the code below.

[sourcecode language=”text”]
———————————————————————-+
; procedure install_interrupts : |
; The main goal of this procedure is to initialize the real mode |
; intterrupt table . The real mode interrupt table is initialized |
; as follows [0000 : int_no * 4 ] := handler offset address and |
; [0000 : int_no *4 +2 ] := handler segment address . |
; |
; input : none |
; output : sets the real mode interrupt table |
;———————————————————————-+

install_interrupts:
push ax
push es
cli
xor ax , ax
mov es , ax
; install the int20 interrupt handler
mov WORD [es : 0x20 *4] , int20_handler
mov WORD [es : 0x20 * 4 + 2] , cs
; install the int21 interrupt handler
mov WORD [es : 0x21 *4 ] ,int21_handler
mov WORD [es : 0x21 *4 + 2],cs
sti
pop es
pop ax
ret

[/sourcecode]

Implementing Multitasking in real mode

This link explains it very well  : http://nw08.american.edu/~mblack/projects/OSProjectE.doc

Books on real mode OS development

FreeDos kernel

Dissecting DOS

Operating  System Source code worth reading

MikeOS Operating System :-  http://mikeos.berlios.de/

Public Domain DOS – pdos86  :- http://sourceforge.net/projects/pdos/

Free DOS Operating System – http://sourceforge.net/projects/freedos/

RxDOS Operating System –  http://rxdos.sourceforge.net/

Pico Embedded RTOS :-http://sourceforge.net/projects/picoos/?source=directory

PS : This article has become very messy because i could not really devote much time to it , i will work on it when i get some more time.

Crash course in game development with pygame

Today I will ramble about game development with python . Python is very easy to learn and it is a very easy to prototype games  with python. Pygame  is a SDL binding fo python , visit pygame.org for more details.

2D Game Development Concepts

Sprites : Sprites are moveable game entities , I bet all of you have played super mario. The mario character you control is basically a sprite .

Game Loop :  Game is loop is very common in most of the games , it something of this form(  C is psuedo code )

while ( not_game_over)

{

if ( an_event_occurred )

handle_event()

}

Collision detection : In a game you often need to find out when you characters collide , this is called collision detection. There are many ways to perform collision detection.  The easiest way is to define a bounding rectangle for the sprite and determine when these two rectangles overlap .

Input handling : While programming your game , you need to determine what needs to be done when user press the keyboard or mouse . With newer operating system this is way too easy you just need to use the services provided by the operating system . Back in the good old days of DOS this was not the case , you need to write a separate keyboard  handler , mouse handler etc so that your game responds well.

Sound and  Music : You also need to  play sound for special game events , eg a sound when you won the game etc

Handling game states : Each game entity and the game itself maintains a state and actions need to be performed based on the current state of the game. One crude way to  handle states is to use an enumeration. But  when the number of states increase they become very cumbersome to mange.  A better way is to use a variation of the state pattern

I am too lazy to write my own game now , i am therefore copy pasting the example games provided by the pygame itself 🙂 . They are well commented and easy to understand

Getting started with pygame

your first pgame program
[sourcecode language=”python”]
import pygame

pygame.init();
dimensions = ( 640 , 480 )
color_red = ( 255 , 0 , 0 )
screen = pygame.display.set_mode(dimensions)
pygame.display.set_caption("Pygame Template")
game_running = True
clock = pygame.time.Clock()
while game_running == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False

screen.fill(color_red)
pygame.display.flip();
clock.tick(20)

pygame.quit()
[/sourcecode]
Chimp line by line example
[sourcecode language=”python”]
#!/usr/bin/env python
"""
This simple example is used for the line-by-line tutorial
that comes with pygame. It is based on a ‘popular’ web banner.
Note there are comments here, but for the full explanation,
follow along in the tutorial.
"""

#Import Modules
import os, pygame
from pygame.locals import *
from pygame.compat import geterror

if not pygame.font: print (‘Warning, fonts disabled’)
if not pygame.mixer: print (‘Warning, sound disabled’)

main_dir = os.path.split(os.path.abspath(__file__))[0]
data_dir = os.path.join(main_dir, ‘data’)

#functions to create our resources
def load_image(name, colorkey=None):
fullname = os.path.join(data_dir, name)
try:
image = pygame.image.load(fullname)
except pygame.error:
print (‘Cannot load image:’, fullname)
raise SystemExit(str(geterror()))
image = image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()

def load_sound(name):
class NoneSound:
def play(self): pass
if not pygame.mixer or not pygame.mixer.get_init():
return NoneSound()
fullname = os.path.join(data_dir, name)
try:
sound = pygame.mixer.Sound(fullname)
except pygame.error:
print (‘Cannot load sound: %s’ % fullname)
raise SystemExit(str(geterror()))
return sound

#classes for our game objects
class Fist(pygame.sprite.Sprite):
"""moves a clenched fist on the screen, following the mouse"""
def __init__(self):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image, self.rect = load_image(‘fist.bmp’, -1)
self.punching = 0

def update(self):
"move the fist based on the mouse position"
pos = pygame.mouse.get_pos()
self.rect.midtop = pos
if self.punching:
self.rect.move_ip(5, 10)

def punch(self, target):
"returns true if the fist collides with the target"
if not self.punching:
self.punching = 1
hitbox = self.rect.inflate(-5, -5)
return hitbox.colliderect(target.rect)

def unpunch(self):
"called to pull the fist back"
self.punching = 0

class Chimp(pygame.sprite.Sprite):
"""moves a monkey critter across the screen. it can spin the
monkey when it is punched."""
def __init__(self):
pygame.sprite.Sprite.__init__(self) #call Sprite intializer
self.image, self.rect = load_image(‘chimp.bmp’, -1)
screen = pygame.display.get_surface()
self.area = screen.get_rect()
self.rect.topleft = 10, 10
self.move = 9
self.dizzy = 0

def update(self):
"walk or spin, depending on the monkeys state"
if self.dizzy:
self._spin()
else:
self._walk()

def _walk(self):
"move the monkey across the screen, and turn at the ends"
newpos = self.rect.move((self.move, 0))
if self.rect.left < self.area.left or \
self.rect.right > self.area.right:
self.move = -self.move
newpos = self.rect.move((self.move, 0))
self.image = pygame.transform.flip(self.image, 1, 0)
self.rect = newpos

def _spin(self):
"spin the monkey image"
center = self.rect.center
self.dizzy = self.dizzy + 12
if self.dizzy >= 360:
self.dizzy = 0
self.image = self.original
else:
rotate = pygame.transform.rotate
self.image = rotate(self.original, self.dizzy)
self.rect = self.image.get_rect(center=center)

def punched(self):
"this will cause the monkey to start spinning"
if not self.dizzy:
self.dizzy = 1
self.original = self.image

def main():
"""this function is called when the program starts.
it initializes everything it needs, then runs in
a loop until the function returns."""
#Initialize Everything
pygame.init()
screen = pygame.display.set_mode((468, 60))
pygame.display.set_caption(‘Monkey Fever’)
pygame.mouse.set_visible(0)

#Create The Backgound
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))

#Put Text On The Background, Centered
if pygame.font:
font = pygame.font.Font(None, 36)
text = font.render("Pummel The Chimp, And Win $$$", 1, (10, 10, 10))
textpos = text.get_rect(centerx=background.get_width()/2)
background.blit(text, textpos)

#Display The Background
screen.blit(background, (0, 0))
pygame.display.flip()

#Prepare Game Objects
clock = pygame.time.Clock()
whiff_sound = load_sound(‘whiff.wav’)
punch_sound = load_sound(‘punch.wav’)
chimp = Chimp()
fist = Fist()
allsprites = pygame.sprite.RenderPlain((fist, chimp))

#Main Loop
going = True
while going:
clock.tick(60)

#Handle Input Events
for event in pygame.event.get():
if event.type == QUIT:
going = False
elif event.type == KEYDOWN and event.key == K_ESCAPE:
going = False
elif event.type == MOUSEBUTTONDOWN:
if fist.punch(chimp):
punch_sound.play() #punch
chimp.punched()
else:
whiff_sound.play() #miss
elif event.type == MOUSEBUTTONUP:
fist.unpunch()

allsprites.update()

#Draw Everything
screen.blit(background, (0, 0))
allsprites.draw(screen)
pygame.display.flip()

pygame.quit()

#Game Over

#this calls the ‘main’ function when this script is executed
if __name__ == ‘__main__’:
main()

[/sourcecode]

The aliens example

[sourcecode language=”python”]

#!/usr/bin/env python

import random, os.path

#import basic pygame modules
import pygame
from pygame.locals import *

#see if we can load more than standard BMP
if not pygame.image.get_extended():
raise SystemExit("Sorry, extended image module required")

#game constants
MAX_SHOTS = 2 #most player bullets onscreen
ALIEN_ODDS = 22 #chances a new alien appears
BOMB_ODDS = 60 #chances a new bomb will drop
ALIEN_RELOAD = 12 #frames between new aliens
SCREENRECT = Rect(0, 0, 640, 480)
SCORE = 0

main_dir = os.path.split(os.path.abspath(__file__))[0]

def load_image(file):
"loads an image, prepares it for play"
file = os.path.join(main_dir, ‘data’, file)
try:
surface = pygame.image.load(file)
except pygame.error:
raise SystemExit(‘Could not load image "%s" %s’%(file, pygame.get_error()))
return surface.convert()

def load_images(*files):
imgs = []
for file in files:
imgs.append(load_image(file))
return imgs

class dummysound:
def play(self): pass

def load_sound(file):
if not pygame.mixer: return dummysound()
file = os.path.join(main_dir, ‘data’, file)
try:
sound = pygame.mixer.Sound(file)
return sound
except pygame.error:
print (‘Warning, unable to load, %s’ % file)
return dummysound()

# each type of game object gets an init and an
# update function. the update function is called
# once per frame, and it is when each object should
# change it’s current position and state. the Player
# object actually gets a "move" function instead of
# update, since it is passed extra information about
# the keyboard

class Player(pygame.sprite.Sprite):
speed = 10
bounce = 24
gun_offset = -11
images = []
def __init__(self):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = self.images[0]
self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom)
self.reloading = 0
self.origtop = self.rect.top
self.facing = -1

def move(self, direction):
if direction: self.facing = direction
self.rect.move_ip(direction*self.speed, 0)
self.rect = self.rect.clamp(SCREENRECT)
if direction < 0:
self.image = self.images[0]
elif direction > 0:
self.image = self.images[1]
self.rect.top = self.origtop – (self.rect.left//self.bounce%2)

def gunpos(self):
pos = self.facing*self.gun_offset + self.rect.centerx
return pos, self.rect.top

class Alien(pygame.sprite.Sprite):
speed = 13
animcycle = 12
images = []
def __init__(self):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = self.images[0]
self.rect = self.image.get_rect()
self.facing = random.choice((-1,1)) * Alien.speed
self.frame = 0
if self.facing < 0:
self.rect.right = SCREENRECT.right

def update(self):
self.rect.move_ip(self.facing, 0)
if not SCREENRECT.contains(self.rect):
self.facing = -self.facing;
self.rect.top = self.rect.bottom + 1
self.rect = self.rect.clamp(SCREENRECT)
self.frame = self.frame + 1
self.image = self.images[self.frame//self.animcycle%3]

class Explosion(pygame.sprite.Sprite):
defaultlife = 12
animcycle = 3
images = []
def __init__(self, actor):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = self.images[0]
self.rect = self.image.get_rect(center=actor.rect.center)
self.life = self.defaultlife

def update(self):
self.life = self.life – 1
self.image = self.images[self.life//self.animcycle%2]
if self.life <= 0: self.kill()

class Shot(pygame.sprite.Sprite):
speed = -11
images = []
def __init__(self, pos):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = self.images[0]
self.rect = self.image.get_rect(midbottom=pos)

def update(self):
self.rect.move_ip(0, self.speed)
if self.rect.top <= 0:
self.kill()

class Bomb(pygame.sprite.Sprite):
speed = 9
images = []
def __init__(self, alien):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = self.images[0]
self.rect = self.image.get_rect(midbottom=
alien.rect.move(0,5).midbottom)

def update(self):
self.rect.move_ip(0, self.speed)
if self.rect.bottom >= 470:
Explosion(self)
self.kill()

class Score(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.font = pygame.font.Font(None, 20)
self.font.set_italic(1)
self.color = Color(‘white’)
self.lastscore = -1
self.update()
self.rect = self.image.get_rect().move(10, 450)

def update(self):
if SCORE != self.lastscore:
self.lastscore = SCORE
msg = "Score: %d" % SCORE
self.image = self.font.render(msg, 0, self.color)

def main(winstyle = 0):
# Initialize pygame
pygame.init()
if pygame.mixer and not pygame.mixer.get_init():
print (‘Warning, no sound’)
pygame.mixer = None

# Set the display mode
winstyle = 0 # |FULLSCREEN
bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)
screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)

#Load images, assign to sprite classes
#(do this before the classes are used, after screen setup)
img = load_image(‘player1.gif’)
Player.images = [img, pygame.transform.flip(img, 1, 0)]
img = load_image(‘explosion1.gif’)
Explosion.images = [img, pygame.transform.flip(img, 1, 1)]
Alien.images = load_images(‘alien1.gif’, ‘alien2.gif’, ‘alien3.gif’)
Bomb.images = [load_image(‘bomb.gif’)]
Shot.images = [load_image(‘shot.gif’)]

#decorate the game window
icon = pygame.transform.scale(Alien.images[0], (32, 32))
pygame.display.set_icon(icon)
pygame.display.set_caption(‘Pygame Aliens’)
pygame.mouse.set_visible(0)

#create the background, tile the bgd image
bgdtile = load_image(‘background.gif’)
background = pygame.Surface(SCREENRECT.size)
for x in range(0, SCREENRECT.width, bgdtile.get_width()):
background.blit(bgdtile, (x, 0))
screen.blit(background, (0,0))
pygame.display.flip()

#load the sound effects
boom_sound = load_sound(‘boom.wav’)
shoot_sound = load_sound(‘car_door.wav’)
if pygame.mixer:
music = os.path.join(main_dir, ‘data’, ‘house_lo.wav’)
pygame.mixer.music.load(music)
pygame.mixer.music.play(-1)

# Initialize Game Groups
aliens = pygame.sprite.Group()
shots = pygame.sprite.Group()
bombs = pygame.sprite.Group()
all = pygame.sprite.RenderUpdates()
lastalien = pygame.sprite.GroupSingle()

#assign default groups to each sprite class
Player.containers = all
Alien.containers = aliens, all, lastalien
Shot.containers = shots, all
Bomb.containers = bombs, all
Explosion.containers = all
Score.containers = all

#Create Some Starting Values
global score
alienreload = ALIEN_RELOAD
kills = 0
clock = pygame.time.Clock()

#initialize our starting sprites
global SCORE
player = Player()
Alien() #note, this ‘lives’ because it goes into a sprite group
if pygame.font:
all.add(Score())

while player.alive():

#get input
for event in pygame.event.get():
if event.type == QUIT or \
(event.type == KEYDOWN and event.key == K_ESCAPE):
return
keystate = pygame.key.get_pressed()

# clear/erase the last drawn sprites
all.clear(screen, background)

#update all the sprites
all.update()

#handle player input
direction = keystate[K_RIGHT] – keystate[K_LEFT]
player.move(direction)
firing = keystate[K_SPACE]
if not player.reloading and firing and len(shots) < MAX_SHOTS:
Shot(player.gunpos())
shoot_sound.play()
player.reloading = firing

# Create new alien
if alienreload:
alienreload = alienreload – 1
elif not int(random.random() * ALIEN_ODDS):
Alien()
alienreload = ALIEN_RELOAD

# Drop bombs
if lastalien and not int(random.random() * BOMB_ODDS):
Bomb(lastalien.sprite)

# Detect collisions
for alien in pygame.sprite.spritecollide(player, aliens, 1):
boom_sound.play()
Explosion(alien)
Explosion(player)
SCORE = SCORE + 1
player.kill()

for alien in pygame.sprite.groupcollide(shots, aliens, 1, 1).keys():
boom_sound.play()
Explosion(alien)
SCORE = SCORE + 1

for bomb in pygame.sprite.spritecollide(player, bombs, 1):
boom_sound.play()
Explosion(player)
Explosion(bomb)
player.kill()

#draw the scene
dirty = all.draw(screen)
pygame.display.update(dirty)

#cap the framerate
clock.tick(40)

if pygame.mixer:
pygame.mixer.music.fadeout(1000)
pygame.time.wait(1000)
pygame.quit()

#call the "main" function if running this script
if __name__ == ‘__main__’: main()

[/sourcecode]

Setting up your haXe Development Environment

Introduction

 HaXe is a multi-platform development environment. In this book we will specifically concentrate haXe as a free flash game development platform . With haXe you can develop for windows , Linux , iPhone , android as well as for the world wide web . A source file written in haXe can have multiple targets . The source file may be compiled into different targets such as c++ , JavaScript , neko vm byte code, php . As of writing both Java and .Net back ends are under development. This gives the developer the flexibility to use the right platform for the purpose. The opportunities and applications of haXe is quite endless.

Setting up your haXe Development Environment

 Installing haXe & swfmill

  1. Download appropriate installer from http://haxe.org/download

  2. Run the installer for your platform

  3. Test your haxe installation by typing haxe in your command line

  4. Download swfmill from swfmill.org

Install swfmill by compiling from sources or download the appropriate binary

Free IDE’s for haXe with syntax highlighting and code completion

 Eclihx

Eclihx is an eclipse plug in that allows provides syntax highlighting and code completion features for the haxe development. Since eclipse it in cross platform it works in all platforms including Linux. However as of writing eclihx is still in not yet really stable and has some glitches.

Eclihx home page : http://www.eclihx.org

null

 FlashDevelop

FlashDevelop is another good and free ide for haxe . It is at the time of writing the best available ide for haxe. The downside side of it is that it is available only for the windows operating system.

FlashDevelop home page : http://www.flashdevelop.org/

null

Most of the popular editor like vim , geany , gedit etc have syntax highlighting for haXe . But it is particularly difficult to remember all the class names by heart and for a more productive programming session , I would recommend either flashdevelop or eclihx.


HaXe resources and links

 Haxe home page : http://www.haxe.org/

 haXe game programming blog : http://gamehaxe.org

 haXe documentation and tutorials : http://haxe.org/doc

 haXe projects : http://www.haxe.org/com/projects

Linux kernel development – part 2

IA – 32 Condensed

In this part of the tutorial , we will look at  IA -32 system architecture in brief . I would recommend anyone reading this blog to read the IA-32 system programmers manual . But I am planning to provide some links for quick reference .  I should not reproduce work that others have done very well. So here are the links

That’s all for now. I may edit this some time later 🙂

Linux kernel development – part 1

I will provide a hands on guide on dissecting and learning the Linux kernel . But I am busy with work and so forth and It may not be able to post in regular way. I however will not spoon feed and I will just be providing general guidelines. Also I will covering the linux kernel specific to the ia-32 platform .

Getting Started — Compiling the Linux Kernel

Download the newest linux kernel from www.kernel.org.make sure that you have newer version of gcc. To find out the current gcc version ,type
gcc --version.
To extract do ,
gunzip linux-2.6.xxx.tar.gz
tar -xvf linux-2.6xx.tar

and make your choices and save and exit.

If do not have ncurses library installed
type
make config

if present type
make menuconfig

For a qt based utility type
make xconfig

for gtk based type
make gconfig

if(kernel series is 2.4 )
make depend

Now finally build the kernel
make
make modules (for building modules)

Thus your kernel is made.Installation of newer kernel is bootloader specific grub has a different way,lilo has a different way.But the basic idea is same.For older kernel’s 2.2 vesrions etc we can put this kernel image directly into floppy for testing

Files and Directories to peek at

After extracting and compiling the kernel code, it’s time to peek at the different directories.
Lets discuss them
1)arch -Architecture dependent code
2)cryto -crypto API
3)Documentation-Docs
4)fs -The Virtual File System Implementation
5)init -the boot process and initialization
6)ipc-Inter process Communication
7)lib -Routines..
8)kernel -core systems
9)mm-Memory management
10)net-networking
11)Scripts
12)Security
13)Sound
14)user

Brief on gcc inline assembly

The basic gcc inline assembly format is as follows

asm  (
<IA 32 instructions >:
<output > :
<input >:
<clobbered>
);

you can search the net in detail on how to use inline assembly with gcc.

Frequently used data structures in kernel

  • Linked Lists   :-  See  /include/linux/list.h.The C language does not enforce type safety, Linux kernel provides set of macros for CRUD operations on a linked list
  • Trees             :-    Linux kernel uses balanced trees  ( RED BLACK TREE) in memory management . We will see this later

In Part2 we will focus more on the x86 architecture

GUI toolkits compared

GUI Toolkits Compared

I have worked with few UI libraries during my college days (late night hackwork !). Although It has months since i really coded something in C/C++ . Here is my opinion on most of the UI frameworks ( choices available  :)   ) .

(a) Win32 API , GDI (user32.dll)
This was the most difficult to work with initially . I initially found it more difficult to work with than X , with strange typedef’s and cumbersome hungarian Notation etc . But once you get the hang of it , its quite easy . But getting the hang of it may take some time . You may look at Charles Petzold programming Windows for more information.(Works only on Windows AFAIK , or may be Wine and ReactOS )

(b) MFC
MFC is quite friendly . You can make ui’s pretty quickly and easily . But if you follow one of those ”
teach yourself MFC in xx days ” , you might get stuck at some point of time . You should start from the ground up without using the wizards provided and then later switch to wizards after you get more advanced . It also provides many features (Document View Architecture , to name a few ) and most developers usually do not properly utilize them :(  . Works only on Windows AKIK , or may be Wine and ReactOS )

(c)GTK
The Gimp”s toolkit . It was initially made for the development of the GNU Image manipulation program or the GIMP . Its very easy to write ui’s in GIMP and now you have glade available . The gimp website provides sufficent documentation and its pretty cool ! . The downside of gtk is that , its strong only in *nix platforms . The ui elements may look a touch different depending upon the platform .

(d)FOX
Its yet another cool framework which i have worked with. Its pretty impressive , ui elements look the same in all platforms . But the downside of fox is that it has a slightly steeper learning curve compared to Gtk , and it somewhat mimics MFC in its API .

(e)QT
QT is the best i guess in terms of quality and portability , but qt has a confusing license . Other than that its awesome .It competes with MFC in ease of use and beats it completely in portability   . It boasts of a signal — connect sort of thing , but there is nothing novel in it .

(f)svgalib
its pretty good as well . its easy to use , but need root privilleges ,its quite buggy as well

(g)Allegro
Easy to use multiplatform gaming framework

(h)SDL- Simple DirectMedia Layer
Same as Allegro

(i)Xlib
Honestly its initially easier to learn Xlib , than Win32 API . But it only provides barebones functionality . There is an autoritative X book by main authours themselfves. I havent coded in Xlib for the past 3 years , so forgot most of it . Also if you have experience programming Windows , programming X should not be too difficult .

There are others as well , but I will stop for the time being …….

Popular Open Game Consoles

Some open game consoles I found by searching internet and I taught of posting . Hopefully someone finds this interesting

Fuzebox

“The Fuzebox is a fully open-source, DIY 8-bit game console. It is designed specifically for people who know a little bit of programming to expand into designing and creating their own video games and demos. A full-featured core runs in the background and does all the video and audio processing so that your code stays clean and easy to understand.”
Fuzebox website :- http://www.ladyada.net/make/fuzebox/index.html
Microcontroller / Microprocessor :- ATmega644-20PU
Uzebox

“The Uzebox is a retro-minimalist open source video game console design. It is based on an AVR 8-bit general purpose microcontroller made by Atmel. The particularity of the system is that it uses an interrupt driven kernel and has no frame buffer. Functions such as video sync generation, tile rendering, and music mixing is done realtime by a background task so games can easily be developed in C. The design goal was to be as simple as possible yet have good enough sound and graphics while leaving enough resources to implement interesting games. Emphasis was put on making it easy and fun to assemble and program for any hobbyists. The final design contains only two chips: an ATmega644 and an AD725 RGB-to-NTSC converter.”
Uzebox Website :- http://belogic.com/uzebox/index.asp
Microcontroller/ Microprocessor :-  ATmega644
Hackvision

“Hackvision is a simple, retro gaming platform based on Arduino technology that you can assemble and connect to your TV. You can write your own games and make your own controllers!”
Hackvision website : – http://nootropicdesign.com/hackvision/
Microcontroller/ Microprocessor :- ATmega328

Rbox – A 32 bit game console for the price of a latte
“The RBox is a game console that is simple enough to build on the prototype area of a dev kit; no pcb required just a crystal, a few capacitors and resistors.”
Rbox website :- http://rossum.posterous.com/20131601
Microcontroller/Microprocessor :- ARM Cortex M3 based LPC13XX
EL Jugador Module

“El Jugador is a retro open-source game console based on a Parallax Propeller & designed as module to fit on top of the Propeller Platform USB.”
website:-http://gadgetgangster.com/find-a-project/56?projectnum=265
Microcontroller / Microprocessor :- Parallax Propellor

C51 Snakes

“Welcome to C51Snakes – The Nokia inspired Sankes game implemented on 8051 platform.The game is built on AT89S51 MCU operating at 27MHz crystal frequency. The game uses a 16 * 8 LED dot matrix display and five way keys for user interface. A dedicated delay settings key provides one touch access to the delay settings mode where the speed of the Snake can be adjusted”
website :-  http://www.8051projects.net/tags/c51-snake
Microcontroller /Microprocessor :- AT89S51

PIC Pong

“PIC16F84-based video game generating a composite video signal in real time in software, by Rickard Gunée”
website: http://www.rickard.gunee.com/projects/video/pic/pong.php
Microcontroller / Microprocessor :- PIC16F84

ATMEGA64 Game Console
” An atmega64 based game console by Cedric  Beaudoin”
website :- http://www.innovativedevice.com/gamestation.htm
Microcontroller /Microprocessor :- ATMEGA64