// WebAssembly Z80 Cellular Automata Development Guide
// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})

// What you can build with this ruleset:
A high-performance cellular automata system using WebAssembly and Z80:
- Z80 assembly for core logic
- WebAssembly integration
- Real-time visualization
- Memory-efficient design
- High-performance computation
- Browser-based emulation
- Interactive controls
- State persistence

// Project Structure
src/
  wasm/             # WebAssembly modules
    z80/            # Z80 assembly source
      automata.asm  # Core automata logic
      memory.asm    # Memory management
    build/          # Build artifacts
  js/               # JavaScript interface
    bridge.js       # WASM bridge
    renderer.js     # Canvas rendering
    controls.js     # User interface
  lib/              # Shared utilities
    z80emu/         # Z80 emulator
    memory/         # Memory management
  www/              # Web interface
    index.html      # Main page
    styles/         # CSS styles
  tools/            # Build tools
    assembler/      # Z80 assembler
    linker/         # WASM linker

// Development Guidelines
1. Z80 Assembly:
   - Use efficient instructions
   - Optimize memory access
   - Handle interrupts properly
   - Implement proper timing
   - Use register allocation
   - Minimize memory usage

2. WebAssembly Integration:
   - Implement proper memory sharing
   - Handle data conversion
   - Optimize data transfer
   - Use proper imports/exports
   - Handle errors gracefully
   - Implement proper lifecycle

3. Performance:
   - Use SIMD when possible
   - Optimize memory layout
   - Minimize copying
   - Use proper buffering
   - Implement caching
   - Profile and optimize

// Dependencies
Core:
- z80asm: ^1.0.0
- wasm-pack: ^0.10.0
- wasm-bindgen: ^0.2.84
- web-sys: ^0.3.61
- js-sys: ^0.3.61
- console_error_panic_hook: ^0.1.7

Optional:
- wasm-opt: ^0.110.0
- wabt: ^1.0.32
- wasm-snip: ^0.4.0
- twiggy: ^0.7.0
- wasm-gc: ^0.1.6

// Code Examples:

1. Z80 Assembly Pattern:
```z80
; Cell update routine
; Input: HL = current cell address
; Output: A = new cell state
UpdateCell:
    push bc
    push de
    
    ; Get neighbor count
    ld b, 0          ; Initialize counter
    
    ; Check North
    ld de, -WIDTH
    add hl, de
    ld a, (hl)
    and 1
    add a, b
    ld b, a
    
    ; Check other neighbors...
    
    ; Apply rules
    ld a, (hl)       ; Get current state
    ld c, a          ; Save it
    ld a, b          ; Get neighbor count
    
    cp 2             ; Less than 2 neighbors?
    jr c, .die
    cp 4             ; More than 3 neighbors?
    jr nc, .die
    cp 3             ; Exactly 3 neighbors?
    jr z, .live
    
    ; 2 neighbors - maintain current state
    ld a, c
    jr .done
    
.die:
    xor a            ; Set state to 0
    jr .done
    
.live:
    ld a, 1          ; Set state to 1
    
.done:
    pop de
    pop bc
    ret
```

2. WebAssembly Bridge Pattern:
```rust
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct Automata {
    memory: Vec<u8>,
    width: usize,
    height: usize,
}

#[wasm_bindgen]
impl Automata {
    #[wasm_bindgen(constructor)]
    pub fn new(width: usize, height: usize) -> Self {
        let memory = vec![0; width * height];
        Self {
            memory,
            width,
            height,
        }
    }
    
    #[wasm_bindgen]
    pub fn step(&mut self) {
        let mut new_state = self.memory.clone();
        
        for y in 0..self.height {
            for x in 0..self.width {
                let idx = y * self.width + x;
                new_state[idx] = self.compute_next_state(x, y);
            }
        }
        
        self.memory = new_state;
    }
    
    #[wasm_bindgen]
    pub fn get_memory_ptr(&self) -> *const u8 {
        self.memory.as_ptr()
    }
}
```

3. JavaScript Integration Pattern:
```typescript
class AutomataRenderer {
    private canvas: HTMLCanvasElement;
    private ctx: CanvasRenderingContext2D;
    private memory: WebAssembly.Memory;
    private automata: any;
    
    constructor(
        canvas: HTMLCanvasElement,
        width: number,
        height: number
    ) {
        this.canvas = canvas;
        this.ctx = canvas.getContext('2d')!;
        
        // Initialize WebAssembly
        this.initWasm(width, height);
    }
    
    private async initWasm(width: number, height: number) {
        const wasm = await import('./pkg/automata');
        this.automata = new wasm.Automata(width, height);
        this.memory = wasm.memory;
    }
    
    public step() {
        this.automata.step();
        this.render();
    }
    
    private render() {
        const ptr = this.automata.get_memory_ptr();
        const buffer = new Uint8Array(
            this.memory.buffer,
            ptr,
            this.width * this.height
        );
        
        const imageData = this.ctx.createImageData(
            this.width,
            this.height
        );
        
        for (let i = 0; i < buffer.length; i++) {
            const value = buffer[i] ? 255 : 0;
            imageData.data[i * 4 + 0] = value; // R
            imageData.data[i * 4 + 1] = value; // G
            imageData.data[i * 4 + 2] = value; // B
            imageData.data[i * 4 + 3] = 255;   // A
        }
        
        this.ctx.putImageData(imageData, 0, 0);
    }
}
```

// Best Practices:
1. Optimize Z80 code
2. Handle memory carefully
3. Implement proper timing
4. Use efficient algorithms
5. Profile performance
6. Handle errors properly
7. Implement proper testing
8. Use proper debugging
9. Document assembly code
10. Optimize WebAssembly

// Security Considerations:
1. Validate memory access
2. Handle buffer bounds
3. Sanitize input data
4. Use proper permissions
5. Handle integer overflow
6. Implement proper isolation
7. Use secure random
8. Validate state changes
9. Handle resource limits
10. Implement proper cleanup