aboutsummaryrefslogtreecommitdiff
path: root/sound.c
blob: 798e8c214dafa45b9cf51a1b2db26209c8e93fa6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "config.h"
#include "sound.h"

#if DEBUG
#include "error.h"
#include "platform.h"
#endif

typedef struct {
	int pitch;
	int length;
} Beep;

static struct {
	unsigned t;
	Song song;
	Beep beeps[max_beeps];
	int beep_count;
} sys;

typedef unsigned char (*Song_Func)(unsigned t);

static unsigned char menu_song(unsigned t) {
	return 0;
}

static unsigned char main_song(unsigned t) {
	/* From tejeez 2011-10-05
	 * I didn't have time to make my own music PepeHands */
	return (~t>>2)*((127&t*(7&t>>10))<(245&t*(2+(5&t>>14))));
}

static unsigned char dead_song(unsigned t) {
	return 0;
}

static unsigned char win_song(unsigned t) {
	return 0;
}

void init_sound() {
	sys.t = 0;
	sys.song = song_menu;
}

void set_song(Song song) {
	sys.song = song;
	sys.t = 0;
}

Song_Func get_current_song_f() {
	switch (sys.song) {
		case song_menu:
			return menu_song;
		case song_main:
			return main_song;
		case song_win:
			return win_song;
		case song_dead:
			return dead_song;
	}
	return 0;
}

void play_beep(int pitch, int length) {
	Beep* beep;

#if DEBUG
	if (sys.beep_count >= max_beeps) {
		platform_err("Too many beeps.\n");
		platform_abort(error_sound_error);
	}
#endif

	beep = &sys.beeps[sys.beep_count++];
	beep->pitch = pitch;
	beep->length = length;
}

void sound_mix(unsigned char* stream, int len) {
	int i, j;
	Song_Func f;
	Beep* beep;

	f = get_current_song_f();

	for (i = 0; i < len; i++) {
/*		stream[i] = sys.t % 50;*/
		stream[i] = f(sys.t) / 5;
		for (j = sys.beep_count - 1; j >= 0; j--) {
			beep = &sys.beeps[j];
			stream[i] |= (sys.t % beep->pitch) * 5;
			beep->length--;

			if (beep->length <= 0) {
				if (sys.beep_count > 1) {
					*beep = sys.beeps[sys.beep_count - 1];
				}
				sys.beep_count--;
			}
		}
		sys.t++;
	}
}