Mac OS X ambilight
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AppDelegate.m 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. //
  2. // AppDelegate.m
  3. // DisplayBacklight
  4. //
  5. // Created by Thomas Buck on 21.12.15.
  6. // Copyright © 2015 xythobuz. All rights reserved.
  7. //
  8. #import "AppDelegate.h"
  9. #import "Serial.h"
  10. #import "Screenshot.h"
  11. // ----------------------- Config starts here -----------------------
  12. // The idea behind this algorithm is very simple. It assumes that each LED strand
  13. // follows one edge of one of your displays. So one of the two coordinates should
  14. // always be zero or the width / height of your display.
  15. // Define the amount of LEDs in your strip here
  16. #define LED_COUNT 156
  17. // This defines how large the averaging-boxes should be in the dimension perpendicular
  18. // to the strand. So eg. for a bottom strand, how high the box should be in px.
  19. #define COLOR_AVERAGE_OTHER_DIMENSION_SIZE 100
  20. // Identify your displays here. Currently they're only distinguished by their resolution.
  21. // The ID will be the index in the list, so the first entry is display 0 and so on.
  22. struct DisplayAssignment displays[] = {
  23. { 1920, 1080 },
  24. { 900, 1600 }
  25. };
  26. // This defines the orientation and placement of your strands and is the most important part.
  27. // It begins with the LED IDs this strand includes, starting with ID 0 up to LED_COUNT - 1.
  28. // The second item is the length of this strip, as in the count of LEDs in it.
  29. // The third item is the display ID, defined by the previous struct.
  30. // The fourth and fifth items are the starting X and Y coordinates of the strand.
  31. // As described above, one should always be zero or the display width / height.
  32. // The sixth element is the direction the strand goes (no diagonals supported yet).
  33. // The last element is the size of the averaging-box for each LED, moving with the strand.
  34. // So, if your strand contains 33 LEDs and spans 1920 pixels, this should be (1920 / 33).
  35. // By default you can always use (length in pixel / LED count) for the last item, except
  36. // if your strand does not span the whole length of this screen edge.
  37. //
  38. // For example, this is my personal dual-monitor home setup. The strand starts at the 0
  39. // in the bottom-right of D1, then goes left arount D1, and from there around D2 back
  40. // to the start.
  41. //
  42. // 29
  43. // |------------|
  44. // 5 | /|\ --> -->|
  45. // 33 | | |
  46. // |---------------------------| | |
  47. // |--> --> --> --> -->| \|/ |
  48. // | | |
  49. // 19 | /|\ D1 | D2 | 48
  50. // | | 1920x1080 | 900x1600 |
  51. // | | |
  52. // |<-- <-- <-- <-- <--| 0 | |
  53. // |---------------------------| /|\ \|/ |
  54. // 33 | | |
  55. // 4 | <-- <-- |
  56. // |------------|
  57. // 29
  58. struct LEDStrand strands[] = {
  59. { 0, 33, 0, 1920, 1080, DIR_LEFT, 1920 / 33 },
  60. { 33, 19, 0, 0, 1080, DIR_UP, 1080 / 19 },
  61. { 52, 33, 0, 0, 0, DIR_RIGHT, 1920 / 33 },
  62. { 85, 5, 1, 0, 250, DIR_UP, 250 / 5 },
  63. { 90, 17, 1, 0, 0, DIR_RIGHT, 900 / 17 },
  64. { 107, 28, 1, 900, 0, DIR_DOWN, 1600 / 28 },
  65. { 135, 17, 1, 900, 1600, DIR_LEFT, 900 / 17 },
  66. { 152, 4, 1, 0, 1600, DIR_UP, 180 / 4 }
  67. };
  68. // This defines the update-speed of the Ambilight, in seconds.
  69. // With a baudrate of 115200 and 156 LEDs and 14-bytes Magic-Word,
  70. // theoretically you could transmit:
  71. // 115200 / ((14 + (156 * 3)) * 8) =~ 30 Frames per Second
  72. // Inserting (1.0 / 30.0) here would try to reach these 30FPS,
  73. // but will probably cause high CPU-Usage.
  74. // (Run-Time of the algorithm is ignored here, so real speed will be
  75. // slightly lower.)
  76. #define DISPLAY_DELAY (1.0 / 30.0)
  77. // How many pixels to skip when calculating the average color.
  78. // Slightly increases performance and doesn't really alter the result.
  79. #define AVERAGE_PIXEL_SKIP 2
  80. // Magic identifying string used to differntiate start of packets.
  81. // Has to be the same here and in the Arduino Sketch.
  82. #define MAGIC_WORD @"xythobuzRGBled"
  83. // These are the values stored persistently in the preferences
  84. #define PREF_SERIAL_PORT @"SerialPort"
  85. #define PREF_BRIGHTNESS @"Brightness"
  86. #define PREF_TURNED_ON @"IsEnabled"
  87. // If this is defined it will print the FPS every DEBUG_PRINT_FPS seconds
  88. //#define DEBUG_PRINT_FPS 10
  89. // ToDo Change color-temperature depending on time of day to match f.lux adjustments
  90. #define TARGET_COLOR_TEMPERATURE 2800.0
  91. // ------------------------ Config ends here ------------------------
  92. @interface AppDelegate ()
  93. @property (weak) IBOutlet NSMenu *statusMenu;
  94. @property (weak) IBOutlet NSMenu *menuPorts;
  95. @property (weak) IBOutlet NSMenuItem *buttonAmbilight;
  96. @property (weak) IBOutlet NSMenuItem *brightnessItem;
  97. @property (weak) IBOutlet NSSlider *brightnessSlider;
  98. @property (weak) IBOutlet NSMenuItem *brightnessLabel;
  99. @property (strong) NSStatusItem *statusItem;
  100. @property (strong) NSImage *statusImage;
  101. @property (strong) NSTimer *timer;
  102. @property (strong) Serial *serial;
  103. @property (strong) NSArray *lastDisplayIDs;
  104. @property (assign) BOOL restartAmbilight;
  105. @end
  106. @implementation AppDelegate
  107. @synthesize statusMenu, application;
  108. @synthesize menuPorts, buttonAmbilight;
  109. @synthesize brightnessItem, brightnessSlider, brightnessLabel;
  110. @synthesize statusItem, statusImage, lastDisplayIDs;
  111. @synthesize timer, serial, restartAmbilight;
  112. - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
  113. serial = [[Serial alloc] init];
  114. timer = nil;
  115. restartAmbilight = NO;
  116. // Set default configuration values
  117. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  118. NSMutableDictionary *appDefaults = [NSMutableDictionary dictionaryWithObject:@"" forKey:PREF_SERIAL_PORT];
  119. [appDefaults setObject:[NSNumber numberWithFloat:50.0] forKey:PREF_BRIGHTNESS];
  120. [appDefaults setObject:[NSNumber numberWithBool:NO] forKey:PREF_TURNED_ON];
  121. [store registerDefaults:appDefaults];
  122. [store synchronize];
  123. // Load existing configuration values
  124. NSString *savedPort = [store stringForKey:PREF_SERIAL_PORT];
  125. float brightness = [store floatForKey:PREF_BRIGHTNESS];
  126. BOOL ambilightIsOn = [store boolForKey:PREF_TURNED_ON];
  127. // Prepare status bar menu
  128. statusImage = [NSImage imageNamed:@"MenuIcon"];
  129. statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
  130. [statusImage setTemplate:YES];
  131. [statusItem setImage:statusImage];
  132. [statusItem setMenu:statusMenu];
  133. // Prepare brightness menu
  134. brightnessItem.view = brightnessSlider;
  135. [brightnessSlider setFloatValue:brightness];
  136. [brightnessLabel setTitle:[NSString stringWithFormat:@"Value: %.0f%%", brightness]];
  137. // Prepare serial port menu
  138. BOOL foundPort = NO;
  139. NSArray *ports = [Serial listSerialPorts];
  140. if ([ports count] > 0) {
  141. [menuPorts removeAllItems];
  142. for (int i = 0; i < [ports count]; i++) {
  143. // Add Menu Item for this port
  144. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[ports objectAtIndex:i] action:@selector(selectedSerialPort:) keyEquivalent:@""];
  145. [menuPorts addItem:item];
  146. // Set Enabled if it was used the last time
  147. if ((savedPort != nil) && [[ports objectAtIndex:i] isEqualToString:savedPort]) {
  148. // Try to open serial port
  149. [serial setPortName:savedPort];
  150. if (![serial openPort]) {
  151. foundPort = YES;
  152. [[menuPorts itemAtIndex:i] setState:NSOnState];
  153. }
  154. }
  155. }
  156. if (!foundPort) {
  157. // I'm using a cheap chinese Arduino Nano clone with a CH340 chipset.
  158. // This driver creates device-files in /dev/cu.* that don't correspond
  159. // to the chip-id and change every time the adapter is re-enumerated.
  160. // That means we may have to try and find the device again after the
  161. // stored name does no longer exist. In this case, we simply try the first
  162. // device that starts with /dev/cu.wchusbserial*...
  163. for (int i = 0; i < [ports count]; i++) {
  164. if ([[ports objectAtIndex:i] hasPrefix:@"/dev/cu.wchusbserial"]) {
  165. // Try to open serial port
  166. [serial setPortName:savedPort];
  167. if (![serial openPort]) {
  168. [[menuPorts itemAtIndex:i] setState:NSOnState];
  169. // Reattempt next matching device when opening this one fails.
  170. break;
  171. }
  172. }
  173. }
  174. }
  175. }
  176. [Screenshot init:self];
  177. lastDisplayIDs = [Screenshot listDisplays];
  178. if (ambilightIsOn) {
  179. timer = [NSTimer scheduledTimerWithTimeInterval:DISPLAY_DELAY target:self selector:@selector(visualizeDisplay:) userInfo:nil repeats:NO];
  180. [buttonAmbilight setState:NSOnState];
  181. }
  182. }
  183. - (void)applicationWillTerminate:(NSNotification *)aNotification {
  184. // Stop previous timer setting
  185. if (timer != nil) {
  186. [timer invalidate];
  187. timer = nil;
  188. }
  189. // Remove display callback
  190. [Screenshot close:self];
  191. // Turn off all lights if possible
  192. if ([serial isOpen]) {
  193. [self sendNullFrame];
  194. [serial closePort];
  195. }
  196. }
  197. - (IBAction)relistSerialPorts:(id)sender {
  198. // Refill port list
  199. NSArray *ports = [Serial listSerialPorts];
  200. [menuPorts removeAllItems];
  201. for (int i = 0; i < [ports count]; i++) {
  202. // Add Menu Item for this port
  203. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[ports objectAtIndex:i] action:@selector(selectedSerialPort:) keyEquivalent:@""];
  204. [menuPorts addItem:item];
  205. // Mark it if it is currently open
  206. if ([serial isOpen]) {
  207. if ([[ports objectAtIndex:i] isEqualToString:[serial portName]]) {
  208. [[menuPorts itemAtIndex:i] setState:NSOnState];
  209. }
  210. }
  211. }
  212. }
  213. - (void)selectedSerialPort:(NSMenuItem *)source {
  214. // Store selection for next start-up
  215. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  216. [store setObject:[source title] forKey:PREF_SERIAL_PORT];
  217. [store synchronize];
  218. // De-select all other ports
  219. for (int i = 0; i < [menuPorts numberOfItems]; i++) {
  220. [[menuPorts itemAtIndex:i] setState:NSOffState];
  221. }
  222. // Select only the current port
  223. [source setState:NSOnState];
  224. // Close previously opened port, if any
  225. if ([serial isOpen]) {
  226. [serial closePort];
  227. }
  228. // Stop previous timer setting
  229. if (timer != nil) {
  230. [timer invalidate];
  231. timer = nil;
  232. }
  233. // Turn off ambilight button
  234. [buttonAmbilight setState:NSOffState];
  235. // Try to open selected port
  236. [serial setPortName:[source title]];
  237. if ([serial openPort] != 0) {
  238. [source setState:NSOffState];
  239. }
  240. }
  241. - (IBAction)toggleAmbilight:(NSMenuItem *)sender {
  242. if ([sender state] == NSOnState) {
  243. [sender setState:NSOffState];
  244. // Stop previous timer setting
  245. if (timer != nil) {
  246. [timer invalidate];
  247. timer = nil;
  248. }
  249. [self sendNullFrame];
  250. // Store state
  251. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  252. [store setObject:[NSNumber numberWithBool:NO] forKey:PREF_TURNED_ON];
  253. [store synchronize];
  254. } else {
  255. [sender setState:NSOnState];
  256. timer = [NSTimer scheduledTimerWithTimeInterval:DISPLAY_DELAY target:self selector:@selector(visualizeDisplay:) userInfo:nil repeats:NO];
  257. // Store state
  258. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  259. [store setObject:[NSNumber numberWithBool:YES] forKey:PREF_TURNED_ON];
  260. [store synchronize];
  261. }
  262. }
  263. - (void)stopAmbilight {
  264. restartAmbilight = NO;
  265. if (timer != nil) {
  266. restartAmbilight = YES;
  267. [timer invalidate];
  268. timer = nil;
  269. [buttonAmbilight setState:NSOffState];
  270. }
  271. }
  272. - (void)newDisplayList:(NSArray *)displayIDs {
  273. lastDisplayIDs = displayIDs;
  274. if (restartAmbilight) {
  275. restartAmbilight = NO;
  276. [buttonAmbilight setState:NSOnState];
  277. timer = [NSTimer scheduledTimerWithTimeInterval:DISPLAY_DELAY target:self selector:@selector(visualizeDisplay:) userInfo:nil repeats:NO];
  278. }
  279. }
  280. - (IBAction)brightnessMoved:(NSSlider *)sender {
  281. [brightnessLabel setTitle:[NSString stringWithFormat:@"Value: %.0f%%", [sender floatValue]]];
  282. // Store changed value in preferences
  283. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  284. [store setObject:[NSNumber numberWithFloat:[sender floatValue]] forKey:PREF_BRIGHTNESS];
  285. [store synchronize];
  286. }
  287. - (IBAction)showAbout:(id)sender {
  288. [NSApp activateIgnoringOtherApps:YES];
  289. [application orderFrontStandardAboutPanel:self];
  290. }
  291. - (void)sendLEDFrame {
  292. if ([serial isOpen]) {
  293. [serial sendString:MAGIC_WORD];
  294. [serial sendData:(char *)ledColorData withLength:(sizeof(ledColorData) / sizeof(ledColorData[0]))];
  295. }
  296. }
  297. - (void)sendNullFrame {
  298. for (int i = 0; i < (sizeof(ledColorData) / sizeof(ledColorData[0])); i++) {
  299. ledColorData[i] = 0;
  300. }
  301. [self sendLEDFrame];
  302. }
  303. // ----------------------------------------------------
  304. // ------------ 'Ambilight' Visualizations ------------
  305. // ----------------------------------------------------
  306. UInt8 ledColorData[LED_COUNT * 3];
  307. - (UInt32)calculateAverage:(unsigned char *)data Width:(NSInteger)width Height:(NSInteger)height SPP:(NSInteger)spp Alpha:(BOOL)alpha StartX:(NSInteger)startX StartY:(NSInteger)startY EndX:(NSInteger)endX EndY:(NSInteger)endY {
  308. int redC = 0, greenC = 1, blueC = 2;
  309. if (alpha) {
  310. redC = 1; greenC = 2; blueC = 3;
  311. }
  312. NSInteger xa, xb, ya, yb;
  313. if (startX < endX) {
  314. xa = startX;
  315. xb = endX;
  316. } else {
  317. xa = endX;
  318. xb = startX;
  319. }
  320. if (startY < endY) {
  321. ya = startY;
  322. yb = endY;
  323. } else {
  324. ya = endY;
  325. yb = startY;
  326. }
  327. unsigned long red = 0, green = 0, blue = 0, count = 0;
  328. for (NSInteger i = xa; i < xb; i += AVERAGE_PIXEL_SKIP) {
  329. for (NSInteger j = ya; j < yb; j++) {
  330. count++;
  331. unsigned long index = i + (j * width);
  332. red += data[(index * spp) + redC];
  333. green += data[(index * spp) + greenC];
  334. blue += data[(index * spp) + blueC];
  335. }
  336. }
  337. red /= count;
  338. green /= count;
  339. blue /= count;
  340. red *= [brightnessSlider floatValue] / 100.0f;
  341. green *= [brightnessSlider floatValue] / 100.0f;
  342. blue *= [brightnessSlider floatValue] / 100.0f;
  343. return ((UInt32)red << 16) | ((UInt32)green << 8) | ((UInt32)blue);
  344. }
  345. - (void)visualizeSingleDisplay:(NSInteger)disp Data:(unsigned char *)data Width:(unsigned long)width Height:(unsigned long)height SPP:(NSInteger)spp Alpha:(BOOL)alpha {
  346. for (int i = 0; i < (sizeof(strands) / sizeof(strands[0])); i++) {
  347. if (strands[i].display == disp) {
  348. // Walk the strand, calculating value for each LED
  349. unsigned long x = strands[i].startX;
  350. unsigned long y = strands[i].startY;
  351. unsigned long blockWidth = COLOR_AVERAGE_OTHER_DIMENSION_SIZE;
  352. unsigned long blockHeight = COLOR_AVERAGE_OTHER_DIMENSION_SIZE;
  353. if ((strands[i].direction == DIR_LEFT) || (strands[i].direction == DIR_RIGHT)) {
  354. blockWidth = strands[i].size;
  355. } else {
  356. blockHeight = strands[i].size;
  357. }
  358. for (int led = strands[i].idMin; led < (strands[i].idMin + strands[i].count); led++) {
  359. // First move appropriately in the direction of the strand
  360. unsigned long endX = x, endY = y;
  361. if (strands[i].direction == DIR_LEFT) {
  362. endX -= blockWidth;
  363. } else if (strands[i].direction == DIR_RIGHT) {
  364. endX += blockWidth;
  365. } else if (strands[i].direction == DIR_UP) {
  366. endY -= blockHeight;
  367. } else if (strands[i].direction == DIR_DOWN) {
  368. endY += blockHeight;
  369. }
  370. // But also span the averaging-square in the other dimension, depending on which
  371. // side of the monitor we're at.
  372. if ((strands[i].direction == DIR_LEFT) || (strands[i].direction == DIR_RIGHT)) {
  373. if (y == 0) {
  374. endY = blockHeight;
  375. } else if (y == displays[disp].height) {
  376. endY -= blockHeight;
  377. }
  378. } else {
  379. if (x == 0) {
  380. endX = blockWidth;
  381. } else if (x == displays[disp].width) {
  382. endX -= blockWidth;
  383. }
  384. }
  385. // Calculate average color for this led
  386. UInt32 color = [self calculateAverage:data Width:width Height:height SPP:spp Alpha:alpha StartX:x StartY:y EndX:endX EndY:endY];
  387. #ifdef TARGET_COLOR_TEMPERATURE
  388. struct Color3 c = { ((color & 0xFF0000) >> 16) / 255.0, ((color & 0x00FF00) >> 8) / 255.0, (color & 0x0000FF) / 255.0 };
  389. c = getRGBfromTemperature(TARGET_COLOR_TEMPERATURE, c);
  390. ledColorData[led * 3] = (int)(c.r * 255.0);
  391. ledColorData[(led * 3) + 1] = (int)(c.g * 255.0);
  392. ledColorData[(led * 3) + 2] = (int)(c.b * 255.0);
  393. #else
  394. ledColorData[led * 3] = (color & 0xFF0000) >> 16;
  395. ledColorData[(led * 3) + 1] = (color & 0x00FF00) >> 8;
  396. ledColorData[(led * 3) + 2] = color & 0x0000FF;
  397. #endif
  398. // Move to next LED
  399. if ((strands[i].direction == DIR_LEFT) || (strands[i].direction == DIR_RIGHT)) {
  400. x = endX;
  401. } else {
  402. y = endY;
  403. }
  404. }
  405. }
  406. }
  407. }
  408. - (void)visualizeDisplay:(NSTimer *)time {
  409. #ifdef DEBUG_PRINT_FPS
  410. static NSInteger frameCount = 0;
  411. static NSDate *lastPrintTime = nil;
  412. if (lastPrintTime == nil) {
  413. lastPrintTime = [NSDate date];
  414. }
  415. #endif
  416. //NSLog(@"Running Ambilight-Algorithm (%lu)...", (unsigned long)[lastDisplayIDs count]);
  417. // Create a Screenshot for all connected displays
  418. for (NSInteger i = 0; i < [lastDisplayIDs count]; i++) {
  419. NSBitmapImageRep *screen = [Screenshot screenshot:[lastDisplayIDs objectAtIndex:i]];
  420. unsigned long width = [screen pixelsWide];
  421. unsigned long height = [screen pixelsHigh];
  422. // Ensure we can handle the format of this display
  423. NSInteger spp = [screen samplesPerPixel];
  424. if (((spp != 3) && (spp != 4)) || ([screen isPlanar] == YES) || ([screen numberOfPlanes] != 1)) {
  425. NSLog(@"Unknown image format for %ld (%ld, %c, %ld)!\n", (long)i, (long)spp, ([screen isPlanar] == YES) ? 'p' : 'n', (long)[screen numberOfPlanes]);
  426. continue;
  427. }
  428. // Find out how the color components are ordered
  429. BOOL alpha = NO;
  430. if ([screen bitmapFormat] & NSAlphaFirstBitmapFormat) {
  431. alpha = YES;
  432. }
  433. // Try to find the matching display id for the strand associations
  434. for (int n = 0; n < (sizeof(displays) / sizeof(displays[0])); n++) {
  435. if ((width == displays[n].width) && (height == displays[n].height)) {
  436. unsigned char *data = [screen bitmapData];
  437. [self visualizeSingleDisplay:n Data:data Width:width Height:height SPP:spp Alpha:alpha];
  438. break;
  439. }
  440. }
  441. }
  442. [self sendLEDFrame];
  443. #ifdef DEBUG_PRINT_FPS
  444. frameCount++;
  445. NSDate *now = [NSDate date];
  446. NSTimeInterval interval = [now timeIntervalSinceDate:lastPrintTime];
  447. if (interval >= DEBUG_PRINT_FPS) {
  448. NSLog(@"FPS: %.2f", frameCount / interval);
  449. frameCount = 0;
  450. lastPrintTime = now;
  451. }
  452. #endif
  453. timer = [NSTimer scheduledTimerWithTimeInterval:DISPLAY_DELAY target:self selector:@selector(visualizeDisplay:) userInfo:nil repeats:NO];
  454. }
  455. // ----------------------------------------------------
  456. // ----------- Color Temperature Adjustment -----------
  457. // ----------------------------------------------------
  458. #define LUMINANCE_PRESERVATION 0.75
  459. #define EPSILON 1e-10
  460. #define SATURATION_FACTOR 0.9
  461. struct Color3 {
  462. float r, g, b;
  463. };
  464. float saturateFloat(float v) {
  465. if (v < 0.0f) {
  466. return 0.0f;
  467. } else if (v > 1.0f) {
  468. return 1.0f;
  469. } else {
  470. return v;
  471. }
  472. }
  473. struct Color3 saturateColor(struct Color3 v) {
  474. v.r = saturateFloat(v.r);
  475. v.g = saturateFloat(v.g);
  476. v.b = saturateFloat(v.b);
  477. return v;
  478. }
  479. struct Color3 colorTemperatureToRGB(float temperatureInKelvins) {
  480. struct Color3 retColor;
  481. if (temperatureInKelvins < 1000.0) {
  482. temperatureInKelvins = 1000.0;
  483. } else if (temperatureInKelvins > 40000) {
  484. temperatureInKelvins = 40000.0;
  485. }
  486. temperatureInKelvins /= 100.0;
  487. if (temperatureInKelvins <= 66.0) {
  488. retColor.r = 1.0;
  489. retColor.g = saturateFloat(0.39008157876901960784 * log(temperatureInKelvins) - 0.63184144378862745098);
  490. } else {
  491. float t = temperatureInKelvins - 60.0;
  492. retColor.r = saturateFloat(1.29293618606274509804 * pow(t, -0.1332047592));
  493. retColor.g = saturateFloat(1.12989086089529411765 * pow(t, -0.0755148492));
  494. }
  495. if (temperatureInKelvins >= 66.0) {
  496. retColor.b = 1.0;
  497. } else if (temperatureInKelvins <= 19.0) {
  498. retColor.b = 0.0;
  499. } else {
  500. retColor.b = saturateFloat(0.54320678911019607843 * log(temperatureInKelvins - 10.0) - 1.19625408914);
  501. }
  502. return retColor;
  503. }
  504. float luminance(struct Color3 color) {
  505. float min = fmin(fmin(color.r, color.g), color.b);
  506. float max = fmax(fmax(color.r, color.g), color.b);
  507. return (max + min) / 2.0;
  508. }
  509. struct Color3 HUEtoRGB(float h) {
  510. float r = fabs(h * 6.0 - 3.0) - 1.0;
  511. float g = 2.0 - fabs(h * 6.0 - 2.0);
  512. float b = 2.0 - fabs(h * 6.0 - 4.0);
  513. struct Color3 ret = { r, g, b };
  514. return saturateColor(ret);
  515. }
  516. struct Color3 HSLtoRGB(struct Color3 hsl) {
  517. struct Color3 rgb = HUEtoRGB(hsl.r);
  518. float c = (1.0 - fabs(2.0 * hsl.b - 1.0)) * hsl.g;
  519. struct Color3 ret = { (rgb.r - 0.5) * c + hsl.b, (rgb.g - 0.5) * c + hsl.b, (rgb.b - 0.5) * c + hsl.b };
  520. return ret;
  521. }
  522. struct Color3 RGBtoHCV(struct Color3 rgb) {
  523. // Based on work by Sam Hocevar and Emil Persson
  524. struct Color3 p;
  525. float pw;
  526. if (rgb.g < rgb.b) {
  527. p.r = rgb.b;
  528. p.g = rgb.g;
  529. p.b = -1.0;
  530. pw = 2.0 / 3.0;
  531. } else {
  532. p.r = rgb.g;
  533. p.g = rgb.b;
  534. p.b = 0.0;
  535. pw = -1.0 / 3.0;
  536. }
  537. struct Color3 q;
  538. float qw;
  539. if (rgb.r < p.r) {
  540. q.r = p.r;
  541. q.g = p.g;
  542. q.b = pw;
  543. qw = rgb.r;
  544. } else {
  545. q.r = rgb.r;
  546. q.g = p.g;
  547. q.b = p.b;
  548. qw = p.r;
  549. }
  550. float c = q.r - fmin(qw, q.g);
  551. float h = fabs((qw - q.g) / (6.0 * c + EPSILON) + q.b);
  552. struct Color3 res = { h, c, q.r };
  553. return res;
  554. }
  555. struct Color3 RGBtoHSL(struct Color3 rgb) {
  556. struct Color3 hcv = RGBtoHCV(rgb);
  557. float l = hcv.b - hcv.g * 0.5;
  558. float s = hcv.g / (1.0 - fabs(l * 2.0 - 1.0) + EPSILON);
  559. struct Color3 res = { hcv.r, s, l };
  560. return res;
  561. }
  562. float mixFloat(float a, float b, float factor) {
  563. return a + ((b - a) * factor);
  564. }
  565. struct Color3 mixColor(struct Color3 a, struct Color3 b, float factor) {
  566. struct Color3 res;
  567. res.r = mixFloat(a.r, b.r, factor);
  568. res.g = mixFloat(a.g, b.g, factor);
  569. res.b = mixFloat(a.b, b.b, factor);
  570. return res;
  571. }
  572. struct Color3 blendColor(struct Color3 a, struct Color3 b) {
  573. struct Color3 res;
  574. res.r = a.r * b.r;
  575. res.g = a.g * b.g;
  576. res.b = a.b * b.b;
  577. return res;
  578. }
  579. // http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/
  580. // Given a temperature (in Kelvin), estimate an RGB equivalent
  581. struct Color3 getRGBfromTemperature(float temperature, struct Color3 color) {
  582. struct Color3 tempColor = colorTemperatureToRGB(temperature);
  583. float originalLuminance = luminance(color);
  584. struct Color3 blended = mixColor(color, blendColor(color, tempColor), SATURATION_FACTOR);
  585. struct Color3 resultHSL = RGBtoHSL(blended);
  586. struct Color3 converted = { resultHSL.r, resultHSL.g, originalLuminance };
  587. struct Color3 luminancePreservedRGB = HSLtoRGB(converted);
  588. return mixColor(blended, luminancePreservedRGB, LUMINANCE_PRESERVATION);
  589. }
  590. @end