Example #1
18
void TextStyle::onBeginDrawFrame(const View& _view, Scene& _scene, int _textureUnit) {
    bool contextLost = Style::glContextLost();

    m_fontContext->bindAtlas(0);

    m_shaderProgram->setUniformf("u_uv_scale_factor",
                                 1.0f / m_fontContext->getAtlasResolution());

    if (contextLost) {
        m_shaderProgram->setUniformi("u_tex", 0);
    }

    if (m_dirtyViewport || contextLost) {
        m_shaderProgram->setUniformMatrix4f("u_ortho", glm::value_ptr(_view.getOrthoViewportMatrix()));
        m_dirtyViewport = false;
    }

    Style::onBeginDrawFrame(_view, _scene, 1);

}
Example #2
0
GIL_FORCEINLINE
F transform_pixels_locator( const View& src, const rect_t<std::ptrdiff_t>& srcRod,
							const ViewDst& dst, const rect_t<std::ptrdiff_t>& dstRod,
							const rect_t<std::ptrdiff_t>& renderWin, F& fun )
{
	const std::ptrdiff_t renderWidth = renderWin.x2 - renderWin.x1;
	typename View::xy_locator sloc = src.xy_at( renderWin.x1-srcRod.x1, renderWin.y1-srcRod.y1 );
	for( std::ptrdiff_t y = renderWin.y1; y < renderWin.y2; ++y )
	{
		typename ViewDst::x_iterator dstIt = dst.x_at( renderWin.x1-dstRod.x1, y-dstRod.y1 );
		for( std::ptrdiff_t x = renderWin.x1;
		     x < renderWin.x2;
		     ++x, ++sloc.x(), ++dstIt )
		{
			*dstIt = fun( sloc );
		}
		sloc.x() -= renderWidth; ++sloc.y();
	}
	return fun;
}
Example #3
0
    void Play::drawCharactersFromView(const View& view)
    {
        if(!_isPlaying)
            return ;

        // Draw from view only if it was installed
        for(const auto& v : _views)
        {
            if(v->id() == view.id())
            {
                StageTime time(_drawClock.totalSeconds(),
                               _drawClock.elapsedSeconds(),
                               _drawClock.ticksPerSecond());

                DrawCaller drawCaller(v, time);
                (*_currentAct)->welcome( drawCaller );
                break;
            }
        }
    }
Example #4
0
double State::insert_feature(int feature_idx, vector<double> feature_data,
                             View& which_view) {
    string col_datatype = global_col_datatypes[feature_idx];
    CM_Hypers& hypers = hypers_m[feature_idx];
    double crp_logp_delta, data_logp_delta;
    double score_delta = calc_feature_view_predictive_logp(feature_data,
                         col_datatype,
                         which_view,
                         crp_logp_delta,
                         data_logp_delta,
                         hypers);
    vector<int> data_global_row_indices = create_sequence(feature_data.size());
    which_view.insert_col(feature_data,
                          data_global_row_indices, feature_idx,
                          hypers);
    view_lookup[feature_idx] = &which_view;
    column_crp_score += crp_logp_delta;
    data_score += data_logp_delta;
    return score_delta;
}
Example #5
0
bool LarsonSekaninaInstance::ExecuteOn( View& view )
{
   AutoViewLock lock( view );

   ImageVariant image = view.Image();

   if ( image.IsComplexSample() )
      return false;

   StandardStatus status;
   image.SetStatusCallback( &status );

   Console().EnableAbort();

   ImageVariant sharpImg;
   sharpImg.CreateFloatImage( (image.BitsPerSample() > 32) ? image.BitsPerSample() : 32 );
   sharpImg.AllocateImage( image->Width(), image->Height(), 1, ColorSpace::Gray );

   if ( useLuminance && image->IsColor() )
   {
      ImageVariant L;
      image.GetLightness( L );
      Convolve( L, sharpImg, interpolation, radiusDiff, angleDiff, center, 0 );
      ApplyFilter( L, sharpImg, amount, threshold, deringing, rangeLow, rangeHigh, false, 0, highPass );
      image.SetLightness( L );
   }
   else
   {
      for ( int c = 0, n = image->NumberOfNominalChannels(); c < n; ++c )
      {
         image->SelectChannel( c );
         if ( n > 1 )
            Console().WriteLn( "<end><cbr>Processing channel #" + String( c ) );

         Convolve( image, sharpImg, interpolation, radiusDiff, angleDiff, center, c );
         ApplyFilter( image, sharpImg, amount, threshold, deringing, rangeLow, rangeHigh, disableExtension, c, highPass );
      }
   }

   return true;
}
Example #6
0
void drawScene() {
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_NORMALIZE);
	glEnable(GL_COLOR_MATERIAL);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glEnable(GL_TEXTURE_2D);
	
	glViewport(0,0, width, height);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	v.setView(width, height);
	if (c.isThirdPerson())		c.updateLook(m);
	else						c.updateLook(m.getX()+hx, m.getY()+hy, m.getZ());

	if (phase == 0) introGame();
	if (phase == 1) playGame();
	if (phase == 2) concGame();

	glutSwapBuffers();
}
Example #7
0
void PivotPlugin::pivot()
{
    View *view = dynamic_cast<View *>(parent());
    if (!view) {
        return;
    }

    if ((view->selection()->lastRange().width() < 2) || (view->selection()->lastRange().height() < 2)) {
        KMessageBox::error(view->canvasWidget(), i18n("You must select multiple cells."));
        return;
    }

    QPointer<Pivot> dialog = new Pivot(view->canvasWidget(), view->selection());
    dialog->exec();
    delete dialog;
}
Example #8
0
void viewmap(RenderWindow* window,Vector2i pos,float time)
{


    if (pos.x<=0||Keyboard::isKeyPressed(Keyboard::A))
    {
        if(Keyboard::isKeyPressed(Keyboard::RShift)||Keyboard::isKeyPressed(Keyboard::LShift))
            view.move(-0.6*time, 0);
        else
        view.move(-0.3*time, 0);
    }

    if (pos.x>=(int)window->getSize().x-1||Keyboard::isKeyPressed(Keyboard::D))
    {
        if(Keyboard::isKeyPressed(Keyboard::RShift)||Keyboard::isKeyPressed(Keyboard::LShift))
            view.move(0.3*time, 0);
        else
        view.move(0.3*time, 0);
    }

    if (pos.y<=0||Keyboard::isKeyPressed(Keyboard::W))
    {
        if(Keyboard::isKeyPressed(Keyboard::RShift)||Keyboard::isKeyPressed(Keyboard::LShift))
            view.move(0,-0.6*time);
        else
        view.move(0, -0.3*time);
    }

    if (pos.y>=(int)window->getSize().y-1||Keyboard::isKeyPressed(Keyboard::S))
    {
        if(Keyboard::isKeyPressed(Keyboard::RShift)||Keyboard::isKeyPressed(Keyboard::LShift))
            view.move(0,0.6*time);
        else
        view.move(0, 0.3*time);
    }

}
Example #9
0
View lb::operator|(View const& _a, View const& _b)
{
	if (!!_a->children().size() == !!_b->children().size())
	{
		View ret = FrameBody::create();
		_a->setParent(ret);
		_b->setParent(ret);
		return ret;
	}
	else if (_a->children().size())
	{
		_b->setParent(_a);
		return _a;
	}
	else
	{
		_a->setParent(_b);
		return _b;
	}
}
Example #10
0
GIL_FORCEINLINE
F transform_pixels_locator_progress( const View& src, const OfxRectI& srcRod,
									 const ViewDst& dst, const OfxRectI& dstRod,
									 const OfxRectI& renderWin, const F& fun, IProgress& p )
{
	const std::ptrdiff_t renderWidth = renderWin.x2 - renderWin.x1;
	typename View::xy_locator sloc = src.xy_at( renderWin.x1-srcRod.x1, renderWin.y1-srcRod.y1 );
	for( std::ptrdiff_t y = renderWin.y1; y < renderWin.y2; ++y )
	{
		typename ViewDst::x_iterator dstIt = dst.x_at( renderWin.x1-dstRod.x1, y-dstRod.y1 );
		for( std::ptrdiff_t x = renderWin.x1;
		     x < renderWin.x2;
		     ++x, ++sloc.x(), ++dstIt )
		{
			*dstIt = fun( sloc );
		}
		sloc.x() -= renderWidth; ++sloc.y();
		if( p.progressForward( renderWidth ) )
			return fun;
	}
	return fun;
}
Example #11
0
        /*!
            Estimates shift of current image relative to background image.

            \param [in] current - current image.
            \param [in] region - a region at the background where the algorithm start to search current image. Estimated shift is taken relative of the region.
            \param [in] maxShift - a 2D-point which characterizes maximal possible shift of the region (along X and Y axes).
            \param [in] hiddenAreaPenalty - a parameter used to restrict searching of the shift at the border of background image.
            \param [in] regionAreaMin - a parameter used to set minimal area of region use for shift estimation. By default is equal to 25.
            \return a result of shift estimation.
        */
        bool Estimate(const View & current, const Rect & region, const Point & maxShift, double hiddenAreaPenalty = 0, ptrdiff_t regionAreaMin = REGION_CORRELATION_AREA_MIN)
        {
            assert(current.Size() == region.Size() && region.Area() > 0);
            assert(_current.Size() && _current[0].width >= current.width && _current[0].height >= current.height);

            if (region.Area() < regionAreaMin)
                return false;

            InitLevels(region, maxShift, regionAreaMin);
            SetCurrent(current, region);

            Point shift;
            for (ptrdiff_t i = _levels.size() - 1; i >= 0; i--)
            {
                shift.x *= 2;
                shift.y *= 2;
                if (!SearchLocalMin(_levels[i], shift, hiddenAreaPenalty))
                    return false;
                shift = _levels[i].shift;
            }
            return true;
        }
Example #12
0
File: life.cpp Project: remeh/meh2d
void init(View& view, std::vector<Sprite*>& sprites, bool val[2][WIDTH][HEIGHT]) {
    int i,j;
    for (i = 0; i < HEIGHT; i++) {
        for (j=0; j < WIDTH;j++) {
             Vector2d<float> pos(j*S_WIDTH,i*S_WIDTH);
             Vector2d<float> size(S_WIDTH,S_WIDTH);
             Rect<float> texCoord(0,0,S_WIDTH,S_WIDTH);
             Sprite *s = view.addSprite(pos,size,"bitmap",texCoord);
             Color tColor(System::rnd(10)/10.0f,System::rnd(10)/10.0f,System::rnd(10)/10.0f,1.0f);
             Vector2d<float> c(2,2);
             s->setRotationCenter(c);
             s->setRotationAngle(45.0f);
             s->setTintColor(tColor);
             sprites.push_back(s);
             s->hide();
             val[0][j][i] = false;
             if (System::rnd(7) == 0) {
                val[0][j][i] = true;
             }
        }
    }
}
Example #13
0
typename
sge::image::traits::dim<
	Tag
>::type
size_any(
	View const &_view
)
{
	return
		fcppt::variant::apply_unary(
			[](
				auto const &_src
			)
			{
				return
					sge::image::impl::from_mizuiro_dim(
						_src.size()
					);
			},
			_view.get()
		);
}
Example #14
0
void PoslvControl::renderAxes(View& view, const QColor& color, double length) {
  Line<double, 3> l_1, l_2, l_3;
  l_1[1][0] = length;
  view.render(l_1, color, _T_w_i);
  l_2[1][1] = length;
  view.render(l_2, color, _T_w_i);
  l_3[1][2] = length;
  view.render(l_3, color, _T_w_i);
  Eigen::Vector3d xLabelPosition = _T_w_i * l_1[1];
  Eigen::Vector3d yLabelPosition = _T_w_i * l_2[1];
  Eigen::Vector3d zLabelPosition = _T_w_i * l_3[1];
  view.render("X", xLabelPosition, color, 0.2*length);
  view.render("Y", yLabelPosition, color, 0.2*length);
  view.render("Z", zLabelPosition, color, 0.2*length);
  Eigen::Vector3d labelPosition = _T_w_i * Eigen::Vector3d(0, 0, length + 0.1);
  view.render("poslv", labelPosition, color, 0.2 * length);
}
Example #15
0
void display(sf::RenderWindow *window)
{
	if (frames==0)
		sfclock.restart();
	
	// Draw using SFML
	window->pushGLStates();
	window->resetGLStates();
	//insert SFML drawing code here (any part you are using that does not involve opengl code)
	window->popGLStates();

	//set up the background color of the window. This does NOT clear the window. Right now it is (0,0,0) which is black
	glClearColor(0,0,0,0);
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); //this command actually clears the window.
	glEnable(GL_DEPTH_TEST);
	v.draw(); //simply delegate to our view class that has all the data and does all the rendering

	if (frames>500)
	{
		sf::Time t = sfclock.getElapsedTime();
		frame_rate = frames/t.asSeconds();
		frames = 0;
	}
	else
	{
		frames++;
	}
	stringstream str;

	str << "Frame rate " << frame_rate;
	// Draw some text on top of our OpenGL object
	drawText(window,str.str(),window->getSize().x,20);
    
	
	// Finally, display the rendered frame on screen
	window->display();
//	cout << "Rendering" << endl;
}
Example #16
0
void BinarizeInterface::UpdateReadout( const View& v, const DPoint&, double R, double G, double B, double /*A*/ )
{
   if ( GUI != 0 && IsVisible() )
   {
      if ( instance.isGlobal )
      {
         RGBColorSystem rgbws;
         v.Window().GetRGBWS( rgbws );
         instance.level[0] = instance.level[1] = instance.level[2] = rgbws.Lightness( R, G, B );
      }
      else
      {
         instance.level[0] = R;
         instance.level[1] = G;
         instance.level[2] = B;
      }

      UpdateControls();

      if ( !RealTimePreview::IsUpdating() )
         RealTimePreview::Update();
   }
}
void SummaryDrawWidget::paintEvent( QPaintEvent * )
{
  Channel *ch;

  //if((right - left) <= 0) return;
  View *view = gdata->view;
/*  if (view->totalTime() == 0) {
    buffer = new QPixmap(size());
    buffer->fill(myBackgroundColor);
    bitBlt(this, 0, 0, buffer); */
  if(gdata->totalTime() < 0) return;

  double timeRatio = double(width()) / gdata->totalTime();
  double pitchRatio = double(height()) / (gdata->topPitch() / scaler);

  beginDrawing();

  //draw all the channels
  for(int j = 0; j < (int)gdata->channels.size(); j++) {
    ch = gdata->channels.at(j);
    if(!ch->isVisible()) continue;

    //drawChannel(ch, p, view->leftTime(), (view->totalTime() / (double) width()), 0.0f, (double) view->topNote() / (double) height(), DRAW_VIEW_SUMMARY);
    drawChannel(*this, ch, p, gdata->leftTime(), view->currentTime(), (gdata->totalTime() / (double) width()), 0.0f, (double) gdata->topPitch() / (double) height(), DRAW_VIEW_SUMMARY);
  }

  //draw the view rectangle 
  p.setPen(QPen(colorGroup().highlight(), 1));
  p.drawRect(int((gdata->leftTime()+view->viewLeft())*timeRatio), height()-1-int((view->viewTop())*pitchRatio),
             int(view->viewWidth()*timeRatio), int(view->viewHeight()*pitchRatio));

  //draw the current time line
  p.setPen(QPen(colorGroup().foreground(), 1));
  //p.moveTo(int((gdata->leftTime()+view->currentTime())*timeRatio), 0);
  //p.lineTo(int((gdata->leftTime()+view->currentTime())*timeRatio), height()-1);
  p.drawLine(int((gdata->leftTime()+view->currentTime())*timeRatio), 0, 
             int((gdata->leftTime()+view->currentTime())*timeRatio), height()-1);

  endDrawing();
}
Example #18
0
int main(int argc, char *argv[])
{
    /* parse command line args */
    for (int i = 1; i+1 < argc; i+=2) {
	if (strcmp(argv[i], "-m") == 0)
	    mazefile = argv[i+1];

	else if (strcmp(argv[i], "-a") == 0)
	    algfile = argv[i+1];
    }

    /* initialize program */
    if (algfile && !load_algorithm(algfile, &algorithm)) {
	fprintf(stderr, "error loading algorithm\n");
	return 1;
    }

    if (!parse_maze(mazefile, &maze)) {
	fprintf(stderr, "error reading maze file\n");
	return 1;
    }

    view = create_view();

    controller = create_controller(
	&view, &maze, &mouse, &algorithm);

    /* run program */
    while(!controller.quit) {
	do_command( &controller, getchar() );
    }

    /* cleanup */
    view.destroy();

    return 0;
}
Example #19
0
inline
void
for_each(
	View const &_view,
	Function const &_function,
	MakeIterator const _make_iterator,
	mizuiro::image::algorithm::uninitialized const _uninitialized
)
{
	switch(
		_uninitialized
	)
	{
	case mizuiro::image::algorithm::uninitialized::yes:
		mizuiro::image::algorithm::unary_iteration(
			mizuiro::image::algorithm::detail::wrap_prepare<
				typename
				View::access,
				typename
				View::format
			>(
				_view.format_store(),
				_function
			),
			_view,
			_make_iterator
		);
		return;
	case mizuiro::image::algorithm::uninitialized::no:
		mizuiro::image::algorithm::unary_iteration(
			_function,
			_view,
			_make_iterator
		);
		return;
	}
}
Example #20
0
// Main entry point for the program
int main(int argc, char* argv[])
{
	// window initialization
	View * v = new View(&argc, argv);
	//glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);

	// Open a window
	v->createWindow("CS458 - Assignment 5", 640, 480);

	// Initialize OpenGL and objects
	Initialize();

	// Setup callback functions
	v->onIdle(OnIdle);
	v->onMouse(OnMouseButton);
	v->onDraw(RenderScene);
	v->onResize(OnResize);

	// Start Glut window
	v->start();
	return 0;
}
void remove_all_data(View &v, map<int, vector<double> > data_map) {
  vector<int> rows_in_view;
  for(mapICp_it it=v.cluster_lookup.begin(); it!=v.cluster_lookup.end(); it++) {
    rows_in_view.push_back(it->first);
  }
  for(vectorI_it it=rows_in_view.begin(); it!=rows_in_view.end(); it++) {
    int idx_to_remove = *it;
    vector<double> row = data_map[idx_to_remove];
    vector<int> global_indices = create_sequence(row.size());
    vector<double> aligned_row = v.align_data(row, global_indices);
    v.remove_row(aligned_row, idx_to_remove);
  }
  cout << "removed all data" << endl;
  v.print();
  //
  for(setCp_it it=v.clusters.begin(); it!=v.clusters.end(); it++) {
    v.remove_if_empty(**it);
  }
  assert(v.get_num_vectors()==0);
  assert(v.get_num_clusters()==0);
  cout << "removed empty clusters" << endl; 
  v.print();
}
Example #22
0
void EventSystem::updateCurrentViewStack(Event* event)
{
  Vec2 pos(event->mouseEvent.x, event->mouseEvent.y);
  bool containsPoint = rootView->containsPoint(pos);
  View* view = rootView;
  currentViewStack.clear();
  
  while(view && view->visible() && view->userInteractionEnabled() && containsPoint)
  {
    currentViewStack.push_back(view);
    containsPoint = false;

    for(auto i=view->subviews.rbegin(); i!=view->subviews.rend(); ++i)
    {
      View* v = (*i).get();
      if(v->visible() && v->userInteractionEnabled() && v->containsPoint(pos))
      {
        view = v;
        containsPoint = true;
        break;
      }
    }
  }
}
Example #23
0
void test_image_views(const View& img_view, const string& prefix) {
    check_image(img_view,prefix+"original.jpg");

    check_image(subimage_view(img_view, iround(img_view.dimensions()/4), iround(img_view.dimensions()/2)),prefix+"cropped.jpg");
    check_image(color_converted_view<gray8_pixel_t>(img_view),prefix+"gray8.jpg");
    check_image(color_converted_view<gray8_pixel_t>(img_view,my_color_converter()),prefix+"my_gray8.jpg");
    check_image(transposed_view(img_view),prefix+"transpose.jpg");
    check_image(rotated180_view(img_view),prefix+"rot180.jpg");
    check_image(rotated90cw_view(img_view),prefix+"90cw.jpg");
    check_image(rotated90ccw_view(img_view),prefix+"90ccw.jpg");
    check_image(flipped_up_down_view(img_view),prefix+"flipped_ud.jpg");
    check_image(flipped_left_right_view(img_view),prefix+"flipped_lr.jpg");
    check_image(subsampled_view(img_view,typename View::point_t(2,1)),prefix+"subsampled.jpg");
    check_image(nth_channel_view(img_view,0),prefix+"0th_channel.jpg");

    // some iterator math
    ptrdiff_t dst=(img_view.end()-(img_view.begin()+4500))+4500; ignore_unused_variable_warning(dst);
    ptrdiff_t dst2=img_view.end()-img_view.begin(); ignore_unused_variable_warning(dst2);
    ptrdiff_t sz=img_view.size(); ignore_unused_variable_warning(sz);
    io_error_if(sz!=dst2);
}
Example #24
0
    static void
    GEMM (const Teuchos::ETransp transA,
          const Teuchos::ETransp transB,
          const double& alpha,
          const View<const double**, LayoutLeft, DeviceType>& A,
          const View<const double**, LayoutLeft, DeviceType>& B,
          const double& beta,
          const View<double**, LayoutLeft, DeviceType>& C)
    {
      const int n = static_cast<int> (C.dimension_1 ());

      // For some BLAS implementations (e.g., MKL), GEMM when B has
      // one column may be signficantly less efficient than GEMV.
      if (n == 1 && transB == Teuchos::NO_TRANS) {
        char trans = 'N';
        if (transA == Teuchos::TRANS) {
          trans = 'T';
        }
        else if (transA == Teuchos::CONJ_TRANS) {
          trans = 'C';
        }
        auto B_0 = Kokkos::subview (B, Kokkos::ALL (), 0);
        auto C_0 = Kokkos::subview (C, Kokkos::ALL (), 0);
        KokkosBlas::gemv (&trans, alpha, A, B_0, beta, C_0);
      }
      else {
        const int m = static_cast<int> (C.dimension_0 ());
        const int k = static_cast<int> (transA == Teuchos::NO_TRANS ? A.dimension_1 () : A.dimension_0 ());
        const int lda = static_cast<int> (Impl::getStride2DView (A));
        const int ldb = static_cast<int> (Impl::getStride2DView (B));
        const int ldc = static_cast<int> (Impl::getStride2DView (C));

        Teuchos::BLAS<int,double> blas;
        blas.GEMM (transA, transB, m, n, k, alpha,
                   A.ptr_on_device(), lda,
                   B.ptr_on_device(), ldb,
                   beta, C.ptr_on_device(), ldc);
      }
    }
Example #25
0
void ViewManager::handleMouseEvents(M4EventType event) {
	Common::Point mousePos = _vm->_mouse->currentPos();
	ListIterator i;
	View *view;
	bool blockedFlag;
	bool foundFlag;

	// If a window sets the _captureEvents flag to true, it will receive all events until
	// it sets it to false, even if it's not the top window
	if (_captureEvents) {
		if (_captureScreen->screenFlags().get & SCREVENT_MOUSE)
			(_captureScreen->onEvent)(event, 0, mousePos.x, mousePos.y, _captureEvents);

	} else {
		blockedFlag = false;
		foundFlag = false;
		view = NULL;

		// Loop from the front to back view
		for (i = _views.reverse_begin(); (i != _views.end()) && !foundFlag && !blockedFlag; --i) {
			view = *i;
			if (!view->isVisible()) continue;

			if (view->screenFlags().blocks & SCREVENT_MOUSE)
				blockedFlag = true;
			if ((view->screenFlags().get & SCREVENT_MOUSE) && view->isInside(mousePos.x, mousePos.y))
				foundFlag = true;
		}

		if (foundFlag)
			view->onEvent(event, 0, mousePos.x, mousePos.y, _captureEvents);
		else
			_captureEvents = false;
		if (_captureEvents)
			_captureScreen = view;
	}
}
Example #26
0
Presenter::Presenter(
        Model& m,
        View& v,
        QObject *parent):
    iscore::SettingsDelegatePresenter{m, v, parent}
{
    {
        // view -> model
        con(v, &View::simplificationRatioChanged,
            this, [&] (auto simplificationRatio) {
            if(simplificationRatio != m.getSimplificationRatio())
            {
                m_disp.submitCommand<SetModelSimplificationRatio>(this->model(this), simplificationRatio);
            }
        });

        // model -> view
        con(m, &Model::SimplificationRatioChanged, &v, &View::setSimplificationRatio);

        // initial value
        v.setSimplificationRatio(m.getSimplificationRatio());
    }

    {
        // view -> model
        con(v, &View::simplifyChanged,
            this, [&] (auto simplify) {
            if(simplify != m.getSimplify())
            {
                m_disp.submitCommand<SetModelSimplify>(this->model(this), simplify);
            }
        });

        // model -> view
        con(m, &Model::SimplifyChanged, &v, &View::setSimplify);

        // initial value
        v.setSimplify(m.getSimplify());
    }

    {
        // view -> model
        con(v, &View::modeChanged,
            this, [&] (auto val) {
            if(val != m.getCurveMode())
            {
                m_disp.submitCommand<SetModelCurveMode>(this->model(this), val);
            }
        });

        // model -> view
        con(m, &Model::CurveModeChanged, &v, &View::setMode);

        // initial value
        v.setMode(m.getCurveMode());
    }

    {
        // view -> model
        con(v, &View::playWhileRecordingChanged,
            this, [&] (auto val) {
            if(val != m.getPlayWhileRecording())
            {
                m_disp.submitCommand<SetModelPlayWhileRecording>(this->model(this), val);
            }
        });

        // model -> view
        con(m, &Model::PlayWhileRecordingChanged, &v, &View::setPlayWhileRecording);

        // initial value
        v.setMode(m.getCurveMode());
    }
}
Example #27
0
void MasterClass::playGameOver()
{
	
	View view = window->getView();
	Vector2u window_size = window->getSize();
	Color darkColor(0,0,0,0);
	Color redColor(6,0,0,6);
	RectangleShape darkenedScreen(Vector2f(window_size.x, window_size.y));
	darkenedScreen.setPosition(view.getCenter().x - (float)window_size.x/2, 0);
	darkenedScreen.setFillColor(darkColor);
	
	RectangleShape redScreen(Vector2f(window_size.x, window_size.y));
	redScreen.setPosition(view.getCenter().x - (float)window_size.x/2, 0);
	redScreen.setFillColor(redColor);

    Clock clock;
    Time time;
    int t = 0, cpt = 0, dt = 0;
    
    Texture gameOverTex;
	gameOverTex.loadFromFile("res/tex/decor/game_over.png");
	Sprite gameOverSprite(gameOverTex);
	Vector2u texture_size = gameOverTex.getSize();
	gameOverSprite.scale((float)window_size.x/texture_size.x, (float)window_size.y/texture_size.y);
	gameOverSprite.setPosition(view.getCenter().x - (float)window_size.x/2, 0);
    
    game->updateVolume();
    game->resume();
	while (window->isOpen() && state == GAMEOVER)
    {
    	Event event;
    	while(window->pollEvent(event))
    	{
    		if(event.type == Event::KeyPressed && event.key.code == Keyboard::Escape)
    		{
    			previousState = state;
				state = MAINMENU;
			}
    	}
    	time = clock.restart();
    	dt = time.asMilliseconds();
    	t += dt;
    	cpt += dt;
        game->update(time);
        game->checkCollisions();
        
        if(t < 2550 && cpt >= 50)
        {
        	cpt = 0;
        	if(redColor.r < 250)
        	{
        		redColor.r += 6;
        		redColor.a += 6;
        	}
        	else
        	{
        		redColor.r = 255;
        		redColor.a = 255;
        	}
        	
        	if(darkColor.a < 250)
        		darkColor.a += 6;
        	else
        		darkColor.a = 255;
        }
		
		if(t > 2550)
			redColor.a = 0;
		
		if(t > 2550 && cpt >= 50)
        {
        	cpt = 0;
        	if(darkColor.a > 5)
        		darkColor.a -= 6;
        	else
        		darkColor.a = 0;
        }
        
        darkenedScreen.setFillColor(darkColor);
        redScreen.setFillColor(redColor);
        window->clear();
        game->display(window);
        if(t > 2550)
        	window->draw(gameOverSprite);
        window->draw(redScreen);
        window->draw(darkenedScreen);

        window->display();
    }
}
Example #28
0
void MasterClass::playSettings()
{
	Vector2u window_size = window->getSize();
	Image img = window->capture();
	Texture texture;
	//texture.loadFromImage(img);
	texture.loadFromFile("res/tex/decor/settings_menu.png");
	Vector2u texture_size = texture.getSize();
	Sprite sprite(texture);
	// 0 -> pas transparent et 255 -> transparent
	//sprite.setColor(sf::Color(255, 255, 255, 128));
	sprite.scale((float)window_size.x/texture_size.x, (float)window_size.y/texture_size.y);
	View view = window->getView();
	sprite.setPosition(view.getCenter().x - (float)window_size.x/2, 0);
	
    Font font;
    font.loadFromFile("res/font/arcade.ttf");
    vector<String> vectItems;
    vectItems.push_back("Reprendre");
    const int resume = 0;
    vectItems.push_back("<- Volume musique +>");
    const int musicsVolume = 1;
    vectItems.push_back("<- Volume bruitages +>");
    const int soundEffectsVolume = 2;
    vectItems.push_back("Menu principal");
    const int mainMenu = 3;
    Menu menu(vectItems, window, font, Menu::CENTER, (unsigned int)window_size.y*0.0444);
	
	SoundBuffer buffer;
	Sound s;
	buffer.loadFromFile("res/snd/enemy/rebel/death1.wav");
	s.setBuffer(buffer);
	
	Music music;
    music.openFromFile("res/snd/level/The_Military_System.wav");
    music.setVolume(config.musicsVolume);
    music.setLoop(true);
    music.play();
	
	while (window->isOpen() && state == SETTINGS)
	{
		sf::Event event;
		while(window->pollEvent(event))
		{
			if (event.type == Event::KeyPressed)
        	{
        		switch(event.key.code)
        		{
        			case Keyboard::Escape :
						state = previousState;
						break;
						
					case Keyboard::Up :
				    	menu.moveUp();
				    	break;
				    	
				    case Keyboard::Down :
				    	menu.moveDown();
				    	break;
				    	
				    case Keyboard::Return :
				    	switch(menu.getSelectedItemIndex())
				    	{
				    		case resume :
				    			state = previousState;
				    			break;
				    		
				    		case mainMenu :
				    			previousState = state;
								state = MAINMENU;
				    			break;
				    		
				    		default :
				    			break;
				    	}
				    	break;
					
					case Keyboard::Left :
						switch(menu.getSelectedItemIndex())
				    	{
				    		case musicsVolume :
				    			config.musicsVolume -= 10;
								if(config.musicsVolume < 0)
									config.musicsVolume = 0;
								music.setVolume(config.musicsVolume);
				    			break;
				    		
				    		case soundEffectsVolume :
				    			config.soundEffectsVolume -= 10;
								if(config.soundEffectsVolume < 0)
									config.soundEffectsVolume = 0;
								s.setVolume(config.soundEffectsVolume);
								s.play();
				    			break;
				    		
				    		default :
				    			break;
				    	}
				    	break;
						
					case Keyboard::Right :
						switch(menu.getSelectedItemIndex())
				    	{
				    		case musicsVolume :
				    			config.musicsVolume += 10;
								if(config.musicsVolume > 100)
									config.musicsVolume = 100;
								music.setVolume(config.musicsVolume);
				    			break;
				    		
				    		case soundEffectsVolume :
				    			config.soundEffectsVolume += 10;
								if(config.soundEffectsVolume > 100)
									config.soundEffectsVolume = 100;
								s.setVolume(config.soundEffectsVolume);
								s.play();
				    			break;
				    		
				    		default :
				    			break;
				    	}
				    	break;
						
					default :
						break;
        		}
			}
		}
		window->clear();
		window->draw(sprite);
        menu.draw(window);
		window->display();
	}
}
void CompositeViewer::eventTraversal()
{
    if (_done) return;

    if (_views.empty()) return;

    double cutOffTime = _frameStamp->getReferenceTime();

    double beginEventTraversal = osg::Timer::instance()->delta_s(_startTick, osg::Timer::instance()->tick());

    // need to copy events from the GraphicsWindow's into local EventQueue for each view;
    typedef std::map<osgViewer::View*, osgGA::EventQueue::Events> ViewEventsMap;
    ViewEventsMap viewEventsMap;

    Contexts contexts;
    getContexts(contexts);

    // set done if there are no windows
    checkWindowStatus(contexts);
    if (_done) return;

    osgGA::EventQueue::Events all_events;

    for(Contexts::iterator citr = contexts.begin();
            citr != contexts.end();
            ++citr)
    {
        osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(*citr);
        if (gw)
        {
            gw->checkEvents();

            osgGA::EventQueue::Events gw_events;
            gw->getEventQueue()->takeEvents(gw_events, cutOffTime);

            for(osgGA::EventQueue::Events::iterator itr = gw_events.begin();
                    itr != gw_events.end();
                    ++itr)
            {
                (*itr)->setGraphicsContext(gw);
            }

            all_events.insert(all_events.end(), gw_events.begin(), gw_events.end());
        }
    }

    // sort all the events in time order so we can make sure we pass them all on in the correct order.
    all_events.sort(SortEvents());

    // pass on pointer data onto non mouse events to keep the position data usable by all recipients of all events.
    for(osgGA::EventQueue::Events::iterator itr = all_events.begin();
            itr != all_events.end();
            ++itr)
    {
        osgGA::GUIEventAdapter* event = itr->get();

        switch(event->getEventType())
        {
        case(osgGA::GUIEventAdapter::PUSH):
        case(osgGA::GUIEventAdapter::RELEASE):
        case(osgGA::GUIEventAdapter::DOUBLECLICK):
        case(osgGA::GUIEventAdapter::MOVE):
        case(osgGA::GUIEventAdapter::DRAG):
        {
            if ((event->getEventType()!=osgGA::GUIEventAdapter::DRAG && event->getEventType()!=osgGA::GUIEventAdapter::RELEASE) ||
                    !_previousEvent ||
                    _previousEvent->getGraphicsContext()!=event->getGraphicsContext() ||
                    _previousEvent->getNumPointerData()<2)
            {
                generatePointerData(*event);
            }
            else
            {
                reprojectPointerData(*_previousEvent, *event);
            }

#if 0
            // assign topmost PointeData settings as the events X,Y and InputRange
            osgGA::PointerData* pd = event->getPointerData(event->getNumPointerData()-1);
            event->setX(pd->x);
            event->setY(pd->y);
            event->setInputRange(pd->xMin, pd->yMin, pd->xMax, pd->yMax);
            event->setMouseYOrientation(osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS);
#else
            if (event->getMouseYOrientation()!=osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS)
            {
                event->setY((event->getYmax()-event->getY())+event->getYmin());
                event->setMouseYOrientation(osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS);
            }
#endif

            _previousEvent = event;

            break;
        }
        default:
            if (_previousEvent.valid()) event->copyPointerDataFrom(*_previousEvent);
            break;
        }

        osgGA::PointerData* pd = event->getNumPointerData()>0 ? event->getPointerData(event->getNumPointerData()-1) : 0;
        osg::Camera* camera = pd ? dynamic_cast<osg::Camera*>(pd->object.get()) : 0;
        osgViewer::View* view = camera ? dynamic_cast<osgViewer::View*>(camera->getView()) : 0;

        if (!view)
        {
            if (_viewWithFocus.valid())
            {
                // OSG_NOTICE<<"Falling back to using _viewWithFocus"<<std::endl;
                view = _viewWithFocus.get();
            }
            else if (!_views.empty())
            {
                // OSG_NOTICE<<"Falling back to using first view as one with focus"<<std::endl;
                view = _views[0].get();
            }
        }

        // reassign view with focus
        if (_viewWithFocus != view)  _viewWithFocus = view;

        if (view)
        {
            viewEventsMap[view].push_back( event );

            osgGA::GUIEventAdapter* eventState = view->getEventQueue()->getCurrentEventState();
            eventState->copyPointerDataFrom(*event);
        }

        _previousEvent = event;
    }

    // handle any close windows
    for(osgGA::EventQueue::Events::iterator itr = all_events.begin();
            itr != all_events.end();
            ++itr)
    {
        osgGA::GUIEventAdapter* event = itr->get();
        switch(event->getEventType())
        {
        case(osgGA::GUIEventAdapter::CLOSE_WINDOW):
        {
            bool wasThreading = areThreadsRunning();
            if (wasThreading) stopThreading();

            if (event->getGraphicsContext())
            {
                event->getGraphicsContext()->close();
            }

            if (wasThreading) startThreading();

            break;
        }
        default:
            break;
        }
    }


    for(RefViews::iterator vitr = _views.begin();
            vitr != _views.end();
            ++vitr)
    {
        View* view = vitr->get();

        // get events from user Devices attached to Viewer.
        for(osgViewer::View::Devices::iterator eitr = view->getDevices().begin();
                eitr != view->getDevices().end();
                ++eitr)
        {
            osgGA::Device* es = eitr->get();
            if (es->getCapabilities() & osgGA::Device::RECEIVE_EVENTS)
                es->checkEvents();

            // open question, will we need to reproject mouse coordinates into current view's coordinate frame as is down for GraphicsWindow provided events?
            // for now assume now and just get the events directly without any reprojection.
            es->getEventQueue()->takeEvents(viewEventsMap[view], cutOffTime);
        }

        // generate frame event
        view->getEventQueue()->frame( getFrameStamp()->getReferenceTime() );

        view->getEventQueue()->takeEvents(viewEventsMap[view], cutOffTime);
    }

    if ((_keyEventSetsDone!=0) || _quitEventSetsDone)
    {
        for(ViewEventsMap::iterator veitr = viewEventsMap.begin();
                veitr != viewEventsMap.end();
                ++veitr)
        {
            for(osgGA::EventQueue::Events::iterator itr = veitr->second.begin();
                    itr != veitr->second.end();
                    ++itr)
            {
                osgGA::GUIEventAdapter* event = itr->get();
                switch(event->getEventType())
                {
                case(osgGA::GUIEventAdapter::KEYUP):
                    if (_keyEventSetsDone && event->getKey()==_keyEventSetsDone) _done = true;
                    break;

                case(osgGA::GUIEventAdapter::QUIT_APPLICATION):
                    if (_quitEventSetsDone) _done = true;
                    break;

                default:
                    break;
                }
            }
        }
    }

    if (_done) return;

    if (_eventVisitor.valid())
    {
        _eventVisitor->setFrameStamp(getFrameStamp());
        _eventVisitor->setTraversalNumber(getFrameStamp()->getFrameNumber());

        for(ViewEventsMap::iterator veitr = viewEventsMap.begin();
                veitr != viewEventsMap.end();
                ++veitr)
        {
            View* view = veitr->first;

            if (view && view->getSceneData())
            {
                _eventVisitor->setActionAdapter(view);

                for(osgGA::EventQueue::Events::iterator itr = veitr->second.begin();
                        itr != veitr->second.end();
                        ++itr)
                {
                    osgGA::GUIEventAdapter* event = itr->get();

                    _eventVisitor->reset();
                    _eventVisitor->addEvent( event );

                    view->getSceneData()->accept(*_eventVisitor);

                    // Do EventTraversal for slaves with their own subgraph
                    for(unsigned int i=0; i<view->getNumSlaves(); ++i)
                    {
                        osg::View::Slave& slave = view->getSlave(i);
                        osg::Camera* camera = slave._camera.get();
                        if(camera && !slave._useMastersSceneData)
                        {
                            camera->accept(*_eventVisitor);
                        }
                    }

                    // call any camera event callbacks, but only traverse that callback, don't traverse its subgraph
                    // leave that to the scene update traversal.
                    osg::NodeVisitor::TraversalMode tm = _eventVisitor->getTraversalMode();
                    _eventVisitor->setTraversalMode(osg::NodeVisitor::TRAVERSE_NONE);

                    if (view->getCamera() && view->getCamera()->getEventCallback()) view->getCamera()->accept(*_eventVisitor);

                    for(unsigned int i=0; i<view->getNumSlaves(); ++i)
                    {
                        osg::View::Slave& slave = view->getSlave(i);
                        osg::Camera* camera = view->getSlave(i)._camera.get();
                        if (camera && slave._useMastersSceneData && camera->getEventCallback())
                        {
                            camera->accept(*_eventVisitor);
                        }
                    }

                    _eventVisitor->setTraversalMode(tm);

                }
            }
        }

    }

    for(ViewEventsMap::iterator veitr = viewEventsMap.begin();
            veitr != viewEventsMap.end();
            ++veitr)
    {
        View* view = veitr->first;

        for(osgGA::EventQueue::Events::iterator itr = veitr->second.begin();
                itr != veitr->second.end();
                ++itr)
        {
            osgGA::GUIEventAdapter* event = itr->get();

            for(View::EventHandlers::iterator hitr = view->getEventHandlers().begin();
                    hitr != view->getEventHandlers().end();
                    ++hitr)
            {
                (*hitr)->handleWithCheckAgainstIgnoreHandledEventsMask( *event, *view, 0, _eventVisitor.get());
            }
        }
    }

    for(ViewEventsMap::iterator veitr = viewEventsMap.begin();
            veitr != viewEventsMap.end();
            ++veitr)
    {
        View* view = veitr->first;

        for(osgGA::EventQueue::Events::iterator itr = veitr->second.begin();
                itr != veitr->second.end();
                ++itr)
        {
            osgGA::GUIEventAdapter* event = itr->get();

            if (view->getCameraManipulator())
            {
                view->getCameraManipulator()->handleWithCheckAgainstIgnoreHandledEventsMask( *event, *view);
            }
        }
    }

    if (getViewerStats() && getViewerStats()->collectStats("event"))
    {
        double endEventTraversal = osg::Timer::instance()->delta_s(_startTick, osg::Timer::instance()->tick());

        // update current frames stats
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Event traversal begin time", beginEventTraversal);
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Event traversal end time", endEventTraversal);
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Event traversal time taken", endEventTraversal-beginEventTraversal);
    }
}
void CompositeViewer::updateTraversal()
{
    if (_done) return;

    double beginUpdateTraversal = osg::Timer::instance()->delta_s(_startTick, osg::Timer::instance()->tick());

    _updateVisitor->reset();
    _updateVisitor->setFrameStamp(getFrameStamp());
    _updateVisitor->setTraversalNumber(getFrameStamp()->getFrameNumber());

    Scenes scenes;
    getScenes(scenes);
    for(Scenes::iterator sitr = scenes.begin();
            sitr != scenes.end();
            ++sitr)
    {
        Scene* scene = *sitr;
        scene->updateSceneGraph(*_updateVisitor);
    }

    // if we have a shared state manager prune any unused entries
    if (osgDB::Registry::instance()->getSharedStateManager())
        osgDB::Registry::instance()->getSharedStateManager()->prune();

    // update the Registry object cache.
    osgDB::Registry::instance()->updateTimeStampOfObjectsInCacheWithExternalReferences(*getFrameStamp());
    osgDB::Registry::instance()->removeExpiredObjectsInCache(*getFrameStamp());


    if (_incrementalCompileOperation.valid())
    {
        // merge subgraphs that have been compiled by the incremental compiler operation.
        _incrementalCompileOperation->mergeCompiledSubgraphs(getFrameStamp());
    }

    if (_updateOperations.valid())
    {
        _updateOperations->runOperations(this);
    }

    for(RefViews::iterator vitr = _views.begin();
            vitr != _views.end();
            ++vitr)
    {
        View* view = vitr->get();

        {
            // Do UpdateTraversal for slaves with their own subgraph
            for(unsigned int i=0; i<view->getNumSlaves(); ++i)
            {
                osg::View::Slave& slave = view->getSlave(i);
                osg::Camera* camera = slave._camera.get();
                if(camera && !slave._useMastersSceneData)
                {
                    camera->accept(*_updateVisitor);
                }
            }

            // call any camera update callbacks, but only traverse that callback, don't traverse its subgraph
            // leave that to the scene update traversal.
            osg::NodeVisitor::TraversalMode tm = _updateVisitor->getTraversalMode();
            _updateVisitor->setTraversalMode(osg::NodeVisitor::TRAVERSE_NONE);

            if (view->getCamera() && view->getCamera()->getUpdateCallback()) view->getCamera()->accept(*_updateVisitor);

            for(unsigned int i=0; i<view->getNumSlaves(); ++i)
            {
                osg::View::Slave& slave = view->getSlave(i);
                osg::Camera* camera = slave._camera.get();
                if (camera && slave._useMastersSceneData && camera->getUpdateCallback())
                {
                    camera->accept(*_updateVisitor);
                }
            }

            _updateVisitor->setTraversalMode(tm);
        }


        if (view->getCameraManipulator())
        {
            view->setFusionDistance( view->getCameraManipulator()->getFusionDistanceMode(),
                                     view->getCameraManipulator()->getFusionDistanceValue() );

            view->getCameraManipulator()->updateCamera(*(view->getCamera()));

        }
        view->updateSlaves();

    }

    if (getViewerStats() && getViewerStats()->collectStats("update"))
    {
        double endUpdateTraversal = osg::Timer::instance()->delta_s(_startTick, osg::Timer::instance()->tick());

        // update current frames stats
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Update traversal begin time", beginUpdateTraversal);
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Update traversal end time", endUpdateTraversal);
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Update traversal time taken", endUpdateTraversal-beginUpdateTraversal);
    }

}