Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Atari 2600 VCS Programming

6,972 views

Published on

Introduces the core architecture of the Atari 2600 graphics chip (TIA), its 6502 CPU and showcases a "Hello, World!" application that can be executed on an emulator or on the real console. Includes reference links for those who want to learn more. Originally presented in Brazil at events such as Dev in Sampa and Campus Party.

Atari 2600 VCS Programming

  1. 1. game program™ATARI 2600PROGRAMMINGUse with Keyboard ControllersPROGRAM CONTENTS 2011-2013 CHESTER, INC.©
  2. 2. WhatAn overview of the Atari 2600architecture, covering everythingneeded to create a “Hello,World!”program that can run on emulatorsor even on a real Atarihttp://slideshare.net/chesterbr
  3. 3. Why● Pure nostalgia● Homebrew games● Demoscene● Appreciate masterworks such asEnduro, Pitfall! or River Raid● Feel better about todays toolsand hardware limitations :-)http://slideshare.net/chesterbr
  4. 4. @chesterbrhttp://chester.meWho
  5. 5. Atari 2600(Video Computer System)
  6. 6. Over 600 titles...imagem: mitchelaneous.com
  7. 7. but why were they so...“Atari-ish”?
  8. 8. Lets look inside and find out!(Atari 2600 Jr. printed circuit board)
  9. 9. CPU: 6507
  10. 10. CPU: 65076502
  11. 11. Video:TIA
  12. 12. Everything else: RIOT (6532)
  13. 13. Look ma, no O.S.!Atari programs talk directly to thehardware – there is no middle man!Its 6502 CPU only “understands”memory reads and writes, so all theother chips are hard-wired to act asmemory (even those who arent)
  14. 14. Memory Map(very, very, very simplified*)0000-002C – TIA (write)0030-003D – TIA (read)0080-00FF – RIOT (RAM)0280-0297 – RIOT (I/O,Timer)F000-FFFF – Cartridge (ROM)*http://nocash.emubase.de/2k6specs.htm
  15. 15. Memory MapF000-FFFF – Cartridge (ROM)(this is not your biggest problem...)4 KBytes!
  16. 16. Memory Map0080-00FF – RIOT (RAM)(and still not your biggest problem)128 BYTES!!!!!(1/8 of a KB)
  17. 17. VRAM(frame buffer)Typical video chips translatebit patterns stored onVideo RAM(VRAM) into pixels and colors
  18. 18. VRAMVRAMVRAM3844447C4444EE00
  19. 19. VRAMScreen resolution and color depthare subject toVRAM size limitsMemory was expensive on the70s/80s, leading to trade-offsHow muchVRAM does an Atari have?
  20. 20. Memory Map0000-002C – TIA (write)0030-003D – TIA (read)0080-00FF – RIOT (RAM)0280-0297 – RIOT (I/O,Timer)F000-FFFF – Cartridge (ROM)
  21. 21. Memory Map????-???? – VRAM
  22. 22. Memory Map0 bytes !!!!????-???? – VRAMright, now yougot a problem...
  23. 23. Racing the BeamSince we cant just write pixels tosomeVRAM frame buffer, our codewill need to work a bit closer tothe TV hardware, with a little helpfrom a very unique chip...
  24. 24. TIA(Television Interface Adaptor)
  25. 25. How a TV set worksImage: cc-by wikipedia user Grm_wnr
  26. 26. Scanlinespublic domain illustration by Ian Harvey60 framesper second(NTSCstandard)
  27. 27. TIA is scanline-orientedAs the beam draws each scanline, thegame program must set TIA registersto configure the objects drawn on itMost of this objects have only onecolor, making multiple colors on thesame scanline theoretically impossible...
  28. 28. ...which explains:vs.
  29. 29. constraints ⇒ creativityvs.
  30. 30. Screen Objects● Playfield (PF)● Players (P0, P1)● Missiles/Ball (M0, M1, BL)Scanlines will be rendered based onhow we configure TIAs screen objects:
  31. 31. Playfield (PF)20-bit pattern with a foreground anda background color, renderedover the left side of the scanlineThe right side will either repeat orrefect the same pattern (the latergenerating a symmetrical image)
  32. 32. PLAYFIELD
  33. 33. PLAYFIELD
  34. 34. PLAYFIELD
  35. 35. PLAYFIELD
  36. 36. Playfield configurationPF0 = 0000 ←← orderPF1 = 00000000 order →→PF2 = 00000000 ←← orderREFLECT = 0resulting scanline
  37. 37. Playfield configurationPF0 = 0001 ←← orderPF1 = 00000000 order →→PF2 = 00000000 ←← orderREFLECT = 0resulting scanline_ _
  38. 38. Playfield configurationPF0 = 0011 ←← orderPF1 = 00000000 order →→PF2 = 00000000 ←← orderREFLECT = 0resulting scanline__ __
  39. 39. Playfield configurationPF0 = 0111 ←← orderPF1 = 00000000 order →→PF2 = 00000000 ←← orderREFLECT = 0resulting scanline___ ___
  40. 40. Playfield configurationPF0 = 1111 ←← orderPF1 = 11110000 order →→PF2 = 00000000 ←← orderREFLECT = 0resulting scanline________ _______
  41. 41. Playfield configurationPF0 = 1111 ←← orderPF1 = 11111110 order →→PF2 = 00010101 ←← orderREFLECT = 0resulting scanline___________ _ _ _ ___________ _ _ _
  42. 42. Playfield configurationPF0 = 1111 ←← orderPF1 = 11111110 order →→PF2 = 00010101 ←← orderREFLECT = 1resulting scanline___________ _ _ _ _ _ _ ___________
  43. 43. ___________ _ _ _ _ _ _ ___________
  44. 44. Players (P0, P1)Each one is an independent 8 bit pattern(GRP0/GRP1) with a foreground color(COLUP0 / COLUP1) that can bepositioned at any column of the scanlinee.g.: 10100001 → ████████
  45. 45. PLAYERS
  46. 46. PLAYERS
  47. 47. PlayersEach player can be horizontallystretched, multiplied or inverted bysetting NUSIZn / REFPn (n=0/1)(number/size and reflect player)
  48. 48. NUSIZ0 (or NUSIZ1)000001010011100101110111NUSIZn
  49. 49. With REFP0 (or REFP1) on000001010011100101110111NUSIZn
  50. 50. NUSIZn
  51. 51. NUSIZn
  52. 52. NUSIZn
  53. 53. NUSIZn
  54. 54. NUSIZn
  55. 55. Missiles/Ball (M0/M1/BL)Can be positioned just like players, butno bit pattern, just a pixel (although itcan be horizontally stretched 2/4/8x)M0/M1 use P0/P1colors, whileBL uses the PF foreground color
  56. 56. MISSILES
  57. 57. BALL
  58. 58. BALL
  59. 59. BALLMISSILE
  60. 60. BALLMISSILE
  61. 61. Master PlanFor each scanline, configure theoptions for each object before thebeam reaches its intended positionThe time slot is very short, forcingprogrammers to pick and choose whatto change, reusing as much as they can
  62. 62. How short?6502 ≈ 1,19Mhz (1.194.720 cycles/sec)NTSC: 60 frames per second1.194.720/60 ≅ 19.912 cycles per frame
  63. 63. How short?CPU: 19.912 cyles per frameNTSC: 262 scanlines per frame19.912 / 262 = 76 cycles per scanline
  64. 64. How short?CPU: 19.912 cyles per frameNTSC: 262 scanlines per frame19.912 / 262 = 76 cycles per scanlineand what can we do with 76 cycles?(by the way:WTF is a “cycle”?)
  65. 65. Assembly 6502
  66. 66. 6502
  67. 67. 6502 (Atari-wise)Reads a program from the cartridge(ROM) composed of operations thatmanipulate and transfer bytes betweencartridge, RIOT (RAM, I/O, timers) andTIA, keeping state on internal registers
  68. 68. OperationsEach operation that composes a 6502program in memory is identified by a1-byte opcode and can be followedby up to 2 bytes of parametersAn instruction can take up to 6cycles to be executed
  69. 69. RegistersA = Accumulator (8 bits)X,Y= Indexes (8 bits)S = Stack Pointer (8 bits)P = Status (fags, 8 bits)PC = Program Counter (16 bits)
  70. 70. Example program“add 2 to a value stored at amemory position; store the resultinto another memory position”
  71. 71. Implementation● Read the byte stored on memoryposition 0200 into register A● Add 2 to register As value● Write register As value intomemory position 0201
  72. 72. 6502 Machine CodeAD Opcode (Memory → A)00 Last part of “0200”02 First part of “0200”69 Opcode (value + A → A)02 Value to add8D Opcode (A → Memory)01 Last part of “0201”02 First part of “0201”
  73. 73. 6502 Assembly LanguageAssociates the 151 opcodeswith 56 mnnemonic instructionsand a notation for theirparameters (access mode)
  74. 74. 6502 Machine CodeAD Opcode (Memory → A)00 Last part of “0200”02 First part of “0200”69 Opcode (value + A → A)02 Value to add8D Opcode (A → Memory)01 Last part of “0201”02 First part of “0201”
  75. 75. Assembly 6502AD LDA $0200000269 ADC #02028D STA $02010102
  76. 76. AssemblerProgram that reads a text filewritten in Assembly language andassembles a binary file with thecorresponding machine codefoo.asmLDA $0200ADC #02STA $0201...foo.binAD000269028D0102...ASSEMBLER
  77. 77. Macro AssemblerORG $0100 ; Start @ memory 0100...SomeLabel:LDX #$10 ; No idea where thisDEX ; will be in memory,BNE SomeLabel ; and dont need to!...
  78. 78. DASM● 6502 Macro Assembler● Includes Atari headers● Multiplataform● Free and open-source (GPLv2)http://dasm-dillon.sourceforge.net/
  79. 79. Notation (for today)#... = decimal value#$... = hex value$... = hex address$... , X = hex address + Xhttp://www.obelisk.demon.co.uk/6502/addressing.html
  80. 80. 6502 Instruction Set= most relevant for Atari 2600 programming
  81. 81. Data TransferLDA, LDX, LDY = LoadSTA, STX, STY = StoreTAX,TAY,TXA,TYA,TSX,TXS = TransferLDA #$10 0x10→ASTY $0200 Y→m(0x0200)TXA X→A
  82. 82. ArithmeticADC, SBC = +,- (w/ carry)INC, INX, INY = ++DEC, DEX, DEY = --ADC $0100 m(0x100)+A→AINC $0200 m(0x200)+1→m(0x200)DEX X-1→X
  83. 83. Bit OperationsAND, ORA, EOR = &, |, ^ (A)ASL, LSR = Arithmetic shiftROL, ROR = “Rotating” shiftAND #$11 A&0x11→ALSR A>>1→A (A/2→A)ROR A>>1 (bit 7=carry)
  84. 84. Comparing / BranchingCMP, CPX, CPY = compare A/X/Y (-)BCS, BCC = ⇗ if carry set / clearBEQ, BNE = ⇗ if equal / not equalBVS, BVC = ⇗ if overfow set / clearBMI, BPL = ⇗ if minus / plusCPY $1234 if y=m(0x1234),BEQ $0200 0x0200→PC
  85. 85. Stack and SubroutinesJSR, RTS = call/return subroutinePHA, PLA = push / pull APHP, PLP = push / pull status (P)JSR $1234 PC(+3)→stack,0x1234→PCRTS stack→PC
  86. 86. Everything else...NOP = No OperationJMP = Direct Jump (GOTO)SEC, CLC = Set/Clear CarrySEV, CLV = Set/Clear oVerfowSEI, CLI = Set/Clear Interrupt-offSED, CLD = Set/Clear DecimalRTI = Return from InterruptBRK = Break
  87. 87. Neo:“I know kung fu.”Morpheus:“Show me.”© 1999 Warner Bros
  88. 88. Hello,World!
  89. 89. Hello,World!Horizontal writing is hard(too many pixels per scanline)
  90. 90. Hello,World!Vertical writingis the way →(less pixels/scanline)We can use a playeror the playfield
  91. 91. Hello,World!Our display kernel will configure eachpair of visible scanlines with a bytefrom a “hello world” bitmap (storedon the card, just after the code)Lets find which are visible, and howwe need to deal with TV timings
  92. 92. Source: Stella Programmers Guide, SteveWright, 1979GAMELOGIC(3+37+30).76=5320cyclesKERNEL
  93. 93. Program structureVertical SyncVertical BlankOverscanPlayfield
  94. 94. mainloop(infinite)KernelX: count 0 to 191(192 scanlines)Program structureVertical SyncVertical BlankOverscan11 chars *8 bytes *2 scanlinesper byte =176scanlines
  95. 95. Program structureVertical SyncVertical BlankKernelOverscan
  96. 96. Lets begin!PROCESSOR 6502INCLUDE "vcs.h"ORG $F000 ; Cart begins hereVertical SyncVertical BlankKernelOverscan
  97. 97. Frame (main loop) startStartFrame:lda #%00000010 ; Signal VSYNC start bysta VSYNC ; setting bit 1REPEAT 3 ; lasts 3 scanlinessta WSYNC ; (WSYNC = wait untilREPEND ; scanline is finished)lda #0 ; Signal VSYNC end (andsta VSYNC ; VBLANK start)Vertical SyncVertical BlankKernelOverscan
  98. 98. Vertical BlankPreparePlayfield:lda #$00sta ENABL ; Disable ballsta ENAM0 ; Disable missilessta ENAM1sta GRP0 ; Disable playerssta GRP1 ; (with a 0s-only shape)Vertical SyncVertical BlankKernelOverscan
  99. 99. Vertical Blanksta COLUBK ; Background (0=preto)sta PF0 ; PF0 and PF2 stay offsta PF2lda #$FF ; Playfield colorsta COLUPF ; (yellow-ish)lda #$00 ; Clear CTRLPF bit 0 tosta CTRLPF ; repeat playfieldldx #0 ; X: scanline counterVertical SyncVertical BlankKernelOverscan
  100. 100. FinishVertical BlankREPEAT 37 ; VBLANK lasts 37 scanlinessta WSYNC ; (useful for game logic)REPEND ;lda #0 ; Signals VBLANK end (willsta VBLANK ; “turn on the beam”)Vertical SyncVertical BlankKernelOverscan
  101. 101. Scanline (inner loop)Scanline:cpx #174 ; Phrase over?bcs ScanlineEnd; if so, skiptxa ; Y=X÷2 (logic shift →lsr ; divides A by 2)tay ;lda Phrase,y ; label,Y = mem[label+Y]sta PF1 ; PF1 = playfield (bits; 4 to 11) Vertical SyncVertical BlankKernelOverscan
  102. 102. Scanline (close inner loop)ScanlineEnd:sta WSYNC ; Finish current scanlineinx ; X=line countercpx #191 ; last visible scanline?bne Scanline ; unless so, repeat!Vertical SyncVertical BlankKernelOverscan
  103. 103. Overscan (close main loop)Overscan:lda #%00000010 ; “turn off” beam againsta VBLANK ; 30 scanlines ofREPEAT 30 ; overscan...sta WSYNCREPENDjmp StartFrame ; ...and start it over,; forever and ever!Vertical SyncVertical BlankKernelOverscan
  104. 104. Hello...Phrase:.BYTE %00000000 ; H.BYTE %01000010.BYTE %01111110.BYTE %01000010.BYTE %01000010.BYTE %01000010.BYTE %00000000.BYTE %00000000 ; E.BYTE %01111110...
  105. 105. ...world....BYTE %00000000 ; D.BYTE %01111000.BYTE %01000100.BYTE %01000010.BYTE %01000010.BYTE %01000100.BYTE %01111000.BYTE %00000000 ; PF1 last value (!)
  106. 106. 6502 configurationORG $FFFA ; Located at the end; of ROM (cart).WORD FrameStart ; NMI address.WORD FrameStart ; BOOT address.WORD FrameStart ; BRK addressEND
  107. 107. Assemble!dasm source.asm -ocart.bin -f3http://stella.sourceforge.net/
  108. 108. Advanced Tricks
  109. 109. Playfield-based score
  110. 110. Playfield-based scoreThe PF color can be replaced withplayer colors (P0 = left side; P1 =right side) by turning CTRLPFsscore mode bit on
  111. 111. PLAYERS COLORS
  112. 112. (how could this improve our Hello World?)
  113. 113. (how could this improve our Hello World?)
  114. 114. Playfield-based scoreQ: How can different patterns beshown at each side of the playfield?A: Change the pattern when thebeam is halfway through the scanline(“race the beam”)
  115. 115. beam...and you have a different shapeat the other half!
  116. 116. Large worlds
  117. 117. Pitfall!
  118. 118. http://pitfallharry.tripod.com/MapRoom/PitfallMap.html
  119. 119. Pitfall!Screen configuration (logs, vines,trees, stairs, crocs) was squeezedinto a single byte, but 255 screens(bytes) are still a huge ROM table(for Atari standards)http://pitfallharry.tripod.com/MapRoom/PitfallMap.html
  120. 120. Pitfall!David Crane implemented a sequencegenerator (LFSR), which, for a givenvalue, would give the previous/nextones, replacing the 255-byte tablewith a 50-byte piece of codehttp://en.wikipedia.org/wiki/Linear_feedback_shift_register
  121. 121. River Raid
  122. 122. River RaidCarol Shaw had used a 16-bit generator,resulting in thousands of non-repeatingriver sectors (tweaking the interpreterto make the first few ones easier)When a player loses a life, renderingrestarts from the last generated number,that is, back on the last bridge
  123. 123. Horizontal positioning
  124. 124. Horizontal positioningThe horizontal position of a player /missile / ball is not a writable registerGames must sync to with the beam andwrite to the appropriate strobe registerwhen it is on the desired location
  125. 125. STROBE TARGETS(in theory)
  126. 126. You can calculate...1 CPU cycle = 3 “color clocks” (pixels)Horizontal Blank = 22.6 cycleshoriz. position ≈ (cycles – 22.6) * 3...but it is an estimate, because TIA onlyreads its registers every 5 CPU cyclesSmooth ↔ movement is also hard
  127. 127. AlternativesA 4-bit register allows moving a player,missile or ball relative to its previousposition (adding -7 to +8 pixels)The missile can also be reset to themiddle of its player, making it easy to“fire” it over and over
  128. 128. STROBE TARGETS
  129. 129. VERTICAL MOVEMENTJust start on a different scanline at each frameHORIZONTAL MOVEMENTstrobe registers HMP0/1 e HMM0/1
  130. 130. Multi-digit Score
  131. 131. Multi-digit scoreThe trick is the same of the playfield-based score (change the registers whilethe beam is drawing the scanline), buttiming is much more of an issue hereLets say the score is 456789...
  132. 132. Multi-digit scoreBegin the scanline with the bits for 4on GRP0 and those for 5 on GRP1Configure NUSIZ0 and NUSIZ1 fora triple repetition:4 4 4 5 5 5Player 0 Player 1
  133. 133. Multi-digit scoreSet player 1 position just to the rightof player 0, overlapping the triplets454545Player 0Player 1
  134. 134. Multi-digit scoreChange the patterns (GRP0/GRP1)syncing with the beam, like this:BEAM454545
  135. 135. Multi-digit scoreWhen the beam is about to finishplayer 1s 1stcopy, change player 0 to6 and player 1 to 7:BEAM454545
  136. 136. Multi-digit scoreRepeat the trick after the 2ndplayer 2copy, this time changing player 0 to 8and player 1 to 9BEAM456767
  137. 137. Multi-digit scoreRepeat it for each scanline.Easy! #notBEAM456789
  138. 138. Multi-digit scoreThere are other hurdles: we cant loadreplaced digits from memory, and weonly have 3 memory-writable registersto store 6 bit patterns......and that is why it is fun!
  139. 139. Final Words
  140. 140. A new look to the old schoolKnowing what the Atari 2600 wasdesigned to do, we can appreciategames that push it beyond its limitsby identifying “impossible” things
  141. 141. It is just the beginning!The Atari homebrew scene is alive andkicking, and these are the basics youneed to create your own games/demosThere are several uncovered topics(sound, timers, collision, I/O...), but withtime and dedication, you can do it!
  142. 142. To learn moreHello, World: https://gist.github.com/chesterbr/5864935Sorteio 2600 http://github.com/chesterbr/sorteio2600Racing The Beam (book): http://bit.ly/dSqhjSDavid Cranes talk: http://youtu.be/MBT1OK6VAIUDavid Cranes iOS tutorials: http://bit.ly/9pwYHs and http://bit.ly/qWBciZStella Programmers Guide: http://emu-docs.org/?page=Atari%202600Classic games disassembled: http://classicdev.org/wiki/2600/Source_CodeAtari 2600 specs: http://nocash.emubase.de/2k6specs.htm6502 reference: http://bit.ly/hxG5c6In-browser emulator: http://jogosdeatari.com.br/Andrew Daves tutorial: http://bit.ly/ptQDdA (the whole site is great)Harmony (SD-reader cart): http://harmony.atariage.com/BAtari (BASIC compiler): http://bataribasic.comTIA sound examples: http://bit.ly/tnbPrpBankswitching (more ROM/RAM): http://bit.ly/tqhLZk
  143. 143. Questions?Thank you!@chesterbrhttp://slideshare.net/chesterbrhttp://chester.me
  144. 144. Credits and LicenseThis presentation is available under thelicença Creative Commons “by-nc” 3.0 l,noticing the exceptions belowImages from third parties were included (with due credits) underfair use assumption and/or under their respective licenses.These are excluded from the license above.Atari™,Adventure™, Donkey Kong™, Pitfall™, Super Mario™ andlikewise characters/games/systems are mentioned uniquely forillustrative purposes, also under fair use assumption.They are propertyof their rights holders, and are also excluded from the license above.

×