Skip to content

Commit 617151c

Browse files
author
Martin Schuhfuss
committed
implement gamma-correction
1 parent 3e8b3e6 commit 617151c

File tree

1 file changed

+36
-12
lines changed

1 file changed

+36
-12
lines changed

lib/ws281x-native.js

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -40,23 +40,45 @@ if(!ws281xNative) {
4040
}
4141

4242

43+
var gammaCorrect = (function() {
44+
var _gamma = 2.8;
45+
var _gammaTable = new Uint8Array(256);
4346

44-
var _numLeds = 0,
45-
_indexMapping = null;
47+
for(var i=0; i<256; i++) {
48+
_gammaTable[i] = Math.floor(Math.pow(i / 255, _gamma) * 255 + 0.5);
49+
}
4650

51+
return function gammaCorrect(color) {
52+
return (
53+
_gammaTable[color & 0xff]
54+
| (_gammaTable[(color >> 8) & 0xff] << 8)
55+
| (_gammaTable[(color >> 16) & 0xff] << 16)
56+
);
57+
};
58+
} ());
4759

48-
function remap(src, indexMapping) {
49-
var dest = new Uint32Array(src.length);
5060

51-
for(var i=0; i<src.length; i++) {
52-
dest[i] = src[indexMapping[i]];
53-
}
61+
var remap = (function() {
62+
var _tmpData = null;
5463

55-
return dest;
56-
}
64+
return function remap(data, indexMapping) {
65+
if(!_tmpData) {
66+
_tmpData = new Uint32Array(data.length);
67+
}
68+
69+
_tmpData.set(data);
70+
71+
for(var i=0; i<data.length; i++) {
72+
data[i] = gammaCorrect(_tmpData[indexMapping[i]]);
73+
}
74+
75+
return data;
76+
};
77+
} ());
5778

5879

5980
var ws281x = new EventEmitter();
81+
var _indexMapping = null;
6082

6183
/**
6284
* configures PWM and DMA for sending data to the LEDs
@@ -67,16 +89,14 @@ var ws281x = new EventEmitter();
6789
* (PWM frequency, DMA channel, GPIO, Brightness)
6890
*/
6991
ws281x.init = function(numLeds, options) {
70-
_numLeds = numLeds;
71-
7292
ws281xNative.init(numLeds, options);
7393
};
7494

7595
/**
7696
* register a mapping to manipulate array-indices within the
7797
* data-array before rendering.
7898
*
79-
* @param {Array.<Number>} map the mapping, indexed by destination.
99+
* @param {Array.<Number>} mapping the mapping, indexed by destination.
80100
*/
81101
ws281x.setIndexMapping = function(mapping) {
82102
_indexMapping = mapping;
@@ -96,6 +116,10 @@ ws281x.render = function(data) {
96116
data = remap(data, _indexMapping);
97117
}
98118

119+
for(var i=0; i<data.length; i++) {
120+
data[i] = gammaCorrect(data[i]);
121+
}
122+
99123
ws281xNative.render(data);
100124
this.emit('render', data);
101125

0 commit comments

Comments
 (0)