CATHODE RAY TOMES

PlayStation Runtime Library Overview

PlayStation (Sony, 1994) · Developer Manual · 330 pages · 101 sections · original scan

Page 1
Scan of page 1

This page is a drawing, shown as the original scan.

Page 2

© 1999 Sony Computer Entertainment Inc.

Publication date: August 1999

Sony Computer Entertainment America 919 E. Hillsdale Blvd., 2nd floor Foster City, CA 94404

Sony Computer Entertainment Europe Waverley House 7-12 Noel Street London W1V 4HH, England

The Run-Time Library Overview manual is supplied pursuant to and subject to the terms of the Sony Computer Entertainment PlayStation® License and Development Tools Agreements, the Licensed Publisher Agreement and/or the Licensed Developer Agreement. The Run-Time Library Overview manual is intended for distribution to and use by only Sony Computer Entertainment licensed Developers and Publishers in accordance with the PlayStation® License and Development Tools Agreements, the Licensed Publisher Agreement and/or the Licensed Developer Agreement. Unauthorized reproduction, distribution, lending, rental or disclosure to any third party, in whole or in part, of this book is expressly prohibited by law and by the terms of the Sony Computer Entertainment PlayStation® License and Development Tools Agreements, the Licensed Publisher Agreement and/or the Licensed Developer Agreement. Ownership of the physical property of the book is retained by and reserved by Sony Computer Entertainment. Alteration to or deletion, in whole or in part, of the book, its presentation, or its contents is prohibited. The information in the Run-Time Library Overview manual is subject to change without notice. The content of this book is Confidential Information of Sony Computer Entertainment. PlayStation and PlayStation logos are registered trademarks of Sony Computer Entertainment Inc. All other trademarks are property of their respective owners and/or their licensors.

Page 3

Summary Table of Contents

About This Manual ix

Chapter 1: Overview of the PlayStation OS 1-1

Chapter 2: Kernel Library 2-1

Chapter 3: Standard C Library 3-1

Chapter 4: Math Library 4-1

Chapter 5: Memory Card Library 5-1

Chapter 6: Extended Memory Card Library 6-1

Chapter 7: Data Compression Library 7-1

Chapter 8: Basic Graphics Library 8-1

Chapter 9: Basic Geometry Library 9-1

Chapter 10: Extended Graphics Library 10-1

Chapter 11: CD/Streaming Library 11-1

Chapter 12: Extended CD-ROM Library 12-1

Chapter 13: Controller/Peripherals Library 13-1

Chapter 14: Link Cable Library 14-1

Chapter 15: Extended Sound Library 15-1

Chapter 16: Basic Sound Library 16-1

Chapter 17: Serial Input/Output Library 17-1

Chapter 18: HMD Library 18-1

Chapter 19: PDA Library 19-1

Chapter 20: Memory Card GUI Module (Mcgui) 20-1

Page 4

iv Table of Contents

List of Figures

Figure 1-1: Boot Sequence Figure 1-2: PlayStation library structure Figure 2-1: Execution File Memory Map Figure 7-1: Data Expansion and Display by MDEC Figure 7-2: 320x240 Image Breakdown Figure 7-3: DCT Processing Figure 7-4: DCT Compression Figure 7-5: DCT Decompression Figure 8–1: Graphics System Figure 8–2: Frame Buffer Figure 8–3: Pixels Figure 8–4: Display Area and Screen Area Figure 8–5: Drawing a Quadrilateral Figure 8–6: Polygon Vertex Format Figure 8–7: Perspective Transformation Figure 8–8: Drawing After Registering in OT Figure 8–9: Packet Double Buffer Figure 8–10: Texture Pattern Format Figure 8–11: Primitive Rendering Speed Figure 8–12: Clipping Figure 8–13: Cache Blocks in Texture Page Figure 8–14: Cache Entries Figure 8–15: Drawing Rule Figure 8–16: Mapping Figure 8–17: Displayed contents Figure 8–18: Mapping Figure 8–19: Displayed Contents Figure 8–20: Mapping Figure 8–21: Displayed Contents Figure 8–22: Mapping Figure 8–23: Displayed Contents Figure 8–24: Display Starting Position Figure 8–25: Switching between even and odd fields Figure 9-1: Coordinate Axes Figure 9-2: Vertex Order Figure 9-3: Four Vertices Figure 9-4: Writing data using DR_LOAD primitives Figure 9-5: Strip Mesh Figure 9-6: Round Mesh Figure 9-7: PACKET Gp Configuration Figure 9-8: VERTEX Figure 10-1: Viewpoint and Screen Figure 10-2: Preset Packet Format Figure 10-3: Three-dimensional Processing Flowchart Figure 10-4: Texture Location Figure 10-5: Polygon Vertex Order Figure 11-1: Process of CD-ROM Transfer Figure 11-2: ADPCM Sector Interleave Figure 11-3: Example Multichannel Interleave Figure 11-4: Ring Buffer Size 4 Example Figure 12-1: CD libraries Figure 13–1: Callback Context Figure 13–2: Callback Context 1-5 1-5 2-16 7-4 7-5 7-5 7-7 7-8 8-4 8-4 8-5 8-7 8-13 8-17 8-17 8-21 8-21 8-24 8-28 8-30 8-31 8-31 8-36 8-37 8-37 8-38 8-38 8-39 8-39 8-40 8-40 8-42 8-45 9-9 9-9 9-10 9-12 9-17 9-17 9-18 9-20 10-7 10-12 10-15 10-19 10-19 11-5 11-17 11-17 11-35 12-3 13-3 13-6

Page 5

Table of Contents v

Figure 13–3: Timing with VSync Interrupts (1) Figure 13–4: Timing with VSync Interrupts (2) Figure 13–5: Figure 15–1: SEQ data format Figure 15–2: SEP data format Figure 15-3: VAB Switching Using Control Changes Figure 15–4: VAB format and VAB header Figure 16-1: Sound Buffer Memory Layout Figure 16-2: Four States and their Transitional States Figure 16-3: Four Callback Functions and Transitional States Figure 18-1: HMD Basic Architecture Figure 18-2: Hierarchical Structure Figure 18-3: Strip Mesh Figure 18-4: Shared Polygons Figure 18-5: Combining vertex and joint MIMe Figure 18-6: Process flow and data structures Figure 18-7: Linking primitive sets and coordinate systems Figure 18-8: Primitive sets, primitives, primitive headers, sections Figure 18-9: Index starting point Figure 18-10: Index reference Figure 18-11: Pointer reference Figure 18-12: Vertex MIMe Figure 18-13: Vertex MIMe reset Figure 18-14: Joint Axes MIMe Figure 18-15: Joint RPY MIMe Figure 19-1: Function calling sequence Figure 19-2: File list functions Figure 19-3: Game selection function Figure 20-1: Save Operation of the Memory Card Screen Figure 20-2: Load Operation of the Memory Card Screen Figure 20-3: Location where textures are loaded in the frame buffer Figure 20-4: mcgui texture data structure 13-7 13-8 13-10 15-4 15-5 15-8 15-8 16-7 16-10 16-11 18-3 18-4 18-5 18-6 18-7 18-8 18-9 18-12 18-13 18-13 18-14 18-14 18-15 18-16 18-17 19-4 19-10 19-11 20-4 20-5 20-7 20-8

Page 6

vi Table of Contents

List of Tables

Table 2-1: SYSTEM.CNF Overview Table 2-2: ToT Entries Table 2-3: Descriptor Bit Patterns Table 2-4: Descriptor Classification Table 2-5: List of Root Counters Table 2-6: Counter Timing Table 2-7: Pixel Display Timing and Display Width Table 2-8: Root Counter Mode (1) Table 2-9: Root Counter Mode (2) Table 2-10: Root Counter Mode (3) Table 2-11: Root Counter Gate Condition Table 2-12: Cause Descriptor (Kernel Library Related Only) Table 2-13: Event Conditions Table 2-14: Event Modes Table 2-15: TCB status Table 2-16: Register-Specified Macro Table 2-17: IO Devices Table 2-18: CD-ROM File System (ISO 9660 Level 1) Table 2-19: Memory Card File System Table 2-20: Summary of Terminal Types Table 2-21: Mouse Table 2-22: 16-Button Analog Table 2-23: Gun Controller (Konami) Table 2-24: 16-Button Table 2-25: Analog Joystick Table 2-26: Gun Controller (Namco) Table 2-27: Analog Controller Table 2-28: Multi Tap Received Data Configuration Table 2-29: Button status bit assignments Table 2-30: Kanji Fonts Table 2-31: Font Data Format Table 2-32: Memory Card allocation functions Table 2-33: Performance comparison between memory allocation functions Table 3–1: Header Files Table 4–1: Float Format Table 4–2: Double Format Table 4–3: Error Notificaton Table 5-1: Memory Card Specifications Table 5-2: Events Associated with the Memory Card Table 5-3: Memory Card BIOS Table 5-4: Memory Card File System Table 5-5: Memory Card File Names Table 5-6: Memory Card File Header Table 5-7: Type Field Table 6-1: Memory Card Specifications Table 6-2: Memory Card Filenames Table 6-3: Memory Card File Header Table 6-4: Type Field Table 7-1: Compression and Decompression Algorithms Table 7-2: Decompression Speed and Resolution Table 7-3: Transfer Speed and Data Size Table 8-1: Display Modes Table 8-2: Double Buffer 2-3 2-4 2-5 2-5 2-7 2-8 2-8 2-8 2-8 2-9 2-9 2-10 2-11 2-11 2-13 2-13 2-14 2-15 2-15 2-17 2-18 2-18 2-18 2-18 2-19 2-19 2-19 2-20 2-20 2-21 2-21 2-23 2-23 3-3 4-3 4-3 4-4 5-3 5-3 5-4 5-7 5-9 5-9 5-10 6-4 6-5 6-5 6-6 7-6 7-10 7-10 8-5 8-7

Page 7

Table of Contents vii

Table 8-3: Polygon Primitives Table 8-4: Line Primitives Table 8-5: Sprite Primitives Table 8-6: Special Primitives Table 8-7: OT Table 8-8: Reset Levels Table 8-9: libgpu callback registering functions Table 8-10: Texture Pattern Modes Table 8-11: Transparent/Semi-Transparent Pixels Table 8-12: Semi-Transparency Rates Table 8-13: Texture Cache Size Table 8-14: Access Cycles Table 8-15: Number of Access Cycles Table 8-16: Number of Cycles in POLY_FT4 Table 8-17: Number of Cycles in SPRT Table 8-18: Number of Cycles Used when Reduction Is Involved Table 8-19: Texture Cache Dependencies Table 8-20: Size of Cache Blocks and Cache Entries Table 8-21: Differences between NTSC and PAL Table 9-1: Recommended Format for GTE Constants Table 9-2: Flag Bit Settings Table 9-3: 16-Bit Flag Bit Settings Table 9-4: 4-Type Bit Configuration Table 9-5: Polygon Division Functions Table 10-1: Hierarchical Structuring Table 10-2: Packet Creation Function Comparison Chart 1 Table 10-3: Packet Creation Function Comparison Chart 2 Table 10-4: State of Scratch Pad Consumption Table 10-5: Scratch pad usage volume Table 10-6: mip-map Low-level Function Group Table 11-1: Sector Types Table 11-2: Primitive Commands and Corresponding Codes Table 11-3: Primitive Command Arguments Table 11-4: Primitive Command Return Values Table 11-5: Bit Assignments of Status Byte Table 11-6: The Operation of CdlSeek/CdlSeekP Table 11-7: Mode Settings of CdlSetmode Table 11-8: CdlGetlocL Parameters Table 11-9: CdlGetlocP Table 11-10: CdlGetTN Table 11-11: CdlGetTD Table 11-12: Primitive Command Processing Status Table 11-13: CdSync() Mode Argument Values and Contents Table 11-14: Retry Read/No-Retry Read Table 11-15: Sector Buffer Status Table 11-16: Information Obtained in Report Mode Table 11-17: Event Services Table 11-18: Callback, Synchronous Functions Table 11-19: Error levels Table 11-20: Interrupt functions Table 12-1: Primitive Commands Table 12-2: Structures Table 12-3: Confirming Completion of Command Table 13-1: Callback Types Table 13-2: Initialization Functions that Call ResetCallback() Table 13-3: Terminal Types 8-9 8-10 8-10 8-10 8-16 8-18 8-19 8-23 8-25 8-25 8-27 8-28 8-29 8-29 8-29 8-29 8-30 8-32 8-41 9-15 9-15 9-16 9-18 9-21 10-6 10-14 10-14 10-17 10-17 10-17 11-3 11-6 11-7 11-8 11-8 11-9 11-10 11-10 11-11 11-11 11-11 11-12 11-12 11-14 11-15 11-18 11-19 11-19 11-28 11-36 12-4 12-5 12-7 13-4 13-4 13-11

Page 8

viii Table of Contents

Table 13-5: Mouse Table 13-6: 16-button Analog Table 13-7: Gun Controller (Konami Ltd.) Table 13-8: Analog Joystick Table 13-9: Gun Controller (Namco Ltd.) Table 13-10: Analog Controller Table 13-11: Receive Data Structure For Multi Tap Controller Table 13-12: Button State Bit Assignments (1) Table 13-13: Button State Bit Assignments (2) Table 13-14: System Clock-Pixel Clock Conversion Table Table 13-15: Actuator Current Drain Table 13-16: Receiving Packet Format Table 13-17: Memory Card Table 13-18: Button Data (bufA, bufB) Table 13-18 Table 13-21: buf0, buf1 structures defined in InitGUN Table 13-20: System Clock/Pixel Clock Conversion Table 14-1: Link Cable Driver Table 14-2: Events Table 14-3: Command Summary Table 14-4: Driver Status Table 14-6: Control Line Status Table 14-8: Communication Mode Table 14-10: Control Line Table 14-11: Communication Specifications Table 14-12: Control Line Transition Table 15-1: Data1-Data3 Contents Table 15-2: Data3 Mode Type Table 15-3: Data3 Reverb Type (See Also Sound Delicatessen DSP) Table 15-4: Looping Using Control Changes Table 15-5: Marking via Control Changes Table 16-1: LFO Control Expression Format Table 19-1: PDA Memory Card specifications Table 19-2: Existing File Header (non-PDA compatible) Table 19-3: Memory Card extended file header Table 19-4: Game selection icon entry table Table 19-5: Device entry table Table 19-6: Icon Types Table 19-7: Icons used in the file list Table 19-8: Icon animation update frequency Table 19-9: Device current consumption Table 20-1: Supported controllers 13-12 13-12 13-12 13-12 13-13 13-13 13-13 13-14 13-14 13-14 13-17 13-18 13-18 13-19 13-20 13-20 13-20 14-3 14-3 14-5 14-6 14-6 14-6 14-7 14-7 14-7 15-6 15-6 15-7 15-7 15-7 16-5 19-5 19-6 19-6 19-8 19-9 19-9 19-10 19-11 19-13 20-6

Page 9

About This Manual

This manual is the latest release of the Library Overview for Run-Time Library 4.6. The purpose of this manual is to provide overview-level information about the PlayStation® libraries. For related descriptions of the PlayStation run-time library functions and structures, please refer to the Run-Time Library Reference.

Changes Since Last Release

Since release 4.5 of the Run-Time Library Overview, the following changes have been made:

Ch. 8: • A “GPU timeout message” item has been added to the “Cautionary Programming Notes” section.

Ch. 11: • Basic Graphics Library

CD/Streaming Library Corrections have been made in the “Skipped Sections” item of the “Notes on Using Low Level Function Groups" section.

Ch. 19: PDA Library • A note has been added to the “”Game selection icon image” item of table 19-3 in the “File Header” section. • Additional information has been added to the “Game selection icons” item in the “File header” section. • A “Notes on icon entry table and icon image position” item has been added to the “Icons” section.

Related Documentation

This manual should be read in conjunction with the Run-Time Library Reference, which defines all structures and functions available in the Run-Time Library.

Manual Structure

Chapter Description Ch. 1: Overview of the PlayStation OS Summarizes the PlayStation operating system and the run-time libraries. Describes the Kernel library (libapi), which provides an interface between applications and the PlayStation OS. Describes the PlayStation’s subset of the standard C library (libc/libc2). This library includes character functions, memory operation functions, character class tests, non-local jumps, and utility functions. Describes the Math Library (libmath), which contains ANSI/IEEE754 compliant math functions, including a software floating point computation package. Describes the Memory Card Library (libcard) for reading/writing to the PlayStation Memory Card and calling the Memory Card BIOS service. Ch. 2: Kernel Library

Ch. 3: Standard C Library

Ch. 4: Math Library

Ch. 5: Memory Card Library

CONFIDENTIAL

Page 10

x About This Manual

Chapter Description Ch. 6: Extended Memory Card Library Describes the Extended Memory Card Library (libmcard), which provides a highlevel interface for accessing the Memory Card. Describes the Data Compression Library (libpress) for compressing (encoding) and expanding (decoding) image and sound data. Describes the Basic Graphics Library (libgpu) for drawing primitives such as sprites, polygons, and lines. Describes the Basic Geometry Library (libgte), which uses the PlayStation GTE coprocessor to handle high-speed geometry operations. Describes the Extended Graphics Library (libgs) which uses the libgpu and the libgte to construct a 3-dimensional graphics system. It deals with more abstract entities such as objects and background surfaces. Describes the CD-ROM Library (libcd), for controlling the PlayStation CD-ROM drive. It also contains functions for “streaming” realtime data such as movies, sounds or vertex data stored on high-capacity media. Describes the Extended CD-ROM Library (libds), which builds a new interface to the libcd kernel. It has the same capabilities as libcd, and places further emphasis on reliable CD-ROM controls such as recovery from system errors. Describes the Controller/Peripherals Library, which consists of a group of libraries (libetc, libgun, libtap, and libpad) for performing lowlevel interrupt processing and controllerrelated functions. Describes the Link Cable Library (libcomb), which provides services for connecting PlayStation units via a “link” cable. Describes the Extended Sound Library (libsnd), which provides functions for working with sound data on the PlayStation. Describes the Basic Sound Library (libspu) for controlling the SPU (sound processing unit). Describes the Serial Input/Output Library (libsio) for supporting communications between the PlayStation and a PC. Ch. 7: Data Compression Library

Ch. 8: Basic Graphics Library

Ch. 9: Basic Geometry Library

Ch. 10: Extended Graphics Library

Ch. 11: CD-ROM Library

Ch. 12: Extended CD-ROM Library

Ch. 13: Controller/Peripherals Library

Ch. 14: Link Cable Library

Ch. 15: Extended Sound Library

Ch. 16: Basic Sound Library

Ch. 17: Serial Input/Output Library

CONFIDENTIAL

Page 11

About This Manual

Chapter Description Ch. 18: HMD Library Describes the HMD Library (libhmd), which provides functions and definitions for handling the HMD format, which integrates modeling, animation, texture, and MIMe data. Describes the PDA Library (libmcx) used to provide access to PDA functions when it is inserted into a Memory Card slot. Describes the module for saving and loading data in game titles, as well as support for the user interface Ch. 19: PDA Library

Ch. 20: mcgui Module

Developer Reference Series

This manual is part of the Developer Reference Series, a series of technical reference volumes covering all aspects of PlayStation development. The complete series is listed below:

Manual Description PlayStation Hardware Describes the PlayStation hardware architecture and overviews its subsystems. Describes the PlayStation operating system and related programming fundamentals. Describes the structure and purpose of the run-time libraries provided for PlayStation software development. Defines all available PlayStation run-time library functions, macros and structures. Describes in-line programming using DMPSX, GTE inline macro and GTE register information. Describes the SDevTC (formerly "Psy-Q") Development Environment for PlayStation software development. Describes how to use the PlayStation 3D Graphics Tools, including the animation and material editors. Describes the Sprite Editor tool for creating sprite data and background picture components. Provides installation and operation instructions for the DTL-H800 Sound Artist Board and explains how to use the Sound Artist Tool software. Describes all native PlayStation data formats. Describes all available PlayStation data conversion utilities, including both standalone and plug-in programs. Provides installation and operation instructions for the CD Emulator subsystem and related software. PlayStation Operating System

Run-Time Library Reference

Inline Programming Reference

SDevTC Development Environment

3D Graphics Tools

Sprite Editor

Sound Artist Tool

File Formats

Data Conversion Utilities

CD Emulator

CONFIDENTIAL xi

Page 12

xii About This Manual

Manual Description CD-ROM Generator Describes how to use the CD-ROM Generator software to write CD-R discs. Provides general instructions for using the Performance Analyzer software. Describes how to measure software performance and interpret the results using the Performance Analyzer. Provides installation and operation instructions for the DTL-H2000 Development System. Provides installation and operation instructions for the DTL-H2500/H2700 Development Systems. Performance Analyzer User Guide

Performance Analyzer Technical Reference

DTL-H2000 Installation and Operation

DTL-H2500/2700 Installation and Operation

Typographic Conventions

Certain Typographic Conventions are used throughout this manual to clarify the meaning of the text:

Convention courier Meaning Indicates literal program code. Indicates names of arguments and structure members (in structure/function definitions only). italic

Developer Support

Sony Computer Entertainment America (SCEA) SCEA developer support is available to licensees in North America only. You may obtain developer support or additional copies of this documentation by contacting the following addresses:

Order Information In North America: Attn: Developer Tools Coordinator Sony Computer Entertainment America 919 East Hillsdale Blvd., 2nd floor Foster City, CA 94404 Tel: (650) 655-8000 Developer Support In North America: E-mail: DevTech_Support@playstation.sony.com Web: http://www.scea.sony.com/dev Developer Support Hotline: (650) 655-8181 (Call Monday through Friday, 8 a.m. to 5 p.m., PST/PDT)

CONFIDENTIAL

Page 13

About This Manual

Sony Computer Entertainment Europe (SCEE) SCEE developer support is available to licensees in Europe only. You may obtain developer support or additional copies of this documentation by contacting the following addresses:

Order Information In Europe: Attn: Production Coordinator Sony Computer Entertainment Europe Waverley House 7-12 Noel Street London W1V 4HH Tel: +44 (0) 171 447 1600 Developer Support In Europe: E-mail: dev_support@playstation.co.uk Web: https://www-s.playstation.co.uk Developer Support Hotline: +44 (0) 171 447 1680 (Call Monday through Friday, 9 a.m. to 6 p.m., GMT or BST/BDT)

CONFIDENTIAL xiii

Page 14
Scan of page 14

This page is a drawing, shown as the original scan.

Page 15

Chapter 1: Overview of the PlayStation OS

Table of Contents

The PlayStation OS 1-3

Features of the PlayStation OS Programming in C Easy Access to the Features of the R3000 Small Size, Emphasis on Performance Provision for Hardware Functions Single and Multitasking The File System Device Driver 1-3 1-3 1-3 1-3 1-3 1-4 1-4

Starting and Operating the OS Activation of the OS Boot Sequence 1-4 1-4 1-4

PlayStation OS Library Components libapi (Kernel Library) libc/libc2 (Standard C Libraries) libmath (Math Library) libcard (Memory Card Library) libmcrd (Extended Memory Card Library) libpress (Data Compression Library) libgpu (Basic Graphics Library) libgte (Basic Geometry Library) libgs (Extended Graphics Library) libcd (CD/Streaming Library) libds (Extended CD-ROM Library) libetc (Peripherals Library) libtap (Multi Tap Library) libgun (Gun Library) libpad (Controller Library) libcomb (Link Cable Library) libsnd (Extended Sound Library) libspu (Basic Sound Library) libsio (Serial Input/Output Library) libhmd (HMD Library) libmcx (PDA Library) mcgui (Memory Card GUI module) 1-5 1-6 1-6 1-6 1-6 1-6 1-6 1-6 1-6 1-6 1-6 1-6 1-7 1-7 1-7 1-7 1-7 1-7 1-7 1-7 1-7 1-7 1-7

Page 16
Scan of page 16

This page is a drawing, shown as the original scan.

Page 17

Overview of the PlayStation OS 1-3

The PlayStation OS

The PlayStation OS is a flexible and powerful operating system, which allows developers to take maximum advantage of the PlayStation’s capabilities.

The OS has been developed for the R3000, which is the PlayStation's CPU. The efficiency of program development relies heavily on the environment and services provided by the OS. If the CPU and peripheral devices are fast enough, you won’t need to spend your time trying to maximize the hardware’s capabilities. You can concentrate on programming using the services the OS provides for you.

The PlayStation OS is designed to give the game program developer an environment in which interrupts can be easily controlled. Based on this concept, the kernel of the PlayStation OS provides services to control PlayStation hardware and the R3000.

Each service is provided as a C language function. By using C, your programs can be more readable and maintainable, and you can program more easily using block structure description and function calls.

Features of the PlayStation OS

This section describes the characteristics of the PlayStation’s design concept.

Programming in C

Most services, such as controlling the R3000 CPU and the PlayStation hardware, are provided as C language functions. Therefore, programs can be written completely in C.

Easy Access to the Features of the R3000

Interrupt control in the R3000 is said to be complicated, but the PlayStation OS uses a substitute “dispatcher” system which has a simple interface. The dispatcher’s overhead is kept very low, and it provides low-level support not available in ordinary operating systems. Because of this, the chip's capabilities can be fully exploited and high quality tuning can be achieved. And because everything can be done in C, it is not necessary to learn the intricacies of R3000 assembler.

Small Size, Emphasis on Performance

Because of the importance of an application's performance, the PlayStation OS was designed so that its RAM usage (64K bytes) and use of the CPU are kept to a minimum. In addition, the OS system tables are disclosed, and consideration given to future expansion of the OS.

To achieve greater speed, the PlayStation OS doesn’t carry out many checks of prohibited items that other operating systems would. This policy allows applications to achieve a higher level of tuning. However, to avoid the risk of prohibited operations being performed, applications may need to perform some checks that would normally be carried out by the operating system.

Provision for Hardware Functions

Previously, to control video game machine hardware, one has had to analyze hardware driver code and painstakingly write one’s code in assembler. The PlayStation OS lightens this burden by providing C language functions to control hardware. The overhead of each function is kept to a minimum.

Page 18

1-4 Overview of the PlayStation OS

Single and Multitasking

The PlayStation OS can carry out many tasks asynchronously while executing code, such as controlling a CD-ROM drive, which is a comparatively slow device, and playing background music.

When the OS starts, it is in single-task mode. If desired, you can specify that your application will have multiple tasks or threads. See Chapter 2, “Kernel Library”, for information on threads.

The File System Device Driver

The PlayStation’s file system (i.e., files of data on CD-ROM) is accessed via a device driver. This allows multiple file systems to coexist, and improves development time by avoiding low level file manipulation problems.

Starting and Operating the OS

The PlayStation OS provides a game program developer's environment. Therefore, there is fundamentally no interface for the user to operate directly (excluding the debug monitor in the debug environment). Applications must provide the user interface.

Activation of the OS

When the system starts, it jumps first a special address in ROM and performs a check on connected hardware (such as a CD-ROM drive).

It then checks for a suitable disk in the CD-ROM drive. If it finds one, it reads the system configuration file (SYSTEM.CNF).

If there is no disk, a ROM-resident demonstration program plays repeatedly.

Boot Sequence

The boot sequence is as follows:

Page 19

Overview of the PlayStation OS 1-5

Figure 1-1: Boot Sequence

Initialize System Operation Memory

Set System Stack

Initialize Kernel Memory

Initialize System Memory Control Capability

Initialize IO Manager

Set Error Handler

Read System Setting File (system.cnf)

Analyze System Setting File

Maintain All System Table Types

Read Boot Execution File

Set Stack

Execute Boot Execution File

PlayStation OS Library Components

PlayStation libraries can be thought of as low-level libraries or high-level libraries, depending on their relationship to the PlayStation OS. They form a two-level library structure. Programs may use any level as needed, and, with some exceptions, may use both levels concurrently.

Figure 1-2: PlayStation library structure

libhmd

libgs

libgpu libgte libsnd

libapi libspu libcd

libpress libds libmcrd

libetc libcard libmcx libpad libcomb libsio libgun libtap libc/libc2 libmath libsn

Page 20

1-6 Overview of the PlayStation OS

A summary of the libraries follows:

libapi (Kernel Library)

Provides an interface (API) between the PlayStation OS and applications.

libc/libc2 (Standard C Libraries)

A subset of the standard C library, including character functions, memory operation functions, character class tests, non-local jumps, and utility functions.

libmath (Math Library)

Contains ANSI/IEEE754 compliant math functions and a software floating point computation package.

libcard (Memory Card Library)

Provides functions for controlling the Memory Card, which preserves data after reset and power off. It includes the Memory Card, the file system, and drivers.

libmcrd (Extended Memory Card Library)

Provides a high-level interface to the Memory Card.

libpress (Data Compression Library)

Provides functions for compressing (encoding) and expanding (decoding) image and sound data.

libgpu (Basic Graphics Library)

Contains commands for the drawing engine and for building a drawing command list. Handles data for simple entities such as sprites, polygons and lines.

libgte (Basic Geometry Library)

A library for controlling the GTE (geometry transformation engine). Handles data such as matrices and vertices.

libgs (Extended Graphics Library)

A three-dimensional graphics system which uses libgpu and libgte. Handles larger entities such as objects and background surfaces.

libcd (CD/Streaming Library)

Reads program, image, and sound data from a CD-ROM drive, and performs playback of DA (digital audio) and XA sound. Also includes fast disk access through a file name key, and a support function for simultaneous data reading and processing streaming techniques.

libds (Extended CD-ROM Library)

Builds a new interface to the CD-ROM library kernel. Has the same capabilities as libcd and places further emphasis on reliable CD-ROM controls such as performing error recovery .

Page 21

Overview of the PlayStation OS 1-7

libetc (Peripherals Library)

Performs callback control for using controllers and other peripheral devices and processing low-level interrrupts.

libtap (Multi Tap Library)

Allows access to 3-8 controllers and memory cards through the optional peripheral multi-tap.

libgun (Gun Library)

Provides access to Light Pen type input equipment which can connect to the controller connector.

libpad (Controller Library)

A library for accessing the controller. Supports extended protocol controllers such as DUAL SHOCK.

libcomb (Link Cable Library)

Communicates between the link cable and PlayStation. It includes an 8-bit block size communication driver.

libsnd (Extended Sound Library)

Plays as background, sound production sequences that have been prerecorded as score data.

libspu (Basic Sound Library)

Controls the SPU (sound processing unit).

libsio (Serial Input/Output Library)

Sets the standard input/output on the debugging station to SIO 1.

libhmd (HMD Library)

Provides functions and definitions for handling the HMD format, which integrates modeling, animation, texture, and MIMe data.

libmcx (PDA Library)

The PDA library provides access to various functions of the PDA when it is inserted into a Memory Card slot.

mcgui (Memory Card GUI module)

This module provides support for loading and saving data in game titles, as well as support for the user interface.

Page 22
Scan of page 22

This page is a drawing, shown as the original scan.

Page 23

Chapter 2: Kernel Library

Table of Contents

Overview Library and Header Files System Designation File System Table Information (ToT) Descriptors Callbacks Inhibition of Interrupts Interrupt Context Kernel Reserved Memory Areas 2-3 2-3 2-3 2-4 2-5 2-6 2-6 2-6 2-7

Root Counter Control Counter Timing Mode Gate Status Immediately After Kernel Starts Root Counter and Critical Section Use of the Root Counter by the Kernel 2-7 2-8 2-8 2-9 2-9 2-9 2-9

Events Cause Descriptor and Type of Event Event Handler Event Status Mode Event Creation Clearing an Event User-Defined Event 2-9 2-10 2-10 2-11 2-11 2-11 2-11 2-12

Threads Context and TCB Status Immediately After Kernel is Started Thread Open and Switching Execution TCB Interrupts and TCB TCB Status Register Specification Macros 2-12 2-12 2-12 2-12 2-13 2-13 2-13

I/O Management CD-ROM File System Memory Card File System Standard I/O Stream 2-14 2-15 2-15 2-15

Module Control Execution File Data Structure 2-16 2-16

Controller Features Initialization Buffer Data Format 2-17 2-17 2-17

Page 24
Scan of page 24

This page is a drawing, shown as the original scan.

Page 25

Kernel Library 2-3

Overview

The Kernel library (libapi) provides an interface (API) by which applications can control basic aspects of the PlayStation OS, including the CPU and other hardware features.

It includes the following services: • Root-counter processing • Event processing • Thread processing • IO processing • Module processing • Controller • Other

Library and Header Files

Programs using kernel services must link with the library file libapi.lib.

Source code must include the header files libapi.h and kernel.h.

System Designation File

You use the system designation file system.cnf to reserve memory for stack, tasks and events. The system reads this file at boot time.

The format of each line of the file is “<KEYWORD> = <CONTENT>”. The table below shows the available keywords. All characters must be uppercase (1 byte alphanumeric) and there must be a space on either side of the equal sign. (If there is more than one line with the same parameter within a file, the first one takes precedence.)

Table 2-1: SYSTEM.CNF Overview Key word Contents BOOT Device name:\Product number; cdrom:PSX.EXE;1 version Example: BOOT = cdrom:\SLUS_123.45;1 0x801FFF00 Stack pointer value when booted Number of task control blocks (hex)* Example: TCB = 5 0x10 Number of event processing blocks (hex)* Example: EVENT = 5 STACK

TCB

EVENT Default Minimum N/A

0x80010000**

  • The maximum number of task control blocks and event control blocks that you can allocate is shown by the following formula: TCB * 192 + EVENT * 32 + 544<4096.

** Since 0-0x0000FFFF is reserved as the system area (see the “Physical Memory Map” section of the “CPU and its Peripherals” chapter in the PlayStation Hardware manual) the minimum address of the user program work area should be at least 0x80010000.

Page 26

2-4 Kernel Library

System Table Information (ToT)

The kernel uses several types of tables, such as task control blocks and event control blocks. To access these tables in a uniform manner, system table information is represented by the structure ToT (Table of Tables), located at address 0x00000100.

Each entry in the ToT is defined by the following structure (defined in kernel.h). The member head is a pointer to the actual table.

struct ToT { unsigned long *head; long size; }; /*system table table*/ /*system table initial address*/ /*system table size (in bytes)*/

The ToT entries are:

Table 2-2: ToT Entries

Entry Corresponding Table

5-31 System Reserved TCBH (pointer to execution TCB) Task control block (TCB) array System reserved Event control block array System reserved

The TCB (Task control block) structure contains information about a specific task. (See “Threads” for more information on using TCBs.) The TCBs are stored in an array, pointed to by the TCB entry of the ToT.

The TCBH structure contains a pointer to the currently executing TCB.

struct TCB { long status; long mode; unsigned long reg [NREGS];

long system[6]; /*task control block*/ /*status*/ /*mode*/ /*register save area*/ /*specify with register-specified macro*/ /*system reserved*/ };

struct TCBH { struct TCB *entry; long flag; }; /*task status queue*/ /*pointer to execution TCB*/ /*system reserved*/

The ToT can be used as follows:

Example 1: Getting the Pointer to the Execution TCB

struct ToT *t = (struct ToT *)0x100; /* address of ToT */ struct TCBH *h = (struct TCBH *)((t + 1)->head); /* address of TCB status queue header, which contains a pointer to currently executing TCB */ struct TCB *tcb_exec = (struct TCB*)(h->entry); /* address of execution TCB */

Example 2: Getting the Pointer to the Start of the TCB Array

struct TCB *tcb_0 = (struct TCB *)((t + 2)->head;

Example 3: Getting the Pointer to the Start of the Event Control Block Array

struct EvCB *evcb_0 = (struct EvCB *)((t + 4)->head);

See the Run-Time Library Reference for the definition of EvCB.

Page 27

Kernel Library 2-5

Descriptors

When you work with certain system resources such as files or threads, the kernel provides you with descriptors to refer to the resources. Descriptors are unsigned 32-bit integers, with the following bit assignments:

Table 2-3: Descriptor Bit Patterns Bit Number Contents 31-24 23-16 15-0 Descriptor classification Reserved by system System table number

The kinds of descriptors available are listed below. Each macro is defined in kernel.h.

Table 2-4: Descriptor Classification Macro Class contents DescTH DescHW DscEV DescRC DescUEV DescSW Thread Hardware Event Root counter User-defined flag System call Notes

System internal use

System internal use

The normal procedure for keying descriptors to system resources is as follows:

  • Obtaining descriptors. First call the Open() function provided for each resource. The return value of the function is the descriptor of that resource.
  • Operation of resources. Use the descriptor returned by the Open() function to specify the resource and perform the operation required.
  • Closing descriptors. After use, close the descriptor with the appropriate Close() function.

Example 1: Thread Descriptor

unsigned long th, th_new; th = OpenTh(0x1000,0x1ffff0,0x00); th_new = OpenTh(0x2000,0x18fff0,0x00); ChangeTh(th); ChangeTh(th_new); CloseTh(th);

Example 2: File Descriptor

unsigned long fd, ret; char buf[2048]; fd = open("cdrom:PSX.EXE;1",O_RDONLY); ret = read(fd, buf, 1048); close(fd);

Page 28

2-6 Kernel Library

Example 3: Event Descriptor

unsigned long ev; extern long (*handle)(); ev = OpenEvent(RCntCNT0, EvSpINT, EvMdINTR, handle); EnableEvent(ev); DisableEvent(ev); CloseEvent(ev);

Callbacks

In libraries (such as libgpu or libsnd) that handle devices using DMA, there is a function for registering callback functions in the kernel. Callback functions are executed after an event has occurred.

Callback functions are executed in the Callback Context (last out), using their callback stack. This stack is declared in libetc and is included in the application data area.

The callback function is called automatically when a DMA transfer is completed. You can execute transfer completion processing by setting a flag in an external variable and issuing an event.

Inhibition of Interrupts

Any functions modifying data within the kernel must be executed in code where interrupts are inhibited. See the Run-Time Library Reference for information about specific functions.

A section of code in which interrupts are inhibited is called a critical section. Interrupts are inhibited at the following times: • Immediately following system start. (They are enabled by calling the function ResetCallbacks()). • By calling the function EnterCriticalSection().To re-enable interrupts, call ExitCriticalSection(). • Immediately following the start of an event handler. To re-enable interrupts, the handler can call ReturnFromException() to return to the original context. It can also call ExitCriticalSection(); however, if an interrupt occurs, control won’t return to the main context but to original interrupt context.

Interrupt Context

We refer to the normal execution of a program as its Main Flow. When an interrupt or exception occurs: • The system saves the contents of the registers in the Execution TCB as the Main Flow Context (see “Thread Management”). The status after saving is called the Interrupt Context. • Processing begins at address 0x00000080, which contains the jump code to the kernel interrupt dispatcher, which in turn calls the appropriate routine to handle the interrupt. • When interrupt processing is completed, the contents of the Main Flow Context registers are restored and execution of the Main Flow resumes.

Functions such as Event Handlers and Callbacks are executed in Interrupt Context (the former uses the interrupt stack, the latter uses the callback stack). When you write code that executes in Interrupt Context, keep the following cautions and prohibitions in mind.

Cautions • Halting interrupts for a long time may adversely affect the system. You should design any routine to be executed in interrupt context so that it completes in the shortest time possible. • Functions that generate internal exceptions (e.g., ExitCriticalSection()) cause destruction of the main flow context. This destruction may be prevented by using the thread management service to change the execution TCB.

Page 29

Kernel Library 2-7

• It is possible to return to the Main Flow by executing ReturnFromException() within an Event Handler. However, since this breaks off the action of the Interrupt Dispatcher and interrupt management returns to Main Flow as incomplete, device related malfunctions may occur. Use ReturnFromException() only for error management functions.

Prohibitions Do not: • Execute functions that use internal interrupts. If interrupts are not generated, the functions cannot complete. • Execute non-re-entrant functions that may be called by the main flow. Most library functions, such as kernel services, are not re-entrant. • Execute the function ReturnFromException() from within a callback function.

Kernel Reserved Memory Areas

The kernel uses the first 64K bytes of memory. The addresses that the user may use begin from 0x00010000.

Root Counter Control

The root counter control system provides functions such as time restrictions and timing adjustments-- indispensable features in game programs.

Since the root counter is a timer that automatically generates counter timing, the following three are provided: • System clock • System clock (8 cycles) • Vertical synch.

A 16-bit target value may be set in each of these counters except vertical synch. Counters count up from zero and when they reach the target value, the following occurs:

  • An interrupt is generated (each counter can be masked).
  • The counter is cleared to zero (counter values capable of search are 0 to target value -1).
  • The counter starts counting again.

Since the target value of vertical synch is fixed at 1, an interrupt is generated at each vertical blank. Interrupts trigger counter generation and execute optional functions from the event management service (this is called an event handler). The value of each counter may be polled. Counter names are defined by macros, and the counters may be accessed using these macros.

Table 2-5: List of Root Counters Macro Root Counter Notes RCntCNT0 RCntCNT1 RCntCNT2 RCntCNT3 System clock System clock (8 cycles) Vertical synch* Target value more than 2 Same as above Target value is fixed at 1

  • halting count is invalid
Page 30

2-8 Kernel Library

Counter Timing

One tick is approximately equal to 0.03 microseconds when counting by the system clock. In the 8-cycle mode, 1 tick equals 8 times .03 microseconds (approximately .24 microseconds).

Table 2-6: Counter Timing Counter Event NTSC PAL Unit Vertical Sync Horizontal Sync Pixel Display 1/60 63.56 Nx0.0186243 1/50 64.00 Nx0.01879578 Second Microsecond Microsecond

Table 2-7: Pixel Display Timing and Display Width Display Width N 256 pixels

The root counter uses the hardware counting function. For this reason, disabled interrupts and software operations calling functions unrelated to counting, such as StopRCnt(), will continue.

The function StopRCnt() will not stop counting. This function uses the RcntMdINTR macro for halting creation of interrupts for counters allowed interrupts. In the same way, the StartRCnt() function only allows interrupts; it does not affect counting.

Mode

For each counter the following modes may be set. Modes are defined by macros. The macros in Tables 2-9, 2-10, and 2-11 below can be set by logic.

Table 2-8: Root Counter Mode (1)

Macro Contents RCntMdINTR RCntMdNOINTR Interrupt permitted Interrupt prohibited (polling only)

Table 2-9: Root Counter Mode (2)

Macro Object root counter Types of counter RCnDtMdSP (Default) RCntCNT0,1 (Use prohibited)

RCntCNT2 RCntCNT3 RCntCNT0,1 RCntCNT2,3 System clock, 8 cycles Vertical blanking System clock Not valid RCntMdSC

Page 31

Kernel Library 2-9

Table 2-10: Root Counter Mode (3) Macro Contents RCntMdFR (default) RCntMdGATE Normal count Valid gate condition

Gate

Each counter will count up only when a condition called gate occurs.

Table 2-11: Root Counter Gate Condition Root counter Gate conditions RCntCNT0 RCntCNT1 RCntCNT2,3 Not during horizontal blanking Not during vertical blanking None (usual time count)

Status Immediately After Kernel Starts

All counters are stopped immediately after activating the kernel. Immediately after the kernel starts all of the counters are stopped or free running. Thus, when they are used they must always be initialized. Also, depending on the service and the library, it may be that the user has to initialize the root counter before use.

Root Counter and Critical Section

A counter interrupt cannot occur within a critical section.

Use of the Root Counter by the Kernel

The kernel will use the root counter in the following circumstances. When using the pertinent service, reset the root counter to the state specified by the kernel.

Obtaining Controller Button Status Use root counter 3 (vertical blanking) to obtain the status of the controller button. The state of the button cannot be read when root counter 3 is stopped or has not been initialized.

Events

An event is either a CPU exception or an interrupt from an external device. Since events can occur asynchronously with the execution of the main program, there are two main methods of dealing with events: • Polling to determine whether an event has occurred and, if so, executing some code appropriately. • Installing an event handler that the system executes automatically when the event occurs.

The system maintains a 4K interrupt stack (last out) within the memory area reserved for the kernel. Handlers execute in Interrupt Context (last out), using the interrupt stack.

GetSysSp() obtains the highest address of an interrupt stack area.

Page 32

2-10 Kernel Library

Cause Descriptor and Type of Event

An event is specified by two 32-bit integers called the cause descriptor and event type.

Table 2-12: Cause Descriptor (Kernel Library Related Only) Cause descriptor Contents Event type RCntCNT0 RCntCNT1 RCntCNT2 RCntCNT3 File descriptor Same as above HwCdRom HwSPU HwGPU HWPIO HwSIO HwCPU DescUEV | m Root counter interrupt Root counter interrupt Root counter interrupt Root counter interrupt File input/output File close CD-ROM decoder interrupt SPU interrupt GPU interrupt Extension parallel port interrupt Extension serial port interrupt Exceptions User-defined event (m=0~0xffff) EvSpINT EvSpINT EvSpINT EvSpINT EvSpEIO EvSpCLOSE EvSpUNKNOWN* EvSpTRAP EvSpTRAP EvSpTRAP EvSPTRAP EvSpTRAP Optional

*Other events are described in the individual libraries.

To install an event handler, you call OpenEvent(), passing in the following parameters: • The cause descriptor ( the cause of the event). • The event type. • The event mode. • The address of the handler function.

If the call to OpenEvent() succeeds, it returns a 32-bit event descriptor that you use to identify the event to other functions such as EnableEvent(). The system keeps track of information about the event in an event control block structure:

struct EvCB { unsigned long desc; long status; long spec; long mode; (long *FHandler)(); long system [2]; }; /*event control block*/ /*cause descriptor*/ /* status*/ /*event type*/ /*mode*/ /*function format handler*/ /*system reserved*/

Event Handler

An event handler is a function that is called when an event is triggered.

When the event occurs, the registers are saved and the handler begins executing. (Event handlers execute on an interrupt stack reserved in the kernel). When the handler completes its processing, it calls ReturnFromException(), which restores the registers and returns to the previous context.

Further, it is possible to permit an interrupt with the ExitCriticalSection() function, to avoid returning to the source of the interrupt and to make that routine the main flow as is. In this case, the user must provide their own stack, allocated before the interrupt. The stack can be changed with the SetSp() function.

Page 33

Kernel Library 2-11

Event Status

An event can have one of four possible statuses. Prior to opening an event, its status is EvStUNUSED. After opening an event with OpenEvent(), its status is EvStWAIT. After calling EnableEvent(), the status becomes EvStACTIVE; that is, the even may occur.

DisableEvent() switches EvStACTIVE and EvStREADY event states to an EvStWAIT state. Once in the EvStWAIT state, the next event activated by EnableEvent() must be in the EvStACTIVE state. The previous state is not saved.

Table 2-13: Event Conditions

Macro Contents Generation EvStUNUSED EvStWAIT EvStACTIVE EvStALREADY Not opened Event generation prohibited Event not yet generated Event already generated Prohibited Prohibited Possible Prohibited

Mode

Events can have two different modes, which you specify when opening the event. With EvMdINTR, you specify a handler function to be called when the event occurs. With EvMdNOINTR, you don’t specify a handler and must test to see whether the event as occurred.

Table 2-14: Event Modes Macro Status after generation Handler function EvMdINTR EvMdNOINTR EvStACTIVE EvStALREADY Active Not active

Event Creation

All applicable enabled events are switched over to the EvStALREADY state based on the source descriptors and event type specified when the DeliverEvent() function is executed. Events in EvMdINTR mode are handled by the event handler within the DeliverEvent() function.

Clearing an Event

Clearing an event means switching its state from EvStALREADY to EvStACTIVE. This may be done by calling UnDeliverEvent() or TestEvent().

UnDeliverEvent() takes a source descriptor and an event type, and clears all applicable events.

TestEvent() takes an event descriptor; if a corresponding event is in the EvStALREADY state, it is switched to EvStACTIVE. An event must be cleared with UnDeliverEvent() before it is reissued.

Page 34

2-12 Kernel Library

User-Defined Event

A user may define events using the DescUEV macro.

DeliverEvent(DescUEV|my_event_num, my_event_spec);

A user-defined event descriptor indicated by the number my_event_num and class my_event_spec may be called with this macro.

long ev; ev = OpenEvent(DescUEV|my_event_num, my_event_spec, EvMdNOINTR, NULL);

is used by WaitEvent() and TestEvent(). The event handler is started when the third argument of OpenEvent() is EvMdINTR and the fourth argument is not NULL.

Threads

Threads allow an application to have multiple flows of control. They provide a form of multi-tasking in which contexts can be switched by calling a switching function. This feature may also be used for changing context at the time of an interrupt.

Context and TCB

The thread context consists of the complete contents of the registers. The context is stored in a data structure called a task control block (TCB). To switch threads, you store the current thread’s context in a TCB and then assign the contents of another TCB to the registers.

The context at any given time will be stored in the execute TCB if triggered by the generation of an interrupt or an explicit function call. The execute TCB is pointed to by the task status queue (TCBH).

For registers, please refer to the section on Register Specification Macros on page 2-13 or to the PlayStation™ Hardware Guide.

Status Immediately After Kernel is Started

When the kernel starts, the task control block (TCB) array is allocated and the zero element is opened with OpenTh() and linked in the task status queue as the execution TCB. The default thread’s descriptor is:

DescTH|0x0000=0xff000000

Thread Open and Switching Execution TCB

TCBs may be run using the ChangeTh() function, while allocating the second and later TCBs from the OpenTh() function.

unsigned long new_th; new_th=OpenTh(0x80020000,0x1ffff0,0x00); ChangeTh(new_th);

When the ChangeTh() function is called: • A software interrupt is issued, which causes a jump into an internal kernel interrupt dispatch routine. Other interrupts are not allowed at the same time. • Context of the ChangeTh() function being executed is shunted into the previously executed TCB. • The specified TCB is linked to the task status queue • The context read from the execution TCB is reopened when the interrupt dispatch routine finishes.

Page 35

Kernel Library 2-13

By changing the newly-executed V0 register value of the context saved in the previously executed TCB, the return value of ChangeTh() may change when execution is recommenced. From this point on, it is possible to transmit information from the thread space.

Interrupts and TCB

The context at the time of interrupt is stored in the TCB that is currently being executed by the interrupt handler. This content will be kept even during a return from the handler to the main flow and will be saved until the next interrupt.

TCB Status

The status of a TCB can be TcbStUNUSED or TcbStACTIVE. When a thread is opened with OpenTh(), its status becomes TcbStACTIVE and you may execute the TCB with ChangeTh().

Table 2-15: TCB status

Macro Status TcbStUNUSED TcbStACTIVE Not used Execution possible

Register Specification Macros

This table shows the macros used to specify the R3000 registers (defined in asm.h).

Table 2-16: Register-Specified Macro Macro (1) Macro (2) Contents R_ZERO R_AT R_V0 R_V1 R_A0 R_A1 R_A2 R_A3 R_T0 R_T1 R_T2 R_T3 R_T4 R_T5 R_T6 R_T7 R_S0 R_S1 R_S2 R_S3 R_R0 R_R1 R_R2 R_R3 R_R4 R_R5 R_R6 R_R7 R_R8 R_R9 R_R10 R_R11 R_R12 R_R13 R_R14 R_R15 R_R16 R_R17 R_R18 R_R19 0 fixed Assembler only Return value Return Value (for double type) Argument #1 Argument #2 Argument #3 Argument #4 Function-internal work Function-internal work Function-internal work Function-internal work Function-internal work Function-internal work Function-internal work Function-internal work Function-internal save Function-internal save Function-internal save Function-internal save

Page 36

2-14 Kernel Library

Macro (1) Macro (2) Contents R_S4 R_S5 R_S6 R_S7 R_T8 R_T9 R_K0 R_K1 R_GP R_SP R_FP R_RA R_EPC R_MDHI R_MDLO R_SR R_CAUSE R_R20 R_R21 R_R22 R_R23 R_R24 R_R25 R_R26 R_R27 R_R28 R_R29 R_R30 R_R31 Function-internal save Function-internal save Function-internal save Function-internal save Function-internal save Function-internal save Kernel only #0 Kernel only #1

Stack pointer Frame pointer Return previous address Interrupt return address Multiplication/division Register (high) Multiplication/division Register (low) Status register Cause register

I/O Management

The PlayStation supports low-level access to files and logical devices. Structures used by the system for input/output are defined by sys/file.h.

The following devices are supported:

Table 2-17: IO Devices Device name Contents cdrom bu CD-ROM file system Memory Card file system Example of file designation cd-rom:PSX.EXE;1 bu00:ABCD12345

Each device has a data access unit called its block size. All data access is done in multiples of the block size. If there is a fraction in the specified size, it is discarded.

Page 37

Kernel Library 2-15

CD-ROM File System

The PlayStation CD-ROM file system conforms to the level 1 format of ISO-9660. File system details are:

Table 2-18: CD-ROM File System (ISO 9660 Level 1) Device name cdrom File format <basename>.<extension name>;<version number> <base name>is 8 letters; <extension>up to 3 letters. Only English capital letters, numbers and “_” (underscore) may be used. <base name> <base name> is 8 letters. Only English capital letters, numbers and “_”(underscore) may be used. Maximum levels in the directory is 8. No root name Physically arranges all file sectors so they are contiguous. 2048 bytes Directory name format

Directory hierarchy format File arrangement Block size

The list of files and directories is only supported as far as it can be stored in one sector (2048 bytes). With standard names (8.3), this allows for up to 45 directories and 30 files per directory. When using short names, it’s possible to store more information. Note: These limitations can be worked around by having the program keep track of its own files and not using CdSearchFile().

Memory Card File System

TheMemory Card file system manages the files on the removable Memory Card used for saving game data. (Mounting and initialization is performed by libcard BIOS calls). Details of the file system are as follows:

Table 2-19: Memory Card File System Item Description Device name buXY X: port (0: A port, 1 : B Port) Y: Extension connector number (1-) or 0 <base name> <base name> ASCII character string to a maximum of 20 bytes. Extension cannot be used. None 128 bytes File format

Directory structure Block size

Standard I/O Stream

The standard I/O stream reserves File Descriptors 0 and 1.

On the game unit, the standard I/O stream is assigned to a NULL device. In the development environment, the standard input stream is assigned to a NULL device and the standard output stream is assigned to Debug Message Window #0.

Page 38

2-16 Kernel Library

Module Control

Functions are provided to allow you to load and execute application modules.

An execution file conforms to the PlayStation EXE format. It includes:

• Code and data linked to fixed addresses • A starting address • A gp register initial value • Initial value data area starting address and size

Prior to executing the module, the stack area must be explicitly defined, or the current execution context will be used as is.

The execution file is divided into the following three sections:

Figure 2-1: Execution File Memory Map

low Header (2048 bytes) starting with XF_HDR

text section

data section (initial value data) 2048 byte multiples

high

Execution File Data Structure

The execution file is structured as follows:

struct EXEC { unsigned long pc0; unsigned long gp0; unsigned long t_addr; /*execution file information*/ /*execution start address*/ /*gp register initial value*/ /*text and data section lead address with initial value*/ unsigned long t_size; /*text and data section size with initial value. */ unsigned long d_addr; /* system reserved */ unsigned long d_size; /* system reserved */ unsigned long b_addr; /*data section lead address with no initial value. Exec() clears this section; however, if b_addr is zero, the section doesn’t exist, so it doesn’t get cleared.*/ unsigned long b_size; /*data section size with no initial value*/ unsigned long s_addr; /*stack area lead address (user specified). Exec() substitutes s_addr+s_size for stack pointer, unless s_addr is zero. */ unsigned long s_size; /*stack area size (user specified) unsigned long sp, fp, gp, ret, base; /*register shunt area for executing Exec()*/ };

Page 39

Kernel Library 2-17

The execution file header is structured as follows:

struct XF_HDR { char key[8}; unsigned long text; unsigned long data; struct EXEC exec; char title[60]; }; /*execution file header */ /*key code*/ /*position of text section within file */ /*position of data section within data file */ /*execution file information*/ /*license code */

Controller Features

Libapi provides a low-level interface to regulate certain controllers on the PlayStation's main input device. Applications may directly process received data; each type of controller may be identified dynamically.

Initialization

The normal procedure for initializing the controller is shown below:

InitPAD(buf0, len0, buf1, len1); StartPAD();

InitPAD() sets up two buffers buf0 and buf1 to receive data from the controllers, and specifies their maximum input lengths, len0 and len1. StartPad() begins reading the controllers, triggered by the vertical blank interrupt.

The presence or absence of the device, as well as its state, may be determined by testing the input buffer's contents.

Buffer Data Format

Data stored in the receive buffer has the following format.

Table 2-20: Summary of Terminal Types Terminal Type Controller Name Main Controller Model Number Mouse 16-Button Analog Gun Controller 16-Button Analog Joystick Gun Controller Analog Controller Multi Tap SCPH-1030 SLPH-00001 (Namco) SLPH-00014 (Konami) SCPH-1080, 1150 SCPH-1110 SLPH-00034 (Namco) SCPH-1150 SCPH-1070

Page 40

2-18 Kernel Library

Table 2-21: Mouse

Offset Contents Received result 0x00:Success, Other: Failure Upper 4 bits: 0x1 Lower 4 bits: Number of received data bytes/2 Button Status: 1: Release, 1: Push Movement Value X Direction (-128~127) Movement Value Y Direction (-128~127) 2,3

Table 2-22: 16-Button Analog

Offset Contents Received result 0x00: Success, Other: Failure Upper 4 Bits: 0x2 Lower 4 Bits: Number of received bytes/2 Button status 1: Release, 0: Push Revolution area 2,3

0~128~255 I Button 0~255 II Button 0~255 L Button 0~255

Table 2-23: Gun Controller (Konami) Offset Contents Received result 0x00: Success, Other: Failure Upper 4 bits: 0x3 Lower 4 bits: Number of received data bytes/2 Button Status 1:Release, 0: Push 2,3

Table 2-24: 16-Button

Offset Contents Received result 0x00: Success, Other: Failure Upper 4 bits: 0x4 Lower 4 bits: Number of received data bytes/2 Button Status 1: Release, 2: Push 2.3

Page 41

Kernel Library 2-19

Table 2-25: Analog Joystick

Offset Contents Received result 0x00: Success, Other: Failure Upper 4 bits: 0x5 Lower 4 bits: Number of received data bytes/2 Button status 1: Release, 0: Push Position X Direction (Right stick) 0~128~255 Position Y Direction (Right stick) 0~128~255 Position X Direction (Left stick) 0~128~255 Position Y Direction (Left stick) 0~128~255 2,3

Table 2-26: Gun Controller (Namco) Offset Contents Received result 0x00: Success, Other: Failure Upper 4 bits: 0x6 Lower 4 bits: Number of received data bytes/2 Button status 1: Release, 0: Push Position X Direction Lower byte Position X Direction Upper byte Position Y Direction Lower byte Position Y Direction Upper byte 2,3

Table 2-27: Analog Controller Offset Contents Received result 0x00: Success, Other: Failure Upper 4 bits: 0x7 Lower 4 bits: Number of received data bytes/2 Button status 1: Release, 0: Push Position X Direction (Right stick) 0~128~255 Position Y Direction (Right stick) 0~128~255 Position X Direction (Left stick) 0~128~255 Position Y Direction (Left stick) 0~128~255 2,3

Page 42

2-20 Kernel Library

Table 2-28: Multi Tap Received Data Configuration

Offset Contents Received result 0x00: Success, Other: Failure 0x80 Received result 0x00: Success, Other: Failure Upper 4 bits: Terminal types Lower 4 bits: Number of received data bytes+2 Received data Port A 4-9 Received result 0x00: Success, Other: Failure Upper 4 bits: Terminal types Lower 4 bits: Number of received data bytes+2 Received data Port B 12-17 Received result 0x00: Success, Other: Failure Upper 4 bits: Terminal types Lower 4 bits: Number of data bytes+2 Received data Port C 20-25 Received result 0x00: Success, Other: Failure Upper 4 bits: Terminal types Lower 4 bits: Number of receive data bytes+2 Received data Port D 28-33

Table 2-29: Button status bit assignments

Bit D15 D14 D13 D12 16-button Analog Controller Analog joystick 16-button analog Mouse Gun controller (Konami) Gun controller (Namco)

Bit 16-button Analog Controller Analog joystick 16-button analog Mouse Gun controller (Konami) Gun controller (Namco) D11 D9 D8

R3 L3 SEL SEL SEL

D3 D2 D1 D0 R1 R1 R1 R Left L1 L1 L1 R2 R2 R2 L2 L2 L2 ST ST ST ST D10

ST A

D7 D6 D5 D4 X X X A

TRG X B B Right

TRG

(All bits 1: released, 0: pressed)

The upper 4 bits of the first byte in the buffer are the terminal type, the lower 4 bits are half the value of the number of bytes received from the terminal (stored in or after the 3rd byte of the buffer.) See the terminal documentation for the physical arrangement and correspondence of each button and channel.

Page 43

Kernel Library 2-21

Kanji Fonts

The PlayStation kernel ROM includes 16 dot x 16 dot 2-value bitmap kanji fonts. Font data must not be stored consecutively in memory to accommodate memory capacity. Use the service function to obtain the starting address of the data for each character.

Table 2-30: Kanji Fonts Item Description Data Format 16 dot x 16 dot 2 value bitmap Character size is 15 dot x 15 dot JIS 1st standard kanji and non-kanji; gothic type non-kanji have a top space (0x2121) Refer to the codeview samples in \psx\kanji\sjiscode for a list of usable fonts and the fonts themselves. Shift-JIS The starting address in ROM of the applicable font pattern may be obtained from the shift-JIS code given to the service function. With that information, the font pattern may be accessed directly. Contents

Code System Access Method

Data Format

In the figure below, the byte of the upper left of the pattern is first, followed by the byte on the upper right. The most significant bit (MSB) faces left.

Table 2-31: Font Data Format #0 #2 : : : #30 #1 #3 : : : #31

Page 44

2-22 Kernel Library

Usage Example

In the following sample program, the function _get_font() returns a font pattern corresponding to the specified shift-JIS code. This pattern is in a format that can be transferred to VRAM as a 16-bit texture.

Example: Getting a Kanji Font

unsigned long _get (char *sjis) { unsigned short sjiscode; sjiscode = *sjis << 8 | *(sjis+1); return Krom2RawAdd(sjiscode); /* get kanji font pattern address */ }

#define COLOR 0x4210 #define BLACK 0x3000

void _get_font (char *s, unsigned short *data ) { unsigned short *p, *d, w; long i,j; if ((p=(unsigned short *)_get(s))!=-1) { d = data; for (i=0; i<15; i++) { for(j=7; j>=0; j--) *d++ = (((*p>>j)&0x01)==0x01)?COLOR:BLACK; for(j=15; j>=8; j--) *d++ = (((*p>>j)&0x01)==0x01)?COLOR:BLACK; p++; } } else { for (d=data, i=0; i<2*16*16; i++) *d++ = BLACK; } }

Page 45

Kernel Library 2-23

Memory Allocation

There are three systems of memory allocation: a ROM-based version (malloc), a RAM-based version (malloc2), and a high-speed RAM-based version (malloc3).

There is a bug in the malloc system in which the area allocated cannot be completely released in free().This bug was fixed in malloc2. (Since malloc is part of the ROM, it cannot be corrected and is left in order to maintain compatibility.) malloc3, which improved upon the speed of malloc2, was added in Library 4.0.

Note: all of these functions allocate memory blocks based on first fit rather than best fit. In some cases, developers may wish to write their own memory allocation routines.

Table 2-32: Memory Card allocation functions Name LIBAPI function LIBC/C2 function Version which calls ROM routine (malloc system) InitHeap() malloc() calloc() realloc() free() RAM-based version (malloc2 system) InitHeap2() malloc2() realloc2() calloc2() free2() InitHeap3() malloc3() realloc3() calloc3() free3() High-speed RAM-based version (malloc3 system)

The table below shows a performance comparison between the three memory allocation systems, in terms of speed of operation and size of code.

Table 2-33: Performance comparison between memory allocation functions Speed Code size Slow Fast

Large malloc2 system malloc3 system Small malloc system

Page 46
Scan of page 46

This page is a drawing, shown as the original scan.

Page 47

Chapter 3: Standard C Library

Table of Contents

Overview Library and Header Files 3-3 3-3

Page 48
Scan of page 48

This page is a drawing, shown as the original scan.

Page 49

Standard C Library 3-3

Overview

The C standard libraries are a subset of the K & R-based C standard libraries, including functions such as character functions and memory operations .

There are two versions of the standard C libraries: • libc accesses library routines in the kernel ROM. This provides a small size advantage, since no additional code needs to be linked with your application. However, libc routines are slower than libc2 routines, because ROM code is not cacheable. • libc2 links with your application. It provides a speed advantage, because the code is cacheable.

Library and Header Files

The standard C library files are libc.lib and libc2.lib. To use standard C routines, you must link with one of these files.

The following header files declare the routines in the C standard library. The Run-Time Library Reference describes the functions in the standard C library and which header file must be included for each one.

Table 3–1: Header Files abs.h assert.h convert.h ctype.h malloc.h memory.h rand.h setjmp.h stdarg.h stddef.h stdlib.h strings.h qsort.h sys/types.h

Page 50
Scan of page 50

This page is a drawing, shown as the original scan.

Page 51

Chapter 4: Math Library

Table of Contents

Overview Library and Header Files 4-3 4-3

Floating-Point Numbers 4-3

Error Processing Error Types Internal Processing at the Time of an Error Error Event Error Variable 4-3 4-3 4-4 4-4 4-4

Page 52
Scan of page 52

This page is a drawing, shown as the original scan.

Page 53

Math Library

Overview

The Math library provides a floating point operation package and K & R-based standard C library math functions.

Library and Header Files

To use the Math library file, your application must link with the file libmath.lib.

Your source code should include the header files libmath.h and limits.h.

Floating-Point Numbers

The math library supports IEEE754 standard single-precision floating-point numbers (float) and doubleprecision floating-point numbers (double). It also has an internal floating-point arithmetic operation package.

The PlayStation hardware doesn’t support float and double operations directly, because the CPU has no floating-point coprocessor. By linking mathlib with your application, it is possible to use the float and double types.

Table 4–1: Float Format Item Specification Size Significant digit count Overflow limit value Underflow limit value 4 bytes 6 decimal digits 2.0**128 = 3.4e38 0.5**126 = 2.2e-38

Table 4–2: Double Format

Item Specification Size Significant digit count Overflow limit value Underflow limit value 8 bytes 15 decimal digits 20**1024 = 1.8e308 0.5**1022 = 2.2e-308

Error Processing

Events are used to report errors in floating-point operations. Error status recording by C standard style external variables is also supported.

Error Types

Math library functions are used to test the range of arguments. These tests are performed on the functions whose specifications cover the range of argument values. If an inappropriate value is detected, the response “area error” (EDOM) is generated.

If the results exceed the area of expression in an application which uses internal functions and arithmetic operators, the response “range error” (ERANGE) is generated. 4-3

Page 54

4-4 Math Library

Internal Processing at the Time of an Error

For any area and range errors, notice is given by the assignment of an error code to an event and external variables.

The result of an operation is an unsigned infinite value, so that operation can be carried on wherever possible. The following are positive infinite bit patterns: • Floating-point value: 0x7F800000 • Double-precision value: 0x7FF0000000000000

The following are negative infinite bit patterns: • Floating-point value: 0xFF800000 • Double-precision value: 0xFFF0000000000000

The following are return values for division by zero: • NaN • Floating-point value: 0x7FFFFFFF • Double-precision value: 0x7FFFFFFFFFFFFFFF

or • -NaN • Floating-point value: 0xFFFFFFFF • Double-precision value: 0xFFFFFFFFFFFFFFFF

(NaN is not a numerical value, but a bit pattern reserved by the operation subroutine to report an error. A normal double-precision variable does not store the same bit pattern as NaN. Thus, subjecting NaN to floating-point operation cannot provide correct results.)

Error Event

An error in a math library function causes an event with cause descriptor SwMATH. Thus, an overflow and division by zero can be detected and a corresponding error generated.

Error Variable

The variable math_errno for storing error codes is defined in libmath.lib and declared as extern in the header file libmath.h; it is initialized to zero. When an error arises in the library, however, one of the constants EDOM or ERANGE (defined in sys/errno.h) is stored in math_errno. This variable is not automatically reset to zero; you must explicitly reset it after error processing.

Table 4–3: Error Notificaton Error math_errno Event value Cause descriptor Type Area error Range error EDOM ERANGE SwMATH SwMATH EvSpEDOM EvSpERANGE

Page 55

Chapter 5: Memory Card Library

Table of Contents

Overview Library and Header Files 5-3 5-3

Memory Card Hardware Events 5-3 5-3 5-3

BIOS 5-4 5-4 5-5 5-5 5-7 Testing for Card Presence and Testing Logical Formats Unconfirm Flags Card Test Use with the Multi Tap

File System 5-7

Realtime Access 5-8

Rules for Use of Memory Card Abnormal Processing Terminology File Names File Headers Written Data Contents Protection Handling Communications Errors 5-8 5-8 5-9 5-9 5-9 5-10 5-11

Other 5-11 5-11 5-11 Coding Notes Known Bugs

Page 56
Scan of page 56

This page is a drawing, shown as the original scan.

Page 57

Memory Card Library 5-3

Overview

The Memory Card library provides functions which make smooth access to the Memory Card in a realtime environment possible. It also performs data reading and writing and calls the Memory Card BIOS service.

Library and Header Files

Programs that use the Memory Card library must link with the file libcard.lib.

The Memory Card library has no unique header file. The header files libapi.h and sys/file.h must be included.

Memory Card

The Memory Card is a memory device that saves data after a reset or power-off. The Memory Card may be inserted or removed while the power is on.

Hardware

The basics of Memory Card hardware are as follows:

Table 5-1: Memory Card Specifications Feature Specification(s) Capacity 120 Kbytes at format (accessed in 128-byte sectors) Synchronous serial communication sharing controller port

  • Cannot access for 20 ms after reading 1 sector
  • Maximum continuous reading speed is about 10 Kbyte/sec. May insert/remove without turning power off 100,000 reads guaranteed Communication Configuration

Access Speed

Other

Events

The Memory Card library uses the following two source descriptors. Also, the Memory Card library does not use internal event descriptors.

Table 5-2: Events Associated with the Memory Card Source descriptor Event class Meaning HwCARD EvSpIOE EvSpERROR EvSpTIMOUT Processing complete Card no good No card

Page 58

5-4 Memory Card Library

Source descriptor Event class Meaning SwCARD EvSpIOE EvSpERROR EvSpTIMOUT EvSpNEW Processing complete Card no good No card New card or uninitialized card

Note: SwCARD/EvSpNEW has one of two meanings, depending on the function that issued the input/output request.

Automatic clearing of events relating to HwCARD Events related to the descriptor HwCARD are automatically cleared by every vertical sync interrupt.

Functions which wait for a vertical interrupt, such as libgpu VSync(), etc., interpose themselves to perform event generation tests, and so run the danger of not being able to detect event generation.

BIOS

Services such as checking the Memory Card connection, logical format testing, accessing in sector units (128 bytes), etc., are provided by the BIOS.

In order to support concurrent controller reading and the accessing of two AB connectors, the BIOS accesses the card at each of two vertical blanks. One sector, 128 bytes of data, may be read in 1 access. Access using BIOS is as follows:

Table 5-3: Memory Card BIOS

Feature Description Start Timing After a vertical blanking interrupt, controller reading occurs, the card connection is checked and then the hardware is checked. Sending and receiving of data is driven by receiving interrupts in units of bytes. Effective speed 30 sectors/sec = 3.75 Kbyte/sec 2.5% when reading continuously from 2 cards 3.2% when writing continuously to 2 cards Effective Speed CPU Load

Testing for Card Presence and Testing Logical Formats

The procedure for testing in the BIOS for the presence of a Memory Card and for logical format is as follows:

  • Test for card presence using _card_info(). If an IOE event has occurred, a card whose connection has already been confirmed remains connected. Go to (5). If a NEWCARD event has occurred, a card which was not confirmed by _card_clear() after connection is connected. Go to (2). If a TIMOUT event has occurred, no card is connected. No more operations are necessary. A communication error is possible, so perform a retry.
  • Perform a confirmation operation using _card_clear(). Usually there is no failure. If a failure occurs, either the card was removed or a communication error occurred. In the case of failure, return to (1) and perform a retry.
Page 59

Memory Card Library 5-5

  • Test logical format using _card_load().

If an IOE event has occurred, formatting is completed. Go to (5).

If a NEWCARD event has occurred, formatting has not been performed. Go to (4).

In other cases, either the card was removed or a communication error occurred. In these cases, return to (1) and perform a retry.

  • Perform logical format using format().

If formatting ends normally, go to (5). In other cases, either the card was removed or a communication error occurred. In such cases, return to (1) and perform a retry.

  • Perform input/output using the file system.

Unconfirm Flags

Inside the card there is a bit switch called the unconfirm flag. This bit is set if the card is inserted in its slot, and is cleared by _card_clear(). This flag provides a means for detecting card replacement. In order to prevent erroneous access, the default is that data cannot be read from or written to a card with this flag set. Any attempt to read or write causes an error. The flag may be accessed after explicitly clearing it with _card_clear().

If you want to create an error for testing, etc., the _new_card() function masks the default test parameters in order to ignore the unconfirmed flag and allow access. This is a function which does not require normal access through the filesystem, so it is different from other libcard functions.

Card Test

Here is a list of sample code for testing cards. See the following section “File System” for the events used.

unsigned long ev0,ev1,ev2,ev3; unsigned long ev10,ev11,ev12,ev13;

main() { ev0 = OpenEvent(SwCARD, EvSpIOE, EvMdNOINTR, NULL); ev1 = OpenEvent(SwCARD, EvSpERROR, EvMdNOINTR, NULL); ev2 = OpenEvent(SwCARD, EvSpTIMOUT, EvMdNOINTR, NULL); ev3 = OpenEvent(SwCARD, EvSpNEW, EvMdNOINTR, NULL); ev10 = OpenEvent(HwCARD, EvSpIOE, EvMdNOINTR, NULL); ev11 = OpenEvent(HwCARD, EvSpERROR, EvMdNOINTR, NULL); ev12 = OpenEvent(HwCARD, EvSpTIMOUT, EvMdNOINTR, NULL); ev13 = OpenEvent(HwCARD, EvSpNEW, EvMdNOINTR, NULL);

PadInit(0); InitCARD(1); StartCARD(); _bu_init(); test_card(); }

test_card() { long ret;

_card_info(0x00); /* deliver a TEST CARD request */ ret = _card_event(); /* get the result */ if(ret==1 || ret==2)) /* NO CARD or Communication error */ goto skip; if(ret==3) { /* if NEWCARD, call _card_clear() */ _clear_event();

Page 60

5-6 Memory Card Library

_card_clear(0x00); ret = _card_event(); /* clear NEW CARD FLAG */ /* wait events */ } _clear_event(); _card_load(0x00); /* deliver a TEST FORMAT request */ if(ret==3) { /* if NEWCARD, call format() */ /* put a message to the operator */ ret = format("bu00:"); /* synchronous function */ if(ret==1) FntPrint("\nDONE\n"); else { /* error happened in format() */ FntPrint("\nERROR IN FORMATTING\n"); goto skip; } } /* put i/o requests */ return 1; skip: return 0; } _card_event() { while(1) { if(TestEvent(ev0)==1) { /* IOE */ return 0; } if(TestEvent(ev1)==1) { /* ERROR */ return 1; } if(TestEvent(ev2)==1) { /* TIMEOUT */ return 2; } if(TestEvent(ev3)==1) { /* NEW CARD */ return 3; } } } _clear_event() { TestEvent(ev0); TestEvent(ev1); TestEvent(ev2); TestEvent(ev3); } _card_event_x() { while(1) { if(TestEvent(ev10)==1) { /* IOE */ return 0; } if(TestEvent(ev11)==1) { /* ERROR */ return 1; } if(TestEvent(ev12)==1) { /* TIMEOUT */ return 2;

Page 61

Memory Card Library 5-7

if(TestEvent(ev13)==1) { return 3; } /* NEW CARD */

} }

_clear_event_x() { TestEvent(ev10); TestEvent(ev11); TestEvent(ev12); TestEvent(ev13); }

Use with the Multi Tap

When switching between multiple Memory Cards connected to one Multi Tap, _card_load() must be executed each time a different Memory Card is accessed.

This is because each port of the PlayStation console has only one directory information buffer and libcard can only control one directory information for multiple Memory Cards connected to one Multi Tap.

File System

The file system as it relates to the Memory Card is as follows:

Table 5-4: Memory Card File System Feature Description Device Name File Name Directory Structure Control Unit: Slot Number of Slots Automatic Replacement Sector Function buX0X: Connector number (0 or 1) ASCII characters, up to 21 characters None 8 Kbyte (64 sectors) --> file size unit 15/card (max. no. of files = 15) 20 replacement sectors/card

Kernel library services which request a file name as an argument may be applied to all bu devices.

File size is given as a parameter during file creation. Afterwards the file size cannot be changed. Size is in units of slots. During file creation, the file system must combine any fragmented memory regions left after deleting files and guarantee the needed capacity.

Example: File Deletion and Creation:

/* Driver initialization */ InitCARD(0); /* Does not coexist with controller */ StartCARD(); _bu_init();

/* Delete file L01 on the card in Port A */ printf("delete\n"); delete("bu00:L01");

Page 62

5-8 Memory Card Library

/* Create new file L01, 2 slots long, on card in Port A */ printf("create\n"); if((fd=open("bu00:L01",O_CREAT|(2<<16)))==-1) printf("error\n"); close(fd); /* Always close once after creating */

Realtime Access

Device bu assumes operation under a realtime environment and supports non-blocking mode. If the macro 0_NOWAITin sys\file.h is used when open, read() and write() end as soon as an input/output request is registered in the driver. Completion of input/output is reported by posting an event.

A slot accepts only one input/output request for checking access speed.

Example: Asynchronous Access

_clear_event() and _card_event() have the same contents as the previous example

sample() { long fd,i,ret; fd = open("bu00:L01",O_WRONLY|O_NOWAIT); printf("open=%d\n",fd); for(i=0;i<50;i++) { clear_event(); while((ret = write(fd,data,384))!=0) ; printf("write=%d\n",ret); ret = _card_event(); printf("event=%d\n",ret); if(ret==1) break; } close(fd); }

Rules for Use of Memory Card

The Memory Card is a resource shared by many applications, so use it according to the rules for sharing.

Abnormal Processing

No standard screen or message is set up to deal with cases of insufficient capacity or detection of an unformatted card while executing an application. Each application should have an abnormal processing screen or message designed for it.

Keep the following points in mind during this design process.

  • Always query the user (game-player) when performing logical initialization. Do not use the automatic initialization function.
  • When a card is not detected, and it is determined that this may limit future operation, always notify the user (game-player). If possible, ask the user whether it is okay to continue processing.
Page 63

Memory Card Library 5-9

Terminology

The unit for required memory capacity in the product catalog is block. This is equivalent to the previouslynoted slot (8 Kbytes).

File Names

Use the following structure for file names:

Table 5-5: Memory Card File Names

Bytes Contents Notes Magic Number Region

2-11 12-20 Title User/Public Always 'B' Japan: 'I' North America: 'A' Europe: 'E' (*1) SCE product number (*2) Use only non-0x00, 0x2a(“*”), 0x3f(“?”) ASCII End with 0x00

*1: None are checked by the system *2: The first disk for multi-disk titles

The SCE product number is decided by our Release Planning Committee (about three weeks before the master is released), and reported to the responsible parties in each company's sales department. Based on this, please decide the following.

Example: If the product code is SLPS-00001, the file name's first 12 characters are BISLPS-00001. Always add zeros to make the numerical portion 5 digits.

File Headers

Put the following headers at the start of each file.

Table 5-6: Memory Card File Header

Item Size (bytes) Header Magic number Type (see table below) No. of slots Text name Pad CLUT Icon image (1) Icon image (2) Icon image (3) Data 2 (always “SC”)

64 (Shift JIS, *1) 28 (All packed in 0x00)

128 (16 x 16 x 4 bits) 128 (Type:0x12, 0x13 only) 128 (Type:0x13 only) Varies (128Byte x N)

*1: Non-kanji and primary standard kanji only, full-size 32 characters. The end of the character string terminates at 0x00.

Page 64

5-10 Memory Card Library

Table 5-7: Type Field

Type Number of icon images (automatically replaced animation)

0x11 0x12

0x13

Written Data Contents Protection

Applications should take precautions to prevent damage to data in the event of a reset or card removal or power off during data writing.

For example, you can set things up so that data is written in duplicate. Writing is performed reciprocally and an individual checksum is added for the final byte of each sector. Test checksum when reading, and use the other data set if an error is detected.

Warning: the file system replacement sector function is only effective on card memory writing errors. The writing contents guarantee function is not supported by hardware or library.

Example: Sector Checksum

/*

  • test check sum for 128byte block
  • return 1:OK * 0:NG */ _test_csum(buf) unsigned char *buf; { long i; unsigned char c; c = 0x00; for(i=0;i<127;i++) c ^= *buf++; if(*buf==c) return 1; return 0; }

/* set check sum to the last byte of 128byte block */ void _set_csum(unsigned char *buf)

{ long i; unsigned char c; c = 0x00; for(i=0;i<127;i++) c ^= *buf++; *buf = c; }

/* sample data strucure */ struct SDB { char name[8]; long size, attr, sector, mode; }

/* common load buffer */ unsigned char load_buf[1024];

Page 65

Memory Card Library 5-11

/* get data from Memory Card with checksum test */ int get(long num, struct SDB *data) { long i,fd;

if((fd=open("bu00:L01",O_WRONLY))<0) return 0; memcpy(&load_buf[0],data,sizeof(struct SDB)); set_csum(&load_buf[0]); i = write(fd,&load_buf[0],128); close(fd);

return (i==128)?1:0; }

/* get data from Memory Card with checksum test */ int get() { long i,fd;

if((fd=open("bu00:L01",O_RDONLY))<0) return 0; if(read(fd,&load_buf[0],1024)!=1024) { close(fd); return 0; }

for(i=0;i<8;i++) if(_test_csum(&load_buf[128*i])==1) memcpy(&data[i],&load_buf[128*i],sizeof(struct SDB)); else memset(&data[i],0xff,sizeof(struct SDB)); close(fd); return 1; }

Handling Communications Errors

There are cases in which access fails due to static discharge or power source noise even though the card connection and access program are normal. Test for the presence or absence of a card, writing and reading with retry (at 1-2 second intervals).

Other

Coding Notes

Consider the following point when coding: Call _new_card() before _card_info() and suppress EvSpNEW events.

Known Bugs

• If read() or write() is issued immediately after open(), an error occurs. When creating a file using open(), make sure you call close() to close the file. • In asynchronous access using read(), the file pointer is updated by 128 bytes too few. It must be corrected using lseek().

Page 66
Scan of page 66

This page is a drawing, shown as the original scan.

Page 67

Chapter 6: Extended Memory Card Library

Table of Contents

Overview Library and Header Files Features of the Library Checking Memory Card Status Reading/Writing Data Detecting a New Card 6-3 6-3 6-3 6-3 6-3 6-3

Libcard and the Card BIOS 6-4

Use with Multi Tap 6-4

The Memory Card Hardware 6-4 6-4

Rules for Using the Memory Card Handling Irregularities Terminology File Names File Header Saving Write Data 6-4 6-4 6-5 6-5 6-5 6-6

Page 68
Scan of page 68

This page is a drawing, shown as the original scan.

Page 69

Extended Memory Card Library 6-3

Overview

The high-level Memory Card library (libmcrd) provides a convenient interface for using Memory Cards installed in the PlayStation.

Library and Header Files

Programs that use extended Memory Card library services must link with the file libmcrd.lib. Internally, libmcrd uses libcard.lib and libapi.lib, so these libraries must also be linked.

Source files must include the header file libmcrd.h.

Features of the Library • Check for presence of Memory Card, check to see if Memory Card is uninitialized, and check for Memory Card invalid state • Write data to Memory Card • Read data from Memory Card • Logical initialization (formatting) of Memory Card • File deletion • File creation • Get directory information

Checking Memory Card Status

The Memory Card can be inserted or removed when the PlayStation is on. Thus, the user application must be designed to take into account the fact that the Memory Card may be inserted or removed at any time.

Libmcrd provides the MemCardAccept() function to determine if a card has been inserted or removed. The status of the card can be obtained by this function when the card is installed.

Reading/Writing Data

When data is being written to or read from the Memory Card, communication errors may occur. Libmcrd internally performs retries when communication errors occur during data reads or writes. However, the written or read data must be checked by the user application using a verification process, checksum, or other method to verify that it is correct.

Detecting a New Card

A Memory Card that has just been inserted is treated as a new card. Because the new card may be unformatted or invalid, the library is designed so the card cannot be accessed until MemCardAccept() is executed.

If the new card was detected with MemCardAccept(), however, it is not necessary to execute MemCardAccept() again, as the various processes such as format checking were already performed.

If a new card is inserted, any function other than MemCardAccept() (such as MemCardExit() or MemCardReadFile()) will return "New card detected" as its result no matter how many times it is called.

Page 70

6-4 Extended Memory Card Library

Libcard and the Card BIOS

Libmcrd uses libcard and card BIOS functions and resources such as the HwCARD and SwCARD events. Consequently, user applications cannot directly use libcard or the card BIOS.

If a user application needs to perform an operation that cannot be implemented using libmcrd, the application must implement all Memory Card operations which use libcard and the card BIOS.

Use with Multi Tap

When switching access between multiple Memory Cards connected to one Multi Tap, call MemCardAccept() every time you access a different Memory Card. The reason for this is that in libmcrd, each port on the PlayStation unit has only one directory information buffer. When multiple Memory Cards are connected to one Multi Tap, only one directory information can be controlled

The Memory Card

The Memory Card is a storage device that retains data even after the PlayStation has been powered off or reset.

Memory Cards can be inserted or removed while the PlayStation is turned on.

Hardware

The specifications for the Memory Card hardware are shown below.

Table 6-1: Memory Card Specifications Capacity

Communication Access speed

Other 120 KBytes (formatted) (Accessed in 128 byte sectors) Synchronous serial port also serving as a controller port

  • No access for 20 msec after writing one sector
  • Approximately 10 KBytes/sec maximum continuous read Can be inserted or removed without turning power off. Guaranteed for 100,000 writes

Rules for Using the Memory Card

The Memory Card is a resource that is shared by multiple applications. Therefore the Memory Card should be used according to a common set of rules.

Handling Irregularities

There is no required screen or message to be output when a card runs out of memory during application execution or when an unformatted card is detected (i.e., there is no requirement that the display be the same as OSD). Rather, these situations can be customized according to the application. Nevertheless, the following points should be taken into consideration. • The user should be notified before formatting occurs. Formatting should not be performed automatically. • The user should be notified when no card is detected but one is expected. If possible, the user should be prompted to insert a card.

Page 71

Extended Memory Card Library 6-5

Terminology

In the product catalogs, the required memory capacity is expressed in terms of "blocks", where one block is 8192 bytes.

File Names

File names should be assigned as follows:

Table 6-2: Memory Card Filenames Byte Description Notes

2-11 12-20 Magic number Location Title User defined Always 'B' 'I' for Japan, 'A' for North America, 'E' for Europe (*1) SCE product number (*2) Use ASCII characters excluding 0x00, 0x2a (“*”), 0x3f (“?”). End with 0x00

*1: Not checked by the system *2: If multi-disc title, use the product number from the first disc.

The SCE product number will be determined at a preliminary sales meeting held by us (approximately three weeks before submission of master) and we will notify the business contact of the subject company. Please use the product number in the following manner.

For example, if the product code is “SLPS-00001”,

The first 12 characters of the filename would be BASLPS-00001".

The numerical portion must be five digits padded with zeros.

File Header

Please use the following header at the beginning of each file:

Table 6-3: Memory Card File Header

Item Size (bytes) Magic number Type (see table 6-4) Number of blocks Name pad Clut Icon image (1) Icon image (2) Icon image (3) Data 2 (always 'SC')

64 (Shift-JIS *1) 28 (All packed at 0x00)

128 (16x16x4 bits) 128 (Type==0x12,0x13 only) 128 (Type==0x13 only) Variable (128 bytes x n)

*1: Non-kanji and Level 1 kanji only. Full-width, 32 characters. However, 0x84bf to 0x889e cannot be used. The end of the character string terminates at 0x00.

Page 72

6-6 Extended Memory Card Library

Table 6-4: Type Field Type Number of icon images (Animation through automatic replacement) 0x11 0x12 0x13

Saving Write Data

The application must handle cases where data is destroyed because the unit was reset, the card was removed, or the power was turned off during a data write operation.

To save data: Write data twice, writing to one data set and then to the other. At the end of each sector add a checksum for the sector. Do a checksum test when reading the sectors. If an error is detected, use the other data set.

Caution: The replacement sector feature of the file system is valid only for memory write errors in the Memory Card. There is no hardware or library support for saving write data contents.
Page 73

Chapter 7: Data Compression Library

Table of Contents

Overview Library and Header Files 7-3 7-3

Compressor and Decompressor Functions 7-3

MDEC 7-3

Compression of Image Data DCT (Discrete Cosine Transform) BVQ (Block Vector Quantization) Huffman Encoding 7-4 7-4 7-5 7-6

DCT (Discrete Cosine Transform) Basic Principles Methods Supported Asynchronous Decoding Callback Playing Movies with the CD-ROM Direct Transmission and Texture Transmission Encoding by Means of the Local Environment 7-6 7-6 7-7 7-8 7-9 7-9 7-10 7-10

BVQ (Block Vector Quantization) CLUT Vector Quantization 7-10 7-11

Huffman Encoding 7-11

Compression of Sound Data 7-11

Page 74
Scan of page 74

This page is a drawing, shown as the original scan.

Page 75

Data Compression Library 7-3

Overview

The data compression library (libpress) is a low-level function library for compressing (encoding) and decompressing (decoding) image and sound data.

Image data that can be compressed and decompressed includes: • Single images. • Frames from a video sequence that have been compressed into the PlayStation MDEC format.

The MDEC is a customized portion of the PlayStation hardware specializing in image decompression.

Three methods of compressing images are available: • DCT (Discrete Cosine Transform) can be used to compress direct color images • BVQ (Block Vector Quantization) likewise combines the number of colors in the direct color image together to create 256/16 colors • Huffman Encoding (fixed codebook) reversibly compresses 4 bit index colors.

For compressing sound data, the library uses ADPCM to compress 16-bit straight PCM to about 1/4. The compressed sound data can be used as SPU sound source data.

Library and Header Files

The filename of the data compression library is libpress.lib; to use library services, you must link with this file. The library header is libpress.h; programs that call library routines must include this file.

Compressor and Decompressor Functions

Compressor functions compress image and sound data in main memory, and return the results to main memory. Compressor functions are used when data needs to be compressed dynamically inside an application, and when data is generated off-line by remote activation from the authoring environment. In fact, the local environment has a built-in DCT circuit which can be used to carry out high-speed compression of images by means of DCT.

Decompressor functions expand compressed data in real time. Note that in some cases, compressor functions produce data formats that are processed without conversion but rather via local environment hardware, like BVQ. Data in these formats cannot be handled by decompressor functions.

MDEC

The PlayStation provides a specialized data display engine, the MDEC (Motion DECoder), for high-speed image data expansion. MDEC expands compressed data in main memory and returns the result back to main memory. This result is transferred to the frame buffer display area, and displayed as an image.

Page 76

7-4 Data Compression Library

Figure 7-1: Data Expansion and Display by MDEC

FrameBuffer

CPU MDEC GPU

CDROM BS RunLevel MacroBlock

BitStream Main Memory

The main bus access which was saved to the main memory is carried out by time sharing with the CPU and other peripheral equipment and can perform expansion processing in parallel with the program and frame buffer transfer, etc.

Compression of Image Data

Algorithms used to compress image data vary according to the type and intended use of the data.

DCT (Discrete Cosine Transform)

DCT is the compression method used in JPEG/MPEG. It compresses direct-color (24-bit/16-bit) images with a high efficiency ratio. The compression is lossy, but the compression ratio can be controlled at will. The compression ratio specified is usually between 5% and 10%.

In DCT, the basic processing unit is a 16x16 24-bit direct-color image called a macroblock. All the images are broken down into macroblocks before being compressed into bitstream format. The output of decompression is also in macroblock units.

For example, when 320x240 image data is broken down into a large number of 16x16 macroblocks, as shown below, they are each compressed into bitstreams.

Page 77

Data Compression Library 7-5

Figure 7-2: 320x240 Image Breakdown

Macroblock Generated image

R

G

B

Figure 7-3: DCT Processing

Macroblock (16x16 RGB rectangular area)

compression Bitstream

decompression Macroblock (16x16 RGB rectangular area)

BVQ (Block Vector Quantization)

BVQ carries out vector quantization on direct-color images, combining colors to give a total of 256 or 16 colors, and generating 8-bit or 4-bit index-color images.

Index-color images are expressed as a two-dimensional array consisting of the CLUT (Color Look Up Table) which gives the actual brightness values, and the index to the CLUT.

Index-color images allow a slightly greater total reduction in data volume than the equivalent direct-color images. For example, if the brightness value of the individual pixels in a picture is 16 or below, the index only takes 4 bits. The volume of an index-color image can therefore be compressed to 25% of the volume of a 16-bit direct-color image.

4-bit/8-bit index-colors can be used as 4-bit/8-bit texture-patterns, doing away with the need for a special decompression filter.

In BVQ, the image is split up into several small areas when compression is carried out, and vector quantization is carried out on each small area, allowing the number of colors to be reduced by combination. At this stage, vector quantization is carried out again on the CLUT generated for each small area, so the number of CLUTs can also be reduced by combination. In this case, each pixel of the image data is indexed doubly: once by the CLUT number held by the small area to which the pixel belongs, and by the index value for that CLUT.

Vector quantization in which the index reference is carried out in stages in this way is called Block Vector Quantization.

Page 78

7-6 Data Compression Library

Huffman Encoding

DCT and BVQ compression and decompression are lossy. Therefore, a Huffman encoding function is provided for reversible compression of 4-bit index colors. The Huffman encoding is the classical type in which the codebook is generated once at the beginning.

Huffman encoding compresses data by assigning codes with a short code length (Huffman codes) in order, starting with the pixel values (index values) which appear most frequently. The table showing the actual pixel values and their corresponding Huffman codes is called the codebook.

The compression ratio for Huffman code varies according to the nature of the source image. Generally, the greater the polarization of the pixel values appearing, the higher the compression ratio will be.

The following table summarizes the compression and decompression methods:

Table 7-1: Compression and Decompression Algorithms

Type Input format Output format Compression ratio DCT BVQ Huffman Lossy 24-bit/16-bit BitStream From 10% to 5% Lossy 24-bit/16-bit 4-bit/8-bit From 50% to 25% Loss-less 4-bit BitStream

DCT (Discrete Cosine Transform)

Basic Principles

Compression DCT belongs to the category of linear transforms generally termed direct transforms, and can be thought of as a kind of frequency transform.

When DCT conversion is carried out on an NxN rectangular image, the low-frequency constituents of that image are concentrated in one place. Compression of the data is achieved by Huffman-encoding the results. In short, DCT is a method for making data compression easier, and does not, in itself, reduce the data size. The actual data compression is done by the Huffman encoding.

When DCT conversion is carried out on an ordinary image, the frequency constituents are concentrated in the low region, so after conversion, most of the constituents are at 0. This means that a much higher compression ratio can be achieved than if the image had been Huffman-encoded directly. This type of Huffman-encoding is called VLC (Variable Length Coding).

The byte/word boundary of VLC-processed data is logically meaningless, and the data is expressed simply as a stream of bits. This is known as a bitstream.

The basic unit for all the processes in this sequence is a 16x16 rectangular area. This unit is known as a macroblock. Accordingly, in DCT compression, macroblocks can be input, compressed, and converted to bitstream format.

After the image has been subjected to DCT conversion, quantization is carried out all at once in given units. The compression ratio can be controlled by controlling the quantization step. Generally speaking, broadening the quantization step improves the compression ratio.

Decompression DCT decompression is carried out in the reverse order to that of compression. That is to say, once VLC decoding has been carried out on the captured bitstream, the result is subjected to IDCT (Inverse Discrete Cosine Transform) to restore the original image.

Page 79

Data Compression Library 7-7

The decompression of the bitstream therefore consists of two passes:

  • VLC decoding
  • IDCT

Methods Supported

Compression In the case of 24-bit color data, intermediate data is output in a format (run level) where the run-length is compressed once DCT conversion has been carried out. This data is subjected to VLC, and a bitstream is output. The compression ratio is controlled by specifying the quantization step in the process generating the run level.

When the actual compression is carried out, the run level (the intermediate data) is not output.

Figure 7-4: DCT Compression

24bit 16x16 macroblock compression ratio setting: Lossy conversion

run-level (intermediate result: not output)

bitstream Huffman encoding: Lossy conversion

Macroblock encoding is performed in the following fashion: • Performs CSC (Color Space Conversion) on the RGB macroblock to convert the Y, Cb and Cr elements. Y is the brightness element and Cb, Cr are color difference elements. • Within the YCbCr macroblock, divides Y into four 8x8 blocks. Thins out Cb, Cr and arranges them as 8x8 macroblocks. As a result, the YCbCr macroblock is divided into six blocks (Y0, Y1, Y2, Y3, Cb, Cr). • Converts each block by DCT (Discrete Cosine Translation). • Quantizes (divides) each element of the block as a fixed value. • Lists each element of the block in zig-zag order. • Run length compresses each element of the block and converts to run level. • Performs VLC (Huffman encoding) on the run level and creates BS.

Decompression is carried out by operations which are the reverse of those used in compression.

The image data handled in DCT is 24-bit direct-color data, but the bitstream produced by compressing this data can be decompressed in either 16-bit or 24-bit mode. The mode can be selected when decompression is carried out.

In the case of a 16-bit pixel, the On/Off status of the first bit (the STP bit) can also be selected when the data is decompressed.

Page 80

7-8 Data Compression Library

Figure 7-5: DCT Decompression

bitstream

VLC decoding

Function name: DecVLC()

run level IDCT

24bit 16x16 macroblock Function name: DecDCTin()/DecDCTout()

MDEC performs decompression from runlevel to macroblock.

The function DecDCTvlc() is used for VLC decoding.

Because IDCT processing takes time, a separate piece of hardware (the MDEC) performs the processing in parallel with the CPU. The function DecDCTin() is therefore provided for transferring the data to the MDEC, and the function DecDCTout() is provided for receiving the decompressed data.

Asynchronous Decoding

The MDEC and the CPU work in parallel, sharing the main memory.

The function DecDCTin() ìsews togetherî the intervals in which the CPU provides the image sections and transmits the run level to the MDEC in the background.

In the same way, the function DecDCTout() transfers decompressed macroblocks to the main memory in the background.

The data decompressed by the MDEC is always transmitted to the frame buffer, via the main memory. When this is done, the exchange between the MDEC and the main memory can be carried out asynchronously. Accordingly, one frame's worth of (640x240) images can be decompressed without creating a frame's worth of buffer in the main memory.

In the example below, the image is split up into long narrow 16x240 (15-macroblock) areas (slices), and the data for each slice is received and transmitted separately.

Example:

extern unsigned long *mdec_bs; /*bitstream*/ extern unsigned long *mdec_rl; /*run level (intermediate data)*/ extern unsigned short mdec_image[15][16][16]; /*decode macroblock*/ DecDCTvlc(mdec_bs, mdec_rl); /*VLC decompression*/ DecDCTin(mdec_rl, 0); /*transmit run level*/ for (rect.x = 0; rect.x < width; rect.x += 16) { DecDCTout(mdec_image, slice); LoadImage(&rect, mdec_image); /*receive*/ /*transfer to frame buffer*/ }

The bitstream transmitted by one execution of the function DecDCTin() is thus received by several executions of the function DecDCTout(), allowing the size of the buffer in the main memory to be reduced.

However, in this case, there has to be a match between the bitstream transmitted and the number of macroblocks received.

Page 81

Data Compression Library 7-9

Callback

DecDCTin() and DecDCTout() are both non-blocking functions that return without waiting for data transmission/reception to terminate.

To detect the termination of the transmission, you can either poll, using the functions DecDCToutSync() and DecDCTinSync(), or register a callback function to be called when the transfer terminates.

To register a callback function, use DecDCToutCallback() and DecDCTinCallback(). You can arrange for image decompression to be carried out asynchronously by designing the callback so that it activates the next data transmission/reception.

In the example below, the next DecDCTout() is activated within DecDCTout's callback function.

Example:

main() { DecDCTout(mdec_image, slice); /*transmission of first block*/ DecDCToutCallback(callback); /*define callback*/ DecDCTvlc(mdec_bs, mdec_rl); /*VLC decoding*/ DecDCTin(mdec_rl, 0); /*transmit run level*/ : /*foreground processing described here*/ : }

callback() { LoadImage(&rect, mdec_image); if((rect.x += 16) < width) /*transfer to frame buffer*/

DecDCTout(mdec_image, slice); /*receive next*/ else DecDCToutCallback(0); /*terminate*/ }

Playing Movies with the CD-ROM

Movies can be played by reading in and playing bitstreams continuously from the CD-ROM. The resolution and number of frames is determined by the decompression speed and the CD-ROM transmission speed.

The MDEC's maximum decompression speed is 9,000 macroblocks per second, or the equivalent of 30 320x240 images. The decompression speed has nothing to do with the compression ratio.

The image resolution and the number of frames played are, of course, inversely proportional. That is to say, with a 320x240 image, a speed of 30 frames a second can be achieved, and with a 640x240 image, speed of 15 frames a second can be achieved.

The process of continuously reading data from a CD-ROM is called streaming. Streaming functions are supplied separately in the libcd library.

Movies are played by placing the bitstream in the containers supplied by the streaming mechanism. Supplementary information such as movie size, etc., is not included in bit stream; therefore, the infomation needed to play a movie is defined separately in the data format (STR format) added to the header.

Page 82

7-10 Data Compression Library

Table 7-2: Decompression Speed and Resolution Resolution Frames per second 320 x 240 640 x 240 640 x 480 7.5 ...

The CD-ROM transmission rate can be set to either 150KB/sec (standard speed) or 300KB/sec (double speed). When playing at double speed, if the bitstream forming one frame is compressed to 10KB (= 300KB/30) or less, and then recorded on the CD-ROM, 30 frames of data per second would be read off the CD-ROM.

Table 7-3: Transfer Speed and Data Size Data size Frames per second 10KB 20KB 30KB 7.5 ...

The moving picture play rate is determined by these two conditions. For example, when playing at double speed, the bitstream comprising one frame (320x240) would be compressed to 10KB (= 300KB/30) before being recorded on the CD-ROM.

Within the range satisfying these conditions, any number of frames, any image resolution, and any compression ratio can be selected.

Direct Transmission and Texture Transmission

Simple moving-picture playback is achieved by using VRAM as a double buffer, and transmitting the images decompressed in the drawing buffer, in succession. The movie transmission is used to clear the background and is also able to draw the object primitive.

The method whereby decompressed images are transferred directly to the drawing area of the frame buffer is called direct transmission.

Conversely, the method whereby texture transmission is carried out by temporarily transmitting decompressed images to the texture area is called texture transmission. When texture transmission is used, the textures used are limited to 16-bit mode.

Encoding by Means of the Local Environment

DCT compression is not normally carried out at run time.

However, if the images created on the drawing device are captured from the frame buffer and compressed there, it is assumed that when authoring is carried out, data compression will be performed using the CPU power of the local environment, so DCT compression functions are also provided in libpress.

The DCT calculations required for compression processing can also be carried out using the MDEC's IDCT calculation circuit, so if the local environment is used, faster encoding is possible.

BVQ (Block Vector Quantization)

BVQ reduces the number of colors in a 24-bit/16-bit direct-color image by vector quantization, and generates an image in 8-bit/4-bit index-color format. Vector quantization is a method in which quantities

Page 83

Data Compression Library 7-11

(vectors) which cannot be ordered one-dimensionally are quantized adaptively, according to their frequency of occurrence.

The data compressed by DCT has already been recoded to 16 bits when it is transmitted to the frame buffer, so there is no saving in terms of the area in the frame buffer itself. However, vector-quantized images have the advantage that they can be transmitted, still in compressed format, to the frame buffer, and used, without conversion, as texture patterns.

To carry out block vector quantization, one image has to be divided up beforehand into several small areas. The division method used generally depends on the way in which the image is used as a texture pattern.

On the PlayStation, an individual CLUT can be assigned to each polygon to be texture-mapped. Accordingly, the areas are normally delineated according to the primitive values (u,v) of each polygon.

CLUT Vector Quantization

When vector quantization is carried out individually on small areas, the number of CLUTs generated is only as big as the number of areas produced by division. However, when the number of divisions is large, the area occupied by the CLUTs becomes too big to be negligible.

To avoid this situation, a function is provided for carrying out further vector quantization on the CLUT itself. For example, when a 320x240 image is divided into 300 16x16 4-bit cells, the 300 CLUTs generated for the cells can be quantized further and combined into 8 CLUTs, for example.

Huffman Encoding

The Huffman encoding supported by libpress is the classical type in which the codebook is fixed. Huffman encoding is only carried out on 4-bit index-color data.

In Huffman encoding, the content of the data is preserved by the process of compression or decompression. This compression method is called reversible compression (or loss-less compression). Generally speaking, in loss-less compression, the compression ratio cannot be controlled.

The Huffman encoder starts by generating a codebook from the frequency of occurrence of the input pixels. The size of the codebook is fixed, regardless of the number of pixels, so when there are not many pixels, the space occupied by the codebook is proportionally high, and compression efficiency is low.

When the codebook is generated, each pixel is compressed in accordance with it. As a result, the data generated is in bitstream format, as with DCT.

The compressed data is always decompressed as a set along with the codebook.

Compression of Sound Data

The PlayStation uses sound data that has been compressed from 16-bit straight PCM data to 4-bit ADPCM. The compressed sound data can be used, without conversion, as SPU sound-source data.

The SPU provides a function called looping so that periodic sound data can be recorded using a small number of samples. When compressing sound data, you can set a suitable loop point.

Page 84
Scan of page 84

This page is a drawing, shown as the original scan.

Page 85

Chapter 8: Basic Graphics Library

Table of Contents

Overview Library and Header Files 8-3 8-3

Graphics System Frame Buffer Addressing Display Area and Drawing Area Drawing Environment Display Environment Display Area and Screen Area Switching Display and Drawing Environments (Double Buffer) Blocking Functions and Non-Blocking Functions Drawing Primitives Special Primitives Primitive Expression Format Initializing Primitives and Setting Their Members Primitive Attributes Combining Primitives Executing Primitives Primitive Drawing Rules 8-3 8-4 8-5 8-5 8-6 8-7 8-7 8-8 8-9 8-10 8-11 8-11 8-12 8-12 8-13 8-13

Ordering Tables Registering Primitives in the OT Registering Special Primitives Linking Primitives Without an OT Ordering Tables and Z Sorting Reverse OT Combining with Geometry Functions Multiple OTs 8-14 8-14 8-14 8-15 8-15 8-16 8-16 8-17

Synchronization and Reset Reset Synchronization 8-18 8-18 8-18

Packet Double Buffer Asynchronous Double Buffer 8-21 8-22

Texture Mapping Texture Pattern Format Texture-Mapping Primitive Brightness Values Repeating Texture Patterns 8-23 8-23 8-26 8-26

Primitive Rendering Speed Access Rules Clipping Structure of the Texture Cache 8-27 8-28 8-30 8-30

Page 86

8-2 Basic Graphics Library

Primitive Division Texture Mapping Distortion Texture Cache Mistakes Clip Overhead Primitive Division 8-33 8-33 8-33 8-33 8-34

Debug Environment Debug Mode Debug String High-Level Library Interface 8-35 8-35 8-35 8-35

Cautionary Programming Notes Texture Polygon Coordinate Specification Handling PAL Format Timing for Updating the Frame Buffer VSync Synchronization in Interlace Mode GPU timeout message 8-36 8-36 8-41 8-43 8-45 8-46

Page 87

Basic Graphics Library 8-3

Overview

The Basic Graphics library (libgpu) is a low-level function library that allows you to work with primitives, such as triangles, rectangles, and sprites. It provides: • System functions for controlling the entire graphics system (for example, graphics system reset). • Frame buffer access functions for directly reading and writing the contents of the frame buffer. • Primitive functions for initializing and manipulating primitive structures and setting the texture page. • Ordering table functions for recording primitives in an ordering table, manipulating ordering tables, and drawing ordering table primitives. • Synchronization functions for synchronizing your code with hardware events, such as the vertical blank period and the completion of drawing operations.

Library and Header Files

To use graphics library services, you must link with the file libgpu.lib. You must also link libapi.lib and libetc.lib when using libgpu.lib.

Your source files should include the header file libgpu.h. In addition, you must include libgte.h and sys/types.h. You include sys/types.h because it defines the following data types used by libgpu.h:

typedef unsigned char typedef unsigned short typedef unsigned int typedef unsigned long u_char; u_short; u_int; u_long;

Graphics System

The PlayStation’s graphics system consists of:

A specialized high-speed graphics rendering engine known as the GPU (Graphics Processing Unit).

A 1MB area of high-speed video memory called the frame buffer. It is used for storing graphics data, including the information used for the current video display, a drawing area, as well as textures and color tables.

A coprocessor (the GTE) for performing high-speed geometry operations. The GPU can use the results of GTE calculations in its commands. The GTE is discussed in Chapter 9 (Basic Geometry Library).

Page 88

8-4 Basic Graphics Library

Figure 8–1: Graphics System

CPU GPU frame buffer video

main bus

command execution command execution

drawing command

main memory

The GPU draws graphics into the frame buffer’s drawing area by executing instruction strings (primitives) stored in main memory. Libgpu’s data structures closely correspond to the primitives recognized by the GPU hardware itself.

Data from the frame buffer is continuously used to create the video signal displayed on your television monitor. By rewriting the frame buffer contents at speeds of up to 60 times per second, moving images are generated. Note: The graphics system contains no special background plane for displaying image data after it is drawn temporarily in the frame buffer.

Frame Buffer Addressing

The frame buffer is arranged as a bitmap that is 1024 pixels wide by 512 pixels tall, with 16 bits per pixel. The total size of the frame buffer is therefore one megabyte (1024 x 512 pixels x 2 bytes per pixel). It is used to store texture patterns and color lookup tables (CLUTs) as well containing drawing and display areas.

Figure 8–2: Frame Buffer

1024

Display region Texture pattern

Drawing region

Texture CLUT

Page 89

Basic Graphics Library 8-5

Pixels in the frame buffer are specified by 2-dimensional coordinates. X-coordinates range from 0 to 1023 and Y-coordinates from 0 to 511. Each pixel has a 16-bit depth: 5 bits for blue, 5 bits for green, and 5 bits for red; the high-order bit indicates semi-transparent mode status, as shown below:

Figure 8–3: Pixels

15 14

S 10 9

B G R

S: semi-transparent FLAG(STP)

Display Area and Drawing Area

The display area is a rectangular section of the frame buffer used to display the video image. Its size depends on the display mode, which ranges from 256 x 240 to 640 x 480 (709 x 488 during overscan). Any of the following combinations can be chosen:

Table 8-1: Display Modes

Width 256, 320, 360, 512, 640 Height Pixel mode Interlace 240 (interlace off), 480 (interlace on), 24-bit, 16-bit On, off (must be off in 480-line mode)

Note: The screen heights assume an NTSC system. For information on working with PAL, see the section “Handling PAL Format”.

The drawing area is a rectangular section of the frame buffer into which graphics data are drawn. Its size is not limited as long as it is fully contained within the frame buffer.

If any part of the drawing area overlaps the display area, its data is shown on the screen. To avoid this effect, a double buffering scheme is typically used. You prepare two separate areas of the same size in the frame buffer. One area is used for drawing while the other is being displayed. After drawing into the drawing area has completed, you switch the areas. Typically, the switching is done during the vertical blank period in order to avoid unsightly screen flashing or tearing.

Drawing Environment

The drawing environment contains general information related to two-dimensional primitive drawing, such as the position of the drawing area and the drawing offset. This information is held in the DRAWENV structure, defined as follows:

typedef struct DRAWENV { RECT clip; short ofs[2]; RECT tw; unsigned short tpage; unsigned char dtd; unsigned char dfe; unsigned char isbg; unsigned char r0, g0, b0; DR_ENV dr_env; }DRAWENV; /*clipping (drawing) area*/ /*drawing offset*/ /*texture window*/ /*texture page*/ /*dither flag (0:off, 1:on)*/ /*display area drawing flag* /*enable to auto-clear)*/ /*initial background color*/ /*reserved*/

Page 90

8-6 Basic Graphics Library

You can use the function SetDefDrawEnv() to set the fields of a DRAWENV structure. You use PutDrawEnv() to make it the current drawing environment. To get a pointer to the current drawing environment, call GetDrawEnv().

DRAWENV contains the following information: • Clipping: The drawing (clipping) area is a rectangular area in the frame buffer defined by (clip.x, clip.y) - (clip.x + clip.w, clip.y + clip.h). • Offset: The offsets ofs[0] and ofs[1] are added to the X and Y values, respectively, of all primitives before drawing. • Texture Window: (tw.x, tw.y) - (tw.x + tw.w, tw.y + tw.h) specifies a rectangle inside the texture page, to be used for drawing textures. • Texture Page: tpage specifies the texture page to be used as the default texture pattern. One texture page has a size of 256 x 256 pixels. • Dither Processing Flag: If dtd is set to 1, the drawing engine performs dithering when drawing pixels. • Display Area Drawing Flag: When dfe is 1, drawing is permitted in the display area. (By default, drawing into the display area is blocked.) • Drawing Area Clear Flag: If isbg is set to 1, the clipping area is cleared to the RGB color specified by the r0, g0, & b0 fields when the drawing environment is set. • Background Color: r0, g0, b0 are the RGB color values used for clearing clipping area when isbg field is set to 1.

Display Environment

Information related to the frame buffer display, such as the position of the display region, is called the display environment. Display environment information is held in the DISPENV structure, defined as follows:

typedef struct DISPENV { RECT disp; RECT screen; unsigned char isinter; unsigned char isrgb24; unsigned short pad0, pad1; }DISPENV; /*display area*/ /*display start point*/ /*interlace 0: off 1: on*/ /*RGB 24-bit mode */ /*reserved */

You can use SetDefDispEnv() to set the fields of a DISPENV structure. To make it the current display environment, call PutDispEnv(). To get a pointer to the current display environment, call GetDispEnv().

DISPENV contains the following information: • Display Area: The rectangular area within the frame buffer (disp.x, disp.y) - (disp.x + disp.w, disp.y + disp.h) is the display area. Its width (disp.w) can be 256, 320, 360, 512 or 640 pixels. Its height (disp.h) can be 240 or 480 pixels. • Screen Area (screen.x, screen.y, screen.w, screen.h): Specifies where on the actual physical screen the display area is shown. The standard monitor screen coordinates are (0, 0) - (256, 240). If you specify a smaller screen area, it is an underscan; if you specify a larger screen area, it is an overscan. For example, if screen.w is set to a value greater than 256, more pixels than 256 cannot be displayed, even if in 320 mode. The size of each pixel does not change. • Interlace: If isinter is set to 1, the display will be in interlace mode. (If the height is 480, display is in interlace mode regardless of the setting of this flag.) • 24-Bit Mode Flag: If isrgb24 is set to 1, frame buffer data is interpreted as being in 24-bit pixel format instead of the standard 16-bit.

Page 91

Basic Graphics Library 8-7

Display Area and Screen Area

The following figure shows the relationship between the display area and the screen area:

Figure 8–4: Display Area and Screen Area

Frame buffer Display

1023

(disp.x,y) (screen.x,y)

Display region

disp.h screen.h

disp.w screen.w

Switching Display and Drawing Environments (Double Buffer)

A double buffering system uses two areas in the frame buffer that switch between display and drawing environments. For example, when buffer 0 occupies the rectangular area (0,0)-(320,240) in the frame buffer and buffer 1 is at (0,240)-(320,480), the respective drawing and display environments are set as follows:

Table 8-2: Double Buffer Buffer 0 Drawing environment (clip.x, clip.y) Clip start point (ofs[0], ofs[1]) Display environment (disp.x, disp.y) Buffer 1

(0,0) Notes

(0,240)

(0,0) (0,240) Drawing offset

(0,240) (0,0) Display area origin

The fields of the DRAWENV and DISPENV structures may be set with the functions SetDefDrawEnv() and SetDefDispEnv(). To switch the drawing and display buffers, use PutDrawEnv() and PutDispEnv()to set the new drawing and display environments.

If you change the drawing environment using PutDrawEnv() while drawing is already taking place, there is no effect on the current primitive being executed or on the remainder of the current primitive list. The new drawing environment takes effect with the next drawing operation.

In addition to using PutDrawEnv(), you may also dynamically switch all or a portion of the drawing environment in the middle of drawing by registering a special primitive in the ordering table. See “Primitives” and “Ordering Tables” for more information.

On the other hand, settings made in the display environment become effective immediately. Therefore, the display location and display area can be changed even when drawing is being carried on in the background.

Page 92

8-8 Basic Graphics Library

The following code shows the basic method of switching double buffers:

DRAWENV drawenv[2]; DISPENV dispenv[2]; int dispid = 0; /*drawing environments*/ /*display environments*/ /*display buffer ID*/

while (1) { VSync(0); dispid = (dispid + 1) %2; PutDrawEnv(&drawenv[dispid]); PutDispEnv(&dispenv[dispid]); } /*wait for vertical blank*/ /*toggle buffer ID between 0 and 1*/ /*switch drawing environment*/ /*switch display environment*/

If you use interlace mode with a height of 480 lines, it may not be possible or practical to set up a double buffer. (For example, in 640 x 480 mode there isn’t room for two buffers in the frame buffer.) Therefore, a single buffer may be used for both drawing and display.

In interlace mode, in each frame (1/60 second), the display updates either the odd or even lines of the buffer, alternately. In effect, odd lines are re-displayed every 1/30 second, and the same for even lines.

If you set the dfe flage of your DRAWENV structure to zero, drawing is prohibited to the areas of the screen currently being displayed. This has the effect of allowing drawing only to the odd lines when even lines are being displayed, and even lines when odd lines are being displayed. This is the equivalent of the usual double-buffer switching. You don’t need to do any explicit switching between display and drawing environments.

Note: for this scheme to be effective, drawing must complete within 1/60 second.

Blocking Functions and Non-Blocking Functions

Functions that complete their processing before returning are called blocking functions. That is, the program is blocked and the next instruction can’t execute until the current one finishes.

Several drawing functions that typically take a long time are processed in the background and return without awaiting completion. These are called non-blocking functions.

The following functions, which directly access the contents of the frame buffer, are non-blocking: • LoadImage() - Transfer from main memory to frame buffer • StoreImage() - Transfer from frame buffer to main memory • MoveImage() - Transfer from frame buffer to frame buffer

The following functions, which draw primitives, are also non-blocking. See the sections on “Primitives” and “Ordering Tables” for more information. • DrawPrim() - Draw a primitive • DrawOTag() - Execute a list of GPU primitves.

All functions other than those listed above are blocking functions.

To detect whether non-blocking functions have finished, or to wait for them to finish, you can call DrawSync(). For example:

LoadImage(&rect, pix); DrawSync(0); /*A non-blocking function*/ /*Waits for drawing to complete*/

See “Synchronization” for more information about DrawSync().

A maximum of 64 non-blocking functions may be queued. For example:

DrawOTag(ot0); DrawOTag(ot1); DrawOTag(ot2); : /*0*/ /*1*/ /*2*/

Page 93

Basic Graphics Library 8-9

If DrawOTag(ot0) is not completed when DrawOTag(ot1) is invoked, the system simply registers the request to the queue and returns. DrawOTag(ot1) waits until DrawOTag(ot0) has finished, and then executes automatically.

The queue contains a maximum of 64 items, so if a 65th request reaches the queue, it is blocked until the queue is opened.

for (i = 0; i<100; i++) LoadImage(....);

In this example, the 65th LoadImage is blocked until the first LoadImage is completed and the waiting queue is available.

Primitives The smallest command that the graphics system can handle is called a primitive (or a packet). Primitives are data structures that are created and stored in main memory, and the CPU and the GPU may both refer to them at the same time.

Primitives are classified as one of the following: • Drawing primitives actually draw pixels in the frame buffer. • Special primitives change certain parameters of the GPU, such as the clipping area and texture page, while drawing is being done. They do not directly change the contents of the frame buffer.

Drawing Primitives

The drawing primitives are listed below. There are four different types of drawing primitive: Polygon, Line, Sprite, and Tile.

Polygon Primitives When drawing polygons, you can choose: • Number of sides (3 or 4) • Shading (Gouraud or flat) • Texture mapping (on or off)

Therefore, the following polygon primitives can be used:

Table 8-3: Polygon Primitives Primitive name Contents POLY_F3 POLY_FT3 POLY_G3 POLY_GT3 POLY_F4 POLY_FT4 POLY_G4 POLY_GT4 3-sided polygon (triangle), flat shaded 3-sided polygon (triangle), flat shaded, textured 3-sided polygon (triangle), Gouraud shaded 3-sided polygon (triangle), Gouraud shaded, textured 4-sided polygon (quad), flat shaded 4-sided polygon (quad), flat shaded, textured 4-sided polygon (quad), Gouraud shaded 4-sided polygon (quad), Gouraud shaded, textured

Page 94

8-10 Basic Graphics Library

Line Primitives Line primitives draw straight lines.

Table 8-4: Line Primitives

Primitive name Contents LINE_F2 LINE_G2 LINE_F3 LINE_G3 LINE_F4 LINE_G4 A straight line between two points Same as LINE_F2, except with color gradation Two connected lines running from points A to B, then B to C Same as LINE_F3, except with color gradation Three connected lines running from points A to B, B to C, and C to D Same as LINE_F4, except with color gradation

Sprite and Tile Primitives These primitives are used for drawing rectangular areas. Tiles are drawn with a solid color, while sprites are texture-mapped.

Table 8-5: Sprite Primitives

Primitive Name Contents SPRT SPRT_8 SPRT_16 TILE TILE_1 Texture-mapped Sprite (free any size) Texture-mapped Sprite (fixed size of 8 x 8 pixels) Texture-mapped Sprite (fixed size of 16 x 16 pixels) Non-textured solid color tile (free any size) Non-textured solid color tile (fixed size of 1 pixel by 1 pixel, i.e. a single dot) Non-textured Solid color tile (fixed size of 8 x 8 pixels) Non-textured Solid color tile (fixed size of 16 x 16 pixels) TILE_8 TILE_16

Special Primitives

Special primitives change all or part of the drawing environment during drawing.

Table 8-6: Special Primitives

Primitive name Parameter to be changed Corresponding DRAWENV members DR_ENV Changes drawing environment Drawing, texture mode Texture window Drawing area Drawing offset All members

DR_MODE DR_TWIN DR_AREA DR_OFFSET tpage, dtd, dfe, tw tw clip offset

Page 95

Basic Graphics Library 8-11

Primitive Expression Format

Primitives are defined as C structures. The first two words of all drawing primitives are the same:

typedef struct { unsigned long *tag; unsigned char r0, g0, b0, code; } P_TAG;

tag represents an internal pointer to the next primitive. It allows primitives to be grouped in a linked list structure so that multiple primitives can be executed together.

The following is an example of a complete primitive structure. POLY_FT4 is defined as a four-sided, flat, textured polygon:

typedef struct { unsigned long *tag; unsigned char r0, g0, b0, code; short x0, y0; unsigned char u0, v0; unsigned short clut; short x1, y1; unsigned char ul, v1; unsigned short tpage; short x2, y2; unsigned char u2, v2 unsigned short pad1; short x3, y3; unsigned char u3, v3; unsigned short pad2 } POLY_FT4;

tag:

code:

r0,g0,b0:

tpage:

clut:

x0,y0,...x3,y3:

u0,v0,...u3,v3:

pad1, pad2: Top 8-bits: Number of GPU words in packet Bottom 24-bits: pointer to next primitive primitive identifier (system reserved value) display color (Red, Green, Blue, values 0-255) texture page ID CLUT (Color Look-Up Table) ID Screen coordinates of polygon vertices Coordinates within texture page for texture Reserved, must be set to 0

Initializing Primitives and Setting Their Members

Primitives must be initialized before they can be executed. When initializing a primitive, call the initializing function for that particular type of primitive; these functions set the tag, code, and pad members appropriately. For example, before drawing a POLY_FT4 (rectangular, flat-shaded, textured polygon) primitive, initialize it as follows:

POLY_FT4 ft4 SetPolyFT4(&ft4);

Most of the members of each primitive may be freely written to by your application unless specified as reserved. There are numerous macros provided in libgpu.h for setting primitive members. For example, examples 1 and 2 below generate the same code. For details, refer to libgpu.h.

Page 96

8-12 Basic Graphics Library

Example 1

POLY_F4 f4;

SetPolyF4(&f4); /*initialize primitive*/ setRGB0(&f4, 0, 0, 255); /*R,G,B = 0, 0, 255*/ setXY4(&f4, 0, 0, 100, 0, 0, 100, 100, 100); DrawPrim(&f4); /*execute primitive*/

Example 2

POLY_F4 f4; SetPolyF4(&f4); /*initialize primitive*/

f4.r = 0; f4.g = 0; f4.b = 255; /*These 3 lines are*/ /*the same as doing*/ /*setRGB0(&f4,0,0,255)*/

f4.x0 = 0; f4.y0 = 0; f4.x1 = 100; f4.y1 = 0; f4.x2 = 0; f4.y2 = 100; f4.x3 = 100; f4.y3 = 100; /*These 8 lines are*/ /*the same as doing*/ /*setXY4( &f4,0,0,100,0,*/ /*0,100,100,100 );*/

DrawPrim(&f4); /*execute primitive*/

Primitive Attributes

The following attributes may be set for primitives:

SemiTrans - Semi-transparent mode

ShadeTex - Inhibits simultaneous texture mapping and shading

You can use SetSemiTrans() and SetShadeTex() to set or clear these attributes for each primitive, as shown below. These functions may be called at any time between initialization and execution of the primitive.

POLY_F4 f4; SetPolyF4(&f4); SetSemiTrans(&f4, 1); SetShadeTex(&f4, 1); /*initialization*/ /*make into semi-transparent primitive*/ /*turn shading OFF*/

Combining Primitives

Many primitives may be used in combination with other primitives; two primitives may be brought together to form a single new primitive. This is done using the MargePrim() function.

typedef struct { DR_MODE mode; SPRT sprt; } TSPRT; /*set mode primitive*/ /*Sprite primitive*/

setTSPRT (TSPRT *p, int dfe, int dtd, int tpage, RECT *tw) { SetDrawMode(&p->mode, dfe, dtd, tpage, tw); SetSprt(&p->sprt); return(MargePrim(&p->mode, &p->sprt)); }

Page 97

Basic Graphics Library 8-13

The setTSPRT() function initializes a new user-defined primitive called TSPRT. A primitive TSPRT initialized in this manner can be used with AddPrim() and DrawPrim() in the same manner as other primitives.

Note: A combined primitive may not be more than 16 long words in total size.

Executing Primitives

Primitives that have been initialized may be executed individually with the DrawPrim() function as in the following example.

POLY_F4 f4; SetPolyF4(&f4); setXY4(&fr, 0, 0, 100, 0, 0, 100, 100, 100); setRGBO(&f4, 0xff, 0x00, 0x00); DrawPrim(&f4); /*(0,0)-(100,100)*/ /*RGB = (255, 0, 0)*/ /*draw*/

When displaying multiple primitives, the order of execution determines the display priority, because when a primitive is executed it is drawn on top of previously drawn primitives.

In the following example, prim[0] is displayed furthest back and prim[99] is displayed furthest forward.

for (i = 0; i<100; i++) DrawPrim(&prim[i]);

However, multiple primitives are usually stored as a linked list in an ordering table and executed together using the DrawOTag() function. See “Ordering Tables” for more information.

Primitive Drawing Rules

The pixels drawn for a primitive are those where the center of each pixel lies within the boundary of the polygon vertices. When the center of a pixel is outside this area, the following rules are used: • If the pixel to the right is inside the drawing area --> can be drawn • If the pixel to the left is inside the drawing area --> cannot be drawn • If the pixel above is inside the drawing area --> cannot be drawn • If the pixel below is inside the drawing area --> 33 can be drawn

With POLY_* primitives, the extreme right and lowest points cannot be drawn. In the case of drawing a quadrilateral, the rules apply as follows:

Figure 8–5: Drawing a Quadrilateral

Drawing allowed

Drawing allowed Drawing not allowed

Drawing not allowed

This ensures that the pixels along the polygon boundary are not drawn more than once when polygons are placed next to each other.

See “Texture Polygon Coordinate Specification” for more information on drawing rules involving texture mapping.

Page 98

8-14 Basic Graphics Library

Ordering Tables

In order to more easily control the order of execution for large numbers of primitives, the graphics library uses a mechanism known as an ordering table (OT). The ordering table is a variation of a basic linked list, designed to allow easy insertion of drawing primitives which represent portions of a three-dimensional display.

Primitives can be registered in an ordering table with AddPrim() or AddPrims(). The registered primitives are then executed using DrawOTag(). Since DrawOTag()is a non-blocking function, the CPU can perform further processing without waiting for the completion of drawing by the GPU.

The OT consists of an array of pointers to primitives held in main memory. Its size is determined by the required resolution of the display priority. For example, the following example creates an ordering table with 256 levels of priority:

unsigned long ot[256]; ClearOTag(ot, 256); /* initialize the OT */

ClearOTag() converts the basic array into a simple linked list, as shown below, where (EndofPrim) is a special value used to indicate the end of the list of primitives:

ot[0]-> ot[1] -> ... -> ot[255] -> (EndofPrim)

Registering Primitives in the OT

Before drawing, primitives must be registered in the OT with AddPrim():

AddPrim (ot + i, &prim); /* AddPrim(&ot[i], &prim);*/

The execution priority of each primitive is determined by its position in the OT. The primitives at the start of the OT will be executed first (and hence displayed furthest back), and the primitives at the end of the OT will be executed last (and hence displayed furthest forward).

In the following example, the primitives p1 and p2 are registered in the OT. Then DrawOTag() is called to execute the primitives in the table. p1 is executed first (displayed furthest back on the screen) and p2 is executed last(displayed furthest forward, i.e. it overwrites any primitives already drawn).

unsigned long ot[256]; Clear0Tag(ot, 256); AddPrim(&ot[0], p1); AddPrim(&ot[255], p2); DrawOTag(ot); /*OT (256 entries)*/ /*OT initialization*/ /*register primitive p1 in ot[0]*/ /*register primitive p in ot[255]*/ /*execute primitives in OT*/

Multiple primitives may be registered in the same OT entry. In this case, primitives will be executed after the primitives subsequently registered in the same entry. In the following example, primitives will be executed in the order p0, p3, p2, p1, p4.

AddPrim (&ot[2], p0); AddPrim (&ot[3], p1); AddPrim (&ot[3], p2); AddPrim (&ot[3], p3); AddPrim (&ot[4], p4); /*register in ot[2]*/ /*register in ot[3]*/ /*register in ot[3]*/ /*register in ot[3]*/ /*register in ot[4]*/

Registering Special Primitives

Special primitives can be used to switch all or part of the drawing environment during the drawing process. These special primitives, like normal primitives, may be registered in the OT, then executed together with normal primitives using the DrawOTag() function.

Page 99

Basic Graphics Library 8-15

The scope of the special primitives depends on their location in the ordering table. In the following example the env primitive setting is valid for execution of primitives registered after ot[128]; therefore only p2 receives the influence of the env primitive.

AddPrim(&ot[0], &p1); AddPrim(&ot[128], &env); AddPrim(&ot[255], &p2); DrawOTag(ot); /*register drawing primitive p1*/ /*register special primitive env*/ /*register drawing primitive p2*/

Linking Primitives Without an OT

You may set up your own linked list of primitives rather than using the ordering table structure. Such a list may still be executed using DrawOTag(). For example, the following provides the same operation as DrawPrim().

myDrawPrim(void *p) { TermPrim(p); DrawOTag(p); /* terminate the primitive */ /* list and execute it. */

}

drawSprites(SPRT *p, int n) { int i; for (i = 0; i < n-1; i++, p++) CatPrim(p, p+1); /* link primitive p to primitive p+1 */ TermPrim(p); DrawOTag(p); }

Note that when you link primitives directly to one another, you give up the flexibility of the ordering table structure.

Ordering Tables and Z Sorting

You can use an OT to implement Z sorting, which is a method of eliminating hidden surfaces by sorting a list of primitives by their depth (z-value) in 3D space. To do this, you calculate a primitive’s position in the OT from its Z-value, as shown in this example:

unsigned long *ot[256]; : AddPrim(ot+256-z0,p0); :

In the basic geometry library (libgte), many of the functions calculate an otz value (to help create a Z-ordered OT) while performing 3-dimensional coordinate conversion.

SVECTOR x3, x2; int flg, otz;

otz = RotTransPers(&x3, (long*)&x2, &flg);

In this case, the RotTransPers() function performs coordinate and transparent conversion of the 3-dimensional values pointed at by x3, using the current matrix, and stores the 2-dimensional coordinates obtained at x2. At the same time it returns an index to the OT called otz. The otz value is the Z coordinate divided by 4; therefore, it is sufficient to provide an OT with 1/4 of the dynamic range of the actual Z-depth. By making use of otz, a 3-dimensional Z sort can be performed at high speed.

Page 100

8-16 Basic Graphics Library

Reverse OT

The otz variable takes a large value for distant objects; as they get closer, the value approaches zero. Because of this, it is necessary to invert the value of otz before using it as an index into the OT array. To avoid this, the libraries make it possible to reverse the order of the entries in the OT. The ClearOTagR() function initializes the OT in reverse order. Then the order of OT execution will be reversed.

The ClearOTag() function will initialize the OT array as follows:

ClearOTag(ot, OTSIZE) ot[0]-> ot[1] -> ot[2] -> ... -> ot[OTSIZE-1] -> (EndofPrim)

The ClearOTagR() function will initialize the OT array as follows:

ClearOTagR(ot, OTSIZE) ot[OTSIZE-1]-> ot[OTSIZE-2] -> ... -> ot[0] -> (EndofPrim)

When using ClearOTagR(), the parameters you pass to other functions are changed accordingly, as shown in the table below:

Table 8-7: OT Using ClearOTag() Using ClearOTagR() #define OTSIZE 1024 unsigned long *ot[OTSIZE];

ClearOTag (ot,OTSIZE);

AddPrim (ot+OTSIZE-otz, &prim); AddPrim (ot+otz, &prim);

DrawOTag (ot); #define OTSIZE 1024 unsigned long *ot[OTSIZE];

ClearOTagR (ot, OTSIZE);

DrawOTag (ot+OTSIZE-1);

Note how the pointers into the OT are done differently when using ClearOTagR(). In particular, the calculations required to calculate the index into the OT for the AddPrim function are simpler, and since this function is likely to be called very often, the result is a net savings.

The normal order OT is most often used for 2-dimensional graphics applications such as sprite-based games, where the position of each primitive is not necessarily based on a position in 3D space. The reverse order OT is used more often for 3-dimensional graphics applications where the Z-depth of the 3D calculations correspond more directly to positions within the OT.

The reverse order OT is initialized via a high speed hardware function, whereas the normal order OT is initialized via software. Because of this, large OT arrays are initialized much more quickly if they are reverse order.

Combining with Geometry Functions

To display three-dimensional objects, each object is broken up into combinations of triangles and quadrilaterals, and the coordinates of each polygon determine the position of the corresponding primitive which must be drawn. In other words, the (x,y) coordinates of the primitive in the frame buffer are obtained from the 3D coordinates of a polygon component of an object. This coordinate transformation is performed by the geometry library.

Object movement/rotation, and viewpoint movement/rotation may be described in a single rotation matrix and movement vector. The vertices of the polygons which make up the objects are described below.

Page 101

Basic Graphics Library 8-17

Figure 8–6: Polygon Vertex Format

 Sx   m00 m01 m02   Wx   Tx           Sy  =  m10 m11 m12  ×  Wy  +  Ty    Sx     m20 m21 m22     Wz     Tz  

(Wx, Wy, Wz): - Coordinate position in world coordinates (Sx, Sy, Sz): - Coordinate position in screen coordinates (m00,...,m22): - Rotation matrix

The primitive which is drawn is actually a projection onto a two-dimensional plane (the screen). The screen is an imaginary plane a certain distance h from the point of view. This process is known as perspective transformation.

Figure 8–7: Perspective Transformation  x   h × Sx / Sz   y  =  h × Sy / Sz        otz     Sz / 4  

Here the calculated (x, y) are the (x, y) members of the primitive and otz is an OT entry. See the libgte documentation for details. Following is an example of a function performing this operation.

void rotTransPersAddPrim( SVECTOR *pos; SPRT *sp; unsigned long *ot; int ot_size) { long otz, dmy, flg; /*position*/ /*Sprite primitive*/ /*OT*/ /*size of OT*/

otz = RotTransPers(&( pppos->x[0],, (long*)sp ->x0,&dmy,&flg); if (otz > 0 && otz < ot_size) AddPrim(ot+otz, sp); }

Multiple OTs

An entire OT can be inserted into another OT if desired. This method is valid for using more than one hierarchical coordinate system at once.

The following example connects the child-OT ot1 with a length of n to the parent-OT ot0.

AddOT(unsigned long *ot0, unsigned long *ot1, int n) { AddPrims(ot0, ot1, ot1+n-1); }

However, since the link destination for ot1[n-1] is replaced with the ot0 link destination in AddPrims(ot0, ot1+n-1), in certain cases, the primitive linked to ot1[n-1] is not rendered. As a result, the primitive must not be registered in the final ot1 entry.

Page 102

8-18 Basic Graphics Library

Synchronization and Reset

Reset

To reset the graphics system, call ResetGraph(). This function takes one parameter, which determines the reset level. All levels immediately interrupt the drawing command in progress, cancel all the requests remaining in the queue, and enter wait status. • Level 0 ( ResetGraph (0) ) Completely resets the graphics system. It should be executed only once, when the program is activated. The drawing command and queue commands are cancelled and callbacks are initialized. The display mode is initialized at 256x240 and the display is masked (the screen goes black.) • Level 1 ( ResetGraph (1) ) Cancels the command currently being executed and the commands remaining in the queue. The drawing environment and display environment are preserved. This level is used frequently when switching the double buffer. • Level 3 ( ResetGraph (3) ) Equivalent to Level 0 complete reset, except that the display environment and the drawing environment are preserved. Also, the display is not masked. This level is used to initialize all child processes while saving the display screen status set by the parent processes. When shifting control from parent processes to child processes using Exec(), a complete reset is needed in order to switch the callback, but with a level 0 reset, the display is also initialized. Therefore, once the display synchronization misses, the screen becomes disturbed when shifting to child processes. In order to avoid this, child processes should be initialized using ResetGraph(3) at the start, rather than ResetGraph(0).

Below is a summary of the above points:

Table 8-8: Reset Levels Reset Level Callback DISPENV DRAWENV command queue Initialize Save InitializeSave Initialize Save Save Initialize Save Initialize Initialize Initialize

Synchronization

In order to provide a smooth display, programs need a way to synchronize their graphics operations (and other processing) to the vertical blank period of the video display. In addition, programs need a method of detecting the end of drawing operations being performed in the background; that is, non-blocking functions such as DrawOTag().

There are two methods for detecting when asynchronous events have occurred: • Polling: that is, checking to see whether the event has occurred. • Callbacks: setting up functions that are automatically executed when the event occurs.

Polling The DrawSync() function allows you to detect the end of drawing operations. It has the following options: • DrawSync (0) - Blocks until all requests remaining in the queue are finished. • DrawSync (1) - Returns the number of positions in the drawing queue.

Page 103

Basic Graphics Library 8-19

The VSync() function allows you to detect the next vertical blank period, as well as providing other information. It can be used in several different ways:

• VSync (0) - Block until the next vertical blank period begins. • VSync (1) - Return the number of horizontal sync units since the previous VSync(0) or VSync(n) call. • VSync (n) - Where n>0, waits for the nth vertical blank period. (VSync(0) waits for the next VB period. nd VSync(2) waits for the 2 VB period, etc.) • VSync (-n) - Where n<0, returns the number of vertical blank periods since the program was started.

Callbacks

A callback is a function that is called when background processing has been completed. Libgpu provides two functions that let you register callbacks:

Table 8-9: libgpu callback registering functions

Function Name Trigger

VSyncCallback()

DrawSyncCallback() Vertical Synchronization

Drawing completion

DrawSyncCallback lets you define a function that is called at the completion of a non-blocking drawing operation such as DrawOTag().

VSyncCallback() lets you define a function that is called at the beginning of the vertical blank period. This function can be used to switch the display from one buffer to another and to perform other graphics operations which much be synchronized in this fashion.

int buffer = 0; int new_frame_is_ready = 0; /*Active buffer indicator*/ /*“ready to switch buffers” flag*/

: :

void main() { /*initialization routine entered here*/ : : VSyncCallback( vbcallback ); /*defines callback routine*/ : : }

vbcallback() { if( new_frame_is_ready ) {

buffer = 1 - buffer; PutDispEnv(&db[buffer].disp); PutDrawEnv(&db[buffer].draw); new_frame_is_ready = 0; /*This is set within our*/ /*DrawSyncCallback function*/ /*(not shown here) /*Switch buffers*/

/*Reset flag*/ } }

Page 104

8-20 Basic Graphics Library

In the following code, the callback routine increments a counter. The routine MyVSync(), by looping until the counter changes, is functionally equivalent to Vsync(0).

main() { /* Initialization routine entered here */ VSyncCallback (callback); /* Define callback */ while (1) { /* Processing carried out within the frame entered here */ myVSync(); } } static volatile int Vsync_Count = 0; /* Vertical Synchronization counter */ void myVSync(void) { /* Blocks until Vsync_Count variable is updated */ int i = Vsync_Count; while (i == Vsync_Count); } void callback() { /* Counter increases when vertical synchronization is started */ Vsync_Count++; }

Frame Synchronization

To avoid screen flicker, the drawing and display buffers should be switched at the same time as the vertical synchronization. DrawSync() and Vsync() are used to accomplish this.

/* (1) After drawing has concluded, waits until the next vertical synchronization and starts the next drawing */ DrawSync(0); Vsync(0) Draw0Tag(ot);

/* (2) Regardless of whether drawing has concluded or not, waits until the next vertical synchronization and starts the next drawing */ Vsync(0); ResetGraph(1); Draw0Tag(ot);

/* (3) Regardless of whether drawing has concluded or not, waits until the next 2 vertical synchronizations and starts the next drawing */ Vsync(2); ResetGraph (1); Draw0Tag (ot);

Please note that drawing at 60 frames/second in example (2) is not guaranteed. Drawing at 60 frames can be achieved only when the CPU processing terminates in 1/60 second. Also, note that in example (3), counting from the Vsync called immediately prior to the Vsync(2) blocks for two frameblockss.

Page 105

Basic Graphics Library 8-21

Packet Double Buffer

The general term for the area in memory used for the OT and primitives is packet buffer.

Waiting for primitives to be drawn after they have been registered in the OT makes it impossible to operate the CPU and the graphics system in parallel. The primitives and OT cannot be accessed by the CPU until after the graphics system has finished processing them.

Figure 8–8: Drawing After Registering in OT

CPU Registering in OT Registering in OT

GPU OT drawing

Operating the graphic system and the CPU in parallel requires two packet buffers, one is used to contain the OT and primitives currently being generated, the other is used for the OT and primitives which were previously generated and which are now being executed by the graphics system. The two packet buffers assume the tasks of drawing and execution alternately. This is referred to as a packet double buffer system.

Figure 8–9: Packet Double Buffer

CPU Registering in OT #0 Registering in OT #1 Registering in OT #0

GPU Drawing of OT #1 Drawing of OT #0 Drawing of OT#1

This is a packet double buffer. An example of a packet double buffer is given below. The OT and primitive must be combined together when using a packet double buffer.

typedef struct{ unsigned long ot[256]; SPRT sprt[256]; } DB; /*OT*/ /*Sprite Primitive*/

main(){ int j; DB db[2], *cdb; cdb = db[0]; while (1) { cdb=(cdb==db)? db+1: db; /*switch buffers*/ ClearOTag(cdb->ot); /*clear OT*/ for(j=0; j<256; j++){ /*register Sprites in OT*/ /*at this point, calculate the Sprite position*/ AddPrim(cdb->ot, cdb->sprt[j]; } DrawOTag(cdb->ot); /*Draw*/ } }

Page 106

8-22 Basic Graphics Library

Asynchronous Double Buffer

Normally, the packet double buffer is switched at the completion of drawing. When using interlace mode, however, drawing must be updated every 1/60 second, regardless of the calculation/rendering time. In such cases, callbacks can be used to forcibly carry out redrawing.

/*Asynchronous DrawOTag: *The specified OT waits for the next VSync and is executed. */ main() {

VSyncCallback (callback);

while (1) { /*Create primitive list*/ DrawSync(0); make_packet();

unsyncDrawOTag(ot); } }

static void *completed_ot = 0; unsyncDrawOTag (void *ot) { completed_ot = ot; } void callback (void) { if (completed_ot) { ode_patch(); ResetGraph (1); /* stop drawing */ DrawOTagR (completed_ot); /* } } /*Patch for interlace double buffer. */ static void ode_patch (void) { static int ode = 0; DRAWENV draw; GetDispEnv (&draw); if (draw.dfe) { while (GetODE() ==ode); ode = (ode+1) &0x01; } }

In this example, DrawOTag is executed in each field regardless of the load on the CPU. However, when updating of the OT was not performed in time, the previous OT will be reused.

Note: The purpose of ode_patch() is to adjust for a problem in VSync timing when switching the odd/even fields in interlace mode; see “VSync Synchronization in Interlace Mode” for details.
Page 107

Basic Graphics Library 8-23

Texture Mapping

Texture mapping is a method of mapping a two-dimensional bitmapped image known as a texture pattern onto the surfaces of triangles and quadrilaterals.

Textures are stored in areas of the frame buffer (outside the display and drawing areas) called texture pages. A texture page consists of a 256 x 256 bitmap. Its upper left X coordinate in the frame buffer must be a multiple of 64 and the Y coordinate a multiple of 256. (Therefore, it’s possible for texture pages to overlap horizontally.)

Texture Pattern Format

There are three pixel format modes used in texture patterns, as shown in the table below. Each primitive may have a different mode.

Table 8-10: Texture Pattern Modes Mode Type Colors Texture page width 4-bit 8-bit 16-bit CLUT-based CLUT-based Direct RGB 32767

In 16-bit mode, the pixel value from the texture is used directly: 15 bits are used for RGB color information, allowing 32767 colors, plus 1 bit to specify semi-transparent status for that pixel.

The 4-bit and 8-bit texture modes use a color lookup table (CLUT), also known as a palette, to specify the actual color values. Each pixel value in these modes is used as an index into the appropriate CLUT. The CLUT itself a series of 16-bit pixel values arranged in a horizontal format within the frame buffer. Each 16-bit pixel value represents one of the colors to be used for the texture. A 4-bit texture requires a CLUT with 16 consecutive entries, and an 8-bit texture requires a CLUT with 256 consecutive entries.

16-bit textures are stored with one pixel per 16-bit word, while 8-bit textures store 2 pixels in each word, and 4-bit textures store 4 pixels in each word, as shown in the figure below. Since a 256 x 256 pixel texture pattern is placed in 1 texture page, the area actually occupied by a texture page in the frame buffer varies from 256 x 256 (16-bit mode) to 64 x 256 (4-bit mode).

Page 108

8-24 Basic Graphics Library

Figure 8–10: Texture Pattern Format

  • 4bit mode (pseudo color)

12 11

pix3 pix2 pix1 pix0

  • 8bit mode (pseudo color)

pix1 pix0

  • 16bit mode (direct color)

S B G R

S: semi-transparent (STP) bit

When using 4-bit and 8-bit textures, the coordinates of the texture pattern (U,V) and the coordinates in the frame buffer will not directly map to each other. Care must be taken, when using LoadImage(), to load texture patterns into the frame buffer. The same applies to MoveImage() and StoreImage().

The rectangular area specified for these functions is based on standard frame buffer coordinates using 16-bit pixels. For 4-bit textures, the rectangle width must be divided by 4. For 8-bit textures it must be divided by 2. This means that 8-bit textures must be an even multiple of 2 pixels in width, and that 4-bit textures must be an even multiple of 4 pixels in width.

The following code sample illustrates texture mapping on a quadrilateral:

POLY_FT4 ft4;

SetPolyFT4(&ft4); /*initialize primitive */ ft4.tpage = GetTpage (0, 0, 640, 0); /*texture page = (640,0)*/ ft4.clut = GetClut (0, 480); /*texture CLUT = (0, 480)*/ /* texture pattern within the (x,y) = (0,0) - (256, 256) is /* textured mapped to (u,v) = (0,0)-(128,128) within the */ /* texture page */

setXY4(&ft4, 0, 0, 256, 0, 0, 256, 256, 256); setUV4(&ft4, 0, 0, 128, 0, 0, 128, 128, 128);

DrawPrim(&ft4); /*execute primitive*/

Note: GetTPage() and GetClut() require that LoadImage() be used to load the texture and texture CLUT in advance. LoadTPage() and LoadClut() load the texture page and texture CLUT and return the texture page ID and the texture CLUT ID respectively.

Texture CLUTs may be set independently for each primitive regardless of the texture to be used. Multiple textures may use the same CLUT. A 4-bit texture can use any 16 entries from a larger CLUT.

Page 109

Basic Graphics Library 8-25

Setting the Current Texture Page Unlike polygons, sprite primitives (SPRT) do not specify a texture page. Therefore, you must make sure the current texture page is set correctly when executing sprites.

You can specify the initial current texture page in the drawing environment. The special primitive DR_MODE can be used to explicitly change the current texture page. This switches the current texture page mode.

DR_MODE dr_mode; SPRT16 sprt; /*mode primitive*/ /*16 x 16 Sprite primitive*/

SetDrawMode(*&dr_mode, 0, 0, GetTPage(2, 0, 640, 0), 0); SetSprt16(&sprt); setXYO(&sprt, 100, 100);

ClearOTag(ot, 2); AddPrim(ot + 1, &sprt); AddPrim(ot + 1, &dr_mode); DrawOTag(ot); /*register SPRT16 in ot[1]*/ /*register DR_MODE in ot[1]*/

Note that two primitives are registered in the same OT entry. The latest one registered (DR_MODE) is executed first.

Transparent Pixels and Semi-Transparent Pixels You may select transparent, opaque or semi-transparent for each pixel when performing texture mapping. The high bit (bit 15) of each pixel value (or the corresponding CLUT entry in 4 and 8-bit mode) is the semitransparent (STP) bit.

When the pixel value of the texture pattern is 0x0000 (STP, R, G and B are all zero), the pixels are transparent and therefore not drawn.

Pixels with the STP bit set to 1 will be displayed as semi-transparent, if the primitive they are mapped onto is set in semi-transparent mode with the SetSemiTrans() function. Pixels with the STP bit set to 0 but not with R, G and B all zero will always be opaque.

Table 8-11: Transparent/Semi-Transparent Pixels STP, B, G, R (0, 0, 0, 0) (1, 0, 0, 0) (0, n, n, n) (1, n, n, n) Non-transparent primitive Semi-transparent primitive Transparent Black Non-transparent

Transparent Semitransparent Non-transparent black Nontransparent Semi transparent

Primitives that do not use texture mapping may also be set to semi-transparent mode using SetSemiTrans(). In these cases, the primitive’s pixels will all be semi-transparent.

Note: The processing speed of semi-transparent polygons is greatly reduced, because the existing pixels in the frame buffer must be read, processed, and then written back.

The rates of semi-transparent primitives are specified in primitive units. Below is a list of semi-transparency rates which may be specified.

Table 8-12: Semi-Transparency Rates

Background Brightness Value Primitive Brightness Value 0.5 1.0 1.0 1.0 0.5 1.0 -1.0 0.25

Page 110

8-26 Basic Graphics Library

The brightness value is clipped when it exceeds the maximum value. Semi-transparency rates may be used specified by the texture page specified using the DR_MODE primitive. The same rate is applied to primitives that do not perform texture mapping.

See the section above on “Primitive Attributes” for more information.

Texture-Mapping Primitive Brightness Values

In the case of a texture-mapped primitive, the texture pattern brightness value of the pixels of a polygon is specified by the (r, g, b) members of the primitives. These values taken together comprise the actual brightness value.

The brightness value of a pixel being drawn is calculated from the corresponding texture pattern pixel value and the brightness value specified by the (r,g,b) members of the primitive, as shown below:

T = Texture pattern pixel value

L = Brightness value of the pixel as specified by the R,G,B fields of the primitive.

P = (T*L)/128

In other words, if the (r, g, b) fields of the primitive are all set to 128, then all the pixels drawn will be the same brightness value as the source texture. If the resulting brightness value (P) exceeds 255, it will be clipped to a maximum value of 255.

Either the r, g, b members must be set, or this option must be prohibited using the SetShadeTex() function when a texture mapping primitive is initialized.

POLY_FT4 ft4; SetPolyFT4(&f4); /*initializes the primitive*/

SetRGB0(&fT4, 0x80, 0x80, 0x80); /*or*/ SetShadeTex( &ft4, 1 ); /*initializes the RGB values*/

/*inhibit shading*/

Repeating Texture Patterns

It is possible to set one portion of a texture page as a texture window and within that space wrap round (repeat) a texture pattern.

Setting a texture window can be done when setting the drawing environment through the tw field of the DRAWENV structure, or by using the DR_MODE primitive. Please refer to the following example.

Texture windows are normally set to (0,0) - (255, 255), which causes the texture not to be repeated. Setting the texture window to a smaller region will cause the texture to be repeated as necessary when drawing a primitive.

When specifying a texture window in order to repeat a texture, the texture coordinates (U,V) of the primitive should be within the texture window.

u_short tws[2], twe[2]; DR_MODE dr_mode;

tws[0] = tws[1] = 32; tws[0] = tws[1] = 64; /*drawing mode primitive*/

/*texture window (32,32)-(64,64)*/

/*initialization drawing mode primitive*/ SetDrawMode(&dr_mode,0,0, GetTPage(0, 0, 640, 0), tws, twe ); :

Page 111

Basic Graphics Library 8-27

AddPrim(ot+n, &dr_mode);

Texture Cache When rendering a texture-mapped polygon, the texture pattern must be read from the frame buffer. To improve rendering speed, the PlayStation’s GPU contains a 2K high-speed texture cache. When textures are used, they are read from the frame buffer into the cache. Subsequent uses of the same texture pixels (texels) are read directly from the cache, which is much faster than reading from the frame buffer.

Like the frame buffer, textures in the texture cache are referred to by two-dimensional addresses. These addresses depend on the pixel mode of the polygon being drawn. The following table shows the cache sizes for each pixel mode:

Table 8-13: Texture Cache Size

Pixel Mode Size (width x length) 4 bit/pixel 64x64 64x32 32x32

Primitive Rendering Speed

To improve rendering speed on the PlayStation, it’s necessary to determine which is slower, the rendering speed of the GPU or the computation speed of the CPU. This can be determined by calling DrawSync(). • If the speed bottleneck is in the CPU, DrawSync() returns immediately. • If the speed bottleneck is in the GPU, DrawSync() is blocked; that is, it doesn’t return immediately.

The amount of time DrawSync() is forced to wait is a measure of the latency through the GPU.

When the bottleneck is in the GPU, program code optimization will not improve performance, so a means for improving rendering speed is necessary.

This section explains a few of the factors that determine the rendering performance of the GPU and general methods for improving rendering speed.

In the PlayStation, frames are first rendered in the frame buffer, then output to the display. Therefore, rendering performance can be determined essentially from the number of read and write accesses to VRAM (Video RAM).

The rendering (execution) speed of a specific primitive depends on its area and type. Primitive rendering consists of repeated reads and writes to the frame buffer VRAM. The larger the area of the primitive, the greater the amount of VRAM written and hence the greater the rendering time. Semi-transparent rendering is slower than opaque rendering of the same primitive, since semi-transparent rendering requires read access as well as write access.

The rendering speed depends on the primitive type. The execution speed of primitives with the same rendering area are in the following order:

Page 112

8-28 Basic Graphics Library

Figure 8–11: Primitive Rendering Speed

High speed Low speed

TILE

POLY_F* POLY_G*

POLY_FT*(4bit/OnC) POLY_FT*(4bit/OffC) POLY_FT*(8bit/OnC) POLY_FT*(8bit/OffC) POLY_FT*(16bit/OnC) POLY_FT*(16bit/OffC)

POLY_GT*(4bit/OnC) POLY_GT*(4bit/OffC)

POLY_GT*(8bit/OnC) POLY_GT*(8bit/OffC)

POLY_GT*(16bit/OnC)

SPRT(4bit/OnC) POLY_GT*(16bit/OffC)

SPRT(4bit/OffC)

SPRT(8bit/OnC) SPRT(8bit/OffC)

SPRT(16bit/OnC) SPRT(16bit/OffC)

OnC indicates that the texture cache is in hit status, and OffC indicates that the texture cache is in miss status, while 4bit/8bit/16bit indicates the texture mode. Rendering speed is always faster in cache hit, while when the texture cache is in miss state, 4bit mode texture is faster than 8bit, which is faster than 16bit.

Access Rules

Primitive rendering speed can be calculated from the frame buffer access cycle.

Once all the primitives have been rendered to the frame buffer, they are displayed. Rendering performance is related to the frequency of read-write access to the frame buffer.

Basic Rules A write access to the frame buffer corresponds directly to a rendering operation. Read accesses to the frame buffer take place when a texture pattern is being read and when in semi-transparent mode. The rules for access cycles are as follows.

Table 8-14: Access Cycles

Access direction pixels/cycle Notes Write SPRT,TILE,POLY_F3,POLY_F4 Other Texture mapping semi-transparent rendering Read

Page 113

Basic Graphics Library 8-29

For example, the number of cycles required to render a 100x100 POLY_G4 and a 100x100 POLY_F4 are shown below.

Table 8-15: Number of Access Cycles Primitive type POLY_G4 POLY_F4 Total number of pixels Total number of reads Total number of writes Total cycles 100x100=10000

10000 10000 100x100=10000

5000 5000

Texture mapping Calculating the rendering speed of texture maps is extremely complex. However, we can first consider a simple texture miss/hit, where the mapping is 1:1. In the 4-bit texture pattern, four texels (texture pixels) are packed into one 16-bit word. Therefore, four texels can be read together with one access. SImilarly, with an 8-bit texture pattern, two texels are read simultaneously.

In the case of a 100x100 POLY_FT4:

Table 8-16: Number of Cycles in POLY_FT4 Mode 4-bit 8-bit 16-bit Total number of reads Total number of writes Total 10000/4=2500 10000 12500 10000/2=5000 10000 15000 10000 10000 20000

Mode 4-bit 8-bit 16-bit Total number of reads Total number of writes Total 10000/4=2500 5000 7500 10000/2=5000 5000 10000 10000 5000 15000 In the case of a 100x100 SPRT:

Table 8-17: Number of Cycles in SPRT

It can be seen from this presentation that 4-bit textures are the fastest.

Texture Enlargement Ratio Dependencies In these examples, 1:1 texture mapping was performed. However, the calculations differ if the texture is enlarged or reduced. Below, the primitives from the previous examples are reduced horizontally by 2 (4-bit mode).

Table 8-18: Number of Cycles Used when Reduction Is Involved Item Cycles Total number of reads Total number of writes Total 100x100/4=2500 50x100=5000 7500

Note that simply halving the area will not halve the rendering time.

Rendering speed improves when a texture is expanded, because the same texels can be used multiple times, and fewer texture reads are needed to render an area.

Page 114

8-30 Basic Graphics Library

Texture Cache Dependencies In the above examples, the texture cache is always missed. However, a texture for which there is a cache hit can be used directly without a read operation. Calculating using the previous example:

Table 8-19: Texture Cache Dependencies In the case of a 100x100 SPRT

Mode 4-bit 8-bit 16-bit Cache hit Cache miss 5000 7500 5000 10000 5000 15000

Note that if the texture pattern is in cache, rendering speed is constant regardless of the mode.

Clipping

The number of rendering cycles also depends on how polygons are clipped. Rendered polygons are clipped within the rendering area. During clipping, the left and upper portions of the polygon generate empty cycles.

Figure 8–12: Clipping

Drawing range

A

B

Drawing polygon

In this example, empty cycles are generated at A but are not generated at B. Empty cycles also include empty texture read cycles.

Structure of the Texture Cache

This section describes the texture cache for the benefit of programmers who are concerned with optimizing its use.

Cache blocks A texture page is divided into rectangular regions based on cache size. Each of these regions is referred to as a cache block. Cache blocks are numbered in sequence (according to block number).

In 4-bit mode, the size of the cache is 64x64. The texture page is divided into 16 cache blocks as shown below.

Page 115

Basic Graphics Library 8-31

Figure 8–13: Cache Blocks in Texture Page

Cache entries

Each cache block can be divided further into 16 x 1 regions known as cache entries. In 4-bit mode, there are 256 cache entries and they are arranged as shown below.

Figure 8–14: Cache Entries

Each entry is structured as follows:

struct { u_char block_id; u_short data[4]; } Entry[256]; /*block number tag*/ /*texture pattern data*/

Since cache data consists of 4 short words, a 4-bit texture would store 16 texture pixels in a single entry.

Cache strategies

A block number is saved in each entry, and this is used to determine when there is a hit or miss in the cache. In texture mapping, the determination of whether texture pixel (u,v) is in cache or not is performed in the following manner.

The block number to which a texture pixel (u,v) belongs can be calculated as:

block_id = (v>>6)<<2 + (u>>6)

And, the entry number associated with (u,v) can be calculated as:

entry_id = (v&0x3f)<<2 + (u&0x3f)>>4

Page 116

8-32 Basic Graphics Library

Based on these calculations, a cache hit evaluation can be performed with the following code:

is_cache_hit_4bit(u_char u, u_char v) { int block_id = (v>>6)<<2 + (u>>6); int entry_id = (v&0x3f)<<2 + (u&0x3f)>>4;

if (Entry[entry_id].block_id == block_id) return(1); /*cache hit*/ else return(0); /*cache miss*/ }

Since cache block numbers are saved independently in each cache entry, texture pixels having different block numbers can coexist in the cache as long as their entry numbers are different. For example, since the texture pixels in the rectangular area defined by

(u,v) = (0,0)-(63,63)

all belong to the same texture block, they will be saved in the cache together. The texture pixels in the rectangular region defined by

(u,v) = (16,16)-(79,79)

span multiple texture blocks, but they will also be saved in the cache together since there are no overlapping entries. However, the texture pixels in the rectangular region defined by

(u,v) = (8,8)-(71,71)

have some overlapping entry numbers (e.g. (u,v) = (8,8)-(15,8) and (u,v) = (64,8)-(71,8) ). Therefore, these pixels will not be saved in the cache together even though the rectangular area itself fits in a 64x64 area.

Also, pixels that are not in contiguous regions and do not have overlapping entries, such as

(u,v) = ( 0, 0)-(15,15) (u,v) = (80,64)-(95,79)

can be saved in the cache together.

Mode dependencies The sizes of the cache blocks and cache entries vary according to mode. However, the number of entries is always 256.

Table 8-20: Size of Cache Blocks and Cache Entries Mode Block Number of blocks Entry Number of entries 64x64 64x32 32x32 16x1 8x1 4x1

Page 117

Basic Graphics Library 8-33

Primitive Division

Problems can arise when drawing an area that occupies a large space in the display screen with a single texture primitive.

Texture Mapping Distortion

PlayStation uses affine transformation for texture mapping. When mapping a large primitive, the image can become distorted due to conversion errors. The texture coordinates (u ,v) attached to the points within the polygon (x, y) are calculated as:

u = a0*x + a1*y + a2 v = b0*x + b1*y + b2

This does not produce a correct image. On the other hand, the following equations contain correct perspective conversion:

u = (a0*x + a1*y + a2*z + a3) / (c0*x + c1*y + c2*z +c3) v = (b0*x + b1*y + b2*z + b3) / (c0*x + c1*y + c2*z +c3)

If the z depth within the polygon is fixed or changes are few, a correct mapping image can be created.

As a result, when a quadrilateral primitive which occupies a comparatively large area of ground and has large depth changes is drawn, a mapping image with a bent diagonal line will result due to conversion errors.

Texture Cache Mistakes

Texture mapping a large primitive cannot get any value from using the texture cache. In 4-bit mode, one texture cache entry is maintained horizontally 16 texels (4 short words). When the necessary texels are not in the cache, GPU combines the cache entries containing those texels and speculatively reads them. If the surplus 15 texels which are read additionally are used before the entry is flashedflushed, this contributes to the drawing efficiency, but if they are not used, they are discarded as useless.

However, in 4-bit mode the texture cache size is restricted to a 64x64 size. This means that texels separated by 64 texels share the same cache entry. Therefore, when drawing something which has a maximum displacement (du, dv) of the (u,v) within the primitive greater than 64, cache mistakes will occur without fail during drawing.

In the worst case (when the mapping of the u,v direction and x,y direction are exactly 90 degrees) the cache entry texel read speculatively is flashed before it is used next and then becomes useless. In such a situation, the drawing speed is reduced by half.

The difficult point in this problem is that the drawing speed can fluctuate greatly depending on the primitive drawing direction. The drawing direction fluctuates dynamically with the local screen matrix value and the matrix value is moved by the controller input. Undecided elements such as this which cause major fluctuations in the drawing efficiency can make the program more difficult.

Clip Overhead

Drawing a large primitive is disadvantageous from a clipping standpoint. If the entire primitive is outside the drawing area, that primitive is not drawn (that is, not recorded to the OT). However, if even one section falls within the drawing area, that section must be recorded to the OT. Although drawing outside the drawing area can be cancelled by the GPU clipping function, an empty cycle can sometimes be produced. As the primitive increases in size, the chance that its entire area will all be outside the drawing area decreases and the chance that an empty cycle will be produced increases.

Page 118

8-34 Basic Graphics Library

Primitive Division

Almost all of these problems can be solved by dividing a large primitive in advance. For a primitive which has an area which has the possibility of becoming large, the area and distance from viewpoint before perspective conversion are evaluated during drawing and the decided frequency is recursively divided at the mid-point. Depending on the objective, there are several division algorithms and packaging methods. Following is a simple POLY_FT4 recurrent division example:

typedef struct { short u_char short }VERTEX x, y, z u, v x2, y2

/*Macro for performing mid-point division*/ #define half (v0, v1, v2) / (v0)->x3 = ((v1)->x3+(v2)->x3)>>1, / (v0)->y3 = ((v1)->y3+(v2)->y3)>>1, / (v0)->z3 = ((v1)->z3+(v2)->z3)>>1, / (v0)->u = ((v1)->u+(v2)->v )>>1, / (v0)->v = ((v1)->u+(v2)->v)>>1, / get_RotTransPers (&((v0)->x3), &((v0)->x2, &dmy, &dmy, &dmy);

extern POLY_FT4 *heap /*Buffer which saves primitive after division*/ extern POLY_FT4 *sle;tpm; /*Template*/ extern int min_x, max_y; /*Drawing area*/ extern int max_x, max_y; void divideFT4 (int ndiv, VERTEX *v0, VERTEX *v1, VERTEX *v2, VERTEX *v3) { if (min4(v0-> x, v1->x, v2->x, v3->x) > max_x) return; if (min4(v0-> x, v1->x, v2->x, v3->x) > min_x) return; if (min4(v0-> x, v1->x, v2->x, v3->x) > max_y) return; if (min4(v0-> x, v1->x, v2->x, v3->x) > min y) return; if (ndiv) { u_long d; VERTEX v4, v5, v6, v7, v8 half (&v4, v0, v1); half (&v5, v2, v3); half (&v6, v0, v2); half (&v7, v1, v3); half (&v8, &v5, &v6); divideFT4(ndiv-1, v0, &v4, &v6, &v8); divideFT4(ndiv-1, &v4, v1, &v8, &v7); divideFT4(ndiv-1, &v6, &v8, v2, &v5);

divideFT4(ndiv-1, &v8, &v7, &v5, v3); return; } else { *heap = *skelton; setXY4 (heap, v0->x, v0->y, v1->x, v1->y, v2->x, v2->y, v2->x, v2->y); setUV4(heap, v0->u, v0->v, v1->u, v1->v; v2->u, v2->v, v2->u, v2->v); heap++; } }

Page 119

Basic Graphics Library 8-35

Perspective conversion is carried out correctly on the new vertex produced by the division (division vertex). With this method correct conversion is performed only on the division vertex and can be thought of as being interpolated via the primary method. Therefore, when the number of divisions increases (if the number of division vertices increases), the approximate precision increases and the quality of the texture images also increases.

Division also has an effect on the texture cache. The (du, dv) of the primitive after conversion are smaller than those before division. When division is repeated and the (du, dv) stay within the size of the texture cache, the drawing efficiency is greatly increased.

Division is also effective for clipping. By dividing a large primitive the probability that the entire primitive area will fall outside the drawing area increases. As a result, it is possible to reduce the useless empty cycles outside the drawing area.

Debug Environment

Debug Mode

When debug mode is set, each function checks the conformity of the data as far as possible. If there is any problem, it will print a return code and the contents as a debug string.

Debug String

When debug mode is set by the SetGraphDebug() function, or the contents of a structure is output by using the Dump...() function, the output character string is stored in the specified character string buffer. The Fnt...() function is used to display this on screen.

High-Level Library Interface

Libgpu is designed to avoid dependence on any particular data structure and paradigm. It contains no functions that can work directly with PlayStation graphics formats such as TIM (a two-dimensional image related data structure) or TMD (a three-dimensional object data structure). To handle these formats directly, you can use functions of the extended graphics library (libgs).

However, the OpenTMD()/ReadTMD() and OpenTIM()/ReadTIM() functions are available to analyze the contents of TMD data and TIM data only for the debugging of the data itself. There is also an interface between libgpu and libgs.

ReadTIM()interprets as much as possible the header information within TIM format image data of TIM data.

ReadTMD()interprets as much as possible the information of any polygon data inside any object with TMD data.

Page 120

8-36 Basic Graphics Library

Cautionary Programming Notes

This section discusses some topics that you should be aware of when using libgpu. • Texture polygon coordinate specification • Handling PAL format • Timing for updating the frame buffer • VSync synchronization in interlace mode

Texture Polygon Coordinate Specification

The following problems have been reported when drawing textured polygons:

  • When attempting to display a 16x16 texture map on a 16x16 polygon, using the parameters (0, 0) to (15, 0) and (0, 15) to (15, 15) causes the lines at the bottom and right edges not to be displayed.
  • With the textured polygon POLY_FT4, enlarging the texture before displaying the polygon causes an extra dot to be displayed on the right and bottom edges. (x,y)=(0,0)–(16,16), (u,v)=(0,0)–(16,16) (x,y)=(0,0)–(17,17), (u,v)=(0,0)–(16,16) (x,y)=(0,0)–(31,31), (u,v)=(0,0)–(16,16) (x,y)=(0,0)–(32,32), (u,v)=(0,0)–(16,16) Normal Normal Normal Extra dot displayed
  • With the textured polygon POLY_FT4, texture patterns cannot be specified if they touch the right or bottom sides of the texture page.

These problems relate to the following drawing rules.

Drawing Rules The drawing rules for PlayStation POLY_... primitives specify that drawing cannot be performed along the right and bottom edges. This rule prevents the polygon boundary lines from being written twice when polygons are used to cover an area.

An example of this is shown in the following diagram. As can be seen, without this rule, the center intersecting lines of polygons P0, P1, P2, and P3 would be written twice. This might be a problem in some cases, such as when using semi-transparent mode.

Figure 8–15: Drawing Rule

P0 P1

P2 P4

The above example assumes that a square specified by the coordinates (x, y) = (0, 0) to (8, 8) and (u, v) = (0, 0) to (8, 8) is being drawn as POLY_FT4. In other words, the following is assumed.

POLY_FT4 ft4;

SetXY4( &ft4, 0,0, 8,0, 0,8, 8,8 ); SetUV4( &ft4, 0,0, 8,0, 0,8, 8,8 );

Page 121

Basic Graphics Library 8-37

The texture pattern for the above is mapped as shown below.

The numbers in the map represent the texture pattern values (v, u) that are copied to the corresponding pixels. These values are entered in the order of (v, u), not (u, v), in accordance with frame buffer addressing.

Figure 8–16: Mapping

3 4

0 00 01 02 03 04 05 06 07 08

1 10 11 12 13 14 15 16 17 18

2 20 21 22 23 24 25 26 27 28

7 70 71 72 73 74 75 76 77 78 8 80 81 82 83 84 85 86 87 88 The (u.v) values at this point are (8,8).

If the drawing rule described earlier is applied under this condition, the lines at the right and bottom edges are not displayed, so the actual display is as shown below.

Figure 8–17: Displayed contents

3 4

0 00 01 02 03 04 05 06 07

1 10 11 12 13 14 15 16 17

2 20 21 22 23 24 25 26 27

7 70 71 72 73 74 75 76 77

In the example above, texture mapping at (0, 0) to (7, 7) is accurate from pixels (0, 0) to (7, 7).

Next, if (u, v) = (0, 0) to (7, 7), the mapping is as shown below.

Page 122

8-38 Basic Graphics Library

Figure 8–18: Mapping

3 4

0 00 00 01 02 03 04 05 06 07

1 00 00 01 02 03 04 05 06 07

8 70 70 71 72 73 74 75 76 77 The (u,v) values at this point are (7,7).

Applying the drawing rule described above, the lines at the right and bottom edges are deleted, so that the lines represented by texture values u = 7 and v = 7, i.e., the lines at the right and bottom edges, are not displayed.

Figure 8–19: Displayed Contents

3 4

0 00 00 01 02 03 04 05 06

1 00 00 01 02 03 04 05 06

7 60 60 61 62 63 64 65 66

As shown above, correct results will be obtained if (x, y) = (0, 0) to (8, 8) and (u, v) = (0, 0) to (8, 8) are used.

In ordinary texture mapping, no problems should occur when the mapping is contiguous, i.e., when adjacent polygons have adjacent texture patterns applied to them.

However, in background displays, adjacent cells (POLY_FT4 cells) are not required to use adjacent textures by necessity.

In this case, using the normal specification described above would cause the following types of problems to occur.

Inverting or Rotating Textures

For example, suppose you want to rotate the texture described above 180 degrees in the XY direction and then display the rotated texture. Without changing the (u, v) values for POLY_FT4, you can specify the following for (x, y).

SetXY4( &ft4, 8,0, 0,0, 8,8, 0,8 );

The texture pattern for the above is mapped as shown below.

The numbers in the map represent the texture pattern values (u, v) that are copied to the corresponding pixels.

Page 123

Basic Graphics Library 8-39

Figure 8–20: Mapping

3 4

0 08 07 06 05 04 03 02 01 00

1 18 17 16 15 14 13 12 11 10

2 28 27 26 25 24 23 22 21 20

7 78 77 76 75 74 73 72 71 70 8 88 87 86 85 84 83 82 81 80 The (u,v) values at this point are (0,8).

Applying the drawing rule described earlier, the lines at the right and bottom edges are not displayed, and so, as shown below, the line defined as (u, v) = (0, 0) to (0, 7) (the points at each pair of UV spatial coordinates from (0, 0) to (7, 0) ) are not mapped. Instead, the points from (8, 0) to (8, 7) are shown as the left edge, meaning that the entire image is shifted one dot to the left when it is mapped.

Figure 8–21: Displayed Contents

3 4

0 08 07 06 05 04 03 02 01

1 18 17 16 15 14 13 12 11 Here (u,v)=(1,0) is mapped instead of the expected (u,v) = (0,0).

2 28 27 26 25 24 23 22 21

7 78 77 76 75 74 73 72 71

This effect may occur when the texture pattern is inverted vertically or when the polygon is rotated 90 or more degrees.

In particular, when the polygon is rotated, the mapped texture pixels change depending on the angle of rotation.

Enlarging Textures

Let us consider an example in which the same POLY_FT4 as above is enlarged to twice its size.

In this case, specifying (x, y) = (0, 0) to (16, 16) and (u, v) = (0, 0) to (8, 8) causes the texture pattern to be mapped as shown below (values are rounded to the nearest whole number).

Page 124

8-40 Basic Graphics Library

Figure 8–22: Mapping

3 4 9 10 11 12 13 14 15 16

0 00 01 01 02 02 03 03 04 04 05 05 06 06 07 07 08 08

1 00 01 01 02 02 03 03 04 04 05 05 06 06 07 07 08 08

2 10 11 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18

3 10 11 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18

14 70 71 71 72 72 73 73 74 74 75 75 76 76 77 77 78 78

15 80 81 81 82 82 83 83 84 84 85 85 86 86 87 87 88 88

16 80 81 81 82 82 83 83 84 84 85 85 86 86 87 87 88 88

Applying the same drawing rule, the lines at the right and bottom edges are not displayed, so (u, v) is displayed in the range (0, 0) to (8, 8) as shown below.

Figure 8–23: Displayed Contents

3 4 8 9 10 11 12 13 14 15

0 00 01 01 02 02 03 03 04 04 05 05 06 06 07 07 08

1 00 01 01 02 02 03 03 04 04 05 05 06 06 07 07 08

2 10 11 11 12 12 13 13 14 14 15 15 16 16 17 17 18

3 10 11 11 12 12 13 13 14 14 15 15 16 16 17 17 18

14 70 71 71 72 72 73 73 74 74 75 75 76 76 77 77 78

15 80 81 81 82 82 83 83 84 84 85 85 86 86 87 87 88

The “u=8” point remains here

When the mapping is gradually increased from the same scaling factor, this effect occurs precisely when the scaling factor becomes 2.

Page 125

Basic Graphics Library 8-41

Specifying Pixels on the Left and Bottom Edges of the Texture Page For the same reason as explained above, it is not possible to display the lines at the texture pattern right and bottom edges (the lines specified as u = 255 and v = 255, respectively).

In the example used earlier, you must specify the following to display the 8 x 8 section at the right bottom edge of the texture page.

SetUV4( &ft4, 248,248, 256,248 256,256, 248,256 );

But because the resolution of (u, v) is 8 bits, you cannot set a value of 256, because it will overflow to a value of zero. Therefore, these values must be rounded down to 255 as shown below.

SetUV4( &ft4, 248,248, 255,248 255,255, 248,255 );

Note that the line defined by u = 255 and v = 255 is not displayed. This problem occurs when polygons are enlarged by a factor of two or more.

Similarly, this problem occurs at the leftmost line (the line at u = 0) if the texture is mapped as horizontally flipped. If the texture is mapped as both horizontally and vertically flipped, this problem occurs at the top and leftmost lines (the lines at v = 0 and u = 0). In other words, neither of these lines is displayed.

Corrective Measures Subtracting a 1 from the (u, v) values will avoid all of the problems described above, although other problems may occur. This will, however, prevent the right and bottom edges of the texture pattern from being displayed. In other words, if the texture pattern is a 16 x 16 pattern, it will be enlarged to 16:15, and if it is an 8 x 8 pattern, it will be enlarged to 8:7 when displayed. Be sure to note this when creating Sprite patterns.

Handling PAL Format

The information in this chapter assumes an NTSC display. A number of changes are necessary in order to output a signal for PAL-format TV receivers.

Differences between NTSC and PAL The major differences between NTSC and PAL are shown in the following table:

Table 8-21: Differences between NTSC and PAL Video format NTSC PAL Field rate Standard vertical resolution 60Hz 50Hz

Since the PAL field rate is 50Hz, the maximum display rate is 50 frames/second. Also, since vertical sync interrupts only occur 50 times a second, programs that use Vsync for timing will appear to slow down to 5/6 of the NTSC rate.

The vertical resolution that can be displayed on a standard TV is greater for the PAL format. Thus, a larger display area within the frame buffer is needed for full-screen displays on a PAL-format TV. If the NTSCformat display area is used on a PAL TV, an upper or lower section of the screen will appear dark.

Page 126

8-42 Basic Graphics Library

Changes to handle PAL format

Programs designed with the NTSC format in mind must be changed in the following ways to handle PALformat monitors. • Enable PAL mode using the SetVideoMode() function • Adjust the display starting position • Adjust timing • Adjust display area

Of these, changes in the first two are required. Changes in the last two are optional depending on the application.

Enabling PAL mode

For the DTL-H2000, PAL mode can be enabled by setting the DIP switch on the main unit and then using the SetDispMode() function.

#include <libetc.h> main() { SetVideoMode(MODE_PAL);

}

Programs operating in this mode will run on PAL PlayStations as well.

Adjusting the display starting position

With PAL format, although the vertical resolution prerequisite is 256 lines, the vertical resolution of the display is 240 lines in the standard setting. Thus, without any changes, the display area on a PAL TV will appear as if it were shifted to the top of the screen. However, the display area should be centered on the screen by modifying the default values of the screen structure in DISPENV.

Figure 8–24: Display Starting Position

Display area

DISPENV Display area

disp;

disp.screen.x = 0; disp.screen.y = 16; disp.screen.w = 256; disp.screen.h = 256; /*same as NTSC*/ /*(288-256)/2*/ /*same as NTSC*/ /*256*/

PutDispEnv(&disp);

Adjusting timing

In PAL mode, VSync interrupts are generated only 50 times a second. Many programs use the vertical sync interrupt (VSync()) to handle timing, so in these cases timing should be adjusted by 6/5.

Page 127

Basic Graphics Library 8-43

Timing for Updating the Frame Buffer

The PlayStation can update the display area in the frame buffer (in operations such as swapping double buffers) at a rate different from the video frame rate (1/60 sec). However, if the display is updated at an irregular rate (that is, not a multiple of 1/60 second), flicker may result on the screen, which may be perceived by users as a bug in the application.

If the time spent in calculation and rendering operations exceeds the frame rate, motion on the screen may appear delayed for a moment. This is referred to as a skipped frame and is generally tolerated, but it may still be interpreted by some users as a defect.

The following points relate to managing frame rates when developing an application.

Timing for updating double-buffer switching

Switching double buffers is generally synchronized with the vertical sync.

In (A), buffer-switching depends on either rendering or displaying, whichever is slower. Thus, switching will become out of sync with vertical retrace and will take place during the display period. Therefore, unless a special effect is being performed intentionally, a VSync(0) should be executed when the buffers are switched so that synchronization is maintained.

(A) while (1) {

DrawSync(0);

swap_buffer(); DrawOTag(ot); } (B) while (1) {

DrawSync(0); VSync(0); swap_buffer(); DrawOTag(ot); }

Keeping the frame rate constant

If the time required to create a frame is sometimes slightly less than 1/60 second and sometimes slightly more, the application’s frame rate will jitter between 60fps and 30fps. This can cause objects on the screen to move in an unnatural manner, leading to complaints from users.

The same thing applies for other frame rates (such as 20, 15, etc.) whenever the time period for creating a frame is close to a 1/60 second boundary. (Or a 1/50 second boundary for PAL video systems.)

In these cases, the frame rate can be fixed (at the slower rate) by using the VSync counter to determine when to change buffers. The following example fixes the frame rate at 30 fps by calling VSync(2), which waits for the second vertical blank after the last VSync call:

while (1) { DrawSync(0);

/*Wait for 2nd vertical blank after last VSync call*/ VSync(2);

swap_buffer();

DrawOTag(ot); /*build next frame*/ /*draw next frame*/ }

You can fix the frame rate at 20 frames/sec by using VSync(3) and at 15 frames/sec by using VSync(4).

Using absolute time

Sometimes it’s not desirable to synchronize an application to the slowest frame rate, especially if frame rates drop only at specific and relatively rare instances. Also, forcing buffer switching to stay in sync with the fixed vertical sync generates idle periods where the CPU and GPU perform no real operations.

Page 128

8-44 Basic Graphics Library

If the frame rate varies, the internal clock of an application should not be based on the frame rate, because the speed of an object on screen will vary depending on the frame rate. Instead, you can use an absolute counter such as VSync(-1) or RCnt3 for such calculations.

(A) while (1) {

DrawSync(0); VSync(0); swap_buffer(); frame++; DrawOTag(ot); } (B) while (1) {

DrawSync(0); VSync(0); swap_buffer(); frame = VSync(-1); DrawOTag(ot); }

In these examples, frame is used to increment stages of motion or animation. The code in (A) will result in a movement slowdown when the frame rate drops, and a speedup when the frame rate increases. To avoid this, you can calculate frame as shown in (B). In this case, the overall motion will not be delayed or speeded up, even if frames are occasionally skipped due to overflow in calculation or rendering.

If the displacement or scrolling of an object is based on an absolute counter, there is no need to keep a fixed frame rate. Therefore, this approach can be considered a more thorough solution than forcing a fixed frame rate. However, there is an increased load on the program if updates are consistently made independently from double-buffer switching. Therefore, the choice of method should be determined based on the application’s objectives.

Cancelling rendering operations

In interlaced mode, both calculation and rendering operations must be completed within 1/60 second. Therefore, when switching buffers, the vertical sync (VSync) must have a higher priority than drawing completion (DrawSync)

Therefore, rendering must be reset midway to synchronize with VSync(0). In general, rendering time varies more than calculation time so predicting rendering time is difficult. If a large figure is to be drawn and there is an overflow in rendering time, rendering can be reset midway so that screen flicker from interlace mode can be avoided.

(A) while (1) {

DrawSync(0); VSync(0); swap_buffer(); DrawOTag(ot); } (B) while (1) {

VSync(0); ResetGraph(1); swap_buffer(); DrawOTag(ot); }

In particular, performing MoveImage() on rectangles that are 16 dots wide or less and rendering of polygons that are narrow in width generate frequent page breaks and tend to have varying processing times. If these kinds of operations are to be performed often in interlace mode, buffer switching should not be dependent on rendering speed.

Return value from VSync(1)

If you call VSync(1), the return value is the time elapsed since the last VSync(0) or VSync(n) call, in horizontal sync units.

VSync(0); t = VSync(1); /*wait for V-BLNK*/ /*value of H from last VSync(0)*/

In this code, you’d expect t to be close to 0. However, this may not be the case, because functions such as sound callbacks and controller drivers are executed by the system during the vertical blank period.

Page 129

Basic Graphics Library 8-45

VSync Synchronization in Interlace Mode

A problem arises when using the interlace single buffer (vertical 480 dot) mode. When switching the drawing in VSyncCallback() rather than VSync(), only the even fields of the first primitive rendering recorded to the OT are cached. As a result, the background may not be able to be cleared and an afterimage may remain.

Cause In interlace mode, the even and odd fields are alternatively displayed at 1/60 second intervals. In other words, if the mode is 640x480, y displays the even line and the odd line alternatively. At such times, the GPU performs the following operations depending on whether even or odd is being displayed: • When displaying an odd field, only the even line is rendered. • When displaying an even field, only the odd line is rendered.

Though it is a single buffer, it becomes a mechanism whereby the screen being rendered is not displayed.

Therefore, the GPU must know whether the current video output is an odd field or an even field. However, during the vertical blank, the GPU always recognizes it as an even field.

Figure 8–25: Switching between even and odd fields

Video even V-BLNK odd

GPU even even* odd V-BLNK even

even V-BLNK

even*

Note: even* refers to the fact that the GPU recognizes the current field as even when it should be odd.

Vsync is called at the V-BLNK start point (not the end point). Therefore, the items rendered during V-BLNK are only rendered in an even field. In Z-sorting, the section which is normally rendered first becomes the background section. As a result, the background of only half a field is not cleared, BG rendering is not performed, and other such problems arise.

Countermeasures To avoid this, rendering must be started immediately after the vertical blank has terminated. Since VSyncCallback() cannot detect V-BLNK termination, you can use the following options: • Add a callback using H-Sync callback (RCnt2) • Increase the frequency of H-Sync during V-BLNK using VSync(1) is needed. However, a function GetODE() is being introduced as a more reliable method for distinguishing whether the current field is even or odd.

u_long GetODE(void); / *0...EVEN 1...ODD */

GetODE() is formally introduced in Library Ver. 3.7. When using prior libraries, incorporate the abovementioned declaration into libgpu.h, etc.

Please note that the GetODE() value does not indicate the even or odd field of the current video output, but rather the value of the even or odd field recognized by the GPU. Since GetODE() returns only even frames during a V-BLNK immediately after a VSyncCallback(), an expedient is required. Refer to the sample program for details.

Page 130

8-46 Basic Graphics Library

Supplement In interlace mode, the odd and even fields are forcibly switched to 1/60[sec] with NTSC standards. Therefore, when in this mode, all processes must be completed at 1/60[sec]. When rendering time is the cause of processing mistakes (GPU trouble), these can be avoided by cancelling rendering (ResetGraph(1)), although of course a partial polygon will be produced. If the CPU is the cause (CPU trouble), screen disturbance can be avoided by using the previous OT until the CPU generates the next OT to perform rerendering.

A rendering command (Draw0Tag) must be issued within the VSyncCallback() in order to implement this.

GPU timeout message

The following message may appear during program execution, and processing will stop:

GPU timeout:que=...,stat=...,chcr=...,madr=...

This GPU timeout is issued in cases where four seconds (240VSync) have elapsed, but the GPU nonblocking function has not yet terminated. An incorrect primitive link may be the cause.

For example, rendering will never terminate when primitives are listed in a loop, as below:

p0->p1->p2->p3....->p2

In this situation, a GPU timeout will be issued. The meaning of each value is as follows:

GPU timeout:que=%d,stat=%08x,chcr=%08x,madr=%08x • que: Command queue remainder (0 when idle) • stat: Only bit 26 has meaning 1: Rendering in progress 0: idle • chcr: Only bit 24 has meaning 1: Executing in the background 0: idle • madr: Address where DrawOTag() / LoadImage(), etc. are being executed

Page 131

Chapter 9: Basic Geometry Library

Table of Contents

Overview Library and Header Files 9-3 9-3

Theoretical Geometry Operations Using the Basic Geometry Library Coordinate Calculation Light Source Calculation Normal Line Vector, Light Source Vector Direction GPU Code Normal Line Clipping Normal Line Clipping Function 9-3 9-3 9-5 9-8 9-8 9-8 9-9

Depth Cueing Implementation of Depth Cueing (Common Operations) Depth Cueing Using Vertex Colors Depth Cueing Using Textures 9-10 9-10 9-11 9-11

Material Light Source Calculation with Material Quality 9-13

Functions with Three or Four Vertices 9-14

libgte Argument Format Recommended Format 9-14 9-15

Libgte Function Flag Variables 9-15

About libgte Mesh Functions 9-17

Changing Screen Offsets 9-17

PMD Functions PRIMITIVE Group TYPE Packet Data Configurations VERTEX 9-17 9-17 9-18 9-20

SMD, RMD Functions 9-20

Polygon Division 9-21

Page 132
Scan of page 132

This page is a drawing, shown as the original scan.

Page 133

Basic Geometry Library 9-3

Overview

On the PlayStation, polygons are not drawn directly after calculation. Instead, the polygons on a given screen are sorted before drawing takes place:

Geometry arithmetic --> sorting --> drawing

Library and Header Files

Programs using the basic geometry library must link with the file libgte.lib.

Source code must include the header file libgte.h.

Theoretical Geometry Operations Using the Basic Geometry Library

When you use the functions provided by the basic geometry library, the GTE is activated to perform highspeed calculations. It performs two primary types of calculation:

Coordinate calculation, which takes the three-dimensional coordinates of polygon vertices and generates two-dimensional coordinates on the screen. These calculations can involve coordinate and/or perspective conversions.

Light source calculation, which finds the lighting of a polygon on the screen from the direction, color and intensity of a light source and the position of the polygon.

Coordinate Calculation

The basic geometry library assumes three types of fixed coordinate systems on the screen: • Local coordinate system: the fixed coordinate system of the object. • World coordinate system: the fixed coordinates of the world in which the object is placed. • Screen coordinate system: the fixed coordinates of the screen.

An “object” consists of multiple polygons, and multiple objects compose one screen. Therefore, it is possible to have multiple local coordinate systems.

Normally, vertex data for each polygon are specified in the local coordinate system. To convert these into screen coordinates, the following conversions are necessary:

Page 134

9-4 Basic Geometry Library

Local coordinate system  → (Vx, Vy, Vz) World coordinate system (Wx, Wy, Wz) World coordinate system (Wx, Wy, Wz)  → Screen coordinate system (Sx, Sy, Sx)

 Wx   Vx   WLx   Wy  = [ WLij ]  Vy  +  WLy          Vz     WLz     Wz  

 Sx   Wx   SWx   Sy  = [ SWij ]  Wy  +  SWy          Sz     Wz     SWz  

[WLij] is the world/local conversion matrix [WLx, WLy, WLz] is the world/local translating vector [SWij] is the screen/world conversion matrix [SWx, SWy, SWz] are the screen/world translating vectors Synthesizing this results in the following:             Vx   WLx    SWx   Sx     Sy  =  SWij   WLij   Vy  +  WLy  +  SWy                          SWz   Sz  Vz WLz          

           WLx   SWx    Sx   Vx    Sy  =  SWij   WLij   Vy  +   SWij   WLy  +  SWy                         WLz     SWz      Sz   Vz        

The synthesized coordinate conversion matrices between coordinate systems and translating vectors are called:

Rotation matrix (RTM) [ Rij ] = [ SWij ][ WLij ]

Translatin g vector (TRV)  TRx   WLx   SWx   TRy  = [ SWij ]  WLy  +  SWy          TRz     WLz     SWz  

Page 135

Basic Geometry Library 9-5

The local coordinate values may be calculated with the rotation matrix by adding vectors to one matrix multiplied by the screen coordinate.

Local coordinate system (Vx, Vy, Vz)  → Screen coordinate system (Sx, Sy, Sz)

 Sx   Vx   TRx   Sy  = [ Rij ]  Vy  +  TRy          Sz     Vz     TRz  

You can use SetRotMatrix() and SetTransMatrix() to set the constant rotation matrix and the constant translating vector. They don’t need to be changed if the coordinate system and position don’t change. However, when a different local coordinate system is used for each object, each needs to be set separately.

Note: The local coordinate system setting method is up to the user.

You can use RotTrans() to find the screen coordinate value from the local coordinate system. Then coordinate conversion can be performed by the previously-set rotation matrix and translating vector.

Using a screen coordinate value found with RotTrans(), a parallel projected image of the object may be formed on the screen. In real vision, a distant object must be perspective-converted so that it appears small.

Screen coordinate system (Sx, Sy, Sz)         → perspectiv e conversion Screen coordinate system (SSx, SSy)

 SSx   Sx   SSy  = ( h/Sz )  Sy     

h is the distance from the eye to the screen. Perspective conversion is done by multiplying the screen coordinate X and Y components by h/Sz.

You can use RotTransPers() to perform RotTrans() and perspective conversion together.

Note: In practice the following offset value is added in RotTransPers():

 SSx   Sx   OFX   SSy  = ( h/Sz )  Sy  +  OFY       

Also, the depth cueing interpolation coefficient p is calculated at the same time.

Light Source Calculation

The GTE uses a parallel light source complete diffusion reflection model for light source calculations. It doesn’t rely on the position of the point of view, but determines the lighting on the basis of light source attributes and polygon attributes.

The following describes a light source calculation for one vertex of a polygon:

Each vertex of a polygon has two attributes: • Normal line vector - (Nx, Ny, Nz) • Vertex color - (R, G, B)

The normal line vector is usually given in the local coordinate system.

Page 136

9-6 Basic Geometry Library

The light source has three attributes: • Light source vector (direction and intensity) - (Lx, Ly, Lz) • Color of the light source - (Lr, Lg, Lb) • The ambient color - (BKr, BKg, BKb) Since the light source is a parallel light source, there is no position information. Since it is the same for each object, it is given in the world coordinate system. Other than the influence of the light source, the background ambient color is present at all of the vertices. The color (RR, GG, BB) in which the vertices are depicted on the screen is calculated as follows:

  • Convert normal line vector coordinates into the world coordinate system.  → Normal line vector (world) Normal line vector (local)

 NWx   Nx   NWy  = [ WLij ]  Ny        NWz     Nz  

  • Calculate the “light source effect” by taking the inner product of the light source vector and the normal line vector (world).  → Light source effect (L) Normal line vector (world) • Light source vector

L = [ Lx Ly  NWx  Lz ]  NWy  = [ Lx     NWz   Ly  Nx  Lz ] • [ WLij ]  Ny      Nz  

Note: means dot product.
  • Multiply the light source effect by the light source color for each item to get the color effect of the light source (local color) for vertices.

Light source effect (L) * Light source color (Lr, Lg, Lb)  → Light source color effect (LI)

 LIr   Lr   LIg  = L  Lg        LIb     Lb  

  • Add the light source color effects and the ambient colors to find the color effect of the whole environment. Light source color effect (LI) + Ambient color (BK)  → Color effect (LT)

 LTr   Lr   BKr   LTg  = L  Lg  +  BKg          LTb     Lb     BKb  

  • Multiply the vertex color by the color effect to find the vertex color for display. RR = R * LTr GG = G * LTg BB = B * LTb
Page 137

Basic Geometry Library 9-7

For example, if there were three light sources in the above procedure, (1) and (2) would respectively be as follows:  L1   Lx1 Ly1 Lz1   Nx   L2  =  Lx2 Ly2 Lz2  [ WLij ]  Ny          L3     Lx3 Ly3 Lz3     Nz  

Here, if the product of multiplying  Lx1 Ly1 Lz1   Lx2 Ly2 Lz2  [ WLij ]     Lx3 Ly3 Lz3  

is [Lij], then(1) and (2) can result in the following one-off matrix calculation.  L1   Nx   L2  = [ Lij ]  Ny        L3     Nz  

This matrix [Lij] is called the Local Light Matrix (LLM) in GTE. Therefore, there is no need to convert the normal line vector for each polygon into the world coordinate system. It is sufficient to calculate just the local light matrix [Lij] for each object. The local light matrix, like the rotation matrix, is a GTE constant matrix. The local light matrix [Lij] may be set by SetLightMatrix(). Further, if there are three light sources, then there are three light source colors so that (3) above is as follows:  LIr   L1r   L2r   L3r   LIg  = L1  L1g  + L2  L2g  + L3  L3g            LIb     L1b     L2b     L3b  

 L1r L2r L3r   L1  =  L1g L2g L3g   L2        L1b L2b L3b     L3  

If this matrix,  L1r L2r L3r  [ LRij ] =   L1g L2g L3g     L1b L2b L3b  

is [LRij], then (3) and (4) above for 3 light sources will be as follows:  LTr   L1   BKr   LTg  = [ LRij ]  L2  +  BKg          LTb     L3     BKb  

This matrix, [LRij] is called the Local Color Matrix (LCM) in GTE. The local color matrix and local light matrix, like the rotation matrix, are GTE constant matrices. Each may be set by SetLightMatrix() and SetColorMatrix(). Also, ambient color is called Back Color (BK) and may be designated by SetBackColor().

Page 138

9-8 Basic Geometry Library

The procedures (1) (2) (3) (4) and (5) explained above may be summarized as follows based on up to three light sources.

  • Normal line vector (local) --> Light source effect (local light matrix)

 L1   Nx   L2  = [ Lij ]  Ny        L3     Nz  

  • Light source effect --> Color effect (local color matrix, back color)

 LTr   L1   BKr   LTg  = [ LRij ]  L2  +  BKg          LTb     L3     BKb  

  • Color effect, vertex color --> Vertex screen color

RR = R * LTr GG = G * LTg BB = B * LTb

There is a function in the basic geometry library

NormalColorCol()

which performs this 6), 7) and 8) once. In GTE light source effect is called local color (LC).

Normal Line Vector, Light Source Vector Direction

The normal line vector given to each vertex of a polygon should be placed in a direction from the front to the back (pointing into the object). The light source vector is not the position of the light source, but should be the direction of the rays.

GPU Code

The GTE has a register that maintains the GPU packet code. Light source calculation functions output a GPU packet with the RGB value placed at the beginning of the packet. The GPU packet and the RGB code are a single word, so the RGBcd portion of the packet may be created with one memory write. If the GPU packet code register is not specified correctly, the GPU packet cannot be properly generated.

With functions that have no input primary color vector, you should call SetRGBcd() to set the primary color vector and GPU code. These functions are Intpl(), NormalColor(), and NormalColor3().

With functions that do have input color vectors, the GPU packet code is automatically copied from the upper 8 bits of the color vector to the GPU packet code register. These functions are: ColorCol(), ColorDpq(), ColorMatCol(),ColorMatDpq(), DpqColorLight(), DpqColor(), DpqColor3(), NormalColorDpq(), NormalColorDpq3(), NormalColorCol(), NormalColorCol3(), RotColorDpq(), RotColorDpq3(), RotAverageNclipColorDpq3(), RotAverageNclipColorCol3(), RotColorMatDpq().

Normal Line Clipping

Normal line clipping is a method of increasing drawing speed by not drawing polygons that are visible from the back. Whether something is visible from the front or from the back is determined by the sign of the Z component of the normal line screen coordinate system of the polygon.

Normal line clipping is effective when there is a closed curved surface such as that of a sphere. This is also effective in reducing the so-called Z sorting problem.

Page 139

Basic Geometry Library 9-9

Normal Line Clipping Function

The Z component of a polygon normal line screen coordinate system is found by converting the coordinates of the normal line. It may also be found by the vector product of the two sides of the polygon.

A function calculating the 2-dimensional vector product for normal line clipping, Normal Clip() is provided in the basic geometry library. NormalClip() calculates a value to distinguish between the front and back of triangles from the screen coordinates of three vertices. Front and back can be judged by whether the return value is positive or negative, but the sign will change with the direction of the coordinate axis, and the order of the vertices. Here we hypothesize a coordinate system.

Figure 9-1: Coordinate Axes

Z+

X+

eye Y+

The viewpoint is in the negative direction of the Z axis. Looking from the view point, with the three vertices arranged clockwise, NormalClip() will return a positive value.

Figure 9-2: Vertex Order

With the following performing the same calculation as NormalClip(), normal line clipping is performed, coordinate calculation is halted and an incorrect sx, sy value is returned when the vector product is negative or 0. When using these functions, the order of the vertices of a polygon must be modeled so that they will rotate clockwise when seen from the front.

RotNclip() RotNclip3() RotNclip4() RotAverageNclip3() RotAverageNclip4() RotAverageNclipColorDpq3() RotAverageNclipColorCol3()

RotNclip4() and RotAverageNclip4() are functions which perform the same calculations as NormalClip(). Since these functions use the first three points and calculate a vector product value, you must use one of the vertex orderings from Figure 8-3.

Page 140

9-10 Basic Geometry Library

Figure 9-3: Four Vertices (2) (1)

or

However, since GPU will not draw rectangles in the order indicated by (2), it is sensible to use (1).

Depth Cueing

Depth cueing is an effect that makes objects at a distance appear hazy. It is accomplished by blending the original polygon color with the far color, as a function of the Z-value of the screen coordinate system. If the far color is white, distant objects appear slightly obscured by fog. If the far color is black, distant objects appear dark.

The following depth-queuing terms are used in the PlayStation: • Back Color, BK - Ambient color set by SetBackColor() • Far Color, FC - Far color set by SetFarColor() • BG Color - The color applied in the background

To blend colors into the background with depth cueing, match the far color and the background color.

Note that back color and BG color differ.

Depth cueing methods can be broadly divided into two categories: • Using vertex colors. This method is used with non-textured polygons. It can also be used with textured polygons, in cases where

  • either the far color is black or very dark
  • The texture is relatively bright and composed only of colors close to the far color without any dark points. In this case, the object may not completely blend with the far color. • Using texture colors. This method can be used with textured polygons in general.

Implementation of Depth Cueing (Common Operations)

Interpolation coefficients The GTE can perform efficient depth cueing through non-linear interpolation of the far color. You set the depth for depth cueing by calling SetFogNear(), SetFogFar(), or SetFogNearFar().

Once the depth has been set, the non-linear interpolation coefficient p can be obtained by calling one of the RotTransPers() functions, with p having a value within the range 0 to 4096.

If Z is sufficiently small, the value of p will saturate at 0. If Z is sufficiently large, the value of p will saturate at 4096 (please refer to the descriptions for the SetFog…() functions for more information).

In general, the depth cueing interpolation calculation can be represented by

interpolation calculation (o,f,p) = ((o x p) + (f x (4096-p))) / 4096

where o is the original color, f is the far color, and p is the interpolation coefficient.

Page 141

Basic Geometry Library 9-11

If the far color is the same as the background color, rendering the polygon is unnecessary if p is 4096. For a given otz value, otz2p() can be used to obtain roughly the same value of p as the interpolation coefficient generated by GTE. Conversely, p2otz() can be used to determine otz from p. p2otz() and otz2p() are relatively expensive functions that make use of division. It is also possible for the user to specify an independent value for the interpolation coefficient p.

Method for preparing interpolated data (using CLUT or texture) Data can be prepared for different values of p beforehand or generated for specific values of p at runtime. DpqColor() is useful for interpolating colors such as these. (Use SetFarColor() to set the far color before calling DpqColor().)

Depth Cueing Using Vertex Colors

The vertex color method of depth cueing intepolates the polygon vertex colors with the far color. To use it: • Set depth using the SetFog…() functions • Call SetFarColor() to set the far color. • Use the RotTransPers…() functions to obtain the interpolation coefficient p for each vertex of each polygon. • Pass p to a function such as NormalColorDpq(), which selects a vertex screen color that has been interpolated with the far color. Besides NormalColorDpq…(), DpqColor…(), …ColorDpq() and Intpl() functions can also be used for this calculation.

Depth Cueing Using Textures

The texture method of depth cueing interpolates the texture color and the far color. The implementation method is different for each case.

What color to interpolate: • Interpolation using CLUT colors CLUT interpolation can be performed for textures that use a CLUT. • Interpolation using the colors of the texture itself

For textures that do not use a CLUT, the only option is to interpolate with the colors of the texture itself. For textures that use a CLUT, depth cueing can be applied when textures are selected according to depth (e.g. by using the mip-map method). In these cases, interpolation based on texture color can be used in conjunction with interpolation based on the CLUT.

Methods of generating interpolation data • CLUT or texture data can be generated in advance for different values of the interpolation coefficient p, then used according to the Z and p values of the polygon or object to be rendered. This method minimizes calculation time, but requires more memory to store the data, and the resolution of p cannot be very high. • CLUT or texture data can be generated at runtime for specific values of p. This method requires more calculation time during execution, but relatively little memory is needed, and p can have a high resolution.

Changing the rendered texture • Changing the coordinates referred to by the polygon (CLUT or texture) Data for different values of p are saved in free areas in the frame buffer. Depth cueing is implemented by changing the texture coordinates, the CLUT ID, the texture page ID, etc. referred to by each polygon.

Page 142

9-12 Basic Geometry Library

• Changing the CLUT or texture in the frame buffer In this method, the rendered texture is changed by substituting the CLUT or texture in the frame buffer. Since polygon packets do not need to be changed, texture depth cueing can be easily rendered using the extended graphics library (libgs).

The following three methods can be used to modify data in the frame buffer:

  • Using DR_LOAD primitives Data is set up in DR_LOAD primitives and written to the frame buffer. Large amounts of data can be divided up into multiple DR_LOAD primitives. In these cases, it is faster to divide up the data so that it is arranged as wide as possible in the frame buffer.

If one interpolation coefficient p can be used for a single CLUT or texture in a single frame, then this information is entered into the beginning of the ordering table and rendered. If multiple occurrences of p, corresponding to depth, are to be used for a single CLUT or texture in a single frame, the following operations should be performed. DR_LOAD primitives are entered into multiple places in the ordering table to transfer data for the values of p corresponding to the otz values.

In the following examples, four values of p are used. Polygons are assumed to have been entered beforehand into the ordering table using DrawOTag() or libgs.

Figure 9-4: Writing data using DR_LOAD primitives P 4096 p2 p1

otz far near OT

A a b

c d e f g i

B h D j k

l

C

Since polygons deeper than P=4096 do not merge into the background, they are not drawn. The DR_LOAD primitive is registered to the otz head when drawing is necessary.

a-1 : polygon A-D : DR_LOAD primitive A : DR_LOAD transfers (p = 4096 + p2) / 2) data B : DR_LOAD transfers (p = p2 + p1) / 2) data C : DR_LOAD transfers (p = p1 + 0) / 2) data D : DR_LOAD transfers (p = 0) / 2) data

For a value of p corresponding to a rendering range from p1 to p2, a DR_LOAD primitive (B in the Figure) for transferring data using p is entered into the otz position corresponding to p2. A DR_LOAD (C in the figure) for transferring data using the next p is entered into the otz position corresponding to p1.

Page 143

Basic Geometry Library 9-13

For example, the rendering sequence for the case shown in the figure would be

A - a - b - c - d - e - B - f - g - h - C - i - D - j - k - l

Polygons a - e would be rendered with the data transferred using DR_LOAD A, polygons f - h are rendered with the data transferred using DR_LOAD B, and so on.

  • Writing data using DR_MOVE primitives In this method, data for different values of p is written into free areas of the frame buffer. The data is transferred to the actual locations used for rendering before the polygons are rendered. As in the case with the DR_LOAD primitives above, data can be saved in the ordering table so that depth cueing can be achieved on multiple polygons using a single CLUT or texture with values of p corresponding to the depths of each of the polygons.
  • Using LoadImage() to transfer data from main memory In this method, LoadImage()is used to transfer data from main memory to the area to be used in the frame buffer. Note that using LoadImage() too often causes a heavy load on the CPU. Thus, this method is not appropriate if multiple values of p need to be used for a single CLUT or texture within a single frame.

Material Light Source Calculation with Material Quality

Light source calculation in PlayStation (without depth cueing) is summarized as follows:

1.

 L1   Nx   L2  = [ Lij ]  Ny        L3     Nz  

2.

 LTr   L1   BKr   LTg  = [ LRij ]  L2  +  BKg          LTb     L3     BKb  

3.

RR = R × LTr GG = G × LTg BB = B × LTb

Notes:

(Nz, Ny, Nz): Normal vectors [Lij]: Local light matrix (LLM) (L1,L2,L3): Local light vector (LLV) [Lri]: Local color matrix (LCM) (BKr, BKg, BKb): Back color (BK) (RLT,GLT,BLT): Local color (LC) (R, G, B): Original color vectors (RR, GG, BB): Output color vectors

Page 144

9-14 Basic Geometry Library

In this manual the calculation above is abbreviated in the following way:

  • LLV = LLM x v0
  • LC = BK + LCM x LLV
  • v2 = v1 x LC

Following the calculation of (1) you may also obtain LLV again with each item of LLV squared in the following manner:

  • LLV = LLM x v0
  • LLV = LLV = (L1 , L2 , L3 )
  • LC = BK + LCM x LLV
  • v2 = v1 x LC

If this is done, the lighted portion on screen will become narrower and the material quality of the object will appear to have changed. The basic geometry library provides • RotColorMatDpq • ColorMatDpq • ColorMatCol

as functions with material quality.

Functions with Three or Four Vertices

There are functions in the basic geometry library which perform one-off coordinate conversion of polygons with three or four vertices, and light source calculation.

For example, RotTransPers3() and RotTransPers4() functions do one-off coordinate conversion of three and four vertex polygons respectively. Also NormalColorCol3() and NormalColorDpq3() convert the 3 vertex light source calculation once.

By using these functions, triangles and rectangles with independent vertices may be drawn at high speed.

libgte Argument Format

In the GTE, all numbers are expressed in fixed-point notation. For example, each component of a rotational matrix is a (1,3,12) fixed-point number, which means: • Sign : 1 bit • Integer value: 3 bits • Fractional value: 12 bits

Because of this, RotTrans (&v0, &v1, &flag) is calculated in the following manner.

 v1.vx   v0.vx   TRx   v1.vy  = [ Rij ]  v0.vy  +  TRy          v1.vz     v0.vz     TRz  

 (R00 × v0.vx + R01 × v0.vy + R02 × v0.vz) >> 12   TRx  =  (R10 × v0.vx + R11 × v0.vy + R12 × v0.vz) >> 12  +  TRy        (R20 × v0.vx + R21 × v0.vy + R22 × v0.vz) >> 12     TRz  

Page 145

Basic Geometry Library 9-15

v1.vx = TRX + (R00 × v0.vx + R01 × v0.vy + R02 × v0.vz) >> 12 v1.vy = TRY + (R10 × v0.vx + R11 × v0.vy + R12 × v0.vz) >> 12 v1.vz = TRZ + (R20 × v0.vx + R21 × v0.vy + R22 × v0.vz) >> 12

v0, v1 are of type SVECTOR.

typedef struct{ short vx, vy; short vz, pad; } SVECTOR;

[Rij] is a rotation matrix, (TRX, TRY, TRZ) are translating vectors. Therefore the formats of V0 and V1 less than the decimal point are the same as (TRX, TRY, TRZ).

The format of (TRX, TRY, TRZ) is (1, 31, 0), so that v0 is (1, 15, 0) and v1 is (1, 31, 0).

Recommended Format

The recommended format for GTE constants is shown below. Though formats other than this may be calculated, it becomes difficult and it must be taken into account that a 12-bit shift is built into the GTE. Please refer to the libgte reference manual for the argument format of each function.

Table 9-1: Recommended Format for GTE Constants Item Bit Format Rotational matrix [Rij] Translating vector (TRX, TRY, TRZ) Local light matrix [Lij] Local color matrix [L (R, G, B) i] Back color (RBK, GBK, BBK) Far color (RFC, GFC, BFC) (1, 3, 12) (1, 31, 0) (1, 3, 12) (1, 3, 12) (0,32,0)(0...255) (0,32,0)(0...255)

Libgte Function Flag Variables

Flag variables are returned by the following coordinate calculation functions for performing clipping:

RotTransPers(), RotTransPers3(), RotTrans(), RotTransPers4(), RotAverage3(), RotAverage4(), RotNclip(), RotNclip3(), RotNclip4(), RotAverageNclip3(), RotAverageNclip4(), RotColorDpq(), RotColorDpq3(), RotAverageNclipColorDpq3(), RotAverageNclipColorCol3(), RotColorMatDpq()

The flags return to their original state immediately after the functions have finished their coordinate transformations.

Functions doing coordinate transformations on 3 or 4 vertices, such as RotTransPers3() or RotTransPers4(), return an OR of the coordinate transformation result for each vertex. When RotNclip4() or RotAverageNclip4() return a value of -1 (that is, when a vertex cannot be calculated due to a normal clip) it is treated as if it were an OR of the result from a 3-vertex coordinate transformation.

The flag bits are as follows:

Table 9-2: Flag Bit Settings

Bit Contents

  • | (29) | (28) | (27) | (26) | (25) | (24) | (23) | (18) | (17) | (16) | (15) | (14) | (13) | (11) Calculation overflow (>=2^43) Calculation overflow (>=2^43)
Page 146

9-16 Basic Geometry Library

Bit Contents

11~0 Calculation overflow (>=2^43) Calculation overflow (<-2^43) Calculation overflow (<-2^43) Calculation overflow (<-2^43) The output value exceeds (-2^15, 2^15) The output value exceeds (-2^15, 2^15) The output value exceeds (-2^15, 2^15) Output value exceeds(0, 2^8) Output value exceeds (0, 2^8) Output value exceeds (0, 2^8) The value of Z in the screen coordinate system exceeds (0, 2^16) The Z coordinate is smaller than h/2 after perspective transformation* Calculation overflow (>=2^32) Calculation overflow (<-2^32) The X coordinate exceeds (-2^10, 2^10) after perspective transformation The Y coordinate exceeds (-2^10, 2^10) after perspective transformation The value of p exceeds (0, 2^12) Not used

  • h is the distance between the viewpoint and the screen.

The following functions return 16-bit flags: RotTransPersN(), RotTransPers3N()

The 16-bit flag bits are as follows:

Table 9-3: 16-Bit Flag Bit Settings Bit Contents Calculation overflow (>=2^43) Calculation overflow (>=2^43) Calculation overflow (>=2^43) The value of X in the screen coordinate system before perspective transformation exceeds (-2^15, 2^15) The value of Y in the screen coordinate system before perspective transformation exceeds (-2^15, 2^15) The value of Z in the screen coordinate system exceeds (-2^15, 2^15) Output value exceeds (0, 2^8) Output value exceeds (0, 2^8) Output value exceeds (0, 2^8) The value of Z on the screen coordinate system exceeds (0, 2^16) The Z coordinate is smaller than h/2 after perspective transformation* Calculation overflow (>=2^32) Calculation overflow (>=2^32) The X coordinate exceeds (-2^10, 2^10) after perspective transformation The Y coordinate exceeds (-2^10, 2^10) after perspective transformation The value of p exceeds (0, 2^12)

  • h is the distance between the viewpoint and the screen.
Page 147

Basic Geometry Library 9-17

About libgte Mesh Functions

The basic geometry library supports two types of triangular mesh data. By using mesh data, the number of vertex calculations and the volume of data can be reduced.

One is called Strip Mesh and the vertices are arranged in zig-zags as shown below:

Figure 9-5: Strip Mesh

The other is called Round Mesh and the vertices surround vertex 0 as shown below:

Figure 9-6: Round Mesh

In either case, when the first triangle 012 is clockwise in this order, 012 is displayed and the fronts and backs of the other three triangles will be determined by this triangle.

However, when performing light source calculation (shading and depth cueing) with this type of data, normal line clipping cannot be performed so the calculation is not always speeded up. Mesh data is effective in improving calculations with “no shading and depth cueing” and “flat shading.”

Changing Screen Offsets

There are two methods for altering the PlayStation screen offset. One is to use the libgpu function SetDefDrawEnv(). The other is to use the SetGeomOffset() function provided in the basic geometry library.

PMD Functions

Libgte has PMD functions that link GPU packets to the created OT, after they perform coordinate transformations, when reading the data formats shown below. GPU packet data is preset for constants, color variables, texture variables, and the like, so drawings can be done at high speed if just the coordinate variables are set.

PRIMITIVE Group

In PMD data, when polygons having the same attributes are grouped together and the PRIMITIVE Gp object components (primitives) drawing packet is drawn up, one packet represents one primitive.

A primitive defined in PMD is different from a libgpu primitive. Together with the processing of the perspective conversion by libgs it is also converted to the drawing primitive.

Page 148

9-18 Basic Geometry Library

One primitive group is shown below.

Figure 9-7: PACKET Gp Configuration

bit31(MSB) bit0(LSB)

TYPE NPACKET Packet Data #0 Packet Data #1 Packet Data #2 : NPACKET:Number of packets TYPE : Packet type

Table 9-4: 4-Type Bit Configuration

bit No. When 0 When 1

22-31 Triangle Flat Texture-On Independent Vertex Light Source Calculation OFF With Back clip (Reserved) Quadrilateral Gouraud Texture-Off Public Vertex Light Source Calculation ON No Back clip

The Packet Data configuration changes with the TYPE value. The separate TYPE Packet Data configuration is as follows:

Note 1: In order to make the Primitive section (POLY_***) in the configuration correspond to the double buffer, two sets are provided.

Both contents must be initialized beforehand.

Note 2: Bit 20,21 have no effect on the Packet Data configuration.

TYPE Packet Data Configurations

TYPE=00 (Triangle/Flat/Texture-On/Independent Vertex) struct _poly_ft3 { POLY_FT3 pkt[2]; SVECTOR v1, v2, v3; }

TYPE=01 (Quadrilateral/Flat/Texture-On/Independent Vertex) struct _poly_ft4 { POLY_FT4 pkt[2]; SVECTOR v1, v2, v3, v4; }

TYPE=02 (Triangle/Gouraud/Texture-On/Independent Vertex) struct _poly_gt3 { POLY_GT3 pkt[2]; SVECTOR v1, v2, v3; }

Page 149

Basic Geometry Library 9-19

TYPE=03 (Quadrilateral/Gouraud/Texture-On/Independent Vertex)

struct _poly_gt4 { POLY_GT4 pkt[2]; SVECTOR v1, v2, v3, v4; }

TYPE=04 (Triangle/Flat/Texture-Off/Independent Vertex)

struct _poly_f3 { POLY_F3 pkt[2]; SVECTOR v1, v2, v3; }

TYPE=05 (Quadrilateral/Flat/Texture-Off/Independent Vertex)

struct _poly_f4 { POLY_F4 pkt[2]; SVECTOR v1, v2, v3, v4; }

TYPE=06 (Triangle/Gouraud/Texture-Off/Independent Vertex)

struct _poly_g3 { POLY_G3 pkt[2]; SVECTOR v1, v2, v3; }

TYPE=07 (Quadrilateral/Gouraud/Texture-Off/Independent Vertex)

struct _poly_g4 { POLY_G4 pkt[2]; SVECTOR v1, v2, v3, v4; }

TYPE=08 (Triangle/Flat/Texture-On/Shared Vertex)

struct _poly_ft3c { POLY_FT3 pkt[2]; long vp1, vp2, vp3; }

TYPE=09 (Quadrilateral/Flat/Texture-On/Shared Vertex)

struct _poly_ft4c { POLY_FT4 pkt[2]; long vp1, vp2, vp3, vp4; }

TYPE=0a (Triangle/Gouraud/Texture-On/Shared Vertex)

struct _poly_gt3c { POLY_GT3 pkt[2]; long vp1, vp2, vp3; }

TYPE=0b (Quadrilateral/Gouraud/Texture-On/Shared Vertex)

struct _poly_gt4c { POLY_GT4 pkt[2]; long vp1, vp2, vp3, vp4; }

Page 150

9-20 Basic Geometry Library

TYPE=0c (Triangle/Flat/Texture-Off/Shared Vertex)

struct _poly_f3c { POLY_F3 pkt[2]; long vp1, vp2, vp3; }

TYPE=0d (Quadrilateral/Flat/Texture-Off/Shared Vertex)

struct _poly_f4c { POLY_F4 pkt[2]; long vp1, vp2, vp3, vp4; }

TYPE=0e (Triangle/Gouraud/Texture-Off/Shared Vertex) struct _poly_g3c { POLY_G3 pkt[2]; long vp1, vp2, vp3; }

TYPE=0f (Quadrilateral/Gouraud/Texture-Off/Shared Vertex) struct _poly_g4c { POLY_G4 pkt[2]; long vp1, vp2, vp3, vp4; }

The pkt[] is the corresponding drawing primitive packet, the v1~v4 values are the vertex coordinate values, and the vp1~vp4 values are the offsets from the head of the shared coordinates string.

VERTEX

The VERTEX section is the SVECTOR structure array which displays the shared vertex. One structure format is shown below:

Figure 9-8: VERTEX

M SB L SB

VY VX

VZ

VX,VY, VZ: x,y,z values of vertex coordinates (16 bit integers)

SMD, RMD Functions

The SMD and RMD functions are high-speed versions of the PMD function. They both process the same data format as the PMD function. The SMD function usually performs normal clipping, while the RMD function usually does not.

Page 151

Basic Geometry Library 9-21

Polygon Division

The PlayStation is designed to form many small polygons efficiently. When larger polygons are broken down into smaller ones using division, clipping is performed more efficiently, and texture distortion is reduced.

The polygon division process uses the automatic division attribute of libgs that is applied to objects, or it can be invoked by directly calling one of the functions listed below.

Table 9-5: Polygon Division Functions Function name Corresponding primitive DivideF3 DivideF4 DivideFT3 DivideFT4 DivideG3 DivideG4 DivideGT3 DivideGT4 Flat Triangle Flat Quadrilateral Flat Texture Triangle Flat Texture Quadrilateral Gouraud Triangle Gouraud Quadrilateral Gouraud Texture Triangle Gouraud Texture Quadrilateral

Page 152
Scan of page 152

This page is a drawing, shown as the original scan.

Page 153

Chapter 10: Extended Graphics Library

Table of Contents

Overview Library and Header Files Libgs features 10-3 10-3 10-3

Coordinate Systems Order of Rotation/Translation Clearing Flags Examples of Coordinate System Setting 10-4 10-4 10-5 10-5

Objects 10-5 10-6 10-6 10-6 Object Initialization Object Movement (Hierarchical Structuring) Object Attribute Control

Viewing System Viewpoint Setting Screen Setting 10-6 10-6 10-7

Light Sources Parallel Light Ambient Light Depth Cueing Material Lighting 10-7 10-7 10-7 10-8 10-8

Drawing Priority Order (Ordering Table) GsOT and GsOT_TAG OT Initialization Multiple OTs OT Compression Z-Sort Problem OT Double Buffer 10-8 10-8 10-9 10-9 10-9 10-9 10-9

Frame Double Buffer Double Buffer Expression Frame Double Buffer During Interlace 10-10 10-10 10-10

Clipping Two-dimensional Clipping Three-dimensional Clipping Near Clipping Problem 10-10 10-11 10-11 10-11

Packet Preparation Function Packet Buffer Preset Packets TMD Sort Packet Creating Functions 10-11 10-11 10-12 10-13 10-13

Page 154

10-2 Extended Graphics Library

Packet Area Packet Double Buffer 10-14 10-14

Drawing Processing Flowchart 10-15 10-15

Jump Tables Purpose Usage 10-15 10-15 10-16

Scratch Pad Usage Volume Scratch Pad Consumption Status Scratch Pad Consumption Volume Method for Common Use of Scratch Pad by the User Program and Library 10-16 10-17 10-17 10-17

Mip-map Library Usage Method Texture Location Polygon Vertex 10-17 10-17 10-19 10-19

Page 155

Extended Graphics Library 10-3

Overview

The extended graphics library (libgs) integrates the 2D and 3D graphics systems used in libgpu and libgte. It is designed to work well with the standard graphics file formats that can be created by PlayStation authoring tools: • The TIM format stores image resolution, color numbers and color look-up table information. • The TMD format stores multiple objects, scale information and texture address information. • HMD is a new format that was added in version 4.0 of the libraries. See Chapter 18, “HMD Library”, for more information about this format.

In contrast with the libgpu and libgte libraries which process polygon-level data, libgs processes data by object units (groups of polygons), allowing 3D programs to be prototyped easily. By adding attributes to objects, it’s easy to create special effects.

Using libgs involves extra overhead compared to using libgpu and libgte. However, libgs is an open architecture. Therefore, once you are ready to produce your game, you can optimize it by adding userdefined functions (via a jump table) that use libgpu and libgte services.

Library and Header Files

To use the extended graphics library, you must link with the library file libgs.lib.

Source code must include the header file libgs.h.

Libgs features

The main features of libgs are: • Hierarchical coordinate systems Any object’s coordinate system can be designated as a parent or a subordinate of another. Changes to the parent coordinate system are automatically applied to the subordinates. • Light source calculation (3 light sources, depth queuing, ambient) Libgs performs automatic lighting calculations using parameters set by the user. • Automatic division of polygons Libgs can automatically sub-divide large polygons to avoid problems associated with clipping. • Semi-transparent processing Objects and/or their textures can be drawn as semi-transparent/translucent by setting the appropriate attributes • Perspective texture mapping of objects. • Viewpoint control You can easily manipulate the viewing angle using the view structures defined within libgs. • Z-sort processing You can sort and draw objects according to their Z-depth values by using the GsOT structure and the GsSort functions. • OT initialization hierarchic compression Objects with greatly differing Z values may be sorted into separate OTs (Z-sort ordering tables) and then linked into one OT prior to drawing.

Page 156

10-4 Extended Graphics Library

• Frame double buffer Libgs implements a graphics double-buffer system , in order to avoid the problems associated with drawing into memory being displayed. Initialization and switching of the buffers are easily performed. • Automatic adjustment of aspect ratio When the view aspect ratio is not normal dot, the display of an object’s vertical is automatically adjusted to appear as a normal dot aspect ratio. • 2D clipping offset processing Libgs performs 2D clipping according to values set by the user. In addition, you can define a 2D offset, which will be added to the screen coordinates of all objects prior to display. • Sprite/BG/Line Libgs provides structures and routines for easily displaying 2D sprites, lines, and cell-based scrolling backgrounds. • libgpu/libgte coexistence Libgs combines Libgs(2D) and Libgte(3D) into a complete, easy to manage, 3D graphics pipeline.

Coordinate Systems

GsCOORDINATE2 is a structure describing a libgs coordinate system. The coordinate system is a hierarchical structure which takes the world coordinate system as the most significant, and it is integrated from a lower level to a higher level.

GsCOORDINATE2’s members describe the coordinate system and a work area for speeding up coordinate calculations. The MATRIX parameters describe the coordinate system relative to its parent coordinate system. For the size of the coordinate system space, X, Y and Z are all 32 bits.

The definition of the GsCORDINATE2 is as follows:

struct GsCOORDINATE2{ unsigned long flg;

MATRIX coord;

MATRIX workm;

GsCOORD2PARAM *param;

GsCOORDINATE2 *super; GsCOORDINATE2 *sub; /*0: coord has been rewritten 1: workm values are still valid*/ /*A 3 x 3 matrix containing coordinate rotation, translation, and scale info*/ /*Result of multiplication of coord with the WORLD coordinate system*/ /*rotation, scale, and translation parameters*/ /*pointer to superior coordinate system*/ /*pointer to subordinate coordinate system*/ };

GsInitCoordinate2() initializes the members of GsCOORDINATE2. You can also set the members directly.

Order of Rotation/Translation

Rotation is executed first, followed by translation.

The order of rotation,when the rotation matrix is created by the function RotMatrix() and set in GsCOORDINATE2, is [Z --> Y --> X].

Page 157

Extended Graphics Library 10-5

Clearing Flags

When requesting local-to-world matrix from the hierarchical coordinate system, optimization is accomplished by setting the flg member of a previously calculated coordinate system to 1 and preserving the results stored in the member workm.

If the parameters of a GsCOORDINATE2 have been rewritten, always remember to set flg to zero, indicating that the contents of workm have already been used. Recalculation will not be performed unless flg is zero.

If parent coordinates are modified, this is automatically reflected in all of the child coordinates, so there is no need to clear the child coordinate’s flag.

Examples of Coordinate System Setting

Examples of translation and rotation are presented below.

Example 1: Translation GsCOORDINATE2 sample_coord; int x,y,z; /*coordinate system which sets translation */ /*amount of parallel shift*/

sample_coord.coord.t[0] = x; sample_coord.coord.t[1] = y; sample_coord.coord.t[2] = z;

Example 2: Rotation GsCOORDINATE2 sample_coord;

SVECTOR rot; MATRIX tmp1; /*coordinate system in which rotation is set */ /*rotation angle set (x,y,z)*/ /*rotation matrix requested*/

RotMatrix(&rot, &tmp1); /*when RotMatrix() is used the order of rotation is zyx*/ sample_coord.coord = tmp1;

Objects

You manipulate objects by means of 3D object handlers. This section explains the basic object handler used by libgs, GsDOBJ2. The other types of object handlers are GsDOBJ3 and GsDOBJ5.

GsDOBJ2 is defined as follows:

struct GsDOBJ2{ unsigned long attribute; GsCOORDINATE2 *coord2; unsigned long *tmd; unsigned long id; }

coord2 is a pointer to the coordinate system. An object’s location may be controlled by setting the members of the corresponding GsCOORDINATE2 structure.

attribute is for setting object attributes: general attributes such as display/non-display or special effects such as switching of the light source calculation method. See the explanation of GsDOBJ2 in the Run-Time Library Reference for details.

Page 158

10-6 Extended Graphics Library

Object Initialization

Handling an object with GsDOBJ2 requires linking the handler with the read-in TMD data. To do this, you can use GsLinkObject4(), which sets the GsDOBJ2’s tmd member to the address of the TMD object to be linked to it.

Object Movement (Hierarchical Structuring)

Different objects may be linked by defining a hierarchy in the coordinate system in which an object’s member coord2 is specified as subordinate to another object’s GsCOORDINATE2.

In the following figure, Object 1 is defined as the super coordinate system of Object 2:

Table 10-1: Hierarchical Structuring

GSDOBJ2 COORDINATE2 Object1 Coordinate1

Object2 Coordinate2

When Object 1 moves, the location of object 2 is affected as well. When Object 2 moves, Object 1’s location is not affected.

Object Attribute Control

The bits of the GsDOBJ2 attribute member control several properties of objects, such as material attenuation, lighting mode, near clipping, back clipping, and automatic division. See the description of GsDOBJ2 in the Run-Time Library Reference for more detailed information.

Viewing System

In 3D graphics, the image displayed on the two-dimensional screen is a projection of 3D space onto a “window” (viewing-plane), at a specified distance in front of the viewpoint. The viewpoint and “window” value must be set in order to project an image.

Viewpoint Setting

The viewpoint is set by substituting values in the GsRVIEW2 or GsVIEW2 structure members and calling GsSetRefView2() or GsSetView2().

The difference between GsRVIEW2 and GsVIEW2 is in the viewpoint setting method.

GsRVIEW2 sets the viewpoint by setting the coordinates of the viewpoint and a reference point. GsVIEW2 sets the viewpoint by directly setting a transformation matrix to the viewpoint coordinate system.

Both GsVIEW2 and GsRVIEW2 can set a coordinate system which becomes the standard in super. For example, if the standard coordinate system is treated as a world coordinate system, it becomes an objective viewing camera, and if the coordinate systems of each object are taken as local coordinate systems, it becomes a subjective viewing camera for that object.

Page 159

Extended Graphics Library 10-7

Screen Setting

The distance between the viewpoint and the screen is called projection (h). Projection is set by the GsSetProjection() function.

The vertical and horizontal of the screen are equal to the current display resolution. For example, if the display resolution is 640/480, the horizontal of the screen is 640 and the vertical is 480.

When the display resolution is not normal dot (4 to 3 aspect ratio) the vertical is adjusted. For example, in the case of 640/240 dot, the vertical of an object is displayed by reducing it by 1/2. In appearance, this is the same as a normal dot aspect ratio.

To use the libgs three-dimensional service, it is necessary to execute the GsInit3D() function and initialize the screen coordinates. In this way, the center of the screen is the origin of the screen coordinates.

Figure 10-1: Viewpoint and Screen

Visual point

h Projection

Screen

Projection adjusts the angle of an image. If projection is large, the image angle is narrow and is close to parallel projection. If projection is small, the image angle widens, and it becomes a picture in which the impression of perspective is emphasized.

Light Sources

Parallel Light

Libgs allows a maximum of 3 parallel light sources. With a parallel light source, the brightness of a polygon is determined only by the light source and the angle of the polygon. A light source is set by the direction of the light source and its color.

A light source is specified in the system by setting the members of a GsF_LIGHT structure and calling GsSetFlatLight().

Ambient Light

Ambient light is the surrounding light. Even though light does not directly strike it, the shape of an object may be seen with the surrounding light. Ambient light is created in order to achieve this type of phenomena.

For example, if the spot where the light strikes is 1 and spots where the light does not strike are 0.5, GsSetAmbient() is executed as follows (ONE expresses the fixed-point 1):

GsSetAmbient(ONE/2,ONE/2,ONE/2);

In general, the image becomes warm when the ambient light values are increased and cool when they are decreased.

Page 160

10-8 Extended Graphics Library

Depth Cueing

When varying the brightness of an object according to the distance from the viewpoint, distant objects may be dimmed. This is called depth cueing or fog.

Depth cueing may be executed normally for all non-textured polygons. It is possible for texture-mapped polygons only when the color is black.

To use depth cueing, call GsSetLightMode(1) or GsSetLightMode(3) to set cueing on. Then call GsSetFogParam(), passing a GsFOGPARAM structure specifying background colors.

When the background colors are made whitish, the result is the fog effect. When they are made black, there is a “night-time” effect. This is effective in making something like a dungeon difficult to see by darkening the distance.

Depth cueing can be performed on texture-mapped polygons at any time by switching the length of the CLUT. This method is not currently supported in libgs.

Moreover, please be aware that background color and ambient color are generally quite different.

Material Lighting

The intensity of light is determined by the angles of the polygon and the light source. However, the feel of a material can be changed to metallic by making the light attenuation curve steeper. This is called material lighting.

Call GsSetLightMode(2) or GsSetLightMode(3) to execute material lighting.

Attenuation is controlled by setting the material attenuation bit of the GsDOBJ2 member attribute, object by object. The higher the value, the steeper the attenuation and the more the metallic feel increases.

However, this is not possible with the current version.

Drawing Priority Order (Ordering Table)

The PlayStation uses Z-sorting as a method of hidden-surface removal. To speed up the performance of Z-sorting, the concept of an ordering table (OT) has been introduced. Hereafter, Z refers to a coordinate value on the axis perpendicular to the view plane; in other words, the distance between the screen and the polygon.

An ordering table is a kind of Z ruler applied in memory. Each graduation of the ruler may hold any number of polygons.

Polygons are sorted by placing them at the graduation equivalent to their Z value. This means that if polygons are placed all the way up to the end, all the polygons will hang on the ruler according to their Z values. Hidden-surface removal is achieved by transmitting this to a rendering chip and drawing the polygons at the end of the OT (with the largest Z value) first.

GsOT and GsOT_TAG

Ordering tables are handled in libgs by the GsOT structure, which stores a pointer (member org) to an actual OT and parameters that indicate the attributes of that OT. The member length represents the Z graduation resolution as a power of 2 (from 1 to 14). For example, if length is 4, the OT has 2^4 graduations. Each graduation is represented by a GsOT_TAG structure.

Page 161

Extended Graphics Library 10-9

OT Initialization

An OT is initialized by the function GsClearOt(). GsClearOt() takes 3 arguments, offset, point and otp. otp is a pointer to the OT handler. offset and point are explained below.

When an OT is initialized, the polygons are unlinked, and only then is a re-sort possible. Therefore, it is always necessary to initialize an OT prior to executing a sort.

Multiple OTs

libgs allows multiple Ots, which may be sorted by the GsSortOt() function. The GsOT member point refers to the representative value Z of an OT.

It is possible to control the sorting order by using multiple OTs. For example, if local OTs are prepared object by object, and finally collated by sorting the local OTs, sorting by object units is possible.

This is effective when the relationship between before and after is already known, in such cases as when a helicopter is looking down from above at cars which are being driven on a road.

Also, multiple OTs can also be used to achieve a “split-screen” effect. For example, by drawing one OT to the top half of the drawing area, switching the drawing environment and viewpoint settings, and drawing the second OT to the bottom half of the drawing area, two different views can be shown onscreen simultaneously.

OT Compression

Sort speed will be increased by using OTs. However, OTs consume a considerable amount of memory.

Memory consumption can be reduced by decreasing OT resolution. However, this can cause a polygon flicker phenomenon (Z-sort problem) due to errors in Z relationships.

Therefore, there is a method of using an offset to reduce OT memory usage without reducing resolution. If it is known that the Z values of the polygons to be sorted are greater than a certain value, this value can be passed to GsClearOt() as offset. The OT will not store the part up to offset in memory; therefore, memory consumption will be reduced.

Z-Sort Problem

When using Z-sort to perform hidden-surface removal, polygons can flicker because of errors in priority ordering. This phenomena is likely to occur with a polygon of particularly long depth, because its Z value varies greatly across the polygon, but it is sorted with only one average Z value (the center of gravity).

The Z-sort problem can be resolved by dividing polygons into smaller polygons; however, this has the drawbacks associated with an increased number of polygons.

Another countermeasure is to sort by object units. When the Z relationship is clear for every object, if this condition is reflected when sorting, sorting may be achieved without mutual interference of objects.

OT Double Buffer

An OT in which polygons are linked cannot be accessed while it is being drawn. For this reason, you must use a double buffer technique of preparing 2 OTs when drawing in the background. You sort the OT that is not being used for drawing.

Page 162

10-10 Extended Graphics Library

Frame Double Buffer

The PlayStation has a two-dimensional frame buffer, and the image displayed in the window can be reproduced in video memory as is.

The screen can be switched without being disturbed during vertical synchronization (V Blank). If the switched screen is accessed during the time when the television screen is being displayed, the screen will become disturbed.

Due to this both the screen being displayed and the switched screen are necessary. This is called the display double buffer.

In libgs ,the double buffer is defined by GsDefDispBuff().GsSwapDispBuff() switches the buffers. GsGetActiveBuff() can be used to determine which double buffer is currently being drawn.

Double Buffer Expression

Double buffering may be achieved by altering the location of the display area in the frame buffer. The upper left point of the display area (starting point) does not necessarily have to be in the upper left point of the frame buffer.

Drawing that goes to the frame buffer must have an offset attached. You may choose from two methods of offsetting with libgs, determined by the third argument of GsInitGraph(): • Put the offset at the libgte level. The double buffer offset is added at the stage where the packet calculation is being made. • Place the offset at the libgpu level. The offset is added at the stage where a frame buffer not attached to the packet is drawn.

If you are planning on using this in combination with libgpu functions, using the latter method, placing the offset at the libgpu level, is recommended. Using the former method, compatibility with other than previous versions cannot be assured.

Frame Double Buffer During Interlace

In interlace mode, you can specify a vertical resolution of 480. In this case, double-buffering is automatic between even- and odd-numbered scan lines. Therefore, you designate the same buffers as the GsDefDispBuff() arguments.

When vertical resolution is specified as 240 during interlace mode, it is necessary to set different buffers, as you do in non-interlace mode.

Clipping

Libgs supports the following kinds of clipping: • Two-dimensional clipping is clipping after transforming the screen coordinate system. • Three-dimensional clipping is clipping according to the distance from the viewpoint.

Page 163

Extended Graphics Library 10-11

Two-dimensional Clipping

The GPU can designate any rectangle in the frame buffer as a clipping area.

The clipping area is registered in the libgs internal variable set by the GsSetClip2D() function. GsSetDrawBuffClip() sets the internal contents of the variable and makes them effective.

Also, when switching double buffers, switch the clipping area so that an overflowing polygon does not destroy another buffer.

Three-dimensional Clipping

Libgs supports default values for three-dimensional clipping. Any other clipping must be performed at the application level. The three-dimensional clipping default values are as follows: • FAR CLIP - When the screen coordinate system Z value is greater than 65536, the Z value can be clipped (because the Z value is uncoded 16-bit). • NEAR CLIP - When the screen coordinate system Z value is less than h/2, the Z value can be clipped (h is projection).

Near Clipping Problem

The near clipping problem occurs when polygons approach the viewpoint, such as in the road surface of a racing game, and become extremely large due to their nearness. When clipped by polygon units, large holes appear in the road surface close to the viewpoint, and this makes viewing difficult.

As a solution to this problem, libgs supports automatic division of polygons. When an approaching object reaches the near clipping plane, near clipping can be performed smoothly by the setting of the automatic division attribute. However, since the load from automatic division is heavy, use it only when absolutely necessary.

Packet Preparation Function

libgs has three kinds of packet creation functions, GsSortObject3(), GsSortObject4(), and GsSortObject5(). Each of these functions is an appropriate choice under different conditions.

Packet Buffer

There are two types of packet buffer: • Preset packet buffer • Run-time packet buffer

The Preset packet buffer (1) is essential when using the Preset packet buffer object. The object type which uses the preset packet is the GsSortObject5() function which uses GsDOBJ5. The size of the present packet is fixed by the model.

Using the GsPresetObject() return value it is possible to find out how far the buffer has been preset. Initially one preset is necessary.

Since the preset packet creates the packet in the preset buffer area, it does not use up the run-time packet buffer.

However, when automatic division is set to ON in the GsDOBJ5 attribute, the packet created does consume the run-time packet buffer.

The Run-time packet buffer (2) is the buffer used when a packet is created during execution.

Page 164

10-12 Extended Graphics Library

GsSortObject4(), GsSortSprite, etc. use this buffer.

The head of the buffer is specified by GsSetWorkBase() and when GsSortObject4() is called, the packet is created in that area and the current packet area pointer is taken by GsGetWorkBase().

The amount of the buffer used per frame will increase or decrease depending on the number of polygons calculated.

Preset Packets

Preset packets are packets that have been made ahead of time. If preset packets are used, it is not necessary to rewrite every frame. Speed is improved by not having to perform tasks like writing U, V texture values to memory.

PMD format is an exclusive preset packet modeling format which incorporates both modeling data and preset packets. GsSortObject5() is the packet creation function for preset packets.

The packet is a collection of structures (primitives) such as libgpu POLY_FT4. The primitive class can be determined by looking at its type.

To set tpage, set the tpage of the packet structure tpage (if the packet is POLY_FT4, set the tpage of the structure POLY_FT4).

Figure 10-2: Preset Packet Format

header 0 header0: 32 bits. The upper eight bits indicate the preset packet type. The low er 24 bits are a header 1 pointer to the next packet group. header1: Indicates the num ber of preset packets in the packet group. The packet group is preset com posed of packets of the sam e type. packets preset packets: The num ber of preset packets uses double the num ber of packets to provide a packet double buffer.

header 0

header 1

preset

packets

terminator term inator: The address section is all zeros.

Page 165

Extended Graphics Library 10-13

TMD Sort

TMD format modeling data allows the setting-up of random polygons. In realtime, when random polygon types appear that create packets from TMD data and which are subsequently converted, the decode routine is swapped out of the I cache and the processor is unable to keep up.

This is the reason for a TMD data high speed technique for ordering polygons. This technique is the TMD sort.

The GsSortObject4() or GsSortObject5() packet-creating functions are faster if they use sorted TMD data.

TMD sort is carried out at the authoring level. TMDSORT.EXE is the conversion command. See Data Conversion Utilities for details on using this command.

Packet Creating Functions

GsSortObject3() GsSortObject3() creates PMD format packets. It uses the object handler GsDOBJ3. For GsDOBJ3 to handle PMD data, GsLinkObject3() must be called first to link the PMD data and the handler.

The PMD format combines the modeling data and preset packet.

The conversion of TMD to PMD takes place at the authoring level. TMD2PMD.EXE is the conversion tool. See Data Conversion Utilities for details.

GsSortObject4() GsSortObject4() is the most generic object calculation routine. It uses sorted TMD format data for greater speed. The TMD data sort is carried out by the tmdsort.exe command. The object handler GsDOBJ2 is used.

For GsDOBJ4 to handle the TMD data, GsLinkObject4() must be called first to link the TMD data and the handler.

GsSortObject4() uses the preset local/screen matrix and the local/screen light matrix as a reference. The object is local screen converted, sorted and allocated to the OT.

The local/screen matrix is set by GsSetLsMatrix(). Local/screen light matrix setting is performed by GsSetLightMatrix().

The polygons allocated to OT are drawn by GsDrawOt(). This drawing function can return quickly, and drawing may be done in the background.

GsSortObject5() GsSortObject5() is a packet creation function that uses preset packets. It uses sorted TMD format data to increase speed. GsSortObject5() uses the object handler GsDOBJ5. TMD data sort is carried out in the tmdsort.exe command. For GsDOBJ5 to handle the TMD data, GsLinkObject5() must be called first to link the TMD data and the handler.

GsSortObject5() uses GsPresetObject() to create preset packets. For GsSortObject5() to create a packet, GsPresetObject() must be initialized once and a preset packet created.

Page 166

10-14 Extended Graphics Library

Packet Creation Function The functionality of each packet creation function is shown below.

Table 10-2: Packet Creation Function Comparison Chart 1

A B C D E F G H I GsSortObject3 GsSortObject4 GsSortObject5 GsDOBJ3 GsDOBJ2 GsDOBJ5 X X X X O O X O O X X X X X X X O X X O O 250K ? 220K

A. OBJTYPE - Object handler used B. Material attenuation - (See attribute) C. FOG - (See attribute) D. Light source calculation off - (See attribute) E. NearZ CLIP - (See attribute) F. Back CLIP - (See attribute) G. Semi-transparency rate - (See attribute) H. Automatic division - (See attribute) I. Efficiency - 10x10 (Real measurement value of a flat triangle)

GsSortObject4 is more efficient than GsSortObject3 and less efficient than GsSortObject5

Table 10-3: Packet Creation Function Comparison Chart 2

GsSortObject3 GsSortObject4 GsSortObject5 Presort Preset Preshade WorkBase Tools OK OK OK OK NG OK OK OK/NG OK/NG NG OK NG(normal) OK(autodivision) Tmd2pdm rsdlink, TMDSORT rsdlink, TMDSORT

Packet Area

GsSortObject4() creates the packet and allocates it to the ordering table.

The packet creation area is set by the GsSetWorkBase() function.

Packets increase and decrease depending on the type and number of polygons (flat/gouraud, with/without texture). Only a rough estimate can be made of how much area should be maintained. If the area of an actual packet is smaller than the packet created, it will destroy the area behind the packet area.

GsGetWorkBase() is a function to return the area currently available for use by a packet. A program may use this function to estimate the danger of overflow.

It is not necessary to use GsSetWorkBase() to maintain a new packet area when using GsSortObject5(), because the packet area for the preset packet area may be reserved.

You must define a packet area with GsSetWorkBase() when using automatic division, because a packet that has been divided and increased in size may use the packet area set aside by GsSetWorkBase().

Packet Double Buffer

Drawing is executed in the background, so the packets in a drawing cannot be destroyed. Consequently, it is necessary to prepare two packet areas to make a double buffer.

Page 167

Extended Graphics Library 10-15

Drawing

Call the GsDrawOt() function to begin drawing. The drawing area is swapped each time GsSwapDispBuff() is called. Drawing occurs in the background so sufficient time must be allowed to complete the operation.

During the drawing process images from the previous two frames that remain in the drawing area are cleared. Call GsSortClear() to register the “screen-clear” Special Primitive to the OT before clearing the screen. The cleared screen color may be specified as an RGB value in the arguments to the function.

Processing Flowchart

A typical flowchart of 3D processing required for each frame is shown below. See the sample program for details.

Figure 10-3: Three-dimensional Processing Flowchart

Select the buffer to use

Clear OT

Perspective transformation/Z sort ( record command to OT)

V-blanking sync

Start OT drawing

Jump Tables

Purpose

GsSortObject5(),GsSortObject4() dispatches attributes, pre-set data, etc. and calls low-level functions.

There are 64 low-level functions, and a single application is unlikely to use all of them.

You don't need to link GsSortObject5J() and GsSortObject4J() with unnecessary low-level functions, thereby making the code more compact.

In addition to decreasing code size, the GsSortObject…J functions allow the user to customize Libgs. Support for non-standard actions, such as material attenuation, reflection-mapping, etc can be added to the Libgs, by linking user defined functions in place of the library function.

These functions are compatible with GsSortObject5() and GsSortObject4(), which organize low-levell functions as tables.

GsFCALL is the structure in which the function table is defined. The function table is organized according to polygon type, whether or not division is performed, and the light-source calculation mode.

Page 168

10-16 Extended Graphics Library

Usage

The relevant functions are linked by entering the pointers of the appropriate low-level functions in each of the elements. It is possible to avoid linking by not including the pointers and not making extern declarations.

However, if a function that does not have a pointer is called, a BUS ERROR will be generated. To avoid this, Libgte provides dummy (dmy…) functions. With these linked, if a call is made with an unanticipated type, the appropriate dummy function will print its name to standard out.

The abbreviated example below, shows the use of GsSortObject5() with appropriate functions in all the elements. In this example, GsSortObject5J() functions the same as GsSortObject5(). This example is included in the comments

In the file libgs.h.

/* extern and hook only necessary functions */

extern _GsFCALL GsFCALL5; /* GsSortObject5J Func Table */ jt_init() /* Gs SortObject5J Hook Func */ { PACKET *GsPrstF3NL(),*GsPrstF3LFG(),*GsPrstF3L(),*GsPrstNF3(); PACKET *GsTMDdivF3NL(),*GsTMDdivF3LFG(),*GsTMDdivF3L(),*GsTMDdivNF3(); PACKET *GsPrstG3NL(),*GsPrstG3LFG(),*GsPrstG3L(),*GsPrstNG3(); PACKET *GsTMDdivG3NL(),*GsTMDdivG3LFG(),*GsTMDdivG3L(),*GsTMDdivNG3(); PACKET *GsPrstTF3NL(),*GsPrstTF3LFG(),*GsPrstTF3L(),*GsPrstTNF3(); PACKET *GsTMDdivTF3NL(),*GsTMDdivTF3LFG(),*GsTMDdivTF3L(),*GsTMDdivTNF3(); PACKET *GsPrstTG3NL(),*GsPrstTG3LFG(),*GsPrstTG3L(),*GsPrstTNG3(); PACKET *GsTMDdivTG3NL(),*GsTMDdivTG3LFG(),*GsTMDdivTG3L(),*GsTMDdivTNG3(); PACKET *GsPrstF4NL(),*GsPrstF4LFG(),*GsPrstF4L(),*GsPrstNF4(); PACKET *GsTMDdivF4NL(),*GsTMDdivF4LFG(),*GsTMDdivF4L(),*GsTMDdivNF4(); PACKET *GsPrstG4NL(),*GsPrstG4LFG(),*GsPrstG4L(),*GsPrstNG4(); PACKET *GsTMDdivG4NL(),*GsTMDdivG4LFG(),*GsTMDdivG4L(),*GsTMDdivNG4(); PACKET *GsPrstTF4NL(),*GsPrstTF4LFG(),*GsPrstTF4L(),*GsPrstTNF4(); PACKET *GsTMDdivTF4NL(),*GsTMDdivTF4LFG(),*GsTMDdivTF4L(),*GsTMDdivTNF4(); PACKET *GsPrstTG4NL(),*GsPrstTG4LFG(),*GsPrstTG4L(),*GsPrstTNG4(); PACKET *GsTMDdivTG4NL(),*GsTMDdivTG4LFG(),*GsTMDdivTG4L(),*GsTMDdivTNG4(); PACKET *GsPrstF3GNL(),*GsPrstF3GLFG(),*GsPrstF3GL(); PACKET *GsPrst3GNL(),*GsPrstF3GLFG(),*GsPrstF3GL(); /* flat triangle */

}

Scratch Pad Usage Volume

In the Libgs the Scratch Pad address can be passed by argument to GsSortObject4, GsSortObject4J, GsSortObject5 and GsSortObject5J. The scratch pad, a feature of the CPU, allows “high speed access” to as much as 1k of data. It is used in polygon division to improve speed.

The last 162 pages are left out of this plain copy. The reader at this address has every page; it needs JavaScript.