File: generate_constants.cc

package info (click to toggle)
open-roms 0.0~git20210824.e4e324c-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 10,184 kB
  • sloc: asm: 25,386; cpp: 3,333; ansic: 1,667; makefile: 709
file content (267 lines) | stat: -rw-r--r-- 5,724 bytes parent folder | download | duplicates (2)
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
//
// Utility to generate various floating points constants
// in a Commodore-specific variable format
//

#include "common.h"

#include <unistd.h>

#include <cmath>
#include <cstdio>
#include <fstream>
#include <iomanip>
#include <vector>

//
// Basic types definition
//

typedef struct ConstEntry
{
	ConstEntry(const std::string &constName, double constValue) :
		constName(constName),
		constValue(constValue),
		outString(".error \"not generated\"")
	{
	};

	const std::string constName;
	const double      constValue;

	std::string       outString;

} ConstEntry;

//
// Constants to output
//

std::vector<ConstEntry> GLOBAL_constants =
{
	// Constants from:
	// - https://www.c64-wiki.com/wiki/BASIC-ROM
	// Computes Mapping the Commodore 64, pages 103, 105, 113, 114, 116

	ConstEntry(   "QUARTER",      0.25            ),
	ConstEntry(      "HALF",      0.5             ),
	ConstEntry(  "NEG_HALF",     -0.5             ),
	ConstEntry(       "ONE",      1.0             ),
	ConstEntry(       "TEN",     10.0             ),
	ConstEntry( "NEG_32768", -32768.0             ),

	ConstEntry(   "HALF_PI", M_PI / 2.0           ),
	ConstEntry(        "PI", M_PI                 ),
	ConstEntry( "DOUBLE_PI", M_PI * 2.0           ),
	ConstEntry(     "SQR_2", std::sqrt(2.0)       ),
	ConstEntry( "INV_SQR_2", 1.0 / std::sqrt(2.0) ),
	ConstEntry(     "LOG_2", std::log(2.0)        ),
	ConstEntry( "INV_LOG_2", 1.0 / std::log(2.0)  ),

	// Constants for sine approximation, minimized abs. error, degree 11, for [0, pi/2], from:
	// - https://publik-void.github.io/sin-cos-approximations/

	ConstEntry( "POLY_SIN_1", -2.3794713545277060334805162803882547e-8   ),
	ConstEntry( "POLY_SIN_2",  2.75188556386854406868696924998396177e-6  ),
	ConstEntry( "POLY_SIN_3", -0.000198407028626057951892931706291369095 ),
	ConstEntry( "POLY_SIN_4",  0.00833332926445715285723741015926085083  ),
	ConstEntry( "POLY_SIN_5", -0.166666665414391662957238076832950332    ),
	ConstEntry( "POLY_SIN_6",  0.99999999988985190065414932682350994     ),
};

//
// Command line settings
//

std::string CMD_outFile = "out.s";

//
// Common helper functions
//

void printUsage()
{
    std::cout << "\n" <<
        "usage: generate_constants [-o <out file>]" << "\n\n";
}

void printBanner()
{
    printBannerLineTop();
    std::cout << "// Generating floating point constants" << "\n";
    printBannerLineBottom();
}

//
// Top-level functions
//

void parseCommandLine(int argc, char **argv)
{
    int opt;

    // Retrieve command line options

    while ((opt = getopt(argc, argv, "o:")) != -1)
    {
        switch(opt)
        {
            case 'o': CMD_outFile   = optarg; break;
            default: printUsage(); ERROR();
        }
    }
}

//
// Constants generation
//

std::string toAssemblerString(const std::string &constName, double constValue)
{
	uint8_t outFloat[5] = { 0 };

	// Retrieve mantissa nad exponent

	int    exponent = -0x80;
	double mantissa = frexp(std::abs(constValue), &exponent);
	
	// Round the mantissa to output format precission

	const double coeff = 256.0 * 256.0 * 256.0 * 256.0;

	double intPart;
	if (modf(mantissa * coeff, &intPart) >= 0.5)
	{
		mantissa = (intPart + 1.0) / coeff;
	}
	else
	{
		mantissa = intPart / coeff;
	}

	if (mantissa >= 1.0)
	{
		mantissa = 0.5;
		exponent++;
	}

	// Add a bias to exponent

	exponent += 0x80;

	// Check if output format can contain such a number

	if (exponent > 0xFF)
	{
		ERROR(std::string("const '")  + constName + "' abs value too large");
	}
	else if (exponent <= 0)
	{
		ERROR(std::string("const '")  + constName + "' abs value too small");
	}

	// Set output constant exponent

	outFloat[0] = exponent;

	// Set output constant mantissa

	for (uint8_t idxByte = 1; idxByte <= 4; idxByte++)
	{
		for (uint8_t idxBit = 0; idxBit <= 7; idxBit++)
		{
			outFloat[idxByte] = outFloat[idxByte] << 1;
			if (mantissa >= 0.5)
			{
				outFloat[idxByte]++;
				mantissa -= 0.5;
			}

			mantissa *= 2;
		}
	}

	if (mantissa > 0.0)     ERROR(std::string("const '")  + constName + "' export error");
	if (outFloat[1] < 0x80) ERROR(std::string("const '")  + constName + "' not normalized");

	// Set output constant sign

	if (constValue >= 0.0)
	{
		outFloat[1] = outFloat[1] & 0x7F;
	}

	// Return the output constant as string for assembler

	char buf[256] = { 0 };
	snprintf(buf, sizeof(buf), "$%02X, $%02X, $%02X, $%02X, $%02X    // %22.10f",
		outFloat[0],
		outFloat[1],
		outFloat[2],
		outFloat[3],
		outFloat[4],
		constValue);

	std::string outDef = std::string("\n!macro PUT_CONST_") + constName + " {\n\t!byte " + buf + "\n}\n";

	return outDef;
} 


void writeConstants()
{
	// Convert constants to assembler strings

	for (auto &entry : GLOBAL_constants)
	{
		entry.outString = toAssemblerString(entry.constName, entry.constValue);
	}

    // Remove old file

    unlink(CMD_outFile.c_str());

    // Open output file for writing

    std::ofstream outFile(CMD_outFile, std::fstream::out | std::fstream::trunc);
    if (!outFile.good()) ERROR(std::string("can't open oputput file '") + CMD_outFile + "'");

    // Write header

    outFile << "//\n// Generated file - do not edit\n//\n\n";

    // Write constants

	for (auto &entry : GLOBAL_constants)
	{
		outFile << entry.outString;
	}

    if (!outFile.good())
    {
    	outFile.close();
    	unlink(CMD_outFile.c_str());
    	ERROR(std::string("can't write oputput file '") + CMD_outFile + "'");
    }

    // Close the file
   
    outFile.close();

    std::cout << std::string("floating point constants written to: ") + CMD_outFile + "\n\n";
}


//
// Main function
//

int main(int argc, char **argv)
{
    parseCommandLine(argc, argv);

    printBanner();
    writeConstants();

    return 0;
}