Saturday, September 19, 2009

Programming psp

i just make o copy of the psp-programming.com
http://www.psp-programming.com/tutorials/

Lesson 01
Setting up the Development Environment
Get the toolchain and PSPSDK up and running with CYGWIN.

This is the first installment in a series of tutorials focussed on getting a novice programmer well on his way to developing his own homebrew applications for the Sony Playstation Portable (PSP). If you are reading this, congratulations, you have hurdled one of the biggest obstacles for a programmer. Likely the most difficult thing about programming is getting started. Well, by starting to read this tutorial, you are well on your way.

The first step to creating your own program is getting your environment set up. This environment is how you will convert the source code you write into a compiled file formatted for execution on you PSP. We will be setting up two important tools on our system.

If, at any time in this tutorial series, you need help please head over to our forums and post a question. We are always happy to help a fellow programmer.

The first of these tools is called CYGWIN. It is basically a Linux emulator for windows. It will create a simulated Linux environment on your computer so that you can run native Linux applications. This may sound intimidating, but don't worry, it's very simple to use.

The second thing you'll need is the toolchain. This is the key to programming for the PSP. It will set up everything you need, from header files, to libraries, to the compiler itself, to the sample programs. Once you have this installed, you will be nearly ready to create your first program.

Now for the part we've all been waiting for: the installation.

The first step is to install CYGWIN. You can download the install file from the CYGWIN website here. After it has finished downloading, open up the executable. You will see a splash screen; click next. Now you will be asked what you want to do. Select the default option of "Install from Internet," and hit the next button. Now you will be prompted where you want to install CYGWIN. Change the install directory to "C:/cygwin" if it is not set as such already (where C: is your local hard drive). Leave the other options set to their defaults and hit next. Now you will be asked where you want to save the installation files. What you select here doesn't really matter, but I suggest putting them someplace where you will be able to find them and delete them after the installation is complete. Once you have selected a suitable location, click next. The next screen will ask about your network settings, if you don't use a proxy (or don't know what a proxy is), just click next on this screen. If it doesn't work, go back and try letting it use Internet Explorer's settings. Now you should be presented with a list of servers to download the installation files from. Any one of these will do, so select one, and then click on next. Now it will download the package list, this could take a few minutes, depending on your connection speed. Once it is done, scroll down to "devel" and click on where it says "default" so that it becomes "install." Then scroll down to "web," click the "+" next to it, scroll down and set "wget" to "install."

When you are finished, click next. CYGWIN will now download and install the selected packages. This will quite possibly take a while, so go watch a TV show or do some web surfing while you wait. After the install has finished, you are ready to install the toolchain.


Lesson 02
Setting up the Development Environment
The setup, creation, and execution or a "Hello World"

So, after reading Lesson 01, you have a working development environment in which to create your programs. Now what? Well, this is the part you've all been waiting for, your very first program for the PSP. This tutorial will explain the basics of the C programming language and build the foundation upon which you will build your kingd-- err... programs.

If, at any time in this tutorial, you need help please head over to our forums and post a question. We are always happy to help a fellow programmer.

We're going to create a folder hierarchy to organize our projects. Open up a CYGWIN bash shell, and type "mkdir projects" and then hit enter. This command ("mkdir") stands for "make directory" and it will create a directory, or folder, in your current operating directory. So now we have a new folder for all of our projects, navigate into it by typing "cd projects" and hitting enter. Now we are going to create another directory for this specific project. Type "mkdir helloworld" and hit enter. Now switch into the new directory with "cd helloworld."

The next step is to open up a text editor. It doesn't really matter what you open, it can be Notepad, Wordpad, whatever you want. I prefer using an editor that is dedicated to editting C/C++ source code because of the syntax highlighting options that are built in (I use Dev-C++), but honestly, it doesn't matter (so long as you know how to use it).

Now, create a new file and call it "main.c" in our "helloworld" directory. This is going to contain the source code for our program. For those of you who don't know what source code is (and I know there will be a few), the source code is what we write to create a program. It is written in a way that humans can understand. In most languages, the source needs to be converted to a format the computer (or in our case, the PSP) can understand. These are called compiled languages, and C and C++ fall into this category (the conversion is done by the compiler that we set up in Lesson 01). There are a few other programming languages that use what is called an interpreter to interpret the source code and send out machine code on the fly. These are called scripting languages (an example of a scripting language is PHP).

Alright, so we have a new file that is going to hold our source code. Now we need to start writing it. The first part of the program should contain comments to tell anyone reading our code what the aim of the program is, when it was written, and who the author is. Comments are lines of source code that are omitted from the compiled binary (or skipped by the interpretter in scripting languages). Comments are a very important part of your code, because when you (or someone else) come back to edit your source code later, you will not remember all of the intricacies of the program. So, you can leave yourself notes in the form of comments. Comments are signalled with the "//" and "/*" characters. Any time you see a "//" it means that the rest of the line will be a comment. A "/*" means that the compiler (or interpretter) will ignore your code until it reaches a "*/" signal. Comments signalled by the "/*" operator can span many lines, but comments signalled with "//" only comment out the rest of that line.

So, to start off our program, we are going to leave a comment at the top about what it does, when it was created, and who it was written by.
// Hello World - My First App for the PSP

/*
          This program was created by (Your Name Here) on (Date Here)
          It is a simple "Hello World" Application.
*/
The next portion of the program is where we tell the compiler which header files and which include files we are going to use in our program. Basically what the "#include" directive does is copy the code from the file you pass to it into the top of your program. This allows you to keep your program simple, while still using the advanced code that is already written for you. The include directive can include either header files that came with the compiler (or that you add to the compiler), or header files specific to the specific project that you are working on. The way that you discern which of these you are including is by whether you use "<>" to enclose the file or if you use quotes to do it. The less than and greater than signs include a file from the compiler's "include" directory, and the quotes include a file from the same directory as the file including them. We will be including two files in our program. The first is "pspkernel.h." This file will be included in every single program that you write for the PSP. It contains all of the code specific to your PSP. Your program will not work on the PSP if you do not include this file. The second file we are going to include is "pspdebug.h." This file contains several useful functions for debugging your programs, but specifically it includes the function that we are going to use to write text to the screen. So, add this code to your program:
#include
#include
Next we tell the PSP a little bit about the program. This isn't really that important, your program will compile without it, but it is always a good idea to keep it in (if only for forwards compatibility). The first attribute is the name of the program, but it's not really the name of the program that will appear (we'll change that later). The other values are other attributes (just leave it alone), major version, and minor version. We'll just leave all of these except for the name as the defaults. So, add the following line to your program:
PSP_MODULE_INFO("Hello World", 0, 1, 1);
Now we are going to set up the function that we will use to write to the screen. This step is optional, but it makes writing text based programs much easier. The basis behind this line is to change the function that is built into the PSP, called "pspDebugScreenPrintf" into something that's much easier to type. This function is used to write to the screen (which you will see later). What we are basically going to do here is rename "pspDebugScreenPrintf" to "printf." So every time we use "printf" from now on, the compiler will just treat it as if we have typed "pspDebugScreenPrintf." Here's how we'll do it; we'll define "printf" as "pspDebugScreenPrintf" like this:
#define printf pspDebugScreenPrintf



Lesson 03
A Programming Primer
A crash course in the basics of C programming for the PSP.

After reading Lesson 01 and Lesson 02, you should now have a development environment set up, and have compiled your first basic program for the PSP. Now it's time to move on to bigger and better things. A "hello world" application is fine and dandy, a great learning experience, but it doesn't do anything. That's what this tutorial is about. How to make your programs do things.

What you need to understand is that this tutorial is not meant to be the be all and end all of PSP programming. It is much less a "how to create a game" than it is a foot in the door. What you will gain here are the basic building blocks of PSP (and C) programming. You will need to rearrange and add to these blocks together to create your own, functional application.

Having read Lesson 02, or knowing how to set up a basic program is a prerequisite for this tutorial. We will not go through the process of setting up your program in this tutorial. So, to test the code that follows replace the line
printf("Hello World.");
from Lesson 02 except where otherwise noted. Since the other lines were just setup for our program, we need not go through what they do again.

The final product of this tutorial will be a program that counts upwards until the user presses a button or until the counter hits a predefined limit. This is the perfect application for this tutorial; it combines several core elements of C programming to create a simple, yet useful result without requiring many program-specific functions. Covered in this tutorial are: variables, if/then statements, loops, text formatting, and button input.

First off, we will need to add two more header includes. The first one is to give us a little more control over the screen (we need this for one of the functions we will be using later). The second file we will be including allows us to get button input. So to do add these two files (pspdisplay.h and pspctrl.h), we need to add these two lines right below our first two "#include" statements:
#include
#include
And that's all the extra setup we need. Now we'll move on to putting in the functional code. From here on, all code listed should go in your main function, replacing the "printf" statement from Lesson 02. The first thing we will do is declare the variables that we will use in our program. A variable declaration takes the following form:
//EXAMPLE (Psuedo Code)
//DO NOT ADD TO YOUR PROGRAM
type name=value;
The type is the data type of variable. Each data type can contain data (and only that data). For example, type "int" (meaning integer) can hold any non-decimal number from -32767 to 32767. A "float" is like an "int," but it can hold decimals. The "char" type can hold a letter. For our program, we will only use the built in type "int" and a PSP specific type called "SceCtrlData" which holds the button state of the PSP controls.

So, to declare the two variables that we are going to use, we insert the following two lines of code into our program (these should go where your "printf("Hello World.");" line was in Lesson 02; right after the line "SetupCallbacks();."
int counter = 0;
int i = 0;
SceCtrlData pad;
So now we have three variables that we can use. Two of type "int," named "counter" and "i," containing a value of zero for now. And one of type "SceCtrlData," named "pad," which is filled with junk at the moment (since we haven't yet initialized it). This is something to keep in mind when writing your own programs. If you declare a variable without initializing it (like our pad variable), it will not just be empty. It will contain the information that was previously in that chunk of memory. Declaring the variable just allocates a certain amount of memory space for the variable to be stored in. The initialization is what clears it out and allows us to use it. The reason that we haven't initialized "pad" at the same time that we declared it is because it wouldn't really make sense. Since it holds button input, you can't just initialize it by typing in a value. We'll initialize it later, before we use it for anything.

Now we're going to give the user some instructions. The way we do this is by using "printf" to output a statement to them. So put this after the variable declarations:
printf("Press [X] To Start the Timer");
Look familiar? Good. It's the same function we used to output "Hello World" in Lesson 02. So if you ran the program at this point, it would be just like the "hello world" application, except it would print out "Press [X] To Start the Timer" instead of "Hello World."

Now we need the program to wait until the user presses the [X] button before it does anything else. Now, this could be a very difficult, nearly impossible thing to do. Fortunately, we have something perfect for dealing with it. It's called a loop. Basically what it does is run through a block of code multiple times. There are different types of loops available to you (for loops, while loops, do while loops, etc), but this tutorial will only introduce two of those loops, the "while" loop and the "for" loop. How this loop works is that you give it a statement, and it will execute a block of code while that statement is true. For example, if you had a block of code that incremented a variable (starting with a value of zero) by one each time the loop was run, and the statement that you passed in the loop was "i<10" it would execute your code ten times, because on the eleventh time that it checked the value of the variable, it would be 10, which is not less than 10, so the statement would be false (man, this is a run on sentence if I've ever seen one). One other important concept that you will need to grasp is that "true" and "false" are synonymous with "1" and "0" respectively.

Phew. It's not so hard is it? I'm glad you agree (like how I just assume the answer to my rhetorical questions because you can't answer?). So let's move on to the second part of this tutorial.


Lesson 04
Simple Image Processing
A crash course on adding images to your applications.

Since Lesson 03 was released, I have been bombarded with e-mails, instant messages, phone calls, and even the occasional reader banging on my front door pleading with me to release another tutorial. Overwhelmingly they have requested a lesson on adding images to their programs. Well, you guys can finally stop all of that, because this long overdue article is finally here.

At this point, I'll assume that you already have CYGWIN and the PSP toolchain installed, understand how to compile source code into an EBOOT suitable for execution on the PSP, and have at least a basic understanding of the C programming language. If you don't meet these prerequisites, have no fear, read Lesson 01, Lesson 02, and Lesson 03, and then come back.

If it has been a while since you have updated your toolchain, you will need to do that since png.h is necessary for this tutorial and was not originally included in the PSP toolchain. Revisit Lesson 01 if you need a refresher on how to do that. I had to update before I was able to compile this program (if you already have CYGWIN installed, you can skip right to the step where you download the toolchain).

I would like to thank Psilocybeing for allowing me to use his example source code as a base for this tutorial. I had originally planned on using my own example code (adapted from Shine's original Snake game in C) to demonstrate, but that code is antiquated and unnecessarily complex. One major benefit of Psilocybeing's code is that all of the functions and datatypes are defined in external files, allowing you to more easily integrate the code into your own projects.

Before we do anything, we will need to install some new libraries from SVN. What's SVN you ask? Well, SVN is a version management system (it is shorthand for "subversion"). What we will be doing is grabbing some code from online to add more functionality to our compiler. The packages that we will need are zlib and libpng. zlib is a compression library and libpng allows us to work with PNG files (a type of image). To install these libraries, we will need to type the following things into a CYGWIN Bash Shell.
svn checkout svn://svn.pspdev.org/psp/trunk/zlib
"Checkout" is basically SVN's way of saying "download." This will download the zlib source into a folder called "zlib." It will take a minute, a bunch of stuff should scroll down the screen and you should be left back at the "$" for input.

So now we need to compile this new library, so we'll "cd" into the new folder.
cd zlib
We are now in the zlib folder, and are ready to compile. So, like any other thing that we want to compile, we just need to type
make
And voila, it compiles the library for us.

Now we need to put the resulting files into a place where the compiler can access them. So, we'll install them:
make install
And BAM! We've installed zlib. Now wasn't that simple?

Now for libpng. We just need to do the same thing, except we'll substitute "libpng" for "zlib."
cd ..
svn checkout svn://svn.pspdev.org/psp/trunk/libpng
cd libpng
make
make install
And there we are, ready to use PNG's in our program.

Now we'll just clean up those install files by deleting them. To delete things via a Linux shell (which is what CYGWIN emulates), you use the "rm" command. We don't only want to delete one file, though, we want to delete a whole folder and all of its contents, so we'll add the "-R" modifier to it to signify a recursive removal. Basically this just means we want to delete a folder and everything inside of that folder. We'll also use the "-f" modifier to force the deletion of write-protected files so that we don't have to hit "y" for each file we want to delete. So we'll "cd" back to the parent directory and remove both the "zlib" and "libpng" temporary folders that we just created.
rm -Rf zlib
rm -Rf libpng
Now that we have that out of the way, we are ready to start programming.

We'll move on to the second section of this tutorial to continue our program.

Lesson 05
Onwards and Upwards
More PSP Programming methods including overclocking, colors, and graphics based text.

Ok, so you've set up the development environment, written your first program, leaned some programming techniques, and dabbled in image programming, but what's next? Well, since you're on this page, I'll bet it comes as no surprise to you that it's Lesson 05! Here we will improve our programming skills (and by "we," I really mean "you") by learning about some more advanced concepts.

Advanced, though, is subjective. We are still forming the groundwork in C that you will build upon in truly advanced applications. By the end of this lesson, you should know how to "overclock" the PSP to its true speed of 333 MHz, be able to write text to the screen (graphic text, not the debug text we used before), and have an understanding of how colors work on the PSP.

The program that we are going to construct in this tutorial is a "backround changer." Basically, we are going to allow the user to select the color of the background, and we are going to change it accordingly, as well as display the components of that color on the screen.

First, some background. There is a wide misconception about "overclocking" the PSP. Because of preconceived notions, people associate "overclocking" with heat issues and broken hardware. There is a myth that "overclocking" the PSP is dangerous to the hardware. This is simply not the case with the PSP. The truth is that the PSP is underclocked when it ships from the factory. There are several theories for why Sony did this. One theory is that it drained battery life too quickly for Sony's liking (for us, that isn't much of a concern; spinning the UMD takes up far more battery power than loading off of the Memory Stick, so we already have a tremendous advantage in terms of battery life). Another theory is that Sony wanted developers to write streamlined code. And the third prevalent theory (and the most likely in my opinion) is that they want to allow developers to use the full speed at some point in the future to give a boost to games that will come out later. Anyway, the PSP normally runs at 222 MHz. If you need more power for your programs, "overclocking" is an option. The program we make here will not need the power per se, but I think it's a good place to introduce the concept.

So here we go, let's start out our program. You'll need to download another zip file for this lesson. You can get it here. You'll need to make a main.c file in the same folder as the files you extract from the zip file.

#include
#include
#include
#include
#include

#include "graphics.h"
Assuming you have completed the previous lessons, this isn't anything you haven't seen. The only thing that should look new to you is the "psppower.h" include. This file contains the functions we will use to change the PSP's clock speed.

On to some more familiar code:
PSP_MODULE_INFO("Background Changer", 0, 1, 1);

#define RGB(r, g, b) ((r)|((g)<<8)|((b)<<16))
Remember how in Lesson 02 we just glossed over this line without explaining what it really did? Well, I think it's time that you learn. The first parameter is your program identifier, so basically your program name. The second parameter allows you to pass attributes. For most of your programs you will just want to use a 0, but if you are making a kernel mode app, you will need to switch this to "0x1000". The third parameter is for the major version, the fourth is minor version. These are just meant to document the version number of your program.

Now the standard callbacks:
/* Exit callback */
int exit_callback(int arg1, int arg2, void *common) {
          sceKernelExitGame();
          return 0;
}

/* Callback thread */
int CallbackThread(SceSize args, void *argp) {
          int cbid;

          cbid = sceKernelCreateCallback("Exit Callback", exit_callback, NULL);
          sceKernelRegisterExitCallback(cbid);

          sceKernelSleepThreadCB();

          return 0;
}

/* Sets up the callback thread and returns its thread id */
int SetupCallbacks(void) {
          int thid = 0;

          thid = sceKernelCreateThread("update_thread", CallbackThread, 0x11, 0xFA0, 0, 0);
          if(thid >= 0) {
                    sceKernelStartThread(thid, 0, 0);
          }

          return thid;
}
That concludes the set-up portion of this tutorial. Continue on to the second part of this tutorial. Onwards!

Lesson 06
Adding Sound
How to use libmad to play MP3 files in your programs.

This lesson was written by guest writer Stephen Merity (aka Smerity), so thanks to him for his great contribution.

First of all, thanks goes to John_K for porting libmad to the PSP and for developing PSPMediaCenter (which I used some of the code from). Also, a special thank you to seventoes, who posted a while back on PS2Dev.org asking for help with libmad with code that was so close to working!

This tutorial is a simple walkthrough concerning playing music in your programs. Sound FX and background music are two aspects that give an application a polished feeling, but they are often overlooked. Whether that is because a developer is rushing to get a release out of the door or whether it is because they simply don't know how to implement sound (or have any fitting music to to with their application) is unclear. Hopefully this tutorial will help some people get sound into their programs.

The first thing we are going to have to do is grab libmad from SVN. libmad is an MPEG audio decoder released under the GPL. It has been ported to the PSP by John_K.

To do this, open Cygwin, and type
svn checkout svn://svn.ps2dev.org/psp/trunk/libmad
You should see a long list of filenames scroll by as the package is downloaded.

Now we will switch into the libmad directory and compile the library:
cd libmad
make
The next bit is a little deviation from the routine we used to install our libraries in Lesson 04. Usually, you could type "make install" and it would automatically install the files to their appropriate directories. Unfortunately, libmad's install script appears to be broken at the moment. Not to worry though, we can install it manually ourselves.
cp -Rf ./include /usr/local/pspdev/psp/
cp -Rf ./lib/libmad.a /usr/local/pspdev/psp/lib
NOTE: There is a space between "./include" and "/usr..." and between "libmad.a" and "/usr..."

This will copy all of the files into their appropriate place. The "-Rf" tag stands for "Recursive" and "final" -- it will just make sure that you copy everything and that you won't get any permission errors (which some users have reported as a problem without these flags).

Next, download and extract some necessary files into a new project folder. Inside are two files, mp3player.c and mp3player.h which were obtained from John_K's PSPMediaCenter, I made some slight changes to the files as follows (you don't need to do anything with this, it's just in case you were wondering):
//DO NOT ADD THIS TO YOUR PROGRAM
//IT IS EXAMPLE CODE
mp3player.c
Line 76 - /* void void MP3setStubs to end of function */ - specific to stubs again, see mp3player.h

mp3player.h
Line 10 - #include "../../codec.h" - specific to PSPMediaCenter
Line 17 - void MP3setStubs(codecStubs * stubs); - specific to PSPMediaCenter
Other than that, it was very clean. John_K has done a great job in porting it.

Now, on to the fun part. Create main.c in your editor of choice, and begin with your comments:
// Mp3 Player Sample on PSP
// By *YOUR NAME HERE*
The next little section should be standard to you. The only new includes are the "pspaudio.h" and "pspaudiolib.h." These headers are needed for the audio-specific functions that we will use in our program.
#include
#include
#include
#include
#include
#include

#include "mp3player.h"

PSP_MODULE_INFO("Mp3 Player Example", 0, 1, 1);
#define printf pspDebugScreenPrintf
You will also see that we included one of the files that you downloaded, "mp3player.h" (make sure that it's in the same directory as our source file). We also defined printf and did our PSP_MODULE_INFO.

No comments:

Post a Comment