HttpReply handle(HttpRequest &hr) { if (hr.url.size() < 8) { std::string accum = "<html><head><title>Fonts</title></head><body>"; char buffer[1024]; for (std::map<std::string, Font *>::iterator it = Font::fonts.begin(); it != Font::fonts.end(); ++it) { sprintf(buffer, "<a href=\"/fonts/%s\">%s.fnt</a><br />", it->first.c_str(), it->first.c_str()); accum += buffer; } accum += "</body></html>"; return HttpReply(200, "Ok", "text/html", accum.c_str()); } else { std::string name = hr.url.substr(7); if (Font::fonts.find(name) == Font::fonts.end()) return HttpReply::defaultReply(404); Blob data = ResourceManager::Instance().storeResource<Font>(Font::fonts[name]); std::string datastr(data.data, data.size); char *buffer = new char[data.size + 4096]; sprintf(buffer, "<html><head><title>Editing %s</title></head><body><form name=\"input\" action=\"/fonts/%s\" method=\"post\"><textarea cols=\"120\" rows=\"50\">%s</textarea><input type=\"submit\" value=\"Save\" /></form></body></html>", name.c_str(), name.c_str(), datastr.c_str()); Blob webpage(strlen(buffer), buffer); return HttpReply(200, "Ok", "text/html", webpage); } }
void testFactory(vector<char> data, seconds duration, seconds maxTimeToTest, int id) { Puzzle p; HardwareSpeedTester hst(1000, maxTimeToTest); TimeCapsuleFactory<char> tcf(hst); //char rawdata[] = "Hey, I hope it will finish in time.. tho probably not :D ..."; auto capsule = tcf.createTimeCapsule(p, data, duration); capsule.save("capsule_" + to_string(id) + ".dat"); Capsule<char> capsule2; capsule2.load("capsule_" + to_string(id) + ".dat"); auto crdata = capsule.getCryptedData(); auto crdata2 = capsule2.getCryptedData(); assert(capsule.getBase() == capsule2.getBase()); assert(capsule.getN() == capsule2.getN()); assert(capsule.getIV() == capsule2.getIV()); assert(capsule.getCryptedKey() == capsule2.getCryptedKey()); assert(capsule.getNumberOfOperations() == capsule2.getNumberOfOperations()); Logger::log("Original crypted data size: " + to_string(crdata.size())); Logger::log("Copypasted crypted data size: " + to_string(crdata2.size())); string datastr(crdata.begin(), crdata.end()); string datastr2(crdata2.begin(), crdata2.end()); Logger::log("Original crypted data: " + datastr); Logger::log("Copypasted crypted data: " + datastr2); //cout << capsule.getCryptedData().size() << ", " << capsule2.getCryptedData().size() << endl; //assert(capsule.getCryptedData().size() == capsule2.getCryptedData().size()); //for (size_t i = 0; i < capsule.getCryptedData().size(); ++i) // assert(capsule.getCryptedData()[i] == capsule2.getCryptedData()[i]); Puzzle p2(capsule2.getBase()); auto start = chrono::high_resolution_clock::now(); auto key = p2.solve(capsule2.getCryptedKey(), capsule2.getNumberOfOperations(), capsule2.getN()); auto end = chrono::high_resolution_clock::now(); Logger::log("Time specified to decode: " + to_string(duration.count()) + " seconds"); Logger::log("Time taken to decode: " + to_string(chrono::duration_cast<seconds>(end - start).count()) + " seconds"); Encryptor<char> cr; auto databack = cr.decrypt(capsule2.getCryptedData(), key, capsule2.getIV()); string tmpdata(data.begin(), data.end()); string tmpdataback(databack.begin(), databack.end()); Logger::log("Original data: " + tmpdata); Logger::log("Data decrypted: " + tmpdataback); /*char dummychar; if (crdata.size() != crdata2.size()) { Logger::log("PARA VAN!"); cin >> dummychar; }*/ }
void TestSerialization::testStreamRead() { std::string datastr( (const char *)test_serialized_data, sizeof(test_serialized_data)); std::istringstream is(datastr, std::ios_base::binary); UASSERT(readU8(is) == 0x11); UASSERT(readU16(is) == 0x2233); UASSERT(readU32(is) == 0x44556677); UASSERT(readU64(is) == 0x8899AABBCCDDEEFF); UASSERT(readS8(is) == -128); UASSERT(readS16(is) == 30000); UASSERT(readS32(is) == -6); UASSERT(readS64(is) == -43); UASSERT(readF1000(is) == 53.534f); UASSERT(readF1000(is) == -300000.32f); UASSERT(readF1000(is) == F1000_MIN); UASSERT(readF1000(is) == F1000_MAX); UASSERT(deSerializeString(is) == "foobar!"); UASSERT(readV2S16(is) == v2s16(500, 500)); UASSERT(readV3S16(is) == v3s16(4207, 604, -30)); UASSERT(readV2S32(is) == v2s32(1920, 1080)); UASSERT(readV3S32(is) == v3s32(-400, 6400054, 290549855)); UASSERT(readV2F1000(is) == v2f(500.656f, 350.345f)); UASSERT(deSerializeWideString(is) == L"\x02~woof~\x5455"); UASSERT(readV3F1000(is) == v3f(500, 10024.2f, -192.54f)); UASSERT(readARGB8(is) == video::SColor(255, 128, 50, 128)); UASSERT(deSerializeLongString(is) == "some longer string here"); UASSERT(is.rdbuf()->in_avail() == 2); UASSERT(readU16(is) == 0xF00D); UASSERT(is.rdbuf()->in_avail() == 0); }
int main (int argc, char **argv) { char* ntry = (char*)""; if (argc > 1) { ntry = argv[1]; } double fps = FPS; double target_dur = 1.0/fps; double tol = 1.0e-3; double total_dur = 0.0; dc1394_t * d = dc1394_new(); if (!d) { return 1; } dc1394camera_list_t * list; dc1394error_t err = dc1394_camera_enumerate (d, &list); DC1394_ERR_RTN(err,"Failed to enumerate cameras"); if (list->num == 0) { /* Verify that we have at least one camera */ dc1394_log_error("No cameras found"); return 1; } gCamera.init(d, list->ids[0].guid); if (!gCamera.cam()) { dc1394_log_error("Failed to initialize camera with guid %ld", list->ids[0].guid); dc1394_camera_free_list (list); return 1; } dc1394_camera_free_list (list); /*----------------------------------------------------------------------- * have the camera start sending us data *-----------------------------------------------------------------------*/ err = gCamera.start_transmission(); DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Could not start camera iso transmission"); /*----------------------------------------------------------------------- * capture one frame *-----------------------------------------------------------------------*/ uint32_t width = 0; uint32_t height = 0; gCamera.get_image_size(&width, &height); cv::Mat mapping = cv::getRotationMatrix2D(cv::Point2f(width/2.0, height/2.0), 180.0, 1.0); #ifdef USE_SDL static char *var = (char*)"SDL_VIDEO_WINDOW_POS=\"1280,480\""; int ret = putenv(var); if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cerr << "DC1394: Unable to initialize SDL: " << SDL_GetError() << std::endl; return 1; } atexit(SDL_Quit); SDL_Surface *screen; screen = SDL_SetVideoMode(width, height, 24, SDL_HWSURFACE); if (screen == NULL) { std::cerr << "DC1394: Unable to set SDL video mode:" << SDL_GetError() << std::endl; } SDL_Event event; #endif #ifndef LICKOMETER pthread_t save_thread, acq_thread; pthread_create( &save_thread, NULL, &thread_save_image, NULL); #endif pthread_t save_thread, acq_thread; pthread_create( &acq_thread, NULL, &thread_acq_image, NULL); timespec t_sleep, t_rem; t_sleep.tv_sec = 0; t_sleep.tv_nsec = 1000; #ifndef STANDALONE int s; if ((s = socket(SOCKTYPE, SOCK_STREAM, 0)) < 0) { perror("DC1394: client: socket"); cleanup_and_exit(gCamera); return 1; } /* * Create the address we will be connecting to. */ #ifndef INET sockaddr_un sa; sa.sun_family = AF_UNIX; std::ostringstream tmpfn; tmpfn << "fwsocket" << ntry; std::cout << "DC1394: socket name " << tmpfn.str() << std::endl; int nameLen = strlen(tmpfn.str().c_str()); if (nameLen >= (int) sizeof(sa.sun_path) -1) { /* too long? */ cleanup_and_exit(gCamera); return 1; } sa.sun_path[0] = '\0'; /* abstract namespace */ strcpy(sa.sun_path+1, tmpfn.str().c_str()); int len = 1 + nameLen + offsetof(struct sockaddr_un, sun_path); #else sockaddr_in sa; bzero((char *) &sa, sizeof(sa)); sa.sin_family = AF_INET; hostent *server = gethostbyname("128.40.156.129"); bcopy((char *)server->h_addr, (char *)&sa.sin_addr.s_addr, server->h_length); sa.sin_port = htons(35000); int len = sizeof(sa); #endif /* * Try to connect to the address. For this to * succeed, the server must already have bound * this address, and must have issued a listen() * request. * * The third argument indicates the "length" of * the structure, not just the length of the * socket name. */ std::cout << "DC1394: Waiting for connection... " << std::flush; while (true) { // wait for connection: if (connect(s, (sockaddr*)&sa, len) < 0) { nanosleep(&t_sleep, &t_rem); } else { break; } } std::cout << "done" << std::endl; bool connected = false; std::vector<char> data(BUFSIZE); int nrec = recv(s, &data[0], data.size(), 0); std::string datastr(data.begin(), data.end()); if (nrec<=0) { std::cerr << "DC1394: Didn't receive start message; exiting now" << std::endl; cleanup_and_exit(gCamera); close(s); return 1; } connected = true; std::string ready = "ready"; while (send(s, ready.c_str(), ready.size(), 0) < 0) { perror("DC1394: client: send"); } int flags = 0; if (-1 == (flags = fcntl(s, F_GETFL, 0))) flags = 0; if (fcntl(s, F_SETFL, flags | O_NONBLOCK)==-1) { perror("DC1394: client: unblock"); } #endif /* pthread_mutex_lock( &camera_mutex ); gCamera.wait_for_trigger(); pthread_mutex_unlock( &camera_mutex ); Wait for acq_frame_buffer to fill instead */ int ncount = 0; cv::Mat im(cv::Size(width, height), CV_8UC1); cv::Mat thresh = cv::Mat::ones(cv::Size(width, height), CV_8UC1); cv::Mat prevs(cv::Size(width, height), CV_8UC1); cv::Mat gray(cv::Size(width, height), CV_8UC1); // wait for image: int nframes = get_image(im, mapping, false, -1, "", ncount); std::cout << "DC1394: Waiting for first image to arrive... " << std::flush; int nwait = 0; while (!nframes) { nanosleep(&t_sleep, &t_rem); std::cout << "." << std::flush; nframes = get_image(im, mapping, false, -1, "", ncount); nwait++; #ifdef STANDALONE if (nwait > 1000) { #else if (nwait > 100000) { #endif std::cout << "Time out, stopping now\n"; cleanup_and_exit(gCamera); } } timespec time0; clock_gettime(CLOCK_REALTIME, &time0); std::cout << "DC1394: image arrived: " << IplImage(im).depth << " bits, " << IplImage(im).nChannels << " channels, " << IplImage(im).widthStep << " step width" << std::endl; #ifdef USE_SDL SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)im.data, im.cols, im.rows, IplImage(im).depth*IplImage(im).nChannels, IplImage(im).widthStep, 0xffffff, 0xffffff, 0xffffff, 0); screen = SDL_GetVideoSurface(); if(SDL_BlitSurface(surface, NULL, screen, NULL) == 0) SDL_UpdateRect(screen, 0, 0, 0, 0); #else cv::namedWindow("DC1394", CV_WINDOW_AUTOSIZE); cvMoveWindow("DC1394", 1280, 480); cv::imshow("DC1394", im); #endif timespec time1 = time0; timespec time2 = time0; timespec time3 = time0; timespec time4 = time0; timespec t_disconnect = time0; timespec t_notrigger = time0; #ifdef STANDALONE int s = -1; #endif std::string fn = ""; #ifdef LICKOMETER std::string fn_lick = ""; FILE* fp_lick = NULL; #endif int key = 0; int nloop = 0; while (true) { clock_gettime( CLOCK_REALTIME, &time1); #ifndef STANDALONE std::vector<char> data(BUFSIZE); int nrec = recv(s, &data[0], data.size(), 0); std::string datastr(data.begin(), data.end()); #endif nframes += get_image(im, mapping, false, s, fn, ncount); #ifndef STANDALONE // no update from blender in a long time, terminate process if (datastr.find("1")==std::string::npos) { if (connected) { t_disconnect = time1; connected = false; } else { if (tdiff(time1, t_disconnect) > TIMEOUT) { std::cout << "DC1394: Received termination signal" << std::endl; close(s); pthread_cancel(acq_thread); pthread_cancel(save_thread); return 0; } } } else { connected = true; } /* Explicit termination */ if (datastr.find("quit")!=std::string::npos) { std::cout << "DC1394: Game over signal." << std::endl; std::string sclose = "close"; while (send(s, sclose.c_str(), sclose.size(), 0) < 0) { perror("DC1394: client: send"); } close(s); pthread_cancel(acq_thread); pthread_cancel(save_thread); return 0; } // Stop recording if (datastr.find("stop") != std::string::npos && fn != "") { fn = ""; #ifdef LICKOMETER fn_lick = ""; if (fp_lick) { fclose(fp_lick); fp_lick = NULL; } #endif std::cout << "DC1394: Stopping video" << std::endl; connected = true; ncount = 0; } // Start recording if (datastr.find("avi") != std::string::npos && datastr.find("stop") == std::string::npos && fn == "") { std::size_t startpos = datastr.find("begin")+5; std::size_t endpos = datastr.find("end") - datastr.find("begin") - 5; fn = datastr.substr(startpos, endpos); fn = std::string(trunk) + "data/" + fn; #ifdef LICKOMETER fn_lick = fn + "_lick"; fp_lick = fopen(fn_lick.c_str(), "wb"); std::cout << "DC1394: Recording lick detection, writing to " << fn_lick << std::endl; #else boost::filesystem::path path(fn); boost::filesystem::path writepath(path); // Test whether dir exists: if (!boost::filesystem::exists(writepath)) { std::cout << "DC1394: Creating directory " << writepath << std::endl; boost::filesystem::create_directories(writepath); } fn += "/"; /* check save frame buffer */ std::size_t nfb = save_frame_buffer.size(); if (nfb) std::cerr << "DC1394: Frame buffer isn't empty!" << std::endl; std::cout << "DC1394: Starting video, writing to " << fn << std::endl; connected = true; ncount = 0; #endif } #endif // #nstandalone #ifdef USE_SDL if (SDL_PollEvent(&event)) { #ifdef STANDALONE /* Any of these event types will end the program */ if (event.type == SDL_QUIT || event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) { std::cout << std::endl; std::cout << std::endl << "DC1394: Total number of frames was " << nframes << std::endl; std::cout << std::endl << "DC1394: Frame buffer: " << acq_frame_buffer.size() << " frames left" << std::endl; close(s); pthread_cancel(acq_thread); pthread_cancel(save_thread); return 0; } #endif // STANDALONE } surface->pixels = (void*)im.data; // SDL_CreateRGBSurfaceFrom((void*)IplImage(im).imageData, // IplImage(im).width, // IplImage(im).height, // IplImage(im).depth*IplImage(im).nChannels, // IplImage(im).widthStep, // 1, 1, 1, 0); screen = SDL_GetVideoSurface(); if(SDL_BlitSurface(surface, NULL, screen, NULL) == 0) SDL_UpdateRect(screen, 0, 0, 0, 0); #else // not SDL key = cv::waitKey(2); cv::imshow("DC1394", im); if (key == 1114155 || key == 65579 || key==43 /*+*/) { uint32_t gain = 0; err = dc1394_feature_get_value(gCamera.cam(), DC1394_FEATURE_GAIN, &gain); DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't get gain"); if (gain < gCamera.get_maxgain()-10) { gain += 10; pthread_mutex_lock( &camera_mutex ); err = dc1394_feature_set_value(gCamera.cam(), DC1394_FEATURE_GAIN, gain); pthread_mutex_unlock( &camera_mutex ); std::cout << "DC1394: New gain value: " << gain << std::endl; DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't set gain"); } } if (key == 1114207 || key == 45 /*-*/) { uint32_t gain = 0; err = dc1394_feature_get_value(gCamera.cam(), DC1394_FEATURE_GAIN, &gain); DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't get gain"); if (gain > gCamera.get_mingain()+10) { gain -= 10; pthread_mutex_lock( &camera_mutex ); err = dc1394_feature_set_value(gCamera.cam(), DC1394_FEATURE_GAIN, gain); pthread_mutex_unlock( &camera_mutex ); DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't set gain"); } } #endif // not SDL #ifdef LICKOMETER /* IS THIS ALL YOU NEED THEN? Lick detection */ /* Not required because the captured image is already gray cv::Mat gray = bgr2gray(im); */ gray = thresholding(im, LICK_FRAME_THRESHOLD); if (nloop != 0) { cv::absdiff(prevs, gray, thresh); double pixel_sum_thresh = cv::sum(thresh)[0]; double pixel_sum_gray = cv::sum(gray)[0]; if (pixel_sum_thresh > LICK_SUM_THRESHOLD) { std::cout << "DC1394: Lick" << std::endl; } if (fp_lick != NULL) { fwrite(&pixel_sum_thresh, sizeof(pixel_sum_thresh), 1, fp_lick); fwrite(&pixel_sum_gray, sizeof(pixel_sum_gray), 1, fp_lick); } } prevs = gray.clone(); nloop++; #endif #ifdef STANDALONE if (key == 1048689 || key == 113 /*q*/) { std::cout << "DC1394: Mean frame rate was " << nframes/total_dur << " fps" << std::endl; pthread_cancel(acq_thread); pthread_cancel(save_thread); return 0; } if (key == 1048691 /*s*/) { fn = ""; std::cout << "DC1394: Stopping video" << std::endl; ncount = 0; } if (key == 1048690 /*r*/) { fn = trunk + std::string("tmp/"); std::cout << "DC1394: Starting video, writing to " << fn << std::endl; ncount = 0; } #endif // #standalone clock_gettime( CLOCK_REALTIME, &time2); double loop_dur = tdiff(time2, time3); clock_gettime( CLOCK_REALTIME, &time3); double meanfps = 0; total_dur = tdiff(time3, time0); if (total_dur > 0) meanfps = nframes / total_dur; double currentfps = ret / loop_dur; std::cout << "DC1394: Current fps: " << std::setprecision(7) << currentfps << " Average fps: " << std::setprecision(7) << meanfps << "\r" << std::flush; #ifdef STANDALONE // std::cout << capture_dur << "\t" << target_dur << "\t" << rem << "\t" << loop_dur << std::endl; #endif } if (d) { dc1394_free(d); } #ifndef STANDALONE close(s); #endif return 0; }
MapBlock* Database_SQLite3::loadBlock(v3s16 blockpos) { v2s16 p2d(blockpos.X, blockpos.Z); verifyDatabase(); if(sqlite3_bind_int64(m_database_read, 1, getBlockAsInteger(blockpos)) != SQLITE_OK) infostream<<"WARNING: Could not bind block position for load: " <<sqlite3_errmsg(m_database)<<std::endl; if(sqlite3_step(m_database_read) == SQLITE_ROW) { /* Make sure sector is loaded */ MapSector *sector = srvmap->createSector(p2d); /* Load block */ const char * data = (const char *)sqlite3_column_blob(m_database_read, 0); size_t len = sqlite3_column_bytes(m_database_read, 0); std::string datastr(data, len); // srvmap->loadBlock(&datastr, blockpos, sector, false); try { std::istringstream is(datastr, std::ios_base::binary); u8 version = SER_FMT_VER_INVALID; is.read((char*)&version, 1); if(is.fail()) throw SerializationError("ServerMap::loadBlock(): Failed" " to read MapBlock version"); MapBlock *block = NULL; bool created_new = false; block = sector->getBlockNoCreateNoEx(blockpos.Y); if(block == NULL) { block = sector->createBlankBlockNoInsert(blockpos.Y); created_new = true; } // Read basic data block->deSerialize(is, version, true); // If it's a new block, insert it to the map if(created_new) sector->insertBlock(block); /* Save blocks loaded in old format in new format */ //if(version < SER_FMT_VER_HIGHEST || save_after_load) // Only save if asked to; no need to update version //if(save_after_load) // saveBlock(block); // We just loaded it from, so it's up-to-date. block->resetModified(); } catch(SerializationError &e) { errorstream<<"Invalid block data in database" <<" ("<<blockpos.X<<","<<blockpos.Y<<","<<blockpos.Z<<")" <<" (SerializationError): "<<e.what()<<std::endl; // TODO: Block should be marked as invalid in memory so that it is // not touched but the game can run if(g_settings->getBool("ignore_world_load_errors")){ errorstream<<"Ignoring block load error. Duck and cover! " <<"(ignore_world_load_errors)"<<std::endl; } else { throw SerializationError("Invalid block data in database"); //assert(0); } } sqlite3_step(m_database_read); // We should never get more than 1 row, so ok to reset sqlite3_reset(m_database_read); return srvmap->getBlockNoCreateNoEx(blockpos); // should not be using this here } sqlite3_reset(m_database_read); return(NULL); }