view weather.c @ 20:17b2bcc42d72 default tip

added check for empty result; minor stuff
author meillo@marmaro.de
date Sun, 27 Jul 2008 21:34:54 +0200
parents 5937504619f2
children
line wrap: on
line source

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "db.h"


enum {
	Nlast = 2,
};

enum { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };

struct weather {
	float temp;
	float sun;
	float rain;
	float wind;
	float hum;
};

float mean_temp[12] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0};
float mean_sun[12] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0};
float mean_rain[12] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0};
float mean_wind[12] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0};
float mean_hum[12] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0};


/* generates random number between -limit and +limit */
float rand_limit(float limit) {
	int r;

	r = rand() / ( ((float) RAND_MAX + 1) / (2*limit) );
	return r - limit;
}




void getlastweather(struct weather lastw[], int nlast) {
	char query[512];
	int i;

	sprintf(query,
			" select temp, sun, rain, wind, hum from weather "
			" order by tick desc "
			" limit %d "
			, nlast
			);
	stmt = db_query(query);
	for (i = 0; i < nlast && sqlite3_step(stmt) == SQLITE_ROW; i++) {
		lastw[i].temp = sqlite3_column_double(stmt, 0);
		lastw[i].sun = sqlite3_column_double(stmt, 1);
		lastw[i].rain = sqlite3_column_double(stmt, 2);
		lastw[i].wind = sqlite3_column_double(stmt, 3);
		lastw[i].hum = sqlite3_column_double(stmt, 4);
	}
	sqlite3_finalize(stmt);
}


void genweather(struct weather* w, struct weather lastw[], int nlast, int month) {
	w->temp = 0.2 * mean_temp[month] + 0.4 * lastw[0].temp + 0.2 * lastw[1].temp + 0.08 * rand_limit(10); // + 0.02 * rand_limit(100);
	w->sun = 0.2 * mean_sun[month] + 0.4 * lastw[0].sun + 0.2 * lastw[1].sun + 0.08 * rand_limit(10); // + 0.02 * rand_limit(100);
	w->rain = 0.2 * mean_rain[month] + 0.4 * lastw[0].rain + 0.2 * lastw[1].rain + 0.08 * rand_limit(10); // + 0.02 * rand_limit(100);
	w->wind = 0.2 * mean_wind[month] + 0.4 * lastw[0].wind + 0.2 * lastw[1].wind + 0.08 * rand_limit(10); // + 0.02 * rand_limit(100);
	w->hum = 0.2 * mean_hum[month] + 0.4 * lastw[0].hum + 0.2 * lastw[1].hum + 0.08 * rand_limit(10); // + 0.02 * rand_limit(100);
}


int setweather(struct weather* w) {
	char query[512];
	sprintf(query,
			" insert into weather "
			" (tick, temp, sun, rain, wind, hum) "
			" values ('%d', '%f', '%f', '%f', '%f', '%f') "
			, gametime, w->temp, w->sun, w->rain, w->wind, w->hum
			);
	if (!db_update(query)) {
		db_error("weather insertion");
		return 0;
	}
	return 1;
}


int weather(void) {
	struct weather w;
	struct weather lastn[Nlast];

	getlastweather(lastn, Nlast);
	genweather(&w, lastn, Nlast, May);
	return setweather(&w);
	/* FIXME: include all functions in return value */
}