int main (int argc, char *argv[])
{
    std::vector<cv::Point2i> calibration_points;
    calibration_points.push_back(cv::Point2i(0, 0));
    calibration_points.push_back(cv::Point2i(W/2, 0));
    calibration_points.push_back(cv::Point2i(W-1, 0));
    calibration_points.push_back(cv::Point2i(W-1, H/2));
    calibration_points.push_back(cv::Point2i(W-1, H-1));
    calibration_points.push_back(cv::Point2i(W/2, H-1));
    calibration_points.push_back(cv::Point2i(0, H-1));
    calibration_points.push_back(cv::Point2i(0, H/2));
    calibration_points.push_back(cv::Point2i(W/2, H/2));


    srand( time(NULL) );
    cv::VideoCapture cap;
    std::string auth_key;
    std::string file_name;
    std::string data_dir = "../data/";
    std::string input;
    bool is_capturing = false;
    switch (argc)
    {
        case 4:
        {
            file_name = argv[1];
            data_dir  = argv[2];
            auth_key = argv[3];
            input = argv[1];
            cap.open(file_name);
            break;
        }
        case 5:
        {
            file_name = argv[1];
            if (file_name.find("--capture") != std::string::npos)
            {
                cap.open(atoi(argv[2]));
                is_capturing = true;
                file_name = std::string("capture-") + argv[2] + ".csv";
                input = argv[2];
            }
            data_dir = argv[3];
            auth_key = argv[4];
            break;
        }
        default:
        {

#ifdef HARDCODED_PARAMS
        cap.open(0);
        is_capturing = true;
  #ifdef __APPLE__
            
        //get path to Resource directory in OSX app bundle
        CFBundleRef mainBundle;
        mainBundle = CFBundleGetMainBundle();
        CFURLRef resourceURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
        CFURLRef dataURL = CFURLCreateCopyAppendingPathComponent(kCFAllocatorDefault,
                                 resourceURL,
                                   CFSTR("data"),
                                   true);
        char buffer[1024];
        if(CFURLGetFileSystemRepresentation(dataURL, true, (UInt8*)buffer, 1024)) {
            //TODO: fix trailing slash not being appended automatically
            data_dir = std::string(buffer) + "/";
        }
             
  #else
        //same place as executable
        data_dir = "./data/";
  #endif
        auth_key = "medusa123";
#else
         std::cout
         << "Usage: "
         << argv[0]
         << " <videofile> <data dir> <auth key>"
         << std::endl;
         std::cout
         << "       "
         << argv[0]
         << " --capture <camera-id> <data dir> <auth key>"
         << std::endl;
         return -1;
#endif
        }
    }

    if(!cap.isOpened())  // check if we can capture from camera
    {
    	std::cerr 
            << "Couldn't capture video from input "
            << input
            << std::endl;
    	return -1;
    }
    
    cap.set(CV_CAP_PROP_FRAME_WIDTH,
			InSight::getCamWidthRes());
    cap.set(CV_CAP_PROP_FRAME_HEIGHT,
			InSight::getCamHeightRes());
    
    InSight insight(data_dir);
    if(!insight.authenticate(auth_key))
    {
    	std::cerr << insight.getError() << std::endl;
    	return -1;
    }
    
    cv::namedWindow(HUMAN_NAME, CV_WINDOW_NORMAL);
    cv::setWindowProperty(HUMAN_NAME, CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
    // Initialize gaze-grid
    cv::Mat camera, view, temp;
	int pixel_width = InSight::getScreenWidthRes(),
        pixel_height = InSight::getScreenHeightRes();
    view.create(cv::Size(pixel_width, pixel_height), CV_8UC3);
    view.setTo(cv::Scalar(0,0,0));
    cv::Rect roi(pixel_width-CAMVIEW_WIDTH,0,CAMVIEW_WIDTH,CAMVIEW_HEIGHT);
    std::vector<cv::Rect> sections(W*H);
    float width = pixel_width/float(W);
    float height = pixel_height/float(H);
    for (int i = 0; i < H; i++)
    {
        for (int j = 0; j < W; j++)
        {
            sections[i*W+j] =
                    cv::Rect(j*width+BORDER,i*height+BORDER,width-BORDER,height-BORDER);
            temp = view(sections[i*W+j]);
            temp.setTo(cv::Scalar(255,255,255));
        }
    }
    cv::Point2i prev_head_gaze(0);
    cv::Point2i prev_eye_gaze(0);
    int time = 0;
    int timer = 0;
    unsigned int num_point = 0;
    FSM state = ERASE;
    cv::Point2i calib_point(0);
    bool is_ready = false;
    // Start indefinite loop and track eye gaze
    for(;;)
    {
        cap >> camera;

        if (is_capturing)
        {
            cv::flip(camera, camera, 1);
        }

        if (is_ready)
        {
            if (!insight.isInit())
            {
                if(!insight.init(camera))
                {
                    std::cerr << insight.getError() << std::endl;
                }
                cvMoveWindow(HUMAN_NAME,0,0);
            }
            else
            {
                if(!insight.process(camera))
                {
                    std::cerr << insight.getError() << std::endl;
                }
                else
                {
                    if (num_point < calibration_points.size())
                    {
                        switch (state)
                        {
                        case ERASE: {
                            drawPoint(view, calib_point, cv::Scalar(255,255,255));
                            state = DRAW;
                        } break;
                        case DRAW: {
                            calib_point.x = calibration_points[num_point].x * width + width/2;
                            calib_point.y = calibration_points[num_point].y * height + height/2;
                            drawPoint(view, calib_point, cv::Scalar(0,0,255));
                            timer = time + 10;
                            state = IDLE;
                        } break;
                        case IDLE: {
                            if (time > timer)
                            {
                                state = ADD;
                                timer = time + 2;
                            }
                        } break;
                        case ADD: {
                            if (time < timer)
                                insight.addCalibrationPoint(calib_point);
                            else
                            {
                                state = ERASE;
                                num_point++;
                            }
                        } break;
                        default: return -1;
                        }
                        if (num_point == calibration_points.size())
                            insight.calibrate();
                    }
                    else
                    {
                        cv::Point2i head_gaze, eye_gaze;
                        if (insight.getHeadGaze(head_gaze))
                        {
                            head_gaze = cv::Point2i(head_gaze.x / width, head_gaze.y / height);
                            if (prev_head_gaze != head_gaze)
                            {
                                temp = view(sections[prev_head_gaze.y*W+prev_head_gaze.x]);
                                temp.setTo(cv::Scalar(255,255,255));
                            }
                            temp = view(sections.at(head_gaze.y*W+head_gaze.x));
                            temp.setTo(cv::Scalar(255,0,0));
                            prev_head_gaze = head_gaze;
                        }
                        if (insight.getEyeGaze(eye_gaze))
                        {
                            eye_gaze = cv::Point2i(eye_gaze.x / width, eye_gaze.y / height);
                            if (prev_eye_gaze != eye_gaze && prev_eye_gaze != head_gaze)
                            {
                                temp = view(sections[prev_eye_gaze.y*W+prev_eye_gaze.x]);
                                temp.setTo(cv::Scalar(255,255,255));
                            }

                            temp = view(sections.at(eye_gaze.y*W+eye_gaze.x));
                            cv::Scalar color(0,0,255);
                            if (eye_gaze == head_gaze)
                            {
                                color = cv::Scalar(128,0,128);
                            }
                            temp.setTo(color);
                            prev_eye_gaze = eye_gaze;
                        }
                        insight.drawWireFace(camera);
                        cv::resize(camera, temp, cv::Size(CAMVIEW_WIDTH,CAMVIEW_HEIGHT));
                        camera = view(roi);
                        temp.copyTo(camera);
                    }
                }
            }
        }
        imshow(HUMAN_NAME, view);
        char key = cv::waitKey(1);
        switch (key)
        {
        case 'q': return 0;
        case 's': is_ready = true; break;
        default: break;
        }
        time++;
    }
    return 0;
}
Beispiel #2
0
int main(int argc, char* argv[])
{
  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("domain.mesh", &mesh);

  // Perform initial mesh refinements.
  for(int i=0; i < INIT_REF_NUM; i++) mesh.refine_all_elements();

  // Enter boundary markers.
  BCTypes bc_types;
  bc_types.add_bc_dirichlet(Hermes::Tuple<int>(BDY_BOTTOM, BDY_OUTER, BDY_LEFT, BDY_INNER));

  // Enter Dirichlet boudnary values.
  BCValues bc_values;
  bc_values.add_function(Hermes::Tuple<int>(BDY_BOTTOM, BDY_OUTER, BDY_LEFT, BDY_INNER), essential_bc_values);

  // Create an H1 space with default shapeset.
  H1Space space(&mesh, &bc_types, &bc_values, P_INIT);
  int ndof = Space::get_num_dofs(&space);
  info("ndof = %d", ndof);

  // Initialize the weak formulation.
  WeakForm wf;
  wf.add_matrix_form(callback(bilinear_form));
  wf.add_vector_form(callback(linear_form));

  // Initialize the FE problem.
  bool is_linear = true;
  DiscreteProblem dp(&wf, &space, is_linear);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

  // Initialize the solution.
  Solution sln;

  // Assemble the stiffness matrix and right-hand side vector.
  info("Assembling the stiffness matrix and right-hand side vector.");
  dp.assemble(matrix, rhs);

  // Solve the linear system and if successful, obtain the and solution.
  info("Solving the matrix problem.");
  if(solver->solve())
    Solution::vector_to_solution(solver->get_solution(), &space, &sln);
  else
    error ("Matrix solver failed.\n");

  // Visualize the solution.
  ScalarView view("Solution", new WinGeom(0, 0, 440, 350));
  view.show(&sln);

  // Wait for the view to be closed.
  View::wait();

  // Clean up.
  delete solver;
  delete matrix;
  delete rhs;

  return 0;
}
//! render
void CParticleSystemSceneNode::render()
{
	video::IVideoDriver* driver = SceneManager->getVideoDriver();
	ICameraSceneNode* camera = SceneManager->getActiveCamera();

	if (!camera || !driver)
		return;


#if 0
	// calculate vectors for letting particles look to camera
	core::vector3df view(camera->getTarget() - camera->getAbsolutePosition());
	view.normalize();

	view *= -1.0f;

#else

	const core::matrix4 &m = camera->getViewFrustum()->getTransform( video::ETS_VIEW );

	const core::vector3df view ( -m[2], -m[6] , -m[10] );

#endif

	// reallocate arrays, if they are too small
	reallocateBuffers();

	// create particle vertex data
	s32 idx = 0;
	for (u32 i=0; i<Particles.size(); ++i)
	{
		const SParticle& particle = Particles[i];

		#if 0
			core::vector3df horizontal = camera->getUpVector().crossProduct(view);
			horizontal.normalize();
			horizontal *= 0.5f * particle.size.Width;

			core::vector3df vertical = horizontal.crossProduct(view);
			vertical.normalize();
			vertical *= 0.5f * particle.size.Height;

		#else
			f32 f;

			f = 0.5f * particle.size.Width;
			const core::vector3df horizontal ( m[0] * f, m[4] * f, m[8] * f );

			f = -0.5f * particle.size.Height;
			const core::vector3df vertical ( m[1] * f, m[5] * f, m[9] * f );
		#endif

		Buffer->Vertices[0+idx].Pos = particle.pos + horizontal + vertical;
		Buffer->Vertices[0+idx].Color = particle.color;
		Buffer->Vertices[0+idx].Normal = view;

		Buffer->Vertices[1+idx].Pos = particle.pos + horizontal - vertical;
		Buffer->Vertices[1+idx].Color = particle.color;
		Buffer->Vertices[1+idx].Normal = view;

		Buffer->Vertices[2+idx].Pos = particle.pos - horizontal - vertical;
		Buffer->Vertices[2+idx].Color = particle.color;
		Buffer->Vertices[2+idx].Normal = view;

		Buffer->Vertices[3+idx].Pos = particle.pos - horizontal + vertical;
		Buffer->Vertices[3+idx].Color = particle.color;
		Buffer->Vertices[3+idx].Normal = view;

		idx +=4;
	}

	// render all
	core::matrix4 mat;
	if (!ParticlesAreGlobal)
		mat.setTranslation(AbsoluteTransformation.getTranslation());
	driver->setTransform(video::ETS_WORLD, mat);

	driver->setMaterial(Buffer->Material);

	driver->drawVertexPrimitiveList(Buffer->getVertices(), Particles.size()*4,
		Buffer->getIndices(), Particles.size()*2, video::EVT_STANDARD, EPT_TRIANGLES,Buffer->getIndexType());

	// for debug purposes only:
	if ( DebugDataVisible & scene::EDS_BBOX )
	{
		driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
		video::SMaterial deb_m;
		deb_m.Lighting = false;
		driver->setMaterial(deb_m);
		driver->draw3DBox(Buffer->BoundingBox, video::SColor(0,255,255,255));
	}
}
void VatRateController::Edit(VatRate &vatRate, QWidget *caller)
{
    VatRate tempVatRate = vatRate;
    VatRateForm view(tempVatRate, caller);
    if (view.exec() == VatRateForm::Accepted) vatRate = tempVatRate;
}
QGraphicsScene* AbstractLiveEditTool::scene() const
{
    return view()->scene();
}
Beispiel #6
0
void Gui::printToFile()
{
    float pageWidth = page.meta.LPub.page.size.value(0);
    float pageHeight = page.meta.LPub.page.size.value(1);

    if (page.meta.LPub.resolution.type() == DPI) {
        // convert to MM
        pageWidth = int(inches2centimeters(pageWidth));
        pageHeight = int(inches2centimeters(pageHeight));
    }
    pageWidth  *= 10;  // convert to mm
    pageHeight *= 10;

    QPrinter::PaperSize paperSize = QPrinter::PaperSize();
    QPrinter::Orientation orientation = QPrinter::Orientation();
    int bestSize;
    bestSize = bestPaperSizeOrientation(pageWidth,pageHeight,paperSize,orientation);

    // Convert closest page size to pixels for bounding rect

    if (orientation == QPrinter::Portrait) {
        pageWidth = paperSizes[bestSize].width/10.0;  // in centimeters
        pageHeight = paperSizes[bestSize].height/10.0; // in centimeters
    } else {
        pageWidth = paperSizes[bestSize].height/10.0;  // in centimeters
        pageHeight = paperSizes[bestSize].width/10.0; // in centimeters
    }

    if (resolutionType() == DPI) {
        pageWidth = centimeters2inches(pageWidth);
        pageHeight = centimeters2inches(pageHeight);
    }

    pageWidth *= resolution();
    pageHeight *= resolution();

    if (resolutionType() == DPCM) {
        pageWidth = centimeters2inches(pageWidth);
        pageHeight = centimeters2inches(pageHeight);
    }

    QFileInfo fileInfo(curFile);
    QString   baseName = fileInfo.baseName();

    QString fileName = QFileDialog::getSaveFileName(
                           this,
                           tr("Print File Name"),
                           QDir::currentPath() + "/" + baseName,
                           tr("PDF (*.pdf)\nPDF (*.PDF)"));

    if (fileName == "") {
        return;
    }

    fileInfo.setFile(fileName);

    QString suffix = fileInfo.suffix();
    if (suffix == "") {
        fileName += ".pdf";
    } else if (suffix != ".pdf" && suffix != ".PDF") {
        fileName = fileInfo.path() + "/" + fileInfo.completeBaseName() + ".pdf";
    }

    QPrinter printer(QPrinter::ScreenResolution);
    printer.setOutputFileName(fileName);
    printer.setOrientation(orientation);
    printer.setPaperSize(paperSize);
    printer.setPageMargins(0,0,0,0,QPrinter::Inch);
    printer.setFullPage(true);

    QPainter painter;
    painter.begin(&printer);

    int savePageNumber = displayPageNum;

    QGraphicsScene scene;
    LGraphicsView  view(&scene);

    QRectF boundingRect(0.0,0.0,pageWidth,pageHeight);
    QRect  bounding(0,0,pageWidth,pageHeight);
    view.setMinimumSize(pageWidth,pageHeight);
    view.setMaximumSize(pageWidth,pageHeight);
    view.setGeometry(bounding);
    view.setSceneRect(boundingRect);
    view.setRenderHints(QPainter::Antialiasing |
                        QPainter::TextAntialiasing |
                        QPainter::SmoothPixmapTransform);

    view.scale(1.0,1.0);
    view.centerOn(boundingRect.center());
    clearPage(&view,&scene);

    for (displayPageNum = 1; displayPageNum <= maxPages; displayPageNum++) {

        qApp->processEvents();

        drawPage(&view,&scene,true);
        view.render(&painter);
        clearPage(&view,&scene);

        if (maxPages - displayPageNum > 0) {
            printer.newPage();
        }
    }
    painter.end();
    displayPageNum = savePageNumber;
    drawPage(KpageView,KpageScene,false);
}
Beispiel #7
0
int main(int argc, char* argv[])
{
  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("domain.mesh", &mesh);

  // Perform uniform mesh refinement.
  mesh.refine_all_elements();

  // Enter boundary markers.
  BCTypes bc_types;
  bc_types.add_bc_dirichlet(BDY_1);
  bc_types.add_bc_neumann(Hermes::vector<int>(BDY_2, BDY_3, BDY_4, BDY_5));

  // Enter Dirichlet boundary values;
  BCValues bc_values;
  bc_values.add_zero(BDY_1);

  // Create x- and y- displacement space using the default H1 shapeset.
  H1Space u_space(&mesh, &bc_types, &bc_values, P_INIT);
  H1Space v_space(&mesh, &bc_types, &bc_values, P_INIT);
  info("ndof = %d.", Space::get_num_dofs(Hermes::vector<Space *>(&u_space, &v_space)));

  // Initialize the weak formulation.
  WeakForm wf(2);
  wf.add_matrix_form(0, 0, callback(bilinear_form_0_0), HERMES_SYM);  // Note that only one symmetric part is
  wf.add_matrix_form(0, 1, callback(bilinear_form_0_1), HERMES_SYM);  // added in the case of symmetric bilinear
  wf.add_matrix_form(1, 1, callback(bilinear_form_1_1), HERMES_SYM);  // forms.
  wf.add_vector_form_surf(0, callback(linear_form_surf_0), BDY_3);
  wf.add_vector_form_surf(1, callback(linear_form_surf_1), BDY_3);

  // Initialize the FE problem.
  bool is_linear = true;
  DiscreteProblem dp(&wf, Hermes::vector<Space *>(&u_space, &v_space), is_linear);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

  // Initialize the solutions.
  Solution u_sln, v_sln;

  // Assemble the stiffness matrix and right-hand side vector.
  info("Assembling the stiffness matrix and right-hand side vector.");
  dp.assemble(matrix, rhs);

  // Solve the linear system and if successful, obtain the solutions.
  info("Solving the matrix problem.");
  if(solver->solve()) Solution::vector_to_solutions(solver->get_solution(), Hermes::vector<Space *>(&u_space, &v_space), 
                                                    Hermes::vector<Solution *>(&u_sln, &v_sln));
  else error ("Matrix solver failed.\n");
  
  // Visualize the solution.
  ScalarView view("Von Mises stress [Pa]", new WinGeom(0, 0, 800, 400));
  VonMisesFilter stress(Hermes::vector<MeshFunction *>(&u_sln, &v_sln), lambda, mu);
  view.show_mesh(false);
  view.show(&stress, HERMES_EPS_HIGH, H2D_FN_VAL_0, &u_sln, &v_sln, 1.5e5);

  // Wait for the view to be closed.
  View::wait();

  // Clean up.
  delete solver;
  delete matrix;
  delete rhs;

  return 0;
}
Beispiel #8
0
int main(int argc, char* argv[])
{
  // Load the mesh.
  Mesh mesh;
  if (USE_XML_FORMAT == true)
  {
    MeshReaderH2DXML mloader;  
    info("Reading mesh in XML format.");
    mloader.load("domain.xml", &mesh);
  }
  else 
  {
    MeshReaderH2D mloader;
    info("Reading mesh in original format.");
    mloader.load("domain.mesh", &mesh);
  }

  // Perform initial mesh refinements (optional).
  for (int i = 0; i < INIT_REF_NUM; i++) 
    mesh.refine_all_elements();

  // Initialize the weak formulation.
  CustomWeakFormPoisson wf("Aluminum", new Hermes1DFunction<double>(LAMBDA_AL), 
                           "Copper", new Hermes1DFunction<double>(LAMBDA_CU), 
                           new Hermes2DFunction<double>(-VOLUME_HEAT_SRC));
  
  // Initialize essential boundary conditions.
  DefaultEssentialBCConst<double> bc_essential(
      Hermes::vector<std::string>("Bottom", "Inner", "Outer", "Left"), FIXED_BDY_TEMP);
  EssentialBCs<double> bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  H1Space<double> space(&mesh, &bcs, P_INIT);
  int ndof = space.get_num_dofs();
  info("ndof = %d", ndof);

  // Initialize the FE problem.
  DiscreteProblem<double> dp(&wf, &space);

  // Initialize Newton solver.
  NewtonSolver<double> newton(&dp, matrix_solver);

  // Perform Newton's iteration.
  try
  {
    // When newton.solve() is used without any parameters, this means that the initial coefficient 
    // vector will be the zero vector, tolerance will be 1e-8, maximum allowed number of iterations 
    // will be 100, and residual will be measured using Euclidean vector norm.
    newton.solve();
  }
  catch(Hermes::Exceptions::Exception e)
  {
    e.printMsg();
    error("Newton's iteration failed.");
  }

  // Translate the resulting coefficient vector into a Solution.
  Solution<double> sln;
  Solution<double>::vector_to_solution(newton.get_sln_vector(), &space, &sln);

  // VTK output.
  if (VTK_VISUALIZATION) 
  {
    // Output solution in VTK format.
    Linearizer lin;
    bool mode_3D = true;
    lin.save_solution_vtk(&sln, "sln.vtk", "Temperature", mode_3D);
    info("Solution in VTK format saved to file %s.", "sln.vtk");

    // Output mesh and element orders in VTK format.
    Orderizer ord;
    ord.save_orders_vtk(&space, "ord.vtk");
    info("Element orders in VTK format saved to file %s.", "ord.vtk");
  }

  // Visualize the solution.
  if (HERMES_VISUALIZATION) 
  {
    ScalarView view("Solution", new WinGeom(0, 0, 440, 350));
    // Hermes uses adaptive FEM to approximate higher-order FE solutions with linear
    // triangles for OpenGL. The second parameter of View::show() sets the error 
    // tolerance for that. Options are HERMES_EPS_LOW, HERMES_EPS_NORMAL (default), 
    // HERMES_EPS_HIGH and HERMES_EPS_VERYHIGH. The size of the graphics file grows 
    // considerably with more accurate representation, so use it wisely.
    view.show(&sln, HERMES_EPS_HIGH);
    View::wait();
  }

  return 0;
}
Beispiel #9
0
//! gets a combined projection*view transformation from camera (world space to screen space)
math::matrix4x4<float> geometry::Camera::transform() const {
	return perspective() * view();
}
Beispiel #10
0
void AnchorTool::formEditorItemsChanged(const QList<FormEditorItem*> &)
{
    m_anchorLineIndicator.updateItems(view()->scene()->allFormEditorItems());
    m_anchorIndicator.updateItems(view()->scene()->allFormEditorItems());
}
void tst_QGraphicsEffect::draw()
{
    QGraphicsScene scene;
    CustomItem *item = new CustomItem(0, 0, 100, 100);
    scene.addItem(item);

    QGraphicsView view(&scene);
    view.show();
    QTest::qWaitForWindowShown(&view);
    QTRY_VERIFY(item->numRepaints > 0);
    item->reset();

    // Make sure installing the effect triggers a repaint.
    CustomEffect *effect = new CustomEffect;
    item->setGraphicsEffect(effect);
    QTRY_COMPARE(effect->numRepaints, 1);
    QTRY_COMPARE(item->numRepaints, 1);

    // Make sure QPainter* and QStyleOptionGraphicsItem* stays persistent
    // during QGraphicsEffect::draw/QGraphicsItem::paint.
    QVERIFY(effect->m_painter);
    QCOMPARE(effect->m_painter, item->m_painter);
    QCOMPARE(effect->m_styleOption, item->m_styleOption);
    // Make sure QGraphicsEffect::source is persistent.
    QCOMPARE(effect->m_source, effect->source());
    effect->reset();
    item->reset();

    // Make sure updating the source triggers a repaint.
    item->update();
    QTRY_COMPARE(effect->numRepaints, 1);
    QTRY_COMPARE(item->numRepaints, 1);
    QVERIFY(effect->m_sourceChangedFlags & QGraphicsEffect::SourceInvalidated);
    effect->reset();
    item->reset();

    // Make sure changing the effect's bounding rect triggers a repaint.
    effect->setMargin(20);
    QTRY_COMPARE(effect->numRepaints, 1);
    QTRY_COMPARE(item->numRepaints, 1);
    effect->reset();
    item->reset();

    // Make sure change the item's bounding rect triggers a repaint.
    item->setRect(0, 0, 50, 50);
    QTRY_COMPARE(effect->numRepaints, 1);
    QTRY_COMPARE(item->numRepaints, 1);
    QVERIFY(effect->m_sourceChangedFlags & QGraphicsEffect::SourceBoundingRectChanged);
    effect->reset();
    item->reset();

    // Make sure the effect is the one to issue a repaint of the item.
    effect->doNothingInDraw = true;
    item->update();
    QTRY_COMPARE(effect->numRepaints, 1);
    QCOMPARE(item->numRepaints, 0);
    effect->doNothingInDraw = false;
    effect->reset();
    item->reset();

    // Make sure we update the source when disabling/enabling the effect.
    effect->setEnabled(false);
    QTest::qWait(50);
    QCOMPARE(effect->numRepaints, 0);
    QCOMPARE(item->numRepaints, 1);
    effect->reset();
    item->reset();

    effect->setEnabled(true);
    QTRY_COMPARE(effect->numRepaints, 1);
    QTRY_COMPARE(item->numRepaints, 1);
    effect->reset();
    item->reset();

    // Effect is already enabled; nothing should happen.
    effect->setEnabled(true);
    QTest::qWait(50);
    QCOMPARE(effect->numRepaints, 0);
    QCOMPARE(item->numRepaints, 0);

    // Make sure uninstalling an effect triggers a repaint.
    QPointer<CustomEffect> ptr = effect;
    item->setGraphicsEffect(0);
    QVERIFY(!ptr);
    QTRY_COMPARE(item->numRepaints, 1);
}
Beispiel #12
0
void AnchorTool::selectedItemsChanged(const QList<FormEditorItem*> &/*itemList*/)
{
    m_anchorIndicator.setItems(view()->scene()->allFormEditorItems());
    m_anchorIndicator.show();
}
Beispiel #13
0
int main(int argc, char* argv[])
{
  // load the mesh file
  Mesh mesh;
  H2DReader mloader;
  mloader.load("square.mesh", &mesh);

  // initial mesh refinements
  for(int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh.refine_all_elements();
  mesh.refine_towards_boundary(1,INIT_BDY_REF_NUM);

  // initialize the shapeset and the cache
  H1Shapeset shapeset;
  PrecalcShapeset pss(&shapeset);

  // create an H1 space
  H1Space space(&mesh, &shapeset);
  space.set_bc_types(bc_types);
  space.set_bc_values(bc_values);
  space.set_uniform_order(P_INIT);
  space.assign_dofs();

  // previous solution for the Newton's iteration
  Solution u_prev;

  // initialize the weak formulation
  WeakForm wf(1);
  wf.add_biform(0, 0, callback(jac), UNSYM, ANY, 1, &u_prev);
  wf.add_liform(0, callback(res), ANY, 1, &u_prev);

  // initialize the nonlinear system and solver
  UmfpackSolver umfpack;
  NonlinSystem nls(&wf, &umfpack);
  nls.set_spaces(1, &space);
  nls.set_pss(1, &pss);

  // DOF and CPU convergence graphs
  SimpleGraph graph_dof, graph_cpu;

  // project the function init_cond() on the mesh 
  // to obtain initial guess u_prev for the Newton's method
  nls.set_ic(init_cond, &mesh, &u_prev, PROJ_TYPE);

  // visualise the initial ocndition
  ScalarView view("Initial condition", 0, 0, 700, 600);
  view.show(&u_prev);
  OrderView oview("Initial mesh", 720, 0, 700, 600);
  oview.show(&space);
  //printf("Click into the image window and press any key to proceed.\n");
  //view.wait_for_keypress();

  // adaptivity loop
  double cpu = 0.0, err_est;
  int a_step = 1;
  bool done = false;
  do {

    a_step++;

    // Newton's loop on the coarse mesh
    int it = 1;
    double res_l2_norm;
    Solution sln_coarse;
    do
    {
      info("\n---- Adapt step %d, Newton iter %d (coarse mesh) ---------------------------------\n", a_step, it++);
      printf("ndof = %d\n", space.get_num_dofs());

      // time measurement
      begin_time();

      // assemble the Jacobian matrix and residual vector, 
      // solve the system
      nls.assemble();
      nls.solve(1, &sln_coarse);

      // calculate the l2-norm of residual vector
      res_l2_norm = nls.get_residuum_l2_norm();
      info("Residuum L2 norm: %g\n", res_l2_norm);

      // time measurement
      cpu += end_time();

      // visualise the solution
      char title[100];
      sprintf(title, "Temperature (coarse mesh), Newton iteration %d", it-1);
      view.set_title(title);
      view.show(&sln_coarse);
      sprintf(title, "Coarse mesh, Newton iteration %d", it-1);
      oview.set_title(title);
      oview.show(&space);
      //printf("Click into the image window and press any key to proceed.\n");
      //view.wait_for_keypress();

      // save the new solution as "previous" for the 
      // next Newton's iteration
      u_prev.copy(&sln_coarse);
    }
    while (res_l2_norm > NEWTON_TOL);

    // Setting initial guess for the Newton's method on the fine mesh
    Solution sln_fine, u_prev_fine;
    RefNonlinSystem rs(&nls);
    rs.prepare();
    rs.set_ic(&u_prev, &u_prev);

    // Newton's loop on the fine mesh
    it = 1;
    do {
      info("\n---- Adapt step %d, Newton iter %d (fine mesh) ---------------------------------\n", a_step, it++);

      // time measurement
      begin_time();

      // assemble the Jacobian matrix and residual vector, 
      // solve the system
      rs.assemble();
      rs.solve(1, &sln_fine);

      // calculate the l2-norm of residual vector
      res_l2_norm = rs.get_residuum_l2_norm();
      info("Residuum L2 norm: %g\n", res_l2_norm);

      // time measurement
      cpu += end_time();

      // visualise the solution
      char title[100];
      sprintf(title, "Temperature (fine mesh), Newton iteration %d", it-1);
      view.set_title(title);
      view.show(&sln_fine);
      sprintf(title, "Fine mesh, Newton iteration %d", it-1);
      oview.set_title(title);
      oview.show(rs.get_ref_space(0));
      //printf("Click into the image window and press any key to proceed.\n");
      //view.wait_for_keypress();

      u_prev.copy(&sln_fine);
    } while (res_l2_norm > NEWTON_TOL_REF);

    // time measurement
    begin_time();

    // calculate element errors and total error estimate
    H1OrthoHP hp(1, &space);
    err_est = hp.calc_error(&sln_coarse, &sln_fine) * 100;
    info("Error estimate: %g%%", err_est);

    // add entry to DOF convergence graph
    graph_dof.add_values(space.get_num_dofs(), err_est);
    graph_dof.save("conv_dof.dat");

    // add entry to CPU convergence graph
    graph_cpu.add_values(cpu, err_est);
    graph_cpu.save("conv_cpu.dat");

    // if err_est too large, adapt the mesh
    if (err_est < ERR_STOP) done = true;
    else {
      hp.adapt(THRESHOLD, STRATEGY, ADAPT_TYPE, ISO_ONLY, MESH_REGULARITY);
      int ndof = space.assign_dofs();
      if (ndof >= NDOF_STOP) done = true;
    }

    // time measurement
    cpu += end_time();
  }
  while (!done);
  verbose("Total running time: %g sec", cpu);

  // wait for keyboard or mouse input
  View::wait();
  return 0;
}
Beispiel #14
0
int main(int argc, char* argv[])
{
  // Instantiate a class with global functions.
  Hermes2D hermes2d;

  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("domain.mesh", &mesh);

  // Perform initial mesh refinements.
  for(int i=0; i < INIT_REF_NUM; i++) mesh.refine_all_elements();

  // Initialize boundary conditions
  DefaultEssentialBCConst bc_essential("Bottom", T1);
  EssentialBCs bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  H1Space space(&mesh, &bcs, P_INIT);
  int ndof = Space::get_num_dofs(&space);
  info("ndof = %d", ndof);

  // Initialize the weak formulation.
  CustomWeakFormPoissonNewton wf(LAMBDA, ALPHA, T0, "Heat flux");

  // Initialize the FE problem.
  DiscreteProblem dp(&wf, &space);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

  // Initial coefficient vector for the Newton's method.  
  scalar* coeff_vec = new scalar[ndof];
  memset(coeff_vec, 0, ndof*sizeof(scalar));

  // Perform Newton's iteration.
  if (!hermes2d.solve_newton(coeff_vec, &dp, solver, matrix, rhs)) error("Newton's iteration failed.");

  // Translate the resulting coefficient vector into the Solution sln.
  Solution sln;
  Solution::vector_to_solution(coeff_vec, &space, &sln);

  // Visualize the solution.
  ScalarView view("Solution", new WinGeom(0, 0, 300, 400));
  view.show(&sln, HERMES_EPS_VERYHIGH);
  ScalarView gradview("Gradient", new WinGeom(310, 0, 300, 400));
  MagFilter grad(Hermes::vector<MeshFunction *>(&sln, &sln), 
                 Hermes::vector<int>(H2D_FN_DX, H2D_FN_DY));
  gradview.show(&grad, HERMES_EPS_VERYHIGH);

  // Wait for all views to be closed.
  View::wait();

  // Clean up.
  delete solver;
  delete matrix;
  delete rhs;
  delete [] coeff_vec;

  return 0;
}
const char* view_or_value::data() const {
    return view().data();
}
Beispiel #16
0
//! is the bounding box visible?
bool geometry::Camera::visible(const geometry::BoundingBox &bounds) const {
	return visible(bounds, view());
}
Beispiel #17
0
void DiagramEndPoint::MessageDragged(
	BPoint point,
	uint32 transit,
	const BMessage *message)
{
	D_MOUSE(("DiagramEndPoint::MessageDragged()\n"));
	switch (message->what)
	{
		case M_WIRE_DRAGGED:
		{
			D_MESSAGE(("DiagramEndPoint::MessageDragged(M_WIRE_DRAGGED)\n"));
			switch (transit)
			{
				case B_INSIDE_VIEW:
				{
					//PRINT((" -> transit: B_INSIDE_VIEW\n"));
					// this is a WORK-AROUND caused by the unreliability
					// of BViews DragMessage() routine !!
					if (isConnecting())
					{
						break;
					}
					else if (isConnected())
					{
						view()->trackWire(point);
					}
					/* this should be enough in theory:
					if (!isConnecting())
					{
						view()->trackWire(point);
					}
					//break;*/
				}
				case B_ENTERED_VIEW:
				{
					//PRINT((" -> transit: B_ENTERED_VIEW\n"));
					DiagramEndPoint *endPoint;
					if ((message->FindPointer("from", reinterpret_cast<void **>(&endPoint)) == B_OK)
					 && (endPoint != this))
					{
						if (connectionRequested(endPoint))
						{
							view()->trackWire(connectionPoint());
							if (!isConnecting())
							{
								m_connecting = true;
								connected();
							}
						}
						else
						{
							view()->trackWire(point);
							if (isConnecting())
							{
								m_connecting = false;
								disconnected();
							}
						}
					}
					break;
				}
				case B_EXITED_VIEW:
				{
					//PRINT((" -> transit: B_EXITED_VIEW\n"));
					if (isConnecting())
					{
						m_connecting = false;
						disconnected();
					}
					break;
				}
			}
			break;
		}
		default:
		{
			DiagramItem::MessageDragged(point, transit, message);
		}
	}
}
Beispiel #18
0
static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
{
    if (!CheckWarmup(req))
        return false;
    std::string param;
    const RetFormat rf = ParseDataFormat(param, strURIPart);

    std::vector<std::string> uriParts;
    if (param.length() > 1)
    {
        std::string strUriParams = param.substr(1);
        boost::split(uriParts, strUriParams, boost::is_any_of("/"));
    }

    // throw exception in case of an empty request
    std::string strRequestMutable = req->ReadBody();
    if (strRequestMutable.length() == 0 && uriParts.size() == 0)
        return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");

    bool fInputParsed = false;
    bool fCheckMemPool = false;
    std::vector<COutPoint> vOutPoints;

    // parse/deserialize input
    // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...

    if (uriParts.size() > 0)
    {
        //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
        if (uriParts[0] == "checkmempool") fCheckMemPool = true;

        for (size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++)
        {
            uint256 txid;
            int32_t nOutput;
            std::string strTxid = uriParts[i].substr(0, uriParts[i].find("-"));
            std::string strOutput = uriParts[i].substr(uriParts[i].find("-")+1);

            if (!ParseInt32(strOutput, &nOutput) || !IsHex(strTxid))
                return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");

            txid.SetHex(strTxid);
            vOutPoints.push_back(COutPoint(txid, (uint32_t)nOutput));
        }

        if (vOutPoints.size() > 0)
            fInputParsed = true;
        else
            return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
    }

    switch (rf) {
    case RF_HEX: {
        // convert hex to bin, continue then with bin part
        std::vector<unsigned char> strRequestV = ParseHex(strRequestMutable);
        strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
    }

    case RF_BINARY: {
        try {
            //deserialize only if user sent a request
            if (strRequestMutable.size() > 0)
            {
                if (fInputParsed) //don't allow sending input over URI and HTTP RAW DATA
                    return RESTERR(req, HTTP_BAD_REQUEST, "Combination of URI scheme inputs and raw post data is not allowed");

                CDataStream oss(SER_NETWORK, PROTOCOL_VERSION);
                oss << strRequestMutable;
                oss >> fCheckMemPool;
                oss >> vOutPoints;
            }
        } catch (const std::ios_base::failure& e) {
            // abort in case of unreadable binary data
            return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
        }
        break;
    }

    case RF_JSON: {
        if (!fInputParsed)
            return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
        break;
    }
    default: {
        return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
    }
    }

    // limit max outpoints
    if (vOutPoints.size() > MAX_GETUTXOS_OUTPOINTS)
        return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size()));

    // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
    std::vector<unsigned char> bitmap;
    std::vector<CCoin> outs;
    std::string bitmapStringRepresentation;
    std::vector<bool> hits;
    bitmap.resize((vOutPoints.size() + 7) / 8);
    {
        LOCK2(cs_main, mempool.cs);

        CCoinsView viewDummy;
        CCoinsViewCache view(&viewDummy);

        CCoinsViewCache& viewChain = *pcoinsTip;
        CCoinsViewMemPool viewMempool(&viewChain, mempool);

        if (fCheckMemPool)
            view.SetBackend(viewMempool); // switch cache backend to db+mempool in case user likes to query mempool

        for (size_t i = 0; i < vOutPoints.size(); i++) {
            bool hit = false;
            Coin coin;
            if (view.GetCoin(vOutPoints[i], coin) && !mempool.isSpent(vOutPoints[i])) {
                hit = true;
                outs.emplace_back(std::move(coin));
            }

            hits.push_back(hit);
            bitmapStringRepresentation.append(hit ? "1" : "0"); // form a binary string representation (human-readable for json output)
            bitmap[i / 8] |= ((uint8_t)hit) << (i % 8);
        }
    }

    switch (rf) {
    case RF_BINARY: {
        // serialize data
        // use exact same output as mentioned in Bip64
        CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
        ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
        std::string ssGetUTXOResponseString = ssGetUTXOResponse.str();

        req->WriteHeader("Content-Type", "application/octet-stream");
        req->WriteReply(HTTP_OK, ssGetUTXOResponseString);
        return true;
    }

    case RF_HEX: {
        CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
        ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
        std::string strHex = HexStr(ssGetUTXOResponse.begin(), ssGetUTXOResponse.end()) + "\n";

        req->WriteHeader("Content-Type", "text/plain");
        req->WriteReply(HTTP_OK, strHex);
        return true;
    }

    case RF_JSON: {
        UniValue objGetUTXOResponse(UniValue::VOBJ);

        // pack in some essentials
        // use more or less the same output as mentioned in Bip64
        objGetUTXOResponse.push_back(Pair("chainHeight", chainActive.Height()));
        objGetUTXOResponse.push_back(Pair("chaintipHash", chainActive.Tip()->GetBlockHash().GetHex()));
        objGetUTXOResponse.push_back(Pair("bitmap", bitmapStringRepresentation));

        UniValue utxos(UniValue::VARR);
        for (const CCoin& coin : outs) {
            UniValue utxo(UniValue::VOBJ);
            utxo.push_back(Pair("height", (int32_t)coin.nHeight));
            utxo.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));

            // include the script in a json output
            UniValue o(UniValue::VOBJ);
            ScriptPubKeyToUniv(coin.out.scriptPubKey, o, true);
            utxo.push_back(Pair("scriptPubKey", o));
            utxos.push_back(utxo);
        }
        objGetUTXOResponse.push_back(Pair("utxos", utxos));

        // return json string
        std::string strJSON = objGetUTXOResponse.write() + "\n";
        req->WriteHeader("Content-Type", "application/json");
        req->WriteReply(HTTP_OK, strJSON);
        return true;
    }
    default: {
        return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
    }
    }
}
Beispiel #19
0
void Gui::exportAs(QString &suffix)
{
    float pageWidth = page.meta.LPub.page.size.value(0);
    float pageHeight = page.meta.LPub.page.size.value(1);
    if (page.meta.LPub.resolution.type() == DPI) {
        // convert to MM
        pageWidth = int(inches2centimeters(pageWidth)*10);
        pageHeight = int(inches2centimeters(pageHeight)*10);
    }

    QPrinter::PaperSize paperSize = QPrinter::PaperSize();
    QPrinter::Orientation orientation = QPrinter::Orientation();
    int bestSize;
    bestSize = bestPaperSizeOrientation(pageWidth,pageHeight,paperSize,orientation);

    // Convert closest page size to pixels for bounding rect

    if (orientation == QPrinter::Portrait) {
        pageWidth = paperSizes[bestSize].width/10.0;  // in centimeters
        pageHeight = paperSizes[bestSize].height/10.0; // in centimeters
    } else {
        pageWidth = paperSizes[bestSize].height/10.0;  // in centimeters
        pageHeight = paperSizes[bestSize].width/10.0; // in centimeters
    }

    if (resolutionType() == DPI) {
        pageWidth = centimeters2inches(pageWidth);
        pageHeight = centimeters2inches(pageHeight);
    }
    pageWidth *= resolution();
    pageHeight *= resolution();
    if (resolutionType() == DPCM) {
        pageWidth = centimeters2inches(pageWidth);
        pageHeight = centimeters2inches(pageHeight);
    }

    QGraphicsScene scene;
    LGraphicsView  view(&scene);

    int savePageNumber = displayPageNum;

    QFileInfo fileInfo(curFile);
    QString   baseName = fileInfo.baseName();

    //clearPage(KpageView,KpageScene);

    // Strangeness needing to warm up the process?

    QImage image(pageWidth,pageHeight,QImage::Format_ARGB32);

    for (displayPageNum = 1;
            displayPageNum <= maxPages && displayPageNum < 6;
            displayPageNum++) {

        qApp->processEvents();

        QRect  bounding(0,0,pageWidth,pageHeight);
        view.setGeometry(bounding);
        view.setRenderHints(QPainter::Antialiasing |
                            QPainter::TextAntialiasing |
                            QPainter::SmoothPixmapTransform);
        view.scale(1.0,1.0);
        QRectF boundingRect(0.0,0.0,pageWidth,pageHeight);
        view.centerOn(boundingRect.center());
        drawPage(&view,&scene,true);

        QPainter painter;
        painter.begin(&image);
        view.render(&painter);
        QString pn = QString("%1") .arg(displayPageNum);
        image.save(baseName + "_page_" +pn + suffix);
        painter.end();

        clearPage(&view,&scene);
    }

    for (displayPageNum = 1; displayPageNum <= maxPages; displayPageNum++) {

        qApp->processEvents();

        QRect  bounding(0,0,pageWidth,pageHeight);
        view.setGeometry(bounding);
        view.setRenderHints(QPainter::Antialiasing |
                            QPainter::TextAntialiasing |
                            QPainter::SmoothPixmapTransform);
        view.scale(1.0,1.0);
        QRectF boundingRect(0.0,0.0,pageWidth,pageHeight);
        view.centerOn(boundingRect.center());
        drawPage(&view,&scene,true);

        QPainter painter;
        painter.begin(&image);
        view.render(&painter);
        QString pn = QString("%1") .arg(displayPageNum);
        image.save(baseName + "_page_" +pn + suffix);
        painter.end();

        clearPage(&view,&scene);
    }
    displayPageNum = savePageNumber;
    drawPage(KpageView,KpageScene,false);
}
Beispiel #20
0
int main(int argc, char* argv[])
{
  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("domain.mesh", &mesh);

  // Perform initial mesh refinements (optional).
  //mesh.refine_all_elements();

  // Initialize boundary conditions
  DefaultEssentialBCConst bc_essential(Hermes::vector<std::string>(BDY_BOTTOM, BDY_OUTER, BDY_LEFT, BDY_INNER), 0.0);
  EssentialBCs bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  H1Space space(&mesh, &bcs, P_INIT);
  int ndof = Space::get_num_dofs(&space);
  info("ndof = %d", ndof);

  // Initialize the weak formulation. Not providing the order determination form 
  // (or callback) turns on adaptive numerical quadrature. The quadrature begins 
  // with using a first-order rule in the entire element. Then the element is split 
  // uniformly in space and the quadrature order is increased by "adapt_order_increase".
  // Then the form is calculated again by employing the new quadrature in subelements. 
  // This provides a more accurate result. If relative error is less than 
  // "adapt_rel_error_tol", the computation stops, otherwise the same procedure is 
  // applied recursively to all four subelements. 
  int adapt_order_increase = 1;
  double adapt_rel_error_tol = 1e1;
  WeakFormPoisson wf(CONST_F, ADAPTIVE_QUADRATURE, adapt_order_increase, adapt_rel_error_tol);
  
  if (ADAPTIVE_QUADRATURE)
    info("Adaptive quadrature ON.");    
  else
    info("Adaptive quadrature OFF.");    

  // Initialize the FE problem.
  bool is_linear = true;
  DiscreteProblem dp(&wf, &space, is_linear);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

  // Initialize the solution.
  Solution sln;

  // Assemble the stiffness matrix and right-hand side vector.
  info("Assembling the stiffness matrix and right-hand side vector.");
  dp.assemble(matrix, rhs);

  // Solve the linear system and if successful, obtain the solution.
  info("Solving the matrix problem.");
  if(solver->solve()) Solution::vector_to_solution(solver->get_solution(), &space, &sln);
  else error ("Matrix solver failed.\n");

  // VTK output.
  if (VTK_VISUALIZATION) {
    // Output solution in VTK format.
    Linearizer lin;
    bool mode_3D = true;
    lin.save_solution_vtk(&sln, "sln.vtk", "Temperature", mode_3D);
    info("Solution in VTK format saved to file %s.", "sln.vtk");

    // Output mesh and element orders in VTK format.
    Orderizer ord;
    ord.save_orders_vtk(&space, "ord.vtk");
    info("Element orders in VTK format saved to file %s.", "ord.vtk");
  }

  // Visualize the solution.
  if (HERMES_VISUALIZATION) {
    ScalarView view("Solution", new WinGeom(0, 0, 440, 350));
    view.show(&sln);
    View::wait();
  }

  // Clean up.
  delete solver;
  delete matrix;
  delete rhs;

  return 0;
}
VatRate VatRateController::New(QWidget *caller)
{
    VatRate vatRate;
    VatRateForm view(vatRate, caller);
    return (view.exec() == QDialog::Rejected ? VatRate() : vatRate);
}
Beispiel #22
0
bool NounShip::canDetect( Noun * pNoun ) const
{
	return NounGame::canDetect( pNoun, sensor(), view() );
}
Beispiel #23
0
void RenderRegion::getRanges(Vector<RefPtr<Range> >& rangeObjects) const
{
    const RenderNamedFlowThread& namedFlow = view().flowThreadController()->ensureRenderFlowThreadWithName(style()->regionThread());
    namedFlow.getRanges(rangeObjects, this);
}
Beispiel #24
0
int main(int argc, char* argv[])
{	
	// Build your scene and setup your camera here, by calling 
	// functions from Raytracer.  The code here sets up an example
	// scene and renders it from two different view points, DO NOT
	// change this if you're just implementing part one of the 
	// assignment.  
	Raytracer raytracer;
	int width = 640; 
	int height = 480;

	if (argc == 3) {
		width = atoi(argv[1]);
		height = atoi(argv[2]);
	}

	// Camera parameters.
	Point3D eye(0., 0., 0.);
	Vector3D view(0., 0., -1.);
	Vector3D up(0., 1., 0.);
	double fov = 60;

	// Defines a material for shading.
    Material::Ptr gold = std::make_shared<Material>( Colour(0.3, 0.3, 0.3), Colour(0.75164, 0.60648, 0.22648), 
			Colour(0.628281, 0.555802, 0.366065), 
			51.2, 0.3 );
    Material::Ptr silver = std::make_shared<Material>( Colour( 0.3, 0.3, 0.3) , Colour(0.77254902, 0.77647058823, 0.78431372549),
    		Colour(1,1,1), 90, 0.3 );
    Material::Ptr jade = std::make_shared<Material>( Colour(0, 0, 0), Colour(0.54, 0.89, 0.63), 
			Colour(0.316228, 0.316228, 0.316228), 
			12.8 );

	// Defines a point light source.
	// raytracer.addLightSource( std::make_shared<PointLight>(Point3D(0., 0., 1.), 
	// 			Colour(0.9, 0.9, 0.9) ) );

		// Defines a point light source.
	raytracer.addLightSource( std::make_shared<PointLight>(Point3D(-2., 5., 0.), 
				Colour(0.9, 0.9, 0.9) ) );

	// Add a unit square into the scene with material mat.
    SceneDagNode::Ptr sphere = raytracer.addObject( std::make_shared<UnitSphere>(), gold );
    SceneDagNode::Ptr plane = raytracer.addObject( std::make_shared<UnitSquare>(), jade );
	SceneDagNode::Ptr cylinder = raytracer.addObject( std::make_shared<UnitCylinder>(), silver);

	// Apply some transformations to the unit square.
	double factor1[3] = { 1.0, 2.0, 1.0 };
	double factor2[3] = { 6.0, 6.0, 6.0 };
	raytracer.translate(sphere, Vector3D(-1., 0., -5.));	
	raytracer.rotate(sphere, 'x', -45); 
	raytracer.rotate(sphere, 'z', 45); 
	raytracer.scale(sphere, Point3D(0., 0., 0.), factor1);

	raytracer.translate(plane, Vector3D(0., 0., -7.));	
	raytracer.rotate(plane, 'z', 45); 
	raytracer.scale(plane, Point3D(0., 0., 0.), factor2);

	raytracer.translate(cylinder, Vector3D(1., 1., -4.));
	raytracer.rotate(cylinder, 'x', 45);

	// Render the scene, feel free to make the image smaller for
	// testing purposes.	
	raytracer.render(width, height, eye, view, up, fov, "view1.bmp");
	
	// Render it from a different point of view.
	Point3D eye2(4., 2., 0.);
	Vector3D view2(-4., -2., -6.);
	raytracer.render(width, height, eye2, view2, up, fov, "view2.bmp");
	
	return 0;
}
Beispiel #25
0
void RenderFrameSet::layout()
{
    ASSERT(needsLayout());

    bool doFullRepaint = selfNeedsLayout() && checkForRepaintDuringLayout();
    IntRect oldBounds;
    if (doFullRepaint)
        oldBounds = absoluteClippedOverflowRect();

    if (!parent()->isFrameSet() && !document()->printing()) {
#ifdef FLATTEN_FRAMESET
        // Force a grid recalc.
        m_gridCalculated = false;
#endif
        m_width = view()->viewWidth();
        m_height = view()->viewHeight();
    }

    size_t cols = frameSet()->totalCols();
    size_t rows = frameSet()->totalRows();

    if (m_rows.m_sizes.size() != rows || m_cols.m_sizes.size() != cols) {
        m_rows.resize(rows);
        m_cols.resize(cols);
#ifdef FLATTEN_FRAMESET
        m_gridCalculated = false;
#endif
    }

#ifdef FLATTEN_FRAMESET
    if (!m_gridCalculated) {
        m_gridCalculated = true;
        // Make all the child framesets recalculate their grid.
        RenderObject* child = firstChild();
        for (; child; child = child->nextSibling()) {
            if (child->isFrameSet())
                static_cast<RenderFrameSet*>(child)->setGridNeedsLayout();
        }
#endif
    int borderThickness = frameSet()->border();
    layOutAxis(m_rows, frameSet()->rowLengths(), m_height - (rows - 1) * borderThickness);
    layOutAxis(m_cols, frameSet()->colLengths(), m_width - (cols - 1) * borderThickness);
#ifdef FLATTEN_FRAMESET
    }
#endif

    positionFrames();

    RenderContainer::layout();

    computeEdgeInfo();

    if (doFullRepaint) {
        view()->repaintViewRectangle(oldBounds);
        IntRect newBounds = absoluteClippedOverflowRect();
        if (newBounds != oldBounds)
            view()->repaintViewRectangle(newBounds);
    }

    setNeedsLayout(false);
}
Beispiel #26
0
 size_t operator() (const ::std::basic_string<T, Traits, Allocator>& s,
                    charT *buf, size_t buf_len) const noexcept {
     return operator()(view(s), buf, buf_len);
 }
Beispiel #27
0
void Camera::updateViewMatrix()
{
	D3DXVECTOR3 R = this->right;
	D3DXVECTOR3 U = this->up;
	D3DXVECTOR3 L = this->look;
	D3DXVECTOR3 P = this->position;
	
	D3DXVec3Normalize(&L,&L);
	
	D3DXVec3Cross(&U,&L,&R);
	D3DXVec3Normalize(&U,&U);

	D3DXVec3Cross(&R,&U,&L);

	float x = -D3DXVec3Dot(&P,&R);
	float y = -D3DXVec3Dot(&P,&U);
	float z = -D3DXVec3Dot(&P,&L);

	this->right = R;
	this->up = U;
	this->look = L;

	view(0,0) = this->right.x;
	view(1,0) = this->right.y;
	view(2,0) = this->right.z;
	view(3,0) = x;

	view(0,1) = this->up.x;
	view(1,1) = this->up.y;
	view(2,1) = this->up.z;
	view(3,1) = y;

	view(0,2) = this->look.x;
	view(1,2) = this->look.y;
	view(2,2) = this->look.z;
	view(3,2) = z;

	view(0,3) = 0.0f;
	view(1,3) = 0.0f;
	view(2,3) = 0.0f;
	view(3,3) = 1.0f;
}
int main(int argc, char *argv[])
{
    setenv("USE_ASYNC", "1", 1);
    QQuickWindow::setDefaultAlphaBuffer(true);

    QScopedPointer<QGuiApplication> application(SailfishApp::application(argc, argv));
    application->setApplicationName("harbour-webpirate");

    pluginenv();
    ProxyManager::loadAndSet();

    QDBusConnection sessionbus = QDBusConnection::sessionBus();

    if(sessionbus.interface()->isServiceRegistered(WebPirateInterface::INTERFACE_NAME)) // Only a Single Instance is allowed
    {
        WebPirateInterface::sendArgs(application->arguments().mid(1)); // Forward URLs to the running instance

        if(application->hasPendingEvents())
            application->processEvents();

        return 0;
    }

    FilesModel::registerMetaTypes();

    qmlRegisterType<AbstractDownloadItem>("harbour.webpirate.Private", 1, 0, "DownloadItem");
    qmlRegisterType<FavoriteItem>("harbour.webpirate.Private", 1, 0, "FavoriteItem");
    qmlRegisterType<MimeDatabase>("harbour.webpirate.Private", 1, 0, "MimeDatabase");

    qmlRegisterType<TranslationInfoItem>("harbour.webpirate.Translation", 1, 0, "TranslationInfoItem");
    qmlRegisterType<TranslationsModel>("harbour.webpirate.Translation", 1, 0, "TranslationsModel");

    qmlRegisterSingletonType<AES256>("harbour.webpirate.Security", 1, 0, "AES256", &AES256::initialize);
    qmlRegisterSingletonType<NetworkInterfaces>("harbour.webpirate.Network", 1, 0, "NetworkInterfaces", &NetworkInterfaces::initialize);
    qmlRegisterSingletonType<MachineID>("harbour.webpirate.DBus", 1, 0, "MachineID", &MachineID::initialize);
    qmlRegisterSingletonType<Ofono>("harbour.webpirate.DBus", 1, 0, "Ofono", &Ofono::initialize);

    qmlRegisterType<DefaultBrowser>("harbour.webpirate.DBus", 1, 0, "DefaultBrowser");
    qmlRegisterType<WebPirateInterface>("harbour.webpirate.DBus", 1, 0, "WebPirateInterface");
    qmlRegisterType<ScreenBlank>("harbour.webpirate.DBus", 1, 0, "ScreenBlank");
    qmlRegisterType<UrlComposer>("harbour.webpirate.DBus", 1, 0, "UrlComposer");
    qmlRegisterType<NotificationManager>("harbour.webpirate.DBus.Notifications", 1, 0, "Notifications");
    qmlRegisterType<TransferEngine>("harbour.webpirate.DBus.TransferEngine", 1, 0, "TransferEngine");
    qmlRegisterType<TransferMethodModel>("harbour.webpirate.DBus.TransferEngine", 1, 0, "TransferMethodModel");
    qmlRegisterType<ProxyManager>("harbour.webpirate.Network", 1, 0, "ProxyManager");

    qmlRegisterType<AdBlockEditor>("harbour.webpirate.AdBlock", 1, 0, "AdBlockEditor");
    qmlRegisterType<AdBlockDownloader>("harbour.webpirate.AdBlock", 1, 0, "AdBlockDownloader");
    qmlRegisterType<AdBlockManager>("harbour.webpirate.AdBlock", 1, 0, "AdBlockManager");

    qmlRegisterType<CookieJar>("harbour.webpirate.WebKit", 1, 0, "CookieJar");
    qmlRegisterType<WebKitDatabase>("harbour.webpirate.WebKit", 1, 0, "WebKitDatabase");
    qmlRegisterType<WebIconDatabase>("harbour.webpirate.WebKit", 1, 0, "WebIconDatabase");
    qmlRegisterType<DownloadManager>("harbour.webpirate.WebKit", 1, 0, "DownloadManager");

    qmlRegisterType<ClipboardHelper>("harbour.webpirate.Helpers", 1, 0, "ClipboardHelper");
    qmlRegisterType<FilesModel>("harbour.webpirate.Selectors", 1, 0, "FilesModel");
    qmlRegisterType<FavoritesManager>("harbour.webpirate.LocalStorage", 1, 0, "FavoritesManager");

    QScopedPointer<QQuickView> view(SailfishApp::createView());
    QQmlEngine* engine = view->engine();
    QObject::connect(engine, SIGNAL(quit()), application.data(), SLOT(quit()));

    engine->addImageProvider(WebIconDatabase::PROVIDER_NAME, new FaviconProvider());
    view->setSource(SailfishApp::pathTo("qml/harbour-webpirate.qml"));
    view->show();

    return application->exec();
}
FormEditorScene* AbstractFormEditorTool::scene() const
{
    return view()->scene();
}
Beispiel #30
0
static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
{
    int nHashType = SIGHASH_ALL;

    if (flagStr.size() > 0)
        if (!findSighashFlags(nHashType, flagStr))
            throw std::runtime_error("unknown sighash flag/sign option");

    std::vector<CTransaction> txVariants;
    txVariants.push_back(tx);

    // mergedTx will end up with all the signatures; it
    // starts as a clone of the raw tx:
    CMutableTransaction mergedTx(txVariants[0]);
    bool fComplete = true;
    CCoinsView viewDummy;
    CCoinsViewCache view(&viewDummy);

    if (!registers.count("privatekeys"))
        throw std::runtime_error("privatekeys register variable must be set.");
    bool fGivenKeys = false;
    CBasicKeyStore tempKeystore;
    UniValue keysObj = registers["privatekeys"];
    fGivenKeys = true;

    for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
        if (!keysObj[kidx].isStr())
            throw std::runtime_error("privatekey not a string");
        CBitcoinSecret vchSecret;
        bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
        if (!fGood)
            throw std::runtime_error("privatekey not valid");

        CKey key = vchSecret.GetKey();
        tempKeystore.AddKey(key);
    }

    // Add previous txouts given in the RPC call:
    if (!registers.count("prevtxs"))
        throw std::runtime_error("prevtxs register variable must be set.");
    UniValue prevtxsObj = registers["prevtxs"];
    {
        for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
            UniValue prevOut = prevtxsObj[previdx];
            if (!prevOut.isObject())
                throw std::runtime_error("expected prevtxs internal object");

            std::map<std::string,UniValue::VType> types = boost::assign::map_list_of("txid", UniValue::VSTR)("vout",UniValue::VNUM)("scriptPubKey",UniValue::VSTR);
            if (!prevOut.checkObject(types))
                throw std::runtime_error("prevtxs internal object typecheck fail");

            uint256 txid = ParseHashUV(prevOut["txid"], "txid");

            int nOut = atoi(prevOut["vout"].getValStr());
            if (nOut < 0)
                throw std::runtime_error("vout must be positive");

            std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
            CScript scriptPubKey(pkData.begin(), pkData.end());

            {
                CCoinsModifier coins = view.ModifyCoins(txid);
                if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
                    std::string err("Previous output scriptPubKey mismatch:\n");
                    err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+
                        ScriptToAsmStr(scriptPubKey);
                    throw std::runtime_error(err);
                }
                if ((unsigned int)nOut >= coins->vout.size())
                    coins->vout.resize(nOut+1);
                coins->vout[nOut].scriptPubKey = scriptPubKey;
                coins->vout[nOut].nValue = 0;
                if (prevOut.exists("amount")) {
                    coins->vout[nOut].nValue = AmountFromValue(prevOut["amount"]);
                }
            }

            // if redeemScript given and private keys given,
            // add redeemScript to the tempKeystore so it can be signed:
            if (fGivenKeys && scriptPubKey.IsPayToScriptHash() &&
                prevOut.exists("redeemScript")) {
                UniValue v = prevOut["redeemScript"];
                std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
                CScript redeemScript(rsData.begin(), rsData.end());
                tempKeystore.AddCScript(redeemScript);
            }
        }
    }

    const CKeyStore& keystore = tempKeystore;

    bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);

    // Sign what we can:
    for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
        CTxIn& txin = mergedTx.vin[i];
        const CCoins* coins = view.AccessCoins(txin.prevout.hash);
        if (!coins || !coins->IsAvailable(txin.prevout.n)) {
            fComplete = false;
            continue;
        }
        const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
        const CAmount& amount = coins->vout[txin.prevout.n].nValue;

        txin.scriptSig.clear();
        // Only sign SIGHASH_SINGLE if there's a corresponding output:
        if (!fHashSingle || (i < mergedTx.vout.size()))
            SignSignature(keystore, prevPubKey, mergedTx, i, amount, nHashType);

        // ... and merge in other signatures:
        BOOST_FOREACH(const CTransaction& txv, txVariants) {
            txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, amount, txin.scriptSig, txv.vin[i].scriptSig);
        }
        if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
            fComplete = false;
    }