int main() { //Checks for memory leaks in debug mode _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(width, height, "Hikari", nullptr, nullptr); glfwMakeContextCurrent(window); //Set callbacks for keyboard and mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glewExperimental = GL_TRUE; glewInit(); glGetError(); //Define the viewport dimensions glViewport(0, 0, width, height); //Initialize cuda->opengl context cudaCheck(cudaGLSetGLDevice(0)); cudaGraphicsResource *resource; //Create a texture to store ray tracing result GLuint tex; glActiveTexture(GL_TEXTURE0); glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, NULL); cudaCheck(cudaGraphicsGLRegisterImage(&resource, tex, GL_TEXTURE_2D, cudaGraphicsMapFlagsWriteDiscard)); glBindTexture(GL_TEXTURE_2D, 0); Shader final = Shader("fsQuad.vert", "fsQuad.frag"); FullscreenQuad fsQuad = FullscreenQuad(); float4* buffer; cudaCheck(cudaMalloc((void**)&buffer, width * height * sizeof(float4))); cudaCheck(cudaMemset(buffer, 0, width * height * sizeof(float4))); //Mesh float3 offset = make_float3(0); float3 scale = make_float3(15); Mesh cBox("objs/Avent", 0, scale, offset); offset = make_float3(0, 55, 0); scale = make_float3(100); Mesh light("objs/plane", (int)cBox.triangles.size(), scale, offset); cBox.triangles.insert(cBox.triangles.end(), light.triangles.begin(), light.triangles.end()); cBox.aabbs.insert(cBox.aabbs.end(), light.aabbs.begin(), light.aabbs.end()); std::cout << "Num triangles: " << cBox.triangles.size() << std::endl; cBox.root = AABB(fminf(cBox.root.minBounds, light.root.minBounds), fmaxf(cBox.root.maxBounds, light.root.maxBounds)); BVH bvh(cBox.aabbs, cBox.triangles, cBox.root); Camera cam(make_float3(14, 15, 80), make_int2(width, height), 45.0f, 0.04f, 80.0f); Camera* dCam; cudaCheck(cudaMalloc((void**)&dCam, sizeof(Camera))); cudaCheck(cudaMemcpy(dCam, &cam, sizeof(Camera), cudaMemcpyHostToDevice)); cudaCheck(cudaGraphicsMapResources(1, &resource, 0)); cudaArray* pixels; cudaCheck(cudaGraphicsSubResourceGetMappedArray(&pixels, resource, 0, 0)); cudaResourceDesc viewCudaArrayResourceDesc; viewCudaArrayResourceDesc.resType = cudaResourceTypeArray; viewCudaArrayResourceDesc.res.array.array = pixels; cudaSurfaceObject_t viewCudaSurfaceObject; cudaCheck(cudaCreateSurfaceObject(&viewCudaSurfaceObject, &viewCudaArrayResourceDesc)); cudaCheck(cudaGraphicsUnmapResources(1, &resource, 0)); while (!glfwWindowShouldClose(window)) { float currentFrame = float(glfwGetTime()); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; //Check and call events glfwPollEvents(); handleInput(window, cam); if (cam.moved) { frameNumber = 0; cudaCheck(cudaMemset(buffer, 0, width * height * sizeof(float4))); } cam.rebuildCamera(); cudaCheck(cudaMemcpy(dCam, &cam, sizeof(Camera), cudaMemcpyHostToDevice)); frameNumber++; if (frameNumber < 20000) { cudaCheck(cudaGraphicsMapResources(1, &resource, 0)); std::chrono::time_point<std::chrono::system_clock> start, end; start = std::chrono::system_clock::now(); render(cam, dCam, viewCudaSurfaceObject, buffer, bvh.dTriangles, bvh.dNodes, frameNumber, cam.moved); end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed = end - start; std::cout << "Frame: " << frameNumber << " --- Elapsed time: " << elapsed.count() << "s\n"; cudaCheck(cudaGraphicsUnmapResources(1, &resource, 0)); } cam.moved = false; glUseProgram(final.program); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, tex); glClear(GL_COLOR_BUFFER_BIT); final.setUniformi("tRender", 0); fsQuad.render(); //std::cout << glGetError() << std::endl; //Swap the buffers glfwSwapBuffers(window); glfwSetCursorPos(window, lastX, lastY); }
void DoTunnel(float limit) { params.on_speed = 2.0/100.0; params.start_dwell = 2; params.curve_dwell = 0; params.corner_dwell = 2; params.curve_angle = cosf(30.0*(M_PI/180.0)); // 30 deg params.end_dwell = 2; params.snap = 1/100000.0; params.flatness = 0.000005; params.start_wait = 6; params.off_speed = 2.0/30.0; params.end_wait = 3; params.render_flags &= ~RENDER_NOREORDER; olSetRenderParams(¶ms); float ctime = 0; int i,j; olLoadIdentity(); float z = 0.0f; float rz = 0.0f; float dz=1.2; int id=0; while (audiotime < limit) { float left = (limit-audiotime)/AB; olResetColor(); if (ctime < 2.0) olMultColor(C_GREY((int)(255*ctime/2))); else if (left < 2.0) olMultColor(C_GREY((int)(255*left/2))); olLoadIdentity3(); olPerspective(45, 1, 1, 100); while(z > dz) { z -= dz; id++; } olScale3(0.6, 0.6, 1.0); olTranslate3(0, 0, 1.5); olTranslate3(0, 0, -z); tunnel_revxform(rz); for(i=0;i<10;i++) { if ((id+i) > 5) { olPushMatrix3(); olTranslate3(0,0,dz*i); tunnel_xform(rz+dz*(i+id)); olBegin(OL_LINESTRIP); for(j=0;j<11;j++) { float theta = j/5.0*M_PI; uint32_t c = C_RED; if(i==9) { c = C_RED_I((int)(255 * z/dz)); } olVertex3(sinf(theta), cosf(theta), 0, c); //olVertex3(j/11.0,0,0,C_WHITE); } olEnd(); olPopMatrix3(); } } for(j=0;j<10;j++) { float theta = j/5.0*M_PI; olBegin(OL_LINESTRIP); for(i=0;i<9;i++) { if ((id+i) > 5) { olPushMatrix3(); olTranslate3(0,0,dz*i); tunnel_xform(rz+dz*(i+id)); olVertex3(sinf(theta), cosf(theta), 0, C_GREEN_I((int)(255 * i/8.0)) | C_BLUE_I((int)(255 * (1-(i/8.0))))); olPopMatrix3(); } } olEnd(); } ctime += render(); z += ftime*3.2; rz += ftime*3.2; } }
void StereoPainter::paint() { int width = getCanvas()->getSize().x; int height = getCanvas()->getSize().y; // Special handling for side-by-side stereo if (stereoMode_ == SIDE_BY_SIDE) { getCamera()->setRatio(float(width / 2) / height); } // Add headtracking offset if (trackingEnabled_ && headTracker_) { headTracker_->adaptCameraToHead(); } switch (stereoMode_) { default: // Falls through.. case MONOSCOPIC: { glDrawBuffer(GL_BACK); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render middle view // NOTE: Special headtracking frustums might require the stereo handling process // of the camera look() method so we set the eye separation to 0 and render // the left eye view instead of just: // getCamera()->look(Camera::EYE_MIDDLE); float initialEyeSep = getCamera()->getEyeSeparation(); getCamera()->setEyeSeparation(0); getCamera()->look(Camera::EYE_LEFT); getCamera()->setEyeSeparation(initialEyeSep); render(); } break; case FRAME_SEQUENTIAL: glDrawBuffer(GL_BACK); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render left eye view getCamera()->look(Camera::EYE_LEFT); render(); getCanvas()->swap(); // Render right eye view getCamera()->look(Camera::EYE_RIGHT); render(); // For continuous rendering refresh canvas getCanvas()->update(); break; case SIDE_BY_SIDE: glDrawBuffer(GL_BACK); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render left eye view glViewport(0, 0, width / 2, height); getCamera()->look(Camera::EYE_LEFT); render(); // Render right eye view glViewport(width / 2, 0, width / 2, height); getCamera()->look(Camera::EYE_RIGHT); render(); glViewport(0, 0, width, height); break; case ANAGLYPH: glDrawBuffer(GL_BACK); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render left eye view glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE); getCamera()->look(Camera::EYE_LEFT); render(); glClear(GL_DEPTH_BUFFER_BIT); // Render right eye view glColorMask(GL_FALSE, GL_FALSE, GL_TRUE, GL_TRUE); getCamera()->look(Camera::EYE_RIGHT); render(); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); break; case QUADRO_PAGE_FLIPPING: // Render left eye view glDrawBuffer(GL_BACK_LEFT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); getCamera()->look(Camera::EYE_LEFT); render(); // Render right eye view glDrawBuffer(GL_BACK_RIGHT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); getCamera()->look(Camera::EYE_RIGHT); render(); break; case VERTICAL_INTERLACED: glDisable(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glEnable(GL_STENCIL_TEST); glClearStencil(0); glClear(GL_STENCIL_BUFFER_BIT); glStencilMask(0xFFFFFFFF); glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF); glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, width, 0, height, -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glBegin(GL_LINES); for(int x = 0; x < width; x += 2) { glVertex2i(x, 0); glVertex2i(x, height); } glEnd(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render right eye view getCamera()->look(Camera::EYE_RIGHT); glStencilFunc(GL_EQUAL, 1, 0xFFFFFFFF); render(); // Render left eye view getCamera()->look(Camera::EYE_LEFT); glStencilFunc(GL_EQUAL, 0, 0xFFFFFFFF); render(); glDisable(GL_STENCIL_TEST); break; } // Reset camera if (trackingEnabled_ && headTracker_) { headTracker_->resetCamera(); } // Special handling for side-by-side stereo if (stereoMode_ == SIDE_BY_SIDE) { getCamera()->setRatio((float)width / height); } }
void SDLGod::renderTileMap(Arraytrix<prototile>* p_tiles) { blitPrototileMap(p_tiles); render(); }
void DoTitle(float limit) { IldaFile *ild; ild = olLoadIlda("lase_title.ild"); include_dark_points = 1; int count = count_active_points(ild); float cur_draw = 0; float ctime = 0; olSetVertexShader(cutoff); params.render_flags |= RENDER_NOREORDER; olSetRenderParams(¶ms); while(1) { int obj; float w; points_left = cur_draw; olDrawIlda(ild); ctime += render(); cur_draw += ftime * count / 3.0; if (cur_draw > count) { break; } } olSetVertexShader(NULL); while(AB*ctime < 8) { olDrawIlda(ild); ctime += render(); } wipe_center = -1.0; wipe_w = 0.4; wipe_inv = 1; const char *s="A realtime laser demo"; float s_x = -olGetStringWidth(font, 0.2, s) / 2; float s_y = -0.5; float s_h = 0.2; while(1) { olDrawIlda(ild); olSetPixelShader(hwipe); olDrawString(font, s_x, s_y, s_h, C_WHITE, s); olSetPixelShader(NULL); ctime += render(); wipe_center += 1.7*ftime; if(wipe_center > 1.0f) break; } float bright = 300.0f; while(audiotime < limit) { uint32_t col; if (bright > 255.0f) col = C_WHITE; else col = C_GREY((int)bright); olPushColor(); olMultColor(col); olDrawIlda(ild); olDrawString(font, s_x, s_y, s_h, C_WHITE, s); olPopColor(); render(); bright -= ftime * 130.0; if (bright < 0) bright = 0; } }
void carSimulation(std::vector<Car*> cars, std::vector<Wall>* walls, std::vector<glm::vec3>* path, std::vector<double>* distances, GLFWwindow* window) { //TODO: Move this junk to main, or a common class GLuint programID = LoadShaders( "SimpleTransform.vertexshader", "SingleColor.fragmentshader" ); GLuint MatrixID = glGetUniformLocation(programID, "MVP"); GLuint ColorID = glGetUniformLocation(programID, "inColor"); GLuint carbuffer; GLuint carVAO; glGenBuffers(1, &carbuffer); glBindBuffer(GL_ARRAY_BUFFER, carbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(carData), carData, GL_STATIC_DRAW); glGenVertexArrays(1, &carVAO); glBindVertexArray(carVAO); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); GLuint wallbuffer; GLuint wallVAO; glGenBuffers(1, &wallbuffer); glBindBuffer(GL_ARRAY_BUFFER, wallbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(wallData), wallData, GL_STATIC_DRAW); glGenVertexArrays(1, &wallVAO); glBindVertexArray(wallVAO); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); GLuint linebuffer; GLuint lineVAO; glGenBuffers(1, &linebuffer); glBindBuffer(GL_ARRAY_BUFFER, linebuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(lineData), lineData, GL_STATIC_DRAW); glGenVertexArrays(1, &lineVAO); glBindVertexArray(lineVAO); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); glm::mat4 Projection = glm::ortho(-50.0,50.0,-50.0,50.0,0.0,100.0); // In world coordinates int nextPoint = 1; int nbFrames = 0; double StartTime = glfwGetTime(); double time = StartTime; double frameLastTime = StartTime; double oldTime = StartTime; printf("starting\n"); while(cars.size() > 0 && time < 60 * 1) { time = glfwGetTime() - StartTime; // Measure speed double currentTime = glfwGetTime(); nbFrames++; if ( currentTime - frameLastTime >= 1.0 ) { // printf and reset timer printf("%f ms/frame\n", 1000.0/double(nbFrames)); nbFrames = 0; frameLastTime += 1.0; } double now = glfwGetTime(); double deltaTime = now - oldTime; oldTime = now; //test position /* glm::vec3 distance = myCar.getCenter() - path.at(nextPoint); */ /* printf("Next: %i (%f)\n", nextPoint, glm::dot(distance, distance)); */ /* if(glm::dot(distance, distance) < distances.at(nextPoint)*distances.at(nextPoint)) { */ /* nextPoint++; */ /* if (nextPoint > path.size() - 1) { */ /* nextPoint = 0; */ /* } */ /* } */ /* std::vector<Car*> carList = Car::getCarList(); */ glClear( GL_COLOR_BUFFER_BIT ); //start drawing for(std::vector<Car*>::iterator it = cars.begin(); it != cars.end();) { int increment = 1; (*it)->update(deltaTime,*walls); double input[LINE_COUNT + 1]; //For biasing input[0] = 1.0; glm::mat4 carMatrix = Projection * Car::getCamera() * (*it)->getMatrix(); render(programID, MatrixID, ColorID, carbuffer, carVAO, carMatrix, CAR_COLOR); std::vector<DetectLine> lines = (*it)->getLineList(); int i = 0; for (std::vector<DetectLine>::iterator lIt = lines.begin(); lIt != lines.end(); lIt++) { renderLine(programID, MatrixID, ColorID, linebuffer, lineVAO, Projection * Car::getCamera() * lIt->getMatrix(), LINE_COLOR); double closest = -1; for (std::vector<Wall>::iterator wIt = walls->begin(); wIt != walls->end(); wIt++) { glm::mat4 wallMatrix = wIt->getMatrix(); glm::vec3 wallB = glm::vec3(wallMatrix * glm::vec4(1.0,0.0,0.0,1.0)); glm::vec3 wallA = glm::vec3(wallMatrix * glm::vec4(-1.0,0.0,0.0,1.0)); //printf("A:%s, B:%s\n", glm::to_string(wallA).c_str(), glm::to_string(wallB).c_str()); double out = 0; if (collisionLineLine(lIt->getCenter(), lIt->getEnd(), wallA , wallB, &out) == true) { if (closest == -1 || out < closest) { closest = out; } } } input[i+1] = closest; i++; /* printf("Closest:%f\n",closest); */ lIt->setDistance(closest); } NEAT::Organism* org = (*it)->getOrganism(); if (org) { NEAT::Network* net = org->net; net->load_sensors(input); if (!(net->activate())) return; std::vector<NEAT::NNode*>::iterator out_iter = net->outputs.begin(); double steering = (*out_iter)->activation; out_iter++; double accel = (*out_iter)->activation; (*it)->input(accel, steering); glm::vec3 distance = (*it)->getCenter() - path->at(nextPoint); glm::vec3 totalDistance = path->at(nextPoint-1) - path->at(nextPoint); double newFit = (*it)->pointDist + glm::dot(totalDistance, totalDistance)- glm::dot(distance, distance); //remember, distance is squared double deltaFit = org->fitness - newFit; if (deltaFit < 1 && deltaFit > -1) { /* printf("Stuck: %i\n", (*it)->stuckTimer); */ (*it)->stuckTimer += 1; if ((*it)->stuckTimer > 500) { delete (*it); it = cars.erase(it); increment = 0; } } else { (*it)->stuckTimer = 0; } org->fitness = newFit; if(glm::dot(distance, distance) < distances->at(nextPoint)*distances->at(nextPoint)) { (*it)->pointDist += glm::dot(distance, distance); nextPoint++; if (nextPoint > path->size() - 1) { nextPoint = 0; } } /* printf("Fitness: %f\n", org->fitness); */ } if (increment) it++; } for(int i = 0; i < walls->size(); i++) { glm::mat4 wallMatrix = Projection * Car::getCamera() * walls->at(i).getMatrix(); render(programID, MatrixID, ColorID, wallbuffer, wallVAO, wallMatrix, WALL_COLOR); } //finish drawing glfwSwapBuffers(window); glClear( GL_COLOR_BUFFER_BIT ); glfwPollEvents(); } //Done, clean up for(std::vector<Car*>::iterator it = cars.begin(); it != cars.end(); it++) { delete (*it); } cars.clear(); }
int main(int argc, char* argv[]) { printf("SimpleDS\n"); printf("Build: " VERSION_STR " (" SYSTEM_NAME " " SYSTEM_PROCESSOR ")"); #ifdef SDL_HAPTIC_DISABLED printf(" - No Haptic"); #endif printf("\nAuthors: " VERSION_AUTHORS "\n"); args = std::vector<const char*>(argv, argv + argc); int offset = 1; std::string configFile = "./simpleds.conf"; if (hasOpt("-c") || hasOpt("--config")) { configFile = getOpt("-c"); if (configFile.size() == 0) { configFile = getOpt("--config"); } offset += 2; } config = new Config(configFile); if (config->loaded) { printf("Config: %s\n", configFile.c_str()); if (config->has("DS.foo")) { printf("Foo: %s\n", config->getString("DS.foo").c_str()); } } else { printf("Config file couldn't be loaded, won't be able to save\n"); } uint16_t teamNum = (uint16_t)config->getInt32("DS.team"); verbose = (hasOpt("-v") || hasOpt("--verbose")); if (hasOpt("-V") || hasOpt("--version")) { return 0; } if (hasOpt("-h") || hasOpt("--help")) { printUsage(); printf("Options:\n"); printf(" -h, --help Prints this message\n"); printf(" -v, --verbose Output debugging information\n"); printf(" -V, --version Prints version info and exits\n"); printf(" -c, --config Sets the config file to use [default: ./simpleds.conf]\n"); printf(" teamNum The team number to use, must be provided here or in configuration file\n"); return 0; } if (teamNum == 0 && args.begin() + offset == args.end()) { // We're out of arguments printUsage(); return 1; } else { char* endptr; uint16_t argTeamNum = (uint16_t)std::strtol(args[offset], &endptr, 10); if (endptr == args[offset] || *endptr != '\0') { // No team number in config, and none provided if (teamNum == 0) { printUsage(); return 1; } } else { teamNum = argTeamNum; } } printf("Team Number: %d\n", teamNum); bool quit = false; SDL_Event e; auto gui = new GUI(); if (!gui->isValid()) { return 1; } config->setInt32("DS.team", teamNum); config->initInt32("DS.alliance", Alliance::RED); config->initInt32("DS.position", 1); DS::initialize(teamNum); auto ds = DS::getInstance(); enum GUIMode { MAIN, INFO, JOYSTICKS, CONTROL, HELP, COUNT }; GUIMode mode = GUIMode::MAIN; auto runner = std::async(std::launch::async, &DS::run, ds); std::map<GUIMode, Screen*> screens; screens[MAIN] = new ScreenMain(); screens[INFO] = new ScreenInfo(); screens[JOYSTICKS] = new ScreenJoysticks(); screens[CONTROL] = new ScreenControl(); screens[HELP] = new ScreenHelp(); while (!quit) { while (gui->pollEvent(&e) != 0) { if (e.type == SDL_QUIT) { quit = true; } else if (e.type == SDL_JOYDEVICEREMOVED || e.type == SDL_JOYDEVICEADDED) { ds->setEnable(false); ds->loadJoysticks(); } else if (e.type == SDL_KEYDOWN && e.key.repeat == 0) { auto key = e.key.keysym; if (key.sym == SDLK_e) { ds->toggleEnable(); } else if (key.sym == SDLK_SPACE) { ds->setEnable(false); } else if (key.sym == SDLK_0) { ds->setEStop(); } else if (key.sym == SDLK_q) { quit = true; } else if (key.sym == SDLK_r) { if (key.mod & KMOD_SHIFT) { ds->reboot(); } else { ds->restartCode(); } } else if (key.sym == SDLK_BACKQUOTE) { ds->setAlliance(ds->getAlliance() == Alliance::BLUE ? Alliance::RED : Alliance::BLUE); } else if (key.sym >= SDLK_1 && key.sym <= SDLK_9) { uint8_t keyNum = (uint8_t)(1 + key.sym - SDLK_1); if (key.mod & KMOD_CTRL && keyNum >= 1 && keyNum <= 3) { ds->setPosition(keyNum); } else if (key.mod & KMOD_SHIFT && keyNum >= 1 && keyNum <= 3) { ds->setEnable(false); ds->setMode((Mode)(keyNum - 1)); } else if (keyNum >= 1 && keyNum <= GUIMode::COUNT) { mode = (GUIMode)(keyNum - 1); } } } screens[mode]->update(e); } if (gui->readyToDraw()) { gui->setOffset(10, 10); gui->clear(); gui->drawScreen(screens[mode]); gui->setOffset(10, gui->getHeight() - gui->getCharSize().y); gui->drawText(0, 0, "1: Main", mode == GUIMode::MAIN ? Colors::BLACK : Colors::DISABLED); gui->drawTextRel(9, 0, "2: Info", mode == GUIMode::INFO ? Colors::BLACK : Colors::DISABLED); gui->drawTextRel(9, 0, "3: Joysticks", mode == GUIMode::JOYSTICKS ? Colors::BLACK : Colors::DISABLED); gui->drawTextRel(14, 0, "4: Control", mode == GUIMode::CONTROL ? Colors::BLACK : Colors::DISABLED); gui->drawTextRel(12, 0, "5: Help", mode == GUIMode::HELP ? Colors::BLACK : Colors::DISABLED); gui->render(); } std::string s = narf::util::format("Team %d", teamNum); if (ds->isConnected()) { auto rio = ds->getRoboRIO(); s += " - "; if (rio->getEStop()) { s += "E-Stopped"; } else { s += narf::util::format("%s %s", modeNames[rio->getMode()].c_str(), rio->getEnable() ? "Enabled" : "Disabled"); } s += narf::util::format(" - %s %d", allianceNames[ds->getAlliance()].c_str(), ds->getPosition()); if (!rio->getCode()) { s += " - No Code"; } } else { s += " - No Comms"; } gui->setTitle(s); ds->updateJoysticks(); SDL_Delay(25); } ds->saveJoysticks(); ds->stop(); SDL_Quit(); return 0; }
/** * Starting point for the program. * * @param argc The number of command line arguments. * @param argv The array of command line arguments. * @return Program exit status. */ int main(int argc, char **argv) { SDL_Window *win = NULL; SDL_Renderer *rend = NULL; SDL_Texture *tex_player = NULL; if(init(&win, &rend, &tex_player)) { return 1; } Game_Data game_data; game_data.battle_data.state = GAME_BATTLE_MOVE; game_data.battle_data.num_units = 2; game_data.battle_data.board.tiles = malloc(GRID_COLS * GRID_ROWS * sizeof *game_data.battle_data.board.tiles); game_data.battle_data.turn_order = malloc(game_data.battle_data.num_units * sizeof *game_data.battle_data.turn_order); game_data.battle_data.camera_pos = (Coord_f){0.0, 0.0}; game_data.battle_data.camera_vel = (Coord_f){0.0, 0.0}; game_data.battle_data.board.cols = GRID_COLS; game_data.battle_data.board.rows = GRID_ROWS; game_data.battle_data.turn = 0; for(int i = 0; i < GRID_COLS; i++) for(int j = 0; j < GRID_ROWS; j++) { game_data.battle_data.board.tiles[j * GRID_COLS + i].ent = NULL; } SDL_Event event; Battle_Entity *temp; temp = game_data.battle_data.board.tiles[10 * GRID_ROWS + 5].ent = malloc(sizeof(Battle_Entity)); temp->img.tex = tex_player; temp->img.dest_x = 5.0 * WIN_WIDTH / GRID_ROWS; temp->img.dest_y = 10.0 * WIN_HEIGHT / GRID_COLS; temp->img.dest_w = WIN_WIDTH / GRID_ROWS; temp->img.dest_h = WIN_HEIGHT / GRID_COLS; temp->img.src_x = 0.0; temp->img.src_y = 0.0; temp->img.src_w = 0.0; temp->img.src_h = 0.0; temp->team = TEAM_SELECTED; temp->pos = (Coord_f){10.0, 5.0}; temp->vel = (Coord_f){0.0, 0.0}; temp->move_queue.key_size = 0; temp->move_queue.head = NULL; game_data.battle_data.turn_order[0] = temp; temp = game_data.battle_data.board.tiles[19 * GRID_ROWS + 19].ent = malloc(sizeof(Battle_Entity)); temp->img.tex = tex_player; temp->img.dest_x = 19.0 * WIN_WIDTH / GRID_ROWS; temp->img.dest_y = 19.0 * WIN_HEIGHT / GRID_COLS; temp->img.dest_w = WIN_WIDTH / GRID_ROWS; temp->img.dest_h = WIN_HEIGHT / GRID_COLS; temp->img.src_x = 0.0; temp->img.src_y = 0.0; temp->img.src_w = 0.0; temp->img.src_h = 0.0; temp->team = TEAM_SELECTED; temp->pos = (Coord_f){19.0, 19.0}; temp->vel = (Coord_f){0.0, 0.0}; temp->move_queue.key_size = 0; temp->move_queue.head = NULL; game_data.battle_data.turn_order[1] = temp; game_data.battle_data.keys = 0; double time = SDL_GetTicks(); while(game_data.battle_data.state != GAME_STOPPED) { SDL_RenderClear(rend); while(SDL_PollEvent(&event)) { handle_event(&event, &game_data); } update_world(&game_data, SDL_GetTicks() - time); time = SDL_GetTicks(); render(rend, &game_data); SDL_RenderPresent(rend); } free(game_data.battle_data.board.tiles[10 * GRID_ROWS + 5].ent); free(game_data.battle_data.board.tiles[19 * GRID_ROWS + 19].ent); SDL_DestroyTexture(tex_player); SDL_DestroyRenderer(rend); SDL_DestroyWindow(win); SDL_Quit(); return 0; }
void OpenGL::refresh() { clear(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_BGRA, inputFormat, buffer); struct History { GLuint texture; unsigned width, height; GLuint filter, wrap; }; vector<History> history; unsigned sourceWidth = width, sourceHeight = height; history.prepend({texture, sourceWidth, sourceHeight, filter, wrap}); for(auto& p : programs) { unsigned targetWidth = p.absoluteWidth ? p.absoluteWidth : outputWidth; unsigned targetHeight = p.absoluteHeight ? p.absoluteHeight : outputHeight; if(p.relativeWidth) targetWidth = sourceWidth * p.relativeWidth; if(p.relativeHeight) targetHeight = sourceHeight * p.relativeHeight; p.size(targetWidth, targetHeight); glUseProgram(p.program); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, p.framebuffer); glrUniform1i("phase", p.phase); glrUniform1i("sourceLength", history.size()); glrUniform1i("pixmapLength", p.pixmaps.size()); glrUniform4f("targetSize", targetWidth, targetHeight, 1.0 / targetWidth, 1.0 / targetHeight); glrUniform4f("outputSize", outputWidth, outputHeight, 1.0 / outputWidth, 1.0 / outputHeight); //glrUniform4f("targetActualSize", glrSize(targetWidth), glrSize(targetHeight), 1.0 / glrSize(targetWidth), 1.0 / glrSize(targetHeight)); //glrUniform4f("outputActualSize", glrSize(outputWidth), glrSize(outputHeight), 1.0 / glrSize(outputWidth), 1.0 / glrSize(outputHeight)); unsigned aid = 0; for(auto& pixmap : history) { glrUniform1i({"source[", aid, "]"}, aid); glrUniform4f({"sourceSize[", aid, "]"}, pixmap.width, pixmap.height, 1.0 / pixmap.width, 1.0 / pixmap.height); //glrUniform4f({"sourceActualSize[", aid, "]"}, glrSize(pixmap.width), glrSize(pixmap.height), 1.0 / glrSize(pixmap.width), 1.0 / glrSize(pixmap.height)); glActiveTexture(GL_TEXTURE0 + (aid++)); glBindTexture(GL_TEXTURE_2D, pixmap.texture); glrParameters(pixmap.filter, pixmap.wrap); } unsigned bid = 0; for(auto& pixmap : p.pixmaps) { glrUniform1i({"pixmap[", bid, "]"}, aid + bid); glrUniform4f({"pixmapSize[", bid, "]"}, pixmap.width, pixmap.height, 1.0 / pixmap.width, 1.0 / pixmap.height); //glrUniform4f({"pixmapActualSize[", bid, "]"}, glrSize(pixmap.width), glrSize(pixmap.height), 1.0 / glrSize(pixmap.width), 1.0 / glrSize(pixmap.height)); glActiveTexture(GL_TEXTURE0 + aid + (bid++)); glBindTexture(GL_TEXTURE_2D, pixmap.texture); glrParameters(pixmap.filter, pixmap.wrap); } glActiveTexture(GL_TEXTURE0); glrParameters(p.filter, p.wrap); p.render(sourceWidth, sourceHeight, targetWidth, targetHeight); glBindTexture(GL_TEXTURE_2D, p.texture); p.phase = (p.phase + 1) % p.modulo; sourceWidth = p.width, sourceHeight = p.height; history.prepend({p.texture, sourceWidth, sourceHeight, p.filter, p.wrap}); } unsigned targetWidth = absoluteWidth ? absoluteWidth : outputWidth; unsigned targetHeight = absoluteHeight ? absoluteHeight : outputHeight; if(relativeWidth) targetWidth = sourceWidth * relativeWidth; if(relativeHeight) targetHeight = sourceHeight * relativeHeight; glUseProgram(program); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glrUniform1i("source[0]", 0); glrUniform4f("targetSize", targetWidth, targetHeight, 1.0 / targetWidth, 1.0 / targetHeight); glrUniform4f("outputSize", outputWidth, outputHeight, 1.0 / outputWidth, 1.0 / outputHeight); glrParameters(filter, wrap); render(sourceWidth, sourceHeight, outputWidth, outputHeight); }
void setMatrix(MATPTR matrix) { render(&rendered, matrix); }
void RenderablePicoSurface::render (Renderer& renderer, const Matrix4& localToWorld) const { render(renderer, localToWorld, _shader); }
int MusicModel::processArgs(const std::vector<std::string> &args) { System::inform("BEGAN MusicModel::processArgv()...\n"); std::map<std::string, std::string> argsmap; std::string key; for (size_t i = 0, n = args.size(); i < n; ++i) { const std::string token = args[i]; std::string value = ""; if (token.find("--") == 0) { key = token; System::inform("argument[%2d]: %s\n", i, key.c_str()); } else { value = token; System::inform("argument[%2d]: %s = %s\n", i, key.c_str(), value.c_str()); } argsmap[key] = value; } char command[0x200]; int errorStatus = 0; bool postPossible = false; std::string playSoundfileName = getOutputSoundfileName(); if ((argsmap.find("--dir") != argsmap.end()) && !errorStatus) { setOutputDirectory(argsmap["--dir"]); } if ((argsmap.find("--midi") != argsmap.end()) && !errorStatus) { errorStatus = generate(); if (errorStatus) { return errorStatus; } getScore().save(getMidiFilename().c_str()); } if ((argsmap.find("--notation") != argsmap.end()) && !errorStatus) { translateToNotation(); } if ((argsmap.find("--audio") != argsmap.end()) && !errorStatus) { postPossible = false; const char *audiosystem = argsmap["--audio"].c_str(); const char *devicename = argsmap["--device"].c_str(); std::sprintf(command, "csound --midi-key=4 --midi-velocity=5 -m195 -+rtaudio=%s -o %s", audiosystem, devicename); System::inform("Csound command: %s\n", command); setCsoundCommand(command); errorStatus = render(); } if ((argsmap.find("--csound") != argsmap.end()) && !errorStatus) { postPossible = true; errorStatus = render(); } if ((argsmap.find("--pianoteq") != argsmap.end()) && !errorStatus) { std::sprintf(command, "Pianoteq --midi=%s\n", getMidiFilename().c_str()); System::inform("Executing command: %s\n", command); errorStatus = std::system(command); } if ((argsmap.find("--pianoteq-wav") != argsmap.end()) && !errorStatus) { postPossible = true; std::sprintf(command, "Pianoteq --headless --midi %s --rate 48000 --wav %s\n", getMidiFilename().c_str(), getOutputSoundfileName().c_str()); System::inform("Executing command: %s\n", command); errorStatus = std::system(command); } if ((argsmap.find("--playmidi") != argsmap.end()) && !errorStatus) { std::sprintf(command, "%s %s\n", argsmap["--playmidi"].c_str(), getMidiFilename().c_str()); System::inform("Executing command: %s\n", command); errorStatus = std::system(command); } if ((argsmap.find("--post") != argsmap.end()) && !errorStatus && postPossible) { errorStatus = translateMaster(); playSoundfileName = getNormalizedSoundfileName(); } if ((argsmap.find("--playwav") != argsmap.end()) && !errorStatus) { std::sprintf(command, "%s %s\n", argsmap["--playwav"].c_str(), playSoundfileName.c_str()); System::inform("Csound command: %s\n", command); errorStatus = std::system(command); } System::inform("ENDED MusicModel::processArgv().\n"); return errorStatus; }
void _entryPoint() { struct Services services; /****************************> Get Handles <****************************/ //Get a handle to coreinit.rpl OSDynLoad_Acquire("coreinit.rpl", &services.coreinit_handle); //Get a handle to vpad.rpl */ unsigned int vpad_handle; OSDynLoad_Acquire("vpad.rpl", &vpad_handle); /****************************> External Prototypes <****************************/ //VPAD functions int(*VPADRead)(int controller, VPADData *buffer, unsigned int num, int *error); //OS functions void(*_Exit)(); /****************************> Exports <****************************/ //VPAD functions OSDynLoad_FindExport(vpad_handle, 0, "VPADRead", &VPADRead); // Draw functions OSDynLoad_FindExport(services.coreinit_handle, 0, "OSScreenPutPixelEx", &services.OSScreenPutPixelEx); OSDynLoad_FindExport(services.coreinit_handle, 0, "DCFlushRange", &services.DCFlushRange); OSDynLoad_FindExport(services.coreinit_handle, 0, "OSScreenFlipBuffersEx", &services.OSScreenFlipBuffersEx); OSDynLoad_FindExport(services.coreinit_handle, 0, "OSScreenGetBufferSizeEx", &services.OSScreenGetBufferSizeEx); OSDynLoad_FindExport(services.coreinit_handle, 0, "OSScreenPutFontEx", &services.OSScreenPutFontEx); OSDynLoad_FindExport(services.coreinit_handle, 0, "OSScreenClearBufferEx", &services.OSScreenClearBufferEx); //OS functions OSDynLoad_FindExport(services.coreinit_handle, 0, "_Exit", &_Exit); cleanSlate(&services); /****************************> Globals <****************************/ struct SpaceGlobals mySpaceGlobals; //Flag for restarting the entire game. mySpaceGlobals.restart = 1; mySpaceGlobals.services = &services; // initial state is title screen mySpaceGlobals.state = 1; mySpaceGlobals.titleScreenRefresh = 1; //Flags for render states mySpaceGlobals.renderResetFlag = 0; mySpaceGlobals.menuChoice = 0; // 0 is play, 1 is password // setup the password list unsigned int pwSeed = 27; int x; for (x=0; x<100; x++) mySpaceGlobals.passwordList[x] = (int)(prand(&pwSeed)*100000); // set the starting time int64_t (*OSGetTime)(); OSDynLoad_FindExport(services.coreinit_handle, 0, "OSGetTime", &OSGetTime); mySpaceGlobals.seed = OSGetTime(); /****************************> VPAD Loop <****************************/ int error; VPADData vpad_data; // decompress compressed things into their arrays, final argument is the transparent color in their palette decompress_sprite(3061, 200, 100, compressed_title, mySpaceGlobals.title, 39); decompress_sprite(511, 36, 36, compressed_ship, mySpaceGlobals.orig_ship, 14); decompress_sprite(206, 23, 23, compressed_enemy, mySpaceGlobals.enemy, 9); // setup palette and transparent index mySpaceGlobals.curPalette = ship_palette; mySpaceGlobals.transIndex = 14; // initialize starfield for this game initStars(&mySpaceGlobals); mySpaceGlobals.invalid = 1; while (1) { VPADRead(0, &vpad_data, 1, &error); //Get the status of the gamepad mySpaceGlobals.button = vpad_data.btn_hold; mySpaceGlobals.rstick = vpad_data.rstick; mySpaceGlobals.lstick = vpad_data.lstick; mySpaceGlobals.touched = vpad_data.tpdata.touched; if (mySpaceGlobals.touched == 1) { mySpaceGlobals.touchX = ((vpad_data.tpdata.x / 9) - 11); mySpaceGlobals.touchY = ((3930 - vpad_data.tpdata.y) / 16); } if (mySpaceGlobals.restart == 1) { reset(&mySpaceGlobals); mySpaceGlobals.restart = 0; } if (mySpaceGlobals.state == 1) // title screen { displayTitle(&mySpaceGlobals); doMenuAction(&mySpaceGlobals); } else if (mySpaceGlobals.state == 2) // password screen { displayPasswordScreen(&mySpaceGlobals); doPasswordMenuAction(&mySpaceGlobals); } else if (mySpaceGlobals.state == 3) // pause screen { displayPause(&mySpaceGlobals); doMenuAction(&mySpaceGlobals); } else if (mySpaceGlobals.state == 4) // game over screen { displayGameOver(&mySpaceGlobals); doMenuAction(&mySpaceGlobals); } else // game play { //Update location of player1 and 2 paddles p1Move(&mySpaceGlobals); // perform any shooting p1Shoot(&mySpaceGlobals); // handle any collisions handleCollisions(&mySpaceGlobals); // do explosions handleExplosions(&mySpaceGlobals); // if we're out of lives, break if (mySpaceGlobals.lives <= 0 && mySpaceGlobals.state == 4) continue; // add any new enemies addNewEnemies(&mySpaceGlobals); //Render the scene render(&mySpaceGlobals); // check for pausing checkPause(&mySpaceGlobals); } //To exit the game if (mySpaceGlobals.button&BUTTON_HOME) { break; } } cleanSlate(mySpaceGlobals.services); _Exit(); }
void BaseGame::beginGame() { sf::RenderWindow *window = Locator::locate<RenderService>()->getWindow(); // position auto windowSize = window->getSize(); window->setPosition({ Config::getInt("display.position.x") - static_cast<int>(windowSize.x / 2), Config::getInt("display.position.y") - static_cast<int>(windowSize.y / 2) }); // initially fill screen window->clear(backgroundColour); window->display(); start(); fps.init(Config::getFloat("debug.fps-tick-rate")); sf::Clock clock; sf::Event e; // todo separate physics from rendering while (window->isOpen()) { window = Locator::locate<RenderService>()->getWindow(); EventService *es = Locator::locate<EventService>(); // process OS events while (window->pollEvent(e)) { if (e.type == sf::Event::Closed) window->close(); else if (e.type == sf::Event::Resized) Locator::locate<CameraService>()->updateViewSize(e.size.width, e.size.height); else if (e.type == sf::Event::MouseWheelScrolled) { CameraService *camera = Locator::locate<CameraService>(); sf::Vector2i mousePos = {e.mouseWheelScroll.x, e.mouseWheelScroll.y}; const sf::Keyboard::Key &sprintKey = Locator::locate<InputService>()->getKey(KEY_SPRINT); const float increment = sf::Keyboard::isKeyPressed(sprintKey) ? 1.3f : 1.1f; float zoom = e.mouseWheelScroll.delta > 0 ? 1.f / increment : increment; camera->zoomTo(zoom, mousePos, *window); } else if (e.type == sf::Event::KeyPressed || e.type == sf::Event::KeyReleased) { Event event; event.type = EVENT_RAW_INPUT_KEY; event.rawInputKey.key = e.key.code; event.rawInputKey.pressed = e.type == sf::Event::KeyPressed; es->callEvent(event); } else if (e.type == sf::Event::MouseButtonPressed || e.type == sf::Event::MouseButtonReleased) { Event event; event.type = EVENT_RAW_INPUT_CLICK; event.rawInputClick.button = e.mouseButton.button; event.rawInputClick.x = e.mouseButton.x; event.rawInputClick.y = e.mouseButton.y; event.rawInputClick.pressed = e.type == sf::Event::MouseButtonPressed; es->callEvent(event); } } // process game events es->processQueue(); // tick float delta(clock.restart().asSeconds()); tick(delta); // render window->clear(backgroundColour); render(*window); // overlay if (showFPS) { // restore to default for gui display auto windowSize = window->getSize(); window->setView(sf::View(sf::FloatRect(0, 0, windowSize.x, windowSize.y))); fps.tick(delta, *window); } window->display(); } }
PrintSociosBusqueda::PrintSociosBusqueda(QWidget *parent) : QWidget(parent), ui(new Ui::PrintSociosBusqueda) { ui->setupUi(this); ui->labelFecha->setText("FECHA: " + QDate::currentDate().toString("dd/MM/yy")); d_espera = new DialogEspera(); d_espera->setModal (true); d_espera->setWindowTitle("Imprimiendo"); d_espera->setInsideText("Imprimiendo socios"); d_espera->updateValue(1); d_espera->show (); QApplication::processEvents(); int hojas=1; while(model->canFetchMore()) { model->fetchMore(); } int rowCount= model->rowCount(); int maxRowsPerPage = 27; int count=maxRowsPerPage; while (count<rowCount){ count+=maxRowsPerPage; hojas=hojas+1; } hoja=1; hojamax=QString::number(hojas); progressIncrement = static_cast<int>(((100/ hojas)+0.5f)); ui->labelHoja->setText("Hoja 1 de "+hojamax); ui->tableImpresion->setColumnWidth(0,100); ui->tableImpresion->setColumnWidth(1,200); ui->tableImpresion->setColumnWidth(2,200); ui->tableImpresion->setColumnWidth(3,75); ui->tableImpresion->setColumnWidth(4,75); ui->tableImpresion->setColumnWidth(5,120); ui->tableImpresion->setColumnWidth(6,100); ui->tableImpresion->setColumnWidth(7,65); QString styleSheet = "QHeaderView::section {" "spacing: 5px;" "height: 23px;" "background-color: darkcyan;" "color: black;" "border: 1px solid black;" "margin: 0px;" "text-align: right;" "font-family: arialblack;" "font: bold 12px;" "font-size: 12px; }"; ui->tableImpresion->horizontalHeader()->setStyleSheet(styleSheet); int j=0; int i=0; QTableWidgetItem *item; printer.setOutputFormat(QPrinter::PdfFormat); printer.setOrientation(QPrinter::Landscape); QString fileNameAndPath = QFileDialog::getSaveFileName(this, "Guardar en formato PDF", "listaDeSociosAl_" + QDate::currentDate().toString("dd_MM_yy"),"*.pdf"); if (!fileNameAndPath.isNull()) { printer.setOutputFileName(fileNameAndPath); } else { d_espera->close(); delete ui; close(); return; } QPainter painter(&printer); painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::HighQualityAntialiasing); QFont f = QFont(); f.setPixelSize(10); QApplication::processEvents(); while (j<rowCount){ QSqlRecord row = model->record(j); ui->tableImpresion->insertRow(i); item = new QTableWidgetItem(row.value(0).toString()); item->setFont(f); item->setTextAlignment(Qt::AlignCenter); item->setFlags(item->flags()&~Qt::ItemIsEditable); ui->tableImpresion->setItem(i, 0, item); item = new QTableWidgetItem(row.value(2).toString() + ", " + row.value(1).toString()); item->setFont(f); item->setFlags(item->flags()&~Qt::ItemIsEditable); ui->tableImpresion->setItem(i, 1, item); item = new QTableWidgetItem(row.value(3).toString()); item->setFont(f); item->setFlags(item->flags()&~Qt::ItemIsEditable); ui->tableImpresion->setItem(i, 2, item); item = new QTableWidgetItem(row.value(4).toString()); item->setFont(f); item->setTextAlignment(Qt::AlignCenter); item->setFlags(item->flags()&~Qt::ItemIsEditable); ui->tableImpresion->setItem(i, 3, item); item = new QTableWidgetItem(row.value(5).toString()); item->setFlags(item->flags()&~Qt::ItemIsEditable); item->setFont(f); item->setTextAlignment(Qt::AlignCenter); ui->tableImpresion->setItem(i, 4, item); item = new QTableWidgetItem(row.value(6).toString()); item->setFlags(item->flags()&~Qt::ItemIsEditable); item->setFont(f); ui->tableImpresion->setItem(i, 5, item); item = new QTableWidgetItem(row.value(9).toString()); item->setFont(f); item->setFlags(item->flags()&~Qt::ItemIsEditable); ui->tableImpresion->setItem(i, 6, item); item = new QTableWidgetItem(row.value(10).toString()); item->setFont(f); item->setTextAlignment(Qt::AlignCenter); item->setFlags(item->flags()&~Qt::ItemIsEditable); ui->tableImpresion->setItem(i, 7, item); j++; i++; if (i==maxRowsPerPage){ i=0; render(&painter, QPoint(), QRegion(), QWidget::DrawChildren); printer.newPage(); hoja++; ui->tableImpresion->clearContents(); d_espera->updateValue(progressIncrement); QApplication::processEvents(); ui->labelHoja->setText("Hoja "+QString::number(hoja)+" de "+hojamax); } } if (i>0) { render(&painter, QPoint(), QRegion(), QWidget::DrawChildren); QApplication::processEvents(); } painter.end(); d_espera->close(); delete ui; close(); }
int main(int argc, char** argv) { --argc; ++argv; const int WIDTH = 800; const int HEIGHT = 600; /* * Create window */ sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "Window", sf::Style::Default, sf::ContextSettings(32)); /* * Initialize GLEW */ GLenum status = glewInit(); if(status != GLEW_OK) { std::cerr << "[F] GLEW NOT INITIALIZED: "; std::cerr << glewGetErrorString(status) << std::endl; window.close(); return -1; } glEnable(GL_TEXTURE_2D); glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); //glFrontFace(GL_CW); //glCullFace(GL_BACK); //glEnable(GL_CULL_FACE); glClearDepth(1.f); glShadeModel(GL_SMOOTH); /* * Create GUI */ tgui::Gui gui(window); tgui::Gui gui2(window); gui.setGlobalFont("fonts/DejaVuSans.ttf"); loadWidgets(gui, gui2, window); char* args[argc + 1]; /* * load geometry */ Model cube; getArgs(argc, argv, ".obj", args); if (!args[0]) { std::cerr << "[F] MUST SUPPLY 1+ OBJ FILES IN COMMAND LINE ARGS <filename.obj>" << std::endl; exit(-1); } //if cube.mesh = loadMesh(args[0]); if (!cube.mesh) { exit(-1); } //if getArgs(argc, argv, ".scale", args); if (args[0]) { cube.scale = glm::vec3(strtof(args[0], NULL)); } //if else { cube.scale = glm::vec3(1.0f); } //else /* * load shaders */ Shader vertexShader(GL_VERTEX_SHADER); getArgs(argc, argv, ".vs", args); vertexShader.loadFromFile(args[0]? args[0] : ".vs"); vertexShader.compile(); Shader fragmentShader(GL_FRAGMENT_SHADER); getArgs(argc, argv, ".fs", args); fragmentShader.loadFromFile(args[0]? args[0] : ".fs"); fragmentShader.compile(); /* * create program */ ShaderProgram program; program.attachShader(vertexShader); program.attachShader(fragmentShader); program.linkProgram(); program.addAttribute("vertexPosition_modelspace"); program.addAttribute("vertexUV"); //program.addAttribute("vertexNormal_modelspace"); program.addUniform("MVP"); program.addUniform("sampler"); Camera camera; sf::Event event; tgui::Callback callback; Planet p(&cube); /* * main loop */ while (window.isOpen()) { while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::Resized: glViewport(0, 0, event.size.width, event.size.height); camera.projection = glm::perspective(45.0f, float(event.size.width)/float(event.size.height), 0.01f, 100.0f); break; default: break; } //switch gui.handleEvent(event); } //if while (gui.pollCallback(callback)) { gui.handleEvent(event); } //if window.clear(); guiDraw(window, gui2); glClear(GL_DEPTH_BUFFER_BIT); /* * render OpenGL here */ //glValidateProgram(program.program); for (Planet* planet : planets) { render(*planet, camera, program); } //for guiDraw(window, gui); window.display(); } //while // Clean up after ourselves if (window.isOpen()) { window.close(); } //if return EXIT_SUCCESS; } //main
void QwuiWebget::render(QString& mimeType) { mimeType = "text/html"; render(); }
void MainView::keyPressEvent(QKeyEvent *event) { if ( (event->modifiers() & Qt::ControlModifier || event->modifiers() & Qt::ShiftModifier) && event->key() == Qt::Key_Print) { event->accept(); QPrinter printer; printer.setOutputFormat(QPrinter::PdfFormat); printer.setFullPage(true); printer.setResolution(300); QSvgGenerator svggen; svggen.setResolution(90); if (event->modifiers() & Qt::ShiftModifier) { // Print scene printer.setOutputFileName("screenshot-scene.pdf"); printer.setPaperSize(scene()->sceneRect().size().toSize(), QPrinter::Point); QPainter painter(&printer); painter.setRenderHint(QPainter::Antialiasing); scene()->render( &painter ); svggen.setFileName("screenshot-scene.svg"); svggen.setSize(scene()->sceneRect().size().toSize()); QPainter svgPainter(&svggen); svgPainter.setRenderHint(QPainter::Antialiasing); scene()->render(&svgPainter); QImage image(2 * scene()->sceneRect().size().toSize(), QImage::Format_ARGB32); image.fill(Qt::transparent); QPainter pmapPainter(&image); pmapPainter.setRenderHint(QPainter::Antialiasing); //pmapPainter.scale(2,2); scene()->render(&pmapPainter); image.save("screenshot-scene.png"); } else { // Print view printer.setOutputFileName("screenshot-view.pdf"); printer.setPaperSize(viewport()->rect().size(), QPrinter::Point); QPainter painter(&printer); painter.setRenderHint(QPainter::Antialiasing); render(&painter); svggen.setFileName("screenshot-view.svg"); svggen.setSize(viewport()->rect().size()); QPainter svgPainter(&svggen); svgPainter.setRenderHint(QPainter::Antialiasing); render(&svgPainter); QImage image(2 * viewport()->rect().size(), QImage::Format_ARGB32); image.fill(Qt::transparent); QPainter pmapPainter(&image); pmapPainter.setRenderHint(QPainter::Antialiasing); render(&pmapPainter); image.save("screenshot-view.png"); } } else View::keyPressEvent(event); }
void MPGameBrowser::render() { render(0, 0); }
void display() { update(); render(); }
int main() { long double zoom = 1; long double zoom_factor = 1.25; long double shift_x = -11; long double shift_y = 0; // if you have a larger terminal... // should get curses window size int width = 50; int height = 20; int c = 0; short color; initscr(); noecho(); cbreak(); keypad(stdscr,TRUE); color = COLORS >= 256; if (color) { start_color(); init_color(0,62*0,0,0); init_color(1,62*1,0,0); init_color(2,62*2,0,0); init_color(3,62*3,0,0); init_color(4,62*4,0,0); init_color(5,62*5,0,0); init_color(6,62*6,0,0); init_color(7,62*7,0,0); init_color(8,62*8,0,0); init_color(9,62*9,0,0); init_color(10,62*10,0,0); init_color(11,62*11,0,0); init_color(12,62*12,0,0); init_color(13,62*13,0,0); init_color(14,62*14,0,0); init_color(15,62*15,0,0); init_pair(0,0,0); init_pair(1,1,0); init_pair(2,2,0); init_pair(3,3,0); init_pair(4,4,0); init_pair(5,5,0); init_pair(6,6,0); init_pair(7,7,0); init_pair(8,8,0); init_pair(9,9,0); init_pair(10,10,0); init_pair(11,11,0); init_pair(12,12,0); init_pair(13,13,0); init_pair(14,14,0); init_pair(15,15,0); } do { if (c == 'x' || c == 'X' || c == 'q' || c == 'Q') { break; } else if (c == '+') { zoom *= zoom_factor; shift_x *= zoom_factor; shift_y *= zoom_factor; } else if (c == '-') { zoom /= zoom_factor; shift_x /= zoom_factor; shift_y /= zoom_factor; } else if (c == KEY_UP) { shift_y--; } else if (c == KEY_DOWN) { shift_y++; } else if (c == KEY_LEFT) { shift_x--; } else if (c == KEY_RIGHT) { shift_x++; } getmaxyx(stdscr,height,width); if (zoom < 1) zoom = 1; render(color,zoom,shift_x,shift_y,width/2,height/2); refresh(); c = getch(); } while(c); endwin(); return 0; }
int main() { // Init GLFW glfwInit(); // Set all the required options for GLFW glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create a GLFWwindow object that we can use for GLFW's functions GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Fluid simulation", nullptr, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // GLFW Options // glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers glewInit(); // Define the viewport dimensions glViewport(0, 0, WIDTH, HEIGHT); initialize(); Shader vizualizeProgram("defaultVS.vs", "visualize.fs"); Shader advect("defaultVS.vs", "advect.fs"); Shader computeDivergence("defaultVS.vs", "computeDivergence.fs"); Shader makeGravity("defaultVS.vs", "gravityField.fs"); Shader jacobi("defaultVS.vs", "jacobi.fs"); Shader subtractGradient("defaultVS.vs", "subtractGradient.fs"); // Game loop while (!glfwWindowShouldClose(window)) { // Calculate deltatime of current frame GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); update(advect, computeDivergence, makeGravity, jacobi, subtractGradient); render(vizualizeProgram); // Swap the screen buffers glfwSwapBuffers(window); std::this_thread::sleep_for(std::chrono::milliseconds(10)); lastFrame = currentFrame; } // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; }
int main(int argc, char* argv[]){ int verbose_flag; int network_port = PORT; static struct option long_options[] = { {"port", required_argument, 0, 'p' }, {"help", no_argument, 0, 'h'}, {"fullscreen", no_argument, 0, 'f'}, {"verbose", no_argument, &verbose_flag, 'v'}, {0, 0, 0, 0} }; int option_index = 0; int c; while( (c=getopt_long(argc, argv, "p:hfv", long_options, &option_index)) != -1 ) { switch(c) { case 0: break; case 'p': network_port = atoi(optarg); printf("Set port to %i\n", network_port); break; case 'f': fullscreen= true; break; case 'h': show_usage(); exit(0); default: break; } } if ( ! (argc - optind == 2 || argc - optind == 3) ){ show_usage(); exit(1); } const char * nick = argv[optind++]; int team = atoi(argv[optind++])-1; std::string hostname=""; setup(); bool run = true; render_splash(); nw_var_t vars[PAYLOAD_SIZE-1]; if(optind < argc) { hostname = std::string(argv[optind++]); } else { msg = "Searching for server..."; //Try to find with broadcast int sockfd = create_udp_socket(BROADCAST_PORT, true); for(int i=0;i<5 && run; ++i) { render_splash(); printf("Hello, anybody out there?\n"); send_frame(sockfd, broadcast_addr(BROADCAST_PORT), NW_CMD_FIND_SERVER, vars); for(int n=0; n<5 && run; ++n) { //Accept 5 other messages if(data_available(sockfd,2,0)) { addr_t addr; frame_t f = read_frame(sockfd,vars, &addr); if(f.cmd == NW_CMD_EXISTS_SERVER) { hostname = addr.hostname(); network_port = vars[0].i; printf("Yey, found one. Now I'm happy :D\n"); printf("There is a server at %s:%d with %d players\n", hostname.c_str(), network_port, vars[1].i); goto done_searching; } } else break; } printf("Nope :( Maybe later?\n"); poll(&run); usleep(2000000); } done_searching: signal(SIGPIPE, SIG_IGN); //Ignore sigpipe close_socket(sockfd); signal(SIGPIPE, SIG_DFL); //Restore if(hostname == "") { printf("No local server found\n"); cleanup(); exit(3); } } char buffer[256]; sprintf(buffer, "Connecting to %s:%d...", hostname.c_str(), network_port); msg = std::string(buffer); render_splash(); /* verbose dst */ if ( verbose_flag ){ verbose = stdout; } else { verbose = fopen("/dev/null","w"); } srand(time(NULL)); client = new Client(hostname.c_str(), network_port); client->create_me(nick, team); msg = "Connected, loading game..."; while(!ready && run) { render_splash(); usleep(1000); poll(&run); client->incoming_network(); } struct timeval ref; gettimeofday(&ref, NULL); while ( run ){ struct timeval ts; gettimeofday(&ts, NULL); /* calculate dt */ double dt = (ts.tv_sec - ref.tv_sec) * 1000000.0; dt += ts.tv_usec - ref.tv_usec; dt /= 1000000; if(dt > 1) { printf("dt too large, setting to 1: %f\n", dt); dt = 1; } bool last_shield_status = client->me->full_shield; float last_shield_angle = client->me->shield_angle; /* do stuff */ poll(&run); client->incoming_network(); logic(dt); client->run(dt); if(client->me->full_shield != last_shield_status || client->me->shield_angle != last_shield_angle) { client->send_shield(); } render(dt); /* framelimiter */ const int delay = (REF_DT - dt) * 1000000; if ( delay > 0 ){ usleep(delay); } /* store reference time */ ref = ts; } if(ready) client->send_quit(); cleanup(); }
void QGraphicsViewAdapter::repaintRequestedSlot( const QList<QRectF>& ) { // osg::notify(osg::NOTICE)<<"QGraphicsViewAdapter::repaintRequestedSlot"<<std::endl; render(); }
void DoStars(float limit) { int i; float ctime = 0; float lctime = 0; params.start_wait = 7; params.off_speed = 2.0/20.0; params.end_wait = 3; params.render_flags &= ~RENDER_NOREORDER; olSetRenderParams(¶ms); for (i=0; i<NUM_STARS; i++) { stars[i][0] = randf(1.5); stars[i][1] = randf(2*M_PI); stars[i][2] = 0; stars[i][3] = 0; stars[i][4] = randf(255); } ftime = 0; int id = 0; while (!apassed(STAR_ST1)) { for (i=0; i<NUM_PRESETS; i++) { if(apassed(star_deps[i][0]/4.0f)) { printf("%d\n", i); cart_rnd_star(id); stars[id][2] = star_deps[i][1]; stars[id][3] = 1; id = (id+1)%NUM_STARS; } } render_stars(); ctime += render(); for (i=0; i<NUM_STARS; i++) { stars[i][3] -= ftime*0.3; if (stars[i][3] < 0) stars[i][3] = 0; } } int ct = 0; int max; ctime = 0; while (!apassed(STAR_ST2)) { max = ctime * 100.0 / 0x10; while(ct < max) { stars[id][0] = 0.05 + randf(1.50); stars[id][1] = randf(2*M_PI); stars[id][2] = randf(20); stars[id][3] = 1; id = (id+1)%NUM_STARS; ct++; } render_stars(); ctime += render()*AB; } float speed = 0.3; params.start_wait = 6; params.end_wait = 1; olSetRenderParams(¶ms); while (audiotime < limit) { render_stars(); for (i=0; i<NUM_STARS; i++) { stars[i][0] *= (1+speed*ftime); stars[i][3] += speed*ftime; if (stars[i][3] > 1.0) stars[i][3] = 1.0; if (stars[i][0] > 1.5 && audiotime < (limit-2.2*AB)) { stars[i][0] = 0.05 + randf(0.1); stars[i][1] = randf(2*M_PI); stars[i][2] = randf(20); stars[i][3] = 0; } } ctime += render(); if (speed < 2) { speed += 1.2f * ftime; if (speed > 2) speed = 2; } } }
void Chess::run() { sf::Texture textureWhite; std::string textWhiteName = "ChessPiecesTextureWhite.png"; if (!textureWhite.loadFromFile(textWhiteName)) { std::cout << "Couldn't load " << textWhiteName << std::endl; } sf::Texture textureBlack; std::string textBlackName = "ChessPiecesTextureBlack.png"; if (!textureBlack.loadFromFile(textBlackName)) { std::cout << "Couldn't load " << textBlackName << std::endl; } _chessPieces.push_back(new Pawn(textureWhite, _board._tiles[0][6], _player)); _chessPieces.push_back(new Pawn(textureWhite, _board._tiles[1][6], _player)); _chessPieces.push_back(new Pawn(textureWhite, _board._tiles[2][6], _player)); _chessPieces.push_back(new Pawn(textureWhite, _board._tiles[3][6], _player)); _chessPieces.push_back(new Pawn(textureWhite, _board._tiles[4][6], _player)); _chessPieces.push_back(new Pawn(textureWhite, _board._tiles[5][6], _player)); _chessPieces.push_back(new Pawn(textureWhite, _board._tiles[6][6], _player)); _chessPieces.push_back(new Pawn(textureWhite, _board._tiles[7][6], _player)); _chessPieces.push_back(new King(textureWhite, _board._tiles[4][7], _player)); _chessPieces.push_back(new Queen(textureWhite, _board._tiles[3][7], _player)); _chessPieces.push_back(new Rook(textureWhite, _board._tiles[0][7], _player)); _chessPieces.push_back(new Rook(textureWhite, _board._tiles[7][7], _player)); _chessPieces.push_back(new Knight(textureWhite, _board._tiles[1][7], _player)); _chessPieces.push_back(new Knight(textureWhite, _board._tiles[6][7], _player)); _chessPieces.push_back(new Bishop(textureWhite, _board._tiles[2][7], _player)); _chessPieces.push_back(new Bishop(textureWhite, _board._tiles[5][7], _player)); _chessPieces.push_back(new Pawn(textureBlack, _board._tiles[0][1], _computer)); _chessPieces.push_back(new Pawn(textureBlack, _board._tiles[1][1], _computer)); _chessPieces.push_back(new Pawn(textureBlack, _board._tiles[2][1], _computer)); _chessPieces.push_back(new Pawn(textureBlack, _board._tiles[3][1], _computer)); _chessPieces.push_back(new Pawn(textureBlack, _board._tiles[4][1], _computer)); _chessPieces.push_back(new Pawn(textureBlack, _board._tiles[5][1], _computer)); _chessPieces.push_back(new Pawn(textureBlack, _board._tiles[6][1], _computer)); _chessPieces.push_back(new Pawn(textureBlack, _board._tiles[7][1], _computer)); _chessPieces.push_back(new King(textureBlack, _board._tiles[4][0], _computer)); _chessPieces.push_back(new Queen(textureBlack, _board._tiles[3][0], _computer)); _chessPieces.push_back(new Rook(textureBlack, _board._tiles[0][0], _computer)); _chessPieces.push_back(new Rook(textureBlack, _board._tiles[7][0], _computer)); _chessPieces.push_back(new Knight(textureBlack, _board._tiles[1][0], _computer)); _chessPieces.push_back(new Knight(textureBlack, _board._tiles[6][0], _computer)); _chessPieces.push_back(new Bishop(textureBlack, _board._tiles[2][0], _computer)); _chessPieces.push_back(new Bishop(textureBlack, _board._tiles[5][0], _computer)); // Debug test /*std::vector<Tile*> tiles = _chessPieces.back()->possibleMoves(); for (auto t : tiles) { t->_rectShape.setFillColor(sf::Color::Green); }*/ _window = new sf::RenderWindow(sf::VideoMode(600, 600), "Chess", sf::Style::Titlebar | sf::Style::Close); _window->setFramerateLimit(200); // run the program as long as the window is open while (_window->isOpen()) { // check all the window's events that were triggered since the last iteration of the loop sf::Event event; while (_window->pollEvent(event)) { switch (event.type) { // "close requested" event: we close the window case sf::Event::Closed: { _window->close(); } break; case sf::Event::MouseMoved: { _controls._mousePos.x = sf::Mouse::getPosition(*_window).x; _controls._mousePos.y = sf::Mouse::getPosition(*_window).y; } break; case sf::Event::MouseButtonPressed: { switch (event.mouseButton.button) { case sf::Mouse::Left: { _controls._mouseLeft = true; } break; case sf::Mouse::Right: { _controls._mouseRight = true; } break; } } break; case sf::Event::MouseButtonReleased: { switch (event.mouseButton.button) { case sf::Mouse::Left: { _controls._mouseLeft = false; } break; case sf::Mouse::Right: { _controls._mouseRight = false; } break; } } break; case sf::Event::KeyPressed: { switch (event.key.code) { } } break; case sf::Event::KeyReleased: { switch (event.key.code) { } } break; } } update(); _window->clear(); render(); _window->display(); } }
// Build and pop up a buffer containing a list of all screens and their associated buffers. Render buffer and return status. int showScreens(Value *rp,int n) { Buffer *slistp; EScreen *scrp; // Pointer to current screen to list. EWindow *winp; // Pointer into current screens window list. uint wnum; StrList rpt; int windcol = 7; int filecol = 37; char *strp,wkbuf[filecol + 16]; // Get a buffer and open a string list. if(sysbuf(text160,&slistp) != SUCCESS) // "Screens" return rc.status; if(vopen(&rpt,NULL,false) != 0) return vrcset(); // Construct the header lines. if(vputs(text89,&rpt) != 0 || vputc('\n',&rpt) != 0 || // "Screen Window Buffer File" vputs("------ ------ -------------------- -------------------------------",&rpt) != 0) return vrcset(); // For all screens... scrp = sheadp; do { // Store the screen number. sprintf(wkbuf,"\n%4hu ",scrp->s_num); strp = strchr(wkbuf,'\0'); // List screen's window numbers and buffer names. wnum = 0; winp = scrp->s_wheadp; do { Buffer *bufp = winp->w_bufp; // Indent if not first time through. if(wnum != 0) { wkbuf[0] = '\n'; strp = wkbuf + 1; do { *strp++ = ' '; } while(strp <= wkbuf + windcol); } // Store window number, buffer name, and filename. sprintf(strp,"%4u %c%s",++wnum,(bufp->b_flags & BFCHGD) ? '*' : ' ',bufp->b_bname); strp = strchr(strp,'\0'); if(bufp->b_fname != NULL) // Pad if filename exists. do { *strp++ = ' '; } while(strp <= wkbuf + filecol); *strp = '\0'; // Save buffer and add filename. if(vputs(wkbuf,&rpt) != 0 || (bufp->b_fname != NULL && vputs(bufp->b_fname,&rpt) != 0)) return vrcset(); // On to the next window. } while((winp = winp->w_nextp) != NULL); // On to the next screen. } while((scrp = scrp->s_nextp) != NULL); // Add the results to the buffer. if(vclose(&rpt) != 0) return vrcset(); if(bappend(slistp,rpt.sl_vp->v_strp) != SUCCESS) return rc.status; // Display results. return render(rp,n < 0 ? -2 : n,slistp,RENDRESET | (n != INT_MIN && n < -1 ? RENDALTML : 0)); }
//load imgFile and render it at location void ImageCache::render(const std::string imgFile, const Point2D& location) { render(getImage(imgFile), static_cast<int>(location.x), static_cast<int>(location.y)); }
NSCAPI::nagiosReturn CheckWMI::commandLineExec(const std::string &command, const std::list<std::string> &arguments, std::string &result) { try { if (command == "wmi" || command == "help" || command.empty()) { namespace po = boost::program_options; std::string query, ns, user, password, list_cls, list_inst; std::string computer; bool simple; int limit = -1; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "Show help screen") ("select,s", po::value<std::string>(&query), "Execute a query") ("simple", "Use simple format") ("list-classes", po::value<std::string>(&list_cls)->implicit_value(""), "list all classes of a given type") ("list-instances", po::value<std::string>(&list_inst), "list all instances of a given type") ("list-ns", "list all name spaces") ("list-all-ns", "list all name spaces recursively") ("limit,l", po::value<int>(&limit), "Limit number of rows") ("namespace,n", po::value<std::string>(&ns)->default_value("root\\cimv2"), "Namespace") ("computer,c", po::value<std::string>(&computer), "A remote computer to connect to ") ("user,u", po::value<std::string>(&user), "The user for the remote computer") ("password,p", po::value<std::string>(&password), "The password for the remote computer") ; boost::program_options::variables_map vm; if (command == "help") { std::stringstream ss; ss << "wmi Command line syntax:" << std::endl; ss << desc; result = ss.str(); return NSCAPI::isSuccess; } std::vector<std::string> args(arguments.begin(), arguments.end()); po::parsed_options parsed = po::basic_command_line_parser<char>(args).options(desc).run(); po::store(parsed, vm); po::notify(vm); if (vm.count("help") || (vm.count("select") == 0 && vm.count("list-classes") == 0 && vm.count("list-instances") == 0 && vm.count("list-ns") == 0 && vm.count("list-all-ns") == 0)) { std::stringstream ss; ss << "CheckWMI Command line syntax:" << std::endl; ss << desc; result = ss.str(); return NSCAPI::isSuccess; } simple = vm.count("simple") > 0; ns = build_namespace(ns, computer); if (vm.count("select")) { row_type headers; std::vector<std::size_t> widths; std::size_t count = 0; try { wmi_impl::query wmiQuery(query, ns, user, password); std::list<std::string> cols = wmiQuery.get_columns(); count = cols.size(); BOOST_FOREACH(const std::string &col, cols) { headers.push_back(col); widths.push_back(col.size()); } result = render(headers, widths, wmiQuery.execute()); return NSCAPI::isSuccess; } catch (const wmi_impl::wmi_exception &e) { result += "ERROR: " + e.reason(); return NSCAPI::hasFailed; } } else if (vm.count("list-classes")) {
int main (int argc, char **argv) { XEvent event; XSizeHints xsh; XSetWindowAttributes xswa; XVisualInfo *vinfo; glitz_drawable_format_t templ; glitz_drawable_format_t *dformat; unsigned long mask = 0; unsigned int width, height, window_width, window_height; int i; program_name = argv[0]; for (i = 1; i < argc; i++) { if (!strcasecmp ("-image", argv[i])) output_type = IMAGE_TYPE; #ifdef CAIRO_HAS_XLIB_SURFACE else if (!strcasecmp ("-xrender", argv[i])) { output_type = XRENDER_TYPE; } #endif else if (!strcasecmp ("-glx", argv[i])) { output_type = GLX_TYPE; } else if (!strcasecmp ("-noaa", argv[i])) { aa = 0; } else if (!strcasecmp ("-swaa", argv[i])) { aa = 1; } else if (!strcasecmp ("-hwaa", argv[i])) { aa = 3; } else { test_type = get_test_type (argv[i]); } } if (!test_type) { usage(); exit(1); } if (output_type != GLX_TYPE && test_type >= OPENGL_TYPE) { printf ("Sorry, this test only works with OpenGL!\n"); usage(); exit(1); } window_width = width = WINDOW_WIDTH; window_height = height = WINDOW_HEIGHT; if (aa == 3) templ.samples = 4; else templ.samples = 1; templ.depth_size = 16; if (test_type == CUBE_TYPE) mask |= GLITZ_FORMAT_DEPTH_SIZE_MASK; mask |= GLITZ_FORMAT_SAMPLES_MASK; if ((dpy = XOpenDisplay (NULL)) == NULL) { fprintf(stderr, "%s: can't open display: %s\n", argv[0], XDisplayName (NULL)); exit(1); } if (output_type != GLX_TYPE) { xsh.flags = PSize; xsh.width = width; xsh.height = height; xsh.x = 0; xsh.y = 0; win = XCreateWindow (dpy, RootWindow (dpy, DefaultScreen (dpy)), xsh.x, xsh.y, xsh.width, xsh.height, 0, CopyFromParent, CopyFromParent, CopyFromParent, 0, &xswa); XSetStandardProperties (dpy, win, PACKAGE, PACKAGE, None, argv, argc, &xsh); XSetWMHints (dpy, win, &xwmh); XSelectInput (dpy, win, StructureNotifyMask); } else { xsh.flags = PSize; xsh.width = width; xsh.height = height; xsh.x = 0; xsh.y = 0; mask = 0; templ.doublebuffer = 1; mask |= GLITZ_FORMAT_DOUBLEBUFFER_MASK; dformat = glitz_glx_find_window_format (dpy, DefaultScreen (dpy), mask, &templ, 0); vinfo = glitz_glx_get_visual_info_from_format (dpy, DefaultScreen (dpy), dformat); xswa.colormap = XCreateColormap (dpy, RootWindow (dpy, DefaultScreen (dpy)), vinfo->visual, AllocNone); win = XCreateWindow (dpy, RootWindow (dpy, DefaultScreen (dpy)), xsh.x, xsh.y, xsh.width, xsh.height, 0, vinfo->depth, CopyFromParent, vinfo->visual, CWColormap, &xswa); XSetStandardProperties (dpy, win, PACKAGE, PACKAGE, None, argv, argc, &xsh); XSetWMHints (dpy, win, &xwmh); XSelectInput (dpy, win, StructureNotifyMask); } switch (output_type) { case XRENDER_TYPE: resize_pixmap (width, height); break; case IMAGE_TYPE: resize_image (width, height); break; case GLX_TYPE: drawable = glitz_glx_create_drawable_for_window (dpy, 0, dformat, win, width, height); if (!drawable) { printf ("failed to create glitz drawable\n"); exit (1); } break; } if (aa == 3 && dformat->samples < 2) { fprintf (stderr, "hardware multi-sampling not available\n"); exit (1); } if (drawable) { surface = resize_glitz_drawable (drawable, dformat, width, height); } cr = cairo_create (surface); cairo_set_tolerance (cr, 0.5); setup (test_type); XMapWindow (dpy, win); for (;;) { if (XPending (dpy)) { XNextEvent (dpy, &event); if (event.type == ConfigureNotify) { width = event.xconfigure.width; height = event.xconfigure.height; switch (output_type) { #ifdef CAIRO_HAS_XLIB_SURFACE case XRENDER_TYPE: resize_pixmap (width, height); cairo_destroy (cr); cr = cairo_create (surface); cairo_set_tolerance (cr, 0.5); break; #endif case IMAGE_TYPE: resize_image (width, height); cairo_destroy (cr); cr = cairo_create (surface); cairo_set_tolerance (cr, 0.5); break; case GLX_TYPE: cairo_surface_destroy (surface); surface = resize_glitz_drawable (drawable, dformat, width, height); cairo_destroy (cr); cr = cairo_create (surface); cairo_set_tolerance (cr, 0.5); break; } } } else { render (test_type, output_type == GLX_TYPE); switch (output_type) { #ifdef CAIRO_HAS_XLIB_SURFACE case XRENDER_TYPE: XSetWindowBackgroundPixmap (dpy, win, pixmap); XClearWindow (dpy, win); break; #endif case IMAGE_TYPE: { GC gc; XImage *xim; pixmap = XCreatePixmap (dpy, DefaultRootWindow (dpy), width, height, DefaultDepth (dpy, DefaultScreen (dpy))); xim = XCreateImage(dpy, DefaultVisual (dpy, DefaultScreen (dpy)), DefaultDepth(dpy, DefaultScreen (dpy)), ZPixmap, 0, (char *) image, width, height, 32, 0); gc = XCreateGC (dpy, pixmap, 0, NULL); XPutImage (dpy, pixmap, gc, xim, 0, 0, 0, 0, width, height); XFreeGC (dpy, gc); xim->data = NULL; XDestroyImage (xim); XSetWindowBackgroundPixmap (dpy, win, pixmap); XClearWindow (dpy, win); XFreePixmap (dpy, pixmap); } break; } XSync (dpy, 0); } } exit (1); }