source: thomson/code/C/libdemo/trig.c@ f2bbd91

main
Last change on this file since f2bbd91 was f2bbd91, checked in by Adrien Destugues <pulkomandy@…>, 11 years ago

libdemo, with stuff useful for building demos.

git-svn-id: svn://localhost/thomson@39 85ae3b6b-dc8f-4344-a89d-598714f2e4e5

  • Property mode set to 100644
File size: 2.0 KB
Line 
1/* Fast and inexact trigonometry routines
2 * Copyright 2013, Adrien Destugues <pulkomandy@pulkomandy.tk>
3 *
4 * This file is distributed under the terms of the MIT licence
5 */
6#include <stdint.h>
7
8
9unsigned char SIN[512];
10
11// TODO rewrite this in assembler and optimize it ! It should be possible to get
12// a very small code for it. Fast doesn't really matter as this is called once
13// at demo init.
14
15/**
16 * Generate an approximation of a sine wave using a polynomial (x-3)²-1.
17 * http://codebase64.org/doku.php?id=base:generating_approximate_sines_in_assembly
18 *
19 * Output is unsigned 8bit, in the range 0-255.
20 * Deviates from an actual sinewave by about 6%, which is ok for dirty trig, but
21 * also more interesting when you derive (get a triangle) or integrate. So this
22 * adds some distorsion which is nice for plasma curves, and so on.
23 *
24 * Call this once, then use the SIN table to lookup your samples. We *should* be
25 * using a signed char as an offset in the table, which could be used to make
26 * this code a bit more 6809 optimized. For now we don't...
27 */
28void polysine()
29{
30 // Value is the computed valu of the sine at the current point.
31 // Delta is the acceleration we use to build the polynomial iteratively
32 uint16_t value = 0, delta = 0;
33 // These are indices into the wavetable. We compute only 64 points and the
34 // others are built by symetry.
35 uint8_t y = 0x3F, x = 0;
36
37 do
38 {
39 // Compute the value for the next point
40 value += delta;
41
42 // The last half of the sinewave is positive and symetric
43 SIN[256 + 0xC0 + x] = SIN[0xC0 + x] = value >> 8;
44 SIN[256 + 0x80 + y] = SIN[0x80 + y] = value >> 8;
45 // The fist half is negative and a mirror of the last
46 SIN[256 + 0x40 + x] = SIN[0x40 + x] = (value >> 8) ^ 0xFF;
47 SIN[256 + y] = SIN[ y] = (value >> 8) ^ 0xFF;
48
49 // Increase delta (else we get a triangle wave)
50 // Tweak this value if you need the sinewave to have a different amplitude
51 delta += 0x10;
52
53 // Move on to the next sample
54 x++;
55 } while(y-- > 0);
56}
Note: See TracBrowser for help on using the repository browser.