示例#1
0
void myMouseMotionCB(int x, int y)
{
	control.mouseMotionCB(x,y);
}
示例#2
0
	inline void set (const size_t n, bool value) {control.set (n, value);}
//
// NOTE: run this sample from the repo/tests directory.
//
int main(int argc, char** argv)
{
    osg::ArgumentParser arguments(&argc,argv);

    osgViewer::Viewer viewer(arguments);
    s_viewer = &viewer;

    // Start by creating the map:
    s_mapNode = MapNode::load(arguments);
    if ( !s_mapNode )
    {
        Map* map = new Map();

        // Start with a basemap imagery layer; we'll be using the GDAL driver
        // to load a local GeoTIFF file:
        GDALOptions basemapOpt;
        basemapOpt.url() = "../data/world.tif";
        map->addImageLayer( new ImageLayer( ImageLayerOptions("basemap", basemapOpt) ) );

        // That's it, the map is ready; now create a MapNode to render the Map:
        MapNodeOptions mapNodeOptions;
        mapNodeOptions.enableLighting() = false;

        s_mapNode = new MapNode( map, mapNodeOptions );
    }
    s_mapNode->setNodeMask( 0x01 );

        
    // Define a style for the feature data. Since we are going to render the
    // vectors as lines, configure the line symbolizer:
    StyleSheet* styleSheet = buildStyleSheet( Color::Yellow, 2.0f );

    // create a feature list source with the map extents as the default extent.
    s_source = new FeatureListSource( s_mapNode->getMap()->getProfile()->getExtent() );

    LineString* line = new LineString();
    line->push_back( osg::Vec3d(-60, 20, 0) );
    line->push_back( osg::Vec3d(-120, 20, 0) );
    line->push_back( osg::Vec3d(-120, 60, 0) );
    line->push_back( osg::Vec3d(-60, 60, 0) );
    Feature* feature = new Feature(line, s_mapNode->getMapSRS(), Style(), s_fid++);
    s_source->insertFeature( feature );
    s_activeFeature = feature;
  
    s_root = new osg::Group;
    s_root->addChild( s_mapNode.get() );

    Session* session = new Session(s_mapNode->getMap(), styleSheet, s_source.get());

    FeatureModelGraph* graph = new FeatureModelGraph( 
        session,
        FeatureModelSourceOptions(), 
        new GeomFeatureNodeFactory() );

    graph->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
    graph->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);

    s_root->addChild( graph );

    //Setup the controls
    ControlCanvas* canvas = ControlCanvas::get( &viewer );
    s_root->addChild( canvas );
    Grid *toolbar = createToolBar( );
    canvas->addControl( toolbar );
    canvas->setNodeMask( 0x1 << 1 );



    int col = 0;
    LabelControl* addVerts = new LabelControl("Add Verts");
    toolbar->setControl(col++, 0, addVerts );    
    addVerts->addEventHandler( new AddVertsModeHandler( graph ));
    
    LabelControl* edit = new LabelControl("Edit");
    toolbar->setControl(col++, 0, edit );    
    edit->addEventHandler(new EditModeHandler( graph ));

    unsigned int row = 0;
    Grid *styleBar = createToolBar( );
    styleBar->setPosition(0, 50);
    canvas->addControl( styleBar );
    
    //Make a list of styles
    styleBar->setControl(0, row++, new LabelControl("Styles") );    

    unsigned int numStyles = 8;
    for (unsigned int i = 0; i < numStyles; ++i)
    {
        float w = 50;
        osg::Vec4 color = randomColor();

        float widths[3] = {2, 4, 8};

        unsigned int r = row++;
        for (unsigned int j = 0; j < 3; j++) 
        {
            Control* l = new Control();            
            l->setBackColor( color );
            l->addEventHandler(new ChangeStyleHandler(graph, buildStyleSheet( color, widths[j] ) ));
            l->setSize(w,5 * widths[j]);
            styleBar->setControl(j, r, l);
        }
    }
   
    
    viewer.setSceneData( s_root.get() );
    viewer.setCameraManipulator( new EarthManipulator() );

    if ( s_mapNode )
        viewer.getCamera()->addCullCallback( new osgEarth::Util::AutoClipPlaneCullCallback(s_mapNode) );

    // add some stock OSG handlers:
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());
    viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()));

    return viewer.run();
}
示例#4
0
// 2. 加载骨骼数据
void M2Importer::importBoneObject()
{
	// Bone Group Header Node
	INode* groupHeadNode = createGroupHeaderNode();
	groupHeadNode->SetGroupHead(TRUE);
	groupHeadNode->SetGroupMember(FALSE);

	if (m_modelHeader->nameLength > 1)
	{
		TCHAR* modelName = (TCHAR*)(m_m2FileData + m_modelHeader->nameOfs);
		TCHAR boneGroupName[256];
		sprintf(boneGroupName, "%s_bone", modelName);
		groupHeadNode->SetName(boneGroupName);
	}
	else
		groupHeadNode->SetName("BoneGroup");


	// Bone
	// 一个Bone构造一个Node, 并且加入到组中

	ModelBoneDef* boneData = (ModelBoneDef*)(m_m2FileData + m_modelHeader->ofsBones);

	m_boneNodeList.reserve(m_modelHeader->nBones);
	for (unsigned int i = 0; i < m_modelHeader->nBones; ++i)
	{
		ModelBoneDef& boneDef = boneData[i];

		// create bone node
		HelperObject* obj = (HelperObject*)CreateInstance(HELPER_CLASS_ID, Class_ID(BONE_CLASS_ID, 0));

		ImpNode* node = m_impInterface->CreateNode();

		TCHAR boneName[256];
		sprintf(boneName, "bone_%02d", i);
		node->SetName(boneName);

		node->SetPivot(*(Point3*)&(boneDef.pivot));
		node->Reference(obj);

		m_impInterface->AddNodeToScene(node);

		// 设置变换矩阵
		Matrix3 tm;
		tm.IdentityMatrix();
		tm.SetTrans(*(Point3*)&(boneDef.pivot));
		node->SetTransform(0, tm);

		// 添加到组
		INode* realINode = node->GetINode();
		realINode->SetGroupHead(FALSE);
		realINode->SetGroupMember(TRUE);
		groupHeadNode->AttachChild(realINode);

		// 设置Bone父子关系
		realINode->ShowBone(2);
		m_boneNodeList.push_back(realINode);
		if (boneDef.parent != -1)
		{
			INode* parentNode = m_boneNodeList[boneDef.parent];
			parentNode->AttachChild(realINode);
		}

		realINode->EvalWorldState(0);
	}

	// 导入每根骨骼的关键桢数据
	for (unsigned int i = 0; i < m_modelHeader->nBones; ++i)
	{
		ModelBoneDef& boneDef = boneData[i];
		INode* realINode = m_boneNodeList[i];

		Control* tmControl = realINode->GetTMController();

		// Position
		if (boneDef.translation.nKeys)
		{
			// 设置动画控制器为线性控制器
			Control* posControl = createPositionController();
			tmControl->SetPositionController(posControl);

			unsigned int* timeData = (unsigned int*)(m_m2FileData + boneDef.translation.ofsTimes);
			Point3* keyData = (Point3*)(m_m2FileData + boneDef.translation.ofsKeys);

			// 设置动画时间范围
			bool animRangeChanged = false;
			Interval animRange = m_maxInterface->GetAnimRange();
			for (unsigned int j = 0; j < boneDef.translation.nKeys; ++j)
			{
				if (timeData[j] < animRange.Start())
				{
					animRange.SetStart(timeData[j]);
					animRangeChanged = true;
				}
				else if (timeData[j] > animRange.End())
				{
					animRange.SetEnd(timeData[j]);
					animRangeChanged = true;
				}
			}
			if (animRangeChanged)
				m_maxInterface->SetAnimRange(animRange);

			// 设置动画关键桢数据
			Control* xControl = posControl->GetXController();
			IKeyControl* xKeyControl = GetKeyControlInterface(xControl);
			xKeyControl->SetNumKeys(boneDef.translation.nKeys);

			Control* yControl = posControl->GetYController();
			IKeyControl* yKeyControl = GetKeyControlInterface(yControl);
			yKeyControl->SetNumKeys(boneDef.translation.nKeys);

			Control* zControl = posControl->GetZController();
			IKeyControl* zKeyControl = GetKeyControlInterface(zControl);
			zKeyControl->SetNumKeys(boneDef.translation.nKeys);

			for (unsigned int j = 0; j < boneDef.translation.nKeys; ++j)
			{
				// X
				AnyKey bufX;
				ILinFloatKey* keyX = reinterpret_cast<ILinFloatKey*>((IKey*)bufX);
				keyX->time = timeData[j];
				keyX->val = keyData[j].x;
				xKeyControl->AppendKey(keyX);

				// Y
				AnyKey bufY;
				ILinFloatKey* keyY = reinterpret_cast<ILinFloatKey*>((IKey*)bufY);
				keyY->time = timeData[j];
				keyY->val = keyData[j].y;
				yKeyControl->AppendKey(keyY);

				// Z
				AnyKey bufZ;
				ILinFloatKey* keyZ = reinterpret_cast<ILinFloatKey*>((IKey*)bufZ);
				keyZ->time = timeData[j];
				keyZ->val = keyData[j].z;
				zKeyControl->AppendKey(keyZ);
			}
		}
/*
		// Rotation
		if (boneDef.rotation.nKeys)
		{
			Control* rotControl = createRotationController();
			tmControl->SetRotationController(rotControl);

			unsigned int* timeData = (unsigned int*)(m_m2FileData + boneDef.rotation.ofsTimes);
			Quat* keyData = (Quat*)(m_m2FileData + boneDef.rotation.ofsKeys);

			// 设置动画时间范围
			bool animRangeChanged = false;
			Interval animRange = m_maxInterface->GetAnimRange();
			for (unsigned int j = 0; j < boneDef.rotation.nKeys; ++j)
			{
				if (timeData[j] < animRange.Start())
				{
					animRange.SetStart(timeData[j]);
					animRangeChanged = true;
				}
				else if (timeData[j] > animRange.End())
				{
					animRange.SetEnd(timeData[j]);
					animRangeChanged = true;
				}
			}
			if (animRangeChanged)
				m_maxInterface->SetAnimRange(animRange);

			// 设置动画关键桢数据
			IKeyControl* keyControl = GetKeyControlInterface(rotControl);
			keyControl->SetNumKeys(boneDef.rotation.nKeys);

			for (unsigned int j = 0; j < boneDef.rotation.nKeys; ++j)
			{
				AnyKey buf;
				ILinRotKey* key = reinterpret_cast<ILinRotKey*>((IKey*)buf);
				key->time = timeData[j];
				key->val = keyData[j];
				keyControl->AppendKey(key);
			}
		}
*/
		// Scaling
		if (boneDef.scaling.nKeys)
		{
			Control* scaControl = createScaleController();
			tmControl->SetScaleController(scaControl);

			unsigned int* timeData = (unsigned int*)(m_m2FileData + boneDef.scaling.ofsTimes);
			Point3* keyData = (Point3*)(m_m2FileData + boneDef.scaling.ofsKeys);

			// 设置动画时间范围
			bool animRangeChanged = false;
			Interval animRange = m_maxInterface->GetAnimRange();
			for (unsigned int j = 0; j < boneDef.scaling.nKeys; ++j)
			{
				if (timeData[j] < animRange.Start())
				{
					animRange.SetStart(timeData[j]);
					animRangeChanged = true;
				}
				else if (timeData[j] > animRange.End())
				{
					animRange.SetEnd(timeData[j]);
					animRangeChanged = true;
				}
			}
			if (animRangeChanged)
				m_maxInterface->SetAnimRange(animRange);

			// 设置动画关键桢数据
			IKeyControl* keyControl = GetKeyControlInterface(scaControl);
			keyControl->SetNumKeys(boneDef.scaling.nKeys);

			for (unsigned int j = 0; j < boneDef.scaling.nKeys; ++j)
			{
				AnyKey buf;
				ILinScaleKey* key = reinterpret_cast<ILinScaleKey*>((IKey*)buf);
				key->time = timeData[j];
				key->val = ScaleValue(keyData[j]);
				keyControl->AppendKey(key);
			}
		}
	}
}
示例#5
0
void ProjectManager::_load_recent_projects() {

	ProjectListFilter::FilterOption filter_option = project_filter->get_filter_option();
	String search_term = project_filter->get_search_term();

	while(scroll_childs->get_child_count()>0) {
		memdelete( scroll_childs->get_child(0));
	}

	Map<String, String> selected_list_copy = selected_list;

	List<PropertyInfo> properties;
	EditorSettings::get_singleton()->get_property_list(&properties);

	Color font_color = gui_base->get_color("font_color","Tree");

	List<ProjectItem> projects;
	List<ProjectItem> favorite_projects;

	for(List<PropertyInfo>::Element *E=properties.front();E;E=E->next()) {

		String _name = E->get().name;
		if (!_name.begins_with("projects/") && !_name.begins_with("favorite_projects/"))
			continue;

		String path = EditorSettings::get_singleton()->get(_name);
		if (filter_option == ProjectListFilter::FILTER_PATH && search_term!="" && path.findn(search_term)==-1)
			continue;

		String project = _name.get_slice("/",1);
		String conf=path.plus_file("godot.cfg");
		bool favorite = (_name.begins_with("favorite_projects/"))?true:false;

		uint64_t last_modified = 0;
		if (FileAccess::exists(conf)) {
			last_modified = FileAccess::get_modified_time(conf);

			String fscache = path.plus_file(".fscache");
			if (FileAccess::exists(fscache)) {
				uint64_t cache_modified = FileAccess::get_modified_time(fscache);
				if ( cache_modified > last_modified )
					last_modified = cache_modified;
			}

			ProjectItem item(project, path, conf, last_modified, favorite);
			if (favorite)
				favorite_projects.push_back(item);
			else
				projects.push_back(item);
		} else {
			//project doesn't exist on disk but it's in the XML settings file
			EditorSettings::get_singleton()->erase(_name); //remove it
		}
	}

	projects.sort();
	favorite_projects.sort();

	for(List<ProjectItem>::Element *E=projects.front();E;) {
		List<ProjectItem>::Element *next = E->next();
		if (favorite_projects.find(E->get()) != NULL)
			projects.erase(E->get());
		E=next;
	}
	for(List<ProjectItem>::Element *E=favorite_projects.back();E;E=E->prev()) {
		projects.push_front(E->get());
	}

	Ref<Texture> favorite_icon = get_icon("Favorites","EditorIcons");

	for(List<ProjectItem>::Element *E=projects.front();E;E=E->next()) {

		ProjectItem &item = E->get();
		String project = item.project;
		String path = item.path;
		String conf = item.conf;
		bool is_favorite = item.favorite;

		Ref<ConfigFile> cf = memnew( ConfigFile );
		Error err = cf->load(conf);
		ERR_CONTINUE(err!=OK);


		String project_name=TTR("Unnamed Project");

		if (cf->has_section_key("application","name")) {
			project_name = static_cast<String>(cf->get_value("application","name")).xml_unescape();
		}

		if (filter_option==ProjectListFilter::FILTER_NAME && search_term!="" && project_name.findn(search_term)==-1)
			continue;

		Ref<Texture> icon;
		if (cf->has_section_key("application","icon")) {
			String appicon = cf->get_value("application","icon");
			if (appicon!="") {
				Image img;
				Error err = img.load(appicon.replace_first("res://",path+"/"));
				if (err==OK) {

					img.resize(64,64);
					Ref<ImageTexture> it = memnew( ImageTexture );
					it->create_from_image(img);
					icon=it;
				}
			}
		}

		if (icon.is_null()) {
			icon=get_icon("DefaultProjectIcon","EditorIcons");
		}

		String main_scene;
		if (cf->has_section_key("application","main_scene")) {
			main_scene = cf->get_value("application","main_scene");
		}

		selected_list_copy.erase(project);

		HBoxContainer *hb = memnew( HBoxContainer );
		hb->set_meta("name",project);
		hb->set_meta("main_scene",main_scene);
		hb->set_meta("favorite",is_favorite);
		hb->connect("draw",this,"_panel_draw",varray(hb));
		hb->connect("gui_input",this,"_panel_input",varray(hb));
		hb->add_constant_override("separation",10*EDSCALE);

		VBoxContainer *favorite_box = memnew( VBoxContainer );
		TextureButton *favorite = memnew( TextureButton );
		favorite->set_normal_texture(favorite_icon);
		if (!is_favorite)
			favorite->set_modulate(Color(1,1,1,0.2));
		favorite->set_v_size_flags(SIZE_EXPAND);
		favorite->connect("pressed",this,"_favorite_pressed",varray(hb));
		favorite_box->add_child(favorite);
		hb->add_child(favorite_box);

		TextureRect *tf = memnew( TextureRect );
		tf->set_texture(icon);
		hb->add_child(tf);

		VBoxContainer *vb = memnew(VBoxContainer);
		vb->set_name("project");
		hb->add_child(vb);
		Control *ec = memnew( Control );
		ec->set_custom_minimum_size(Size2(0,1));
		vb->add_child(ec);
		Label *title = memnew( Label(project_name) );
		title->add_font_override("font", gui_base->get_font("large","Fonts"));
		title->add_color_override("font_color",font_color);
		vb->add_child(title);
		Label *fpath = memnew( Label(path) );
		fpath->set_name("path");
		vb->add_child(fpath);
		fpath->set_modulate(Color(1,1,1,0.5));
		fpath->add_color_override("font_color",font_color);

		scroll_childs->add_child(hb);
	}

	for (Map<String,String>::Element *E = selected_list_copy.front();E;E = E->next()) {
		String key = E->key();
		selected_list.erase(key);
	}

	scroll->set_v_scroll(0);

	_update_project_buttons();

	EditorSettings::get_singleton()->save();

	tabs->set_current_tab(0);
}
示例#6
0
void SceneTreeDock::_create() {


	if (current_option==TOOL_NEW) {

		Node *parent=NULL;


		if (edited_scene) {

			parent = scene_tree->get_selected();
			ERR_FAIL_COND(!parent);
		} else {

			parent = scene_root;
			ERR_FAIL_COND(!parent);

		}

		Object *c = create_dialog->instance_selected();

		ERR_FAIL_COND(!c);
		Node *child=c->cast_to<Node>();
		ERR_FAIL_COND(!child);

		editor_data->get_undo_redo().create_action("Create Node");

		if (edited_scene) {
			editor_data->get_undo_redo().add_do_method(parent,"add_child",child);
			editor_data->get_undo_redo().add_do_method(child,"set_owner",edited_scene);
			editor_data->get_undo_redo().add_do_method(editor_selection,"clear");
			editor_data->get_undo_redo().add_do_method(editor_selection,"add_node",child);
			editor_data->get_undo_redo().add_do_reference(child);
			editor_data->get_undo_redo().add_undo_method(parent,"remove_child",child);
		} else {

			editor_data->get_undo_redo().add_do_method(editor,"set_edited_scene",child);
			editor_data->get_undo_redo().add_do_reference(child);
			editor_data->get_undo_redo().add_undo_method(editor,"set_edited_scene",(Object*)NULL);

		}

		editor_data->get_undo_redo().commit_action();
		editor->push_item(c);

		if (c->cast_to<Control>()) {
			//make editor more comfortable, so some controls don't appear super shrunk
			Control *ct = c->cast_to<Control>();

			Size2 ms = ct->get_minimum_size();
			if (ms.width<4)
				ms.width=40;
			if (ms.height<4)
				ms.height=40;
			ct->set_size(ms);
		}


	} else if (current_option==TOOL_REPLACE) {
		Node * n = scene_tree->get_selected();
		ERR_FAIL_COND(!n);

		Object *c = create_dialog->instance_selected();

		ERR_FAIL_COND(!c);
		Node *newnode=c->cast_to<Node>();
		ERR_FAIL_COND(!newnode);

		List<PropertyInfo> pinfo;
		n->get_property_list(&pinfo);

		for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
			if (!(E->get().usage&PROPERTY_USAGE_STORAGE))
				continue;
			newnode->set(E->get().name,n->get(E->get().name));
		}

		editor->push_item(NULL);

		//reconnect signals
		List<MethodInfo> sl;

		n->get_signal_list(&sl);
		for (List<MethodInfo>::Element *E=sl.front();E;E=E->next()) {

			List<Object::Connection> cl;
			n->get_signal_connection_list(E->get().name,&cl);

			for(List<Object::Connection>::Element *F=cl.front();F;F=F->next()) {

				Object::Connection &c=F->get();
				if (!(c.flags&Object::CONNECT_PERSIST))
					continue;
				newnode->connect(c.signal,c.target,c.method,varray(),Object::CONNECT_PERSIST);
			}

		}


		String newname=n->get_name();
		n->replace_by(newnode,true);


		if (n==edited_scene) {
			edited_scene=newnode;
			editor->set_edited_scene(newnode);
		}




		editor_data->get_undo_redo().clear_history();
		memdelete(n);
		newnode->set_name(newname);
		editor->push_item(newnode);

		_update_tool_buttons();

	}

}
示例#7
0
  bool Cursynth::textInput(int key) {
    if (state_ == PATCH_LOADING) {
      int num_patches = patches_.size();
      switch(key) {
        case '\n':
          // Finish loading patches.
          state_ = STANDARD;
          gui_.clearPatches();
          return true;
        case KEY_UP:
          // Go to previous patch.
          patch_load_index_ = CLAMP(patch_load_index_ - 1, 0, num_patches - 1);
          gui_.drawPatchLoading(patches_, patch_load_index_);
          loadFromFile(patches_[patch_load_index_]);
          return true;
        case KEY_DOWN:
          // Go to next patch.
          patch_load_index_ = CLAMP(patch_load_index_ + 1, 0, num_patches - 1);
          gui_.drawPatchLoading(patches_, patch_load_index_);
          loadFromFile(patches_[patch_load_index_]);
          return true;
      }
    }

    std::string current_control = gui_.getCurrentControl();
    Control* control = controls_.at(current_control);
    bool should_redraw_control = false;
    lock();
    switch(key) {
      case 'H':
      case KEY_F(1):
        startHelp();
        break;
      case 'S':
        startSave();
        break;
      case 'L':
        startLoad();
        break;
      case 'M':
      case 'm':
        if (state_ != MIDI_LEARN)
          state_ = MIDI_LEARN;
        else
          state_ = STANDARD;
        should_redraw_control = true;
        break;
      case 'C':
      case 'c':
        eraseMidiLearn(control);
        state_ = STANDARD;
        should_redraw_control = true;
        break;
      case KEY_UP:
        current_control = gui_.getPrevControl();
        state_ = STANDARD;
        gui_.drawControl(control, false);
        should_redraw_control = true;
        break;
      case KEY_DOWN:
        current_control = gui_.getNextControl();
        state_ = STANDARD;
        gui_.drawControl(control, false);
        should_redraw_control = true;
        break;
      case KEY_RIGHT:
        control->increment();
        should_redraw_control = true;
        break;
      case KEY_LEFT:
        control->decrement();
        should_redraw_control = true;
        break;
      default:
        // Check if they pressed the slider keys and change the current value.
        size_t slider_size = strlen(SLIDER) - 1;
        for (size_t i = 0; i <= slider_size; ++i) {
          if (SLIDER[i] == key) {
            control->setPercentage((1.0 * i) / slider_size);
            should_redraw_control = true;
            break;
          }
        }

        // Check if they pressed note keys and play the corresponding note.
        for (size_t i = 0; i < strlen(KEYBOARD); ++i) {
          if (KEYBOARD[i] == key) {
            synth_.noteOn(48 + i);
            break;
          }
        }
    }

    if (should_redraw_control) {
      control = controls_.at(current_control);
      gui_.drawControl(control, true);
      gui_.drawControlStatus(control, state_ == MIDI_LEARN);
    }

    unlock();
    return true;
  }
示例#8
0
void GlobePlugin::setupControls()
{
  std::string imgDir = QDir::cleanPath( QgsApplication::pkgDataPath() + "/globe/gui" ).toStdString();
  if ( QgsApplication::isRunningFromBuildDir() )
  {
    imgDir = QDir::cleanPath( QgsApplication::buildSourcePath() + "/src/plugins/globe/images/gui" ).toStdString();
  }
  osgEarth::Util::EarthManipulator* manip = dynamic_cast<osgEarth::Util::EarthManipulator*>( mOsgViewer->getCameraManipulator() );

  osg::Image* yawPitchWheelImg = osgDB::readImageFile( imgDir + "/YawPitchWheel.png" );
  ImageControl* yawPitchWheel = new ImageControl( yawPitchWheelImg );
  int imgLeft = 16;
  int imgTop = 20;
  yawPitchWheel->setPosition( imgLeft, imgTop );
  mControlCanvas->addControl( yawPitchWheel );

  //ROTATE CONTROLS
  Control* rotateCCW = new NavigationControl();
  rotateCCW->setHeight( 22 );
  rotateCCW->setWidth( 20 );
  rotateCCW->setPosition( imgLeft + 0, imgTop + 18 );
  rotateCCW->addEventHandler( new RotateControlHandler( manip, MOVE_OFFSET, 0 ) );
  mControlCanvas->addControl( rotateCCW );

  Control* rotateCW = new NavigationControl();
  rotateCW->setHeight( 22 );
  rotateCW->setWidth( 20 );
  rotateCW->setPosition( imgLeft + 36, imgTop + 18 );
  rotateCW->addEventHandler( new RotateControlHandler( manip, -MOVE_OFFSET, 0 ) );
  mControlCanvas->addControl( rotateCW );

  //Rotate Reset
  Control* rotateReset = new NavigationControl();
  rotateReset->setHeight( 22 );
  rotateReset->setWidth( 16 );
  rotateReset->setPosition( imgLeft + 20, imgTop + 18 );
  rotateReset->addEventHandler( new RotateControlHandler( manip, 0, 0 ) );
  mControlCanvas->addControl( rotateReset );

  //TILT CONTROLS
  Control* tiltUp = new NavigationControl();
  tiltUp->setHeight( 19 );
  tiltUp->setWidth( 24 );
  tiltUp->setPosition( imgLeft + 20, imgTop + 0 );
  tiltUp->addEventHandler( new RotateControlHandler( manip, 0, MOVE_OFFSET ) );
  mControlCanvas->addControl( tiltUp );

  Control* tiltDown = new NavigationControl();
  tiltDown->setHeight( 19 );
  tiltDown->setWidth( 24 );
  tiltDown->setPosition( imgLeft + 16, imgTop + 36 );
  tiltDown->addEventHandler( new RotateControlHandler( manip, 0, -MOVE_OFFSET ) );
  mControlCanvas->addControl( tiltDown );

  // -------

  osg::Image* moveWheelImg = osgDB::readImageFile( imgDir + "/MoveWheel.png" );
  ImageControl* moveWheel = new ImageControl( moveWheelImg );
  imgTop = 80;
  moveWheel->setPosition( imgLeft, imgTop );
  mControlCanvas->addControl( moveWheel );

  //MOVE CONTROLS
  Control* moveLeft = new NavigationControl();
  moveLeft->setHeight( 22 );
  moveLeft->setWidth( 20 );
  moveLeft->setPosition( imgLeft + 0, imgTop + 18 );
  moveLeft->addEventHandler( new PanControlHandler( manip, -MOVE_OFFSET, 0 ) );
  mControlCanvas->addControl( moveLeft );

  Control* moveRight = new NavigationControl();
  moveRight->setHeight( 22 );
  moveRight->setWidth( 20 );
  moveRight->setPosition( imgLeft + 36, imgTop + 18 );
  moveRight->addEventHandler( new PanControlHandler( manip, MOVE_OFFSET, 0 ) );
  mControlCanvas->addControl( moveRight );

  Control* moveUp = new NavigationControl();
  moveUp->setHeight( 19 );
  moveUp->setWidth( 24 );
  moveUp->setPosition( imgLeft + 20, imgTop + 0 );
  moveUp->addEventHandler( new PanControlHandler( manip, 0, MOVE_OFFSET ) );
  mControlCanvas->addControl( moveUp );

  Control* moveDown = new NavigationControl();
  moveDown->setHeight( 19 );
  moveDown->setWidth( 24 );
  moveDown->setPosition( imgLeft + 16, imgTop + 36 );
  moveDown->addEventHandler( new PanControlHandler( manip, 0, -MOVE_OFFSET ) );
  mControlCanvas->addControl( moveDown );

  //Zoom Reset
  Control* zoomHome = new NavigationControl();
  zoomHome->setHeight( 22 );
  zoomHome->setWidth( 16 );
  zoomHome->setPosition( imgLeft + 20, imgTop + 18 );
  zoomHome->addEventHandler( new HomeControlHandler( manip ) );
  mControlCanvas->addControl( zoomHome );

  // -------

  osg::Image* backgroundImg = osgDB::readImageFile( imgDir + "/button-background.png" );
  ImageControl* backgroundGrp1 = new ImageControl( backgroundImg );
  imgTop = imgTop + 62;
  backgroundGrp1->setPosition( imgLeft + 12, imgTop );
  mControlCanvas->addControl( backgroundGrp1 );

  osg::Image* plusImg = osgDB::readImageFile( imgDir + "/zoom-in.png" );
  ImageControl* zoomIn = new NavigationControl( plusImg );
  zoomIn->setPosition( imgLeft + 12 + 3, imgTop + 3 );
  zoomIn->addEventHandler( new ZoomControlHandler( manip, 0, -MOVE_OFFSET ) );
  mControlCanvas->addControl( zoomIn );

  osg::Image* minusImg = osgDB::readImageFile( imgDir + "/zoom-out.png" );
  ImageControl* zoomOut = new NavigationControl( minusImg );
  zoomOut->setPosition( imgLeft + 12 + 3, imgTop + 3 + 23 + 2 );
  zoomOut->addEventHandler( new ZoomControlHandler( manip, 0, MOVE_OFFSET ) );
  mControlCanvas->addControl( zoomOut );

  // -------

  ImageControl* backgroundGrp2 = new ImageControl( backgroundImg );
  imgTop = imgTop + 60;
  backgroundGrp2->setPosition( imgLeft + 12, imgTop );
  mControlCanvas->addControl( backgroundGrp2 );

  //Zoom Reset
#if ENABLE_HOME_BUTTON
  osg::Image* homeImg = osgDB::readImageFile( imgDir + "/zoom-home.png" );
  ImageControl* home = new NavigationControl( homeImg );
  home->setPosition( imgLeft + 12 + 3, imgTop + 2 );
  imgTop = imgTop + 23 + 2;
  home->addEventHandler( new HomeControlHandler( manip ) );
  mControlCanvas->addControl( home );
#endif

  //refresh layers
  osg::Image* refreshImg = osgDB::readImageFile( imgDir + "/refresh-view.png" );
  ImageControl* refresh = new NavigationControl( refreshImg );
  refresh->setPosition( imgLeft + 12 + 3, imgTop + 3 );
  imgTop = imgTop + 23 + 2;
  refresh->addEventHandler( new RefreshControlHandler( this ) );
  mControlCanvas->addControl( refresh );

  //Sync Extent
  osg::Image* syncImg = osgDB::readImageFile( imgDir + "/sync-extent.png" );
  ImageControl* sync = new NavigationControl( syncImg );
  sync->setPosition( imgLeft + 12 + 3, imgTop + 2 );
  sync->addEventHandler( new SyncExtentControlHandler( this ) );
  mControlCanvas->addControl( sync );
}
/**
*  @brief
*    Called when a control event has occurred
*/
void Application65::OnControl(Control &cControl)
{
	// Is it a button and was it just hit?
	if (cControl.GetType() == ControlButton && reinterpret_cast<Button&>(cControl).IsHit()) {
		// Check whether the escape key was pressed
		if (cControl.GetName() == "KeyboardEscape") {
			// Shut down the application
			Exit(0);

		// Show/hide the help text
		} else if (cControl.GetName() == "KeyboardF1") {
			// Get the info text scene node
			SceneNode *pSceneNode = GetRootScene() ? GetRootScene()->GetByName("InfoText") : nullptr;
			if (pSceneNode) {
				// Toggle the active state of the scene node
				pSceneNode->SetActive(!pSceneNode->IsActive());
			}

		// Toggle post processing
		} else if (cControl.GetName() == "KeyboardSpace") {
			// Get the currently used camera
			SceneNode *pCamera = reinterpret_cast<SceneNode*>(GetCamera());
			if (pCamera) {
				// Loop through all available post process scene node modifiers
				uint32			   nIndex    = 0;
				SceneNodeModifier *pModifier = pCamera->GetModifier("PLCompositing::SNMPostProcess", nIndex);
				while (pModifier) {
					// Toggle the active state of the post process scene node modifier
					pModifier->SetActive(!pModifier->IsActive());

					// Next modifier, please
					pModifier = pCamera->GetModifier("PLCompositing::SNMPostProcess", ++nIndex);
				}
			}

		// Next post process effect
		} else if (cControl.GetName() == "KeyboardPageUp") {
			// Get the currently used camera
			SceneNode *pCamera = reinterpret_cast<SceneNode*>(GetCamera());
			if (pCamera) {
				// Increase the current selected modifier index
				m_nCurrentSelectedModifier++;
				if (m_nCurrentSelectedModifier >= m_lstModifierClasses.GetNumOfElements())
					m_nCurrentSelectedModifier = 0;

				// Remove all old modifiers add the new one
				pCamera->ClearModifiers();
				pCamera->AddModifier(m_lstModifierClasses[m_nCurrentSelectedModifier]->GetClassName());
			}

		// Previous post process effect
		} else if (cControl.GetName() == "KeyboardPageDown") {
			// Get the currently used camera
			SceneNode *pCamera = reinterpret_cast<SceneNode*>(GetCamera());
			if (pCamera) {
				// Decrease the current selected modifier index
				if (m_nCurrentSelectedModifier)
					m_nCurrentSelectedModifier--;
				else
					m_nCurrentSelectedModifier = m_lstModifierClasses.GetNumOfElements()-1;

				// Remove all old modifiers add the new one
				pCamera->ClearModifiers();
				pCamera->AddModifier(m_lstModifierClasses[m_nCurrentSelectedModifier]->GetClassName());
			}

		// Custom post process effect: "Rainbow"
		} else if (cControl.GetName() == "Keyboard1") {
			// Get the currently used camera
			SceneNode *pCamera = reinterpret_cast<SceneNode*>(GetCamera());
			if (pCamera) {
				// Remove all old modifiers add the new one
				pCamera->ClearModifiers();
				pCamera->AddModifier("PLPostProcessEffects::SNMPostProcessCrazyBars", "ColorScaleY=\"0.002\"");
			}

		// Custom post process effect: "Cartoon"
		} else if (cControl.GetName() == "Keyboard2") {
			// Get the currently used camera
			SceneNode *pCamera = reinterpret_cast<SceneNode*>(GetCamera());
			if (pCamera) {
				// Remove all old modifiers add the new ones
				pCamera->ClearModifiers();
				pCamera->AddModifier("PLPostProcessEffects::SNMPostProcessEdgeDetect", "LuminanceConvert=\"-0.2125 -0.7154 -0.0721\"");
				pCamera->AddModifier("PLPostProcessEffects::SNMPostProcessCombineMultiplicate");
			}

		// Custom post process effect: "Animated cartoon"
		} else if (cControl.GetName() == "Keyboard3") {
			// Get the currently used camera
			SceneNode *pCamera = reinterpret_cast<SceneNode*>(GetCamera());
			if (pCamera) {
				// Remove all old modifiers add the new ones
				pCamera->ClearModifiers();
				pCamera->AddModifier("PLPostProcessEffects::SNMPostProcessEdgeDetect", "LuminanceConvert=\"-0.2125 -0.7154 -0.0721\"");
				pCamera->AddModifier("PLPostProcessEffects::SNMPostProcessOldFilm");
				pCamera->AddModifier("PLPostProcessEffects::SNMPostProcessCombineMultiplicate");
			}

		// Custom post process effect: "Animated old cartoon"
		} else if (cControl.GetName() == "Keyboard4") {
			// Get the currently used camera
			SceneNode *pCamera = reinterpret_cast<SceneNode*>(GetCamera());
			if (pCamera) {
				// Remove all old modifiers add the new ones
				pCamera->ClearModifiers();
				pCamera->AddModifier("PLPostProcessEffects::SNMPostProcessEdgeDetect", "LuminanceConvert=\"-0.2125 -0.7154 -0.0721\"");
				pCamera->AddModifier("PLPostProcessEffects::SNMPostProcessCombineMultiplicate");
				pCamera->AddModifier("PLPostProcessEffects::SNMPostProcessOldFilm");
			}

		// Custom post process effect: "Scratch"
		} else if (cControl.GetName() == "Keyboard5") {
			// Get the currently used camera
			SceneNode *pCamera = reinterpret_cast<SceneNode*>(GetCamera());
			if (pCamera) {
				// Remove all old modifiers add the new one
				pCamera->ClearModifiers();
				pCamera->AddModifier("PLPostProcessEffects::SNMPostProcessEdgeDetect", "LuminanceConvert=\"-0.2125 -0.7154 -0.0721\"");
			}

		// Custom post process effect: "Animated old scratch"
		} else if (cControl.GetName() == "Keyboard6") {
			// Get the currently used camera
			SceneNode *pCamera = reinterpret_cast<SceneNode*>(GetCamera());
			if (pCamera) {
				// Remove all old modifiers add the new ones
				pCamera->ClearModifiers();
				pCamera->AddModifier("PLPostProcessEffects::SNMPostProcessEdgeDetect", "LuminanceConvert=\"-0.2125 -0.7154 -0.0721\"");
				pCamera->AddModifier("PLPostProcessEffects::SNMPostProcessOldFilm");
			}

		// Custom post process effect: "Edge glow"
		} else if (cControl.GetName() == "Keyboard7") {
			// Get the currently used camera
			SceneNode *pCamera = reinterpret_cast<SceneNode*>(GetCamera());
			if (pCamera) {
				// Remove all old modifiers add the new one
				pCamera->ClearModifiers();
				pCamera->AddModifier("PLPostProcessEffects::SNMPostProcessEdgeDetect", "Filename=\"Data/PostProcesses/EdgeGlow.pp\"");
			}
		}
	}
}
		INT_PTR DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
		{	

			OrientConstRotation* p = (OrientConstRotation*)map->GetParamBlock()->GetOwner();
			UpdateOrientName(p);
			p->hWnd = hWnd;
			int ct = p->pblock->Count(orientation_target_list);
//			int ctf = p->pblock->Count(orientation_target_weight);

			switch (msg) 
			{
				case WM_INITDIALOG:
				{
					int selection = p->last_selection;

					ICustButton *iBut = GetICustButton(GetDlgItem(hWnd,IDC_ORIENT_TARG_PICKNODE));
					iBut->SetType(CBT_CHECK);
					iBut->SetHighlightColor(GREEN_WASH);
					ReleaseICustButton(iBut);
					
					ISpinnerControl* spin = SetupFloatSpinner(hWnd, IDC_ORIENT_CONS_WEIGHT_SPINNER, IDC_ORIENT_CONS_WEIGHT_EDIT, 0.0f, 100.0f, 50.0f, 1.0f);
					spin = GetISpinner(GetDlgItem(hWnd, IDC_ORIENT_CONS_WEIGHT_SPINNER));
					
					// CAL-09/10/02: automatically set last_selection to 0 when there're targets
					if (p->pblock->Count(orientation_target_list) < 1) { 
						// nothing is selected OR there are no targets
						// all buttons - target_delete, weight_edit, weight_spinner -- are disabled
						EnableWindow(GetDlgItem(p->hWnd, IDC_ORIENT_CONS_WEIGHT_EDIT), FALSE);
						EnableWindow(GetDlgItem(p->hWnd, IDC_ORIENT_CONS_WEIGHT_SPINNER), FALSE);
						ICustButton *iPickOb1;
						iPickOb1	= GetICustButton(GetDlgItem(p->hWnd, IDC_REMOVE_ORIENT_TARG));
						if (iPickOb1 != NULL){
							iPickOb1->Enable(FALSE);		
							ReleaseICustButton(iPickOb1);
						}
						spin->SetValue(0.0f, FALSE);		
					} else {
						if (selection < 0)
							p->last_selection = selection = 0;

						// there is a valid selection 
						// automatically means there is AT LEAST one target
						Control *cont = p->pblock->GetControllerByID(orientation_target_weight, selection); 
						// until it is animated, paramblock doesn't have a controller assigned in it yet.
						if (spin) {
							if ((cont != NULL) && cont->IsKeyAtTime(t,KEYAT_ROTATION))
								spin->SetKeyBrackets(TRUE);
							else
								spin->SetKeyBrackets(FALSE);
						}

						if(p->pickWorldFlag){
							ICustButton *iPickOb;
							iPickOb	= GetICustButton(GetDlgItem(p->hWnd, IDC_ORIENT_PICK_WORLD));
							if (iPickOb != NULL){
								iPickOb->Enable(FALSE);
								ReleaseICustButton(iPickOb);
							}

						}

						if (p->pblock->Count(orientation_target_list) == 1){// there is only one target
							// the "delete" button should be enabled
							ICustButton *iPickOb1;
							iPickOb1 = GetICustButton(GetDlgItem(p->hWnd, IDC_REMOVE_ORIENT_TARG));
							if (iPickOb1 != NULL){
								iPickOb1->Enable(TRUE);		
								ReleaseICustButton(iPickOb1);
							}
							// the rest are disabled
//							EnableWindow(GetDlgItem(p->hWnd, IDC_ORIENT_CONS_WEIGHT_EDIT), FALSE);
//							EnableWindow(GetDlgItem(p->hWnd, IDC_ORIENT_CONS_WEIGHT_SPINNER), FALSE);
						}
						else if (p->pblock->Count(orientation_target_list) > 1){ 
							// there are more than one targets
							// all buttons - delete, weight_edit, weight_spinner -- are enabled
							EnableWindow(GetDlgItem(p->hWnd, IDC_ORIENT_CONS_WEIGHT_EDIT), TRUE);
							EnableWindow(GetDlgItem(p->hWnd, IDC_ORIENT_CONS_WEIGHT_SPINNER), TRUE);
							ICustButton *iPickOb1;
							iPickOb1 = GetICustButton(GetDlgItem(p->hWnd, IDC_REMOVE_ORIENT_TARG));
							if (iPickOb1 != NULL){
								iPickOb1->Enable(TRUE);		
								ReleaseICustButton(iPickOb1);
							}
						}
					}
					ReleaseISpinner(spin);
					p->RedrawListbox(GetCOREInterface()->GetTime(), selection);
					return TRUE;	
				}
				break;


				case WM_COMMAND:
				{
					
					int selection;
					
					if (LOWORD(wParam) == IDC_ORIENT_TARG_LIST && HIWORD(wParam) == LBN_SELCHANGE)
					{
						selection = SendDlgItemMessage(p->hWnd, IDC_ORIENT_TARG_LIST, LB_GETCURSEL, 0, 0);
						p->last_selection = selection;
						if (selection >= 0){
						// there is a valid selection 
							// automatically means there is AT LEAST one target
							if (p->pblock->Count(orientation_target_list) == 1){ // there is only one target
								// the "delete" button should be enabled
								ICustButton *iPickOb1;
								iPickOb1 = GetICustButton(GetDlgItem(p->hWnd, IDC_REMOVE_ORIENT_TARG));
								if (iPickOb1 != NULL){
									iPickOb1->Enable(TRUE);		
									ReleaseICustButton(iPickOb1);
								}
//								// the rest are disabled
//								EnableWindow(GetDlgItem(p->hWnd, IDC_ORIENT_CONS_WEIGHT_EDIT), FALSE);
//								EnableWindow(GetDlgItem(p->hWnd, IDC_ORIENT_CONS_WEIGHT_SPINNER), FALSE);
							}

							else  if (p->pblock->Count(orientation_target_list) > 1){ 
							// there are more than one targets
								// all buttons - delete, weight_edit, weight_spinner -- are enabled
								EnableWindow(GetDlgItem(p->hWnd, IDC_ORIENT_CONS_WEIGHT_EDIT), TRUE);
								EnableWindow(GetDlgItem(p->hWnd, IDC_ORIENT_CONS_WEIGHT_SPINNER), TRUE);
								ICustButton *iPickOb1;
								iPickOb1 = GetICustButton(GetDlgItem(p->hWnd, IDC_REMOVE_ORIENT_TARG));
								if (iPickOb1 != NULL){
									iPickOb1->Enable(TRUE);		
									ReleaseICustButton(iPickOb1);
								}

								ISpinnerControl* spin = GetISpinner(GetDlgItem(hWnd, IDC_ORIENT_CONS_WEIGHT_SPINNER));
								float value = map->GetParamBlock()->GetFloat(orientation_target_weight, t, selection);
								spin->SetValue(value, FALSE);

								Control *cont = p->pblock->GetControllerByID(orientation_target_weight, selection); // until it is animated, paramblock doesn't have a controller assigned in it yet.
								if (spin && (cont != NULL)) {
									if (cont->IsKeyAtTime(t,KEYAT_ROTATION)){
										spin->SetKeyBrackets(TRUE);
									} 
								}
								else {
									spin->SetKeyBrackets(FALSE);
								}
								ReleaseISpinner(spin);
							}
							p->RedrawListbox(GetCOREInterface()->GetTime(), selection);							
						}
						
						else if (selection < 0 || p->pblock->Count(orientation_target_list) < 1){ 
						// nothing is selected OR there are no targets
							// all buttons - target_delete, weight_edit, weight_spinner -- are disabled
							EnableWindow(GetDlgItem(p->hWnd, IDC_ORIENT_CONS_WEIGHT_EDIT), FALSE);
							EnableWindow(GetDlgItem(p->hWnd, IDC_ORIENT_CONS_WEIGHT_SPINNER), FALSE);
							ICustButton *iPickOb1;
							iPickOb1	= GetICustButton(GetDlgItem(p->hWnd, IDC_REMOVE_ORIENT_TARG));
							if (iPickOb1 != NULL){
								iPickOb1->Enable(FALSE);		
								ReleaseICustButton(iPickOb1);
							}
						}
					}

					else if (LOWORD(wParam) == IDC_ORIENT_TARG_PICKNODE){
						thePickMode.p  = p;					
						p->ip->SetPickMode(&thePickMode);
					}

					else if (LOWORD(wParam) == IDC_REMOVE_ORIENT_TARG){
						selection = SendDlgItemMessage(p->hWnd, IDC_ORIENT_TARG_LIST, LB_GETCURSEL, 0, 0);
						p->last_selection = selection;
						if (selection >= 0){
							theHold.Begin();
							p->DeleteTarget(selection);
							theHold.Accept(GetString(IDS_AG_ORIENTATION_LIST));
						}
//						p->RedrawListbox(GetCOREInterface()->GetTime(), selection-1);
					}

					else if (LOWORD(wParam) == IDC_ORIENT_PICK_WORLD){
						INode *nullNode = NULL;
						p->AppendTarget(nullNode);
						
						p->pickWorldFlag = 1;

						p->NotifyDependents(FOREVER,PART_ALL,REFMSG_CHANGE); // so that the change is updated
						ICustButton *iPickOb;
						iPickOb	= GetICustButton(GetDlgItem(p->hWnd, IDC_ORIENT_PICK_WORLD));
						if (iPickOb != NULL){
							iPickOb->Enable(FALSE);
							ReleaseICustButton(iPickOb);
						}
						p->RedrawListbox(GetCOREInterface()->GetTime());
					}

				
				}
				break;


				case CC_SPINNER_CHANGE:
				{
					if (LOWORD(wParam) == IDC_ORIENT_CONS_WEIGHT_SPINNER) {
						int selection = SendDlgItemMessage(p->hWnd, IDC_ORIENT_TARG_LIST, LB_GETCURSEL, 0, 0);

						// CAL-09/10/02: need to start a hold if it's not holding to handle type-in values
						BOOL isHold = theHold.Holding();
						if (!isHold) theHold.Begin();

						ISpinnerControl* spin = GetISpinner(GetDlgItem(hWnd, IDC_ORIENT_CONS_WEIGHT_SPINNER));

						if (selection >= 0) {
							float value = ((ISpinnerControl *)lParam)->GetFVal();
							map->GetParamBlock()->SetValue(orientation_target_weight, t, value, selection);

							Control *cont = p->pblock->GetControllerByID(orientation_target_weight, selection); // until it is animated, paramblock doesn't have a controller assigned in it yet.
							if (spin)
								spin->SetKeyBrackets(((cont != NULL) && cont->IsKeyAtTime(t,KEYAT_ROTATION)) ? TRUE : FALSE);

							p->RedrawListbox(GetCOREInterface()->GetTime(), selection);
						} else {
							if (spin) spin->SetValue(0.0f, FALSE);
						}

						if (spin) ReleaseISpinner(spin);

						if (!isHold) theHold.Accept(GetString(IDS_RB_PARAMETERCHANGE));
					}
				}			
				break;

			}
			return FALSE;
		}
示例#11
0
// Process window messages
LRESULT CALLBACK Daemon::WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) {
	// This is a static method, so we don't know which instantiation we're 
	// dealing with. We have stored a pseudo-this in the window user data, 
	// though.
	Daemon *_this = (Daemon *) GetWindowLong(hwnd, GWL_USERDATA);

	switch (iMsg) {

	case WM_CREATE:
		{
			return 0;
		}

	case WM_SOCKEVENT:
		{
			assert(HIWORD(lParam) == 0);
			// A new socket created by accept might send messages to
			// this procedure. We can ignore them.
			if(wParam != _this->m_sock) {
				return 0;
			}

			switch(lParam) {
			case FD_ACCEPT:
				{
					SOCKET hNewSock;
					hNewSock = accept(_this->m_sock, NULL, NULL);
					WSAAsyncSelect(hNewSock, hwnd, 0, 0);
					unsigned long nbarg = 0;
					ioctlsocket(hNewSock, FIONBIO, &nbarg);

					pApp->NewConnection(hNewSock);
					
					break;
				}
			case FD_READ:
				{
					unsigned long numbytes;
					ioctlsocket(_this->m_sock, FIONREAD, &numbytes);
					recv(_this->m_sock, _this->netbuf, numbytes, 0);
					break;
				}
			case FD_CLOSE:
				Log::info(_T("Daemon connection closed\n"));
				DestroyWindow(hwnd);
				break;
			}
			
			return 0;
		}
	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case ID_NEWCONN:
			pApp->NewConnection();
			break;
		case IDC_OPTIONBUTTON:
			{
				Control ctrlThis;
				ctrlThis.setWindow(_this->m_hwnd);

				ConnectionConfigDialog conConfDialog;
				conConfDialog.setParent(&ctrlThis);
				conConfDialog.setConnectionConfig(&_this->m_conConf);
				if (conConfDialog.showModal() == IDOK) {
					ConnectionConfigSM ccsm(_T(".listen"));
					_this->m_conConf.saveToStorage(&ccsm);
				}
			}
			break;
		case ID_CLOSEDAEMON:
			PostQuitMessage(0);
			break;
		case IDD_APP_ABOUT:
			ShowAboutBox();
			break;
		case IDD_CONFIGURATION:
			g_vncViewerConfigDialog.showModal();
			break;
		}
		return 0;
	case WM_TRAYNOTIFY:
		{
			HMENU hSubMenu = GetSubMenu(_this->m_hmenu, 0);
			if (lParam==WM_LBUTTONDBLCLK) {
				// double click: execute first menu item
				::SendMessage(_this->m_nid.hWnd, WM_COMMAND, 
					GetMenuItemID(hSubMenu, 0), 0);
			} else if (lParam==WM_RBUTTONUP) {
				if (hSubMenu == NULL) { 
					Log::warning(_T("No systray submenu\n"));
					return 0;
				}
				// Make first menu item the default (bold font)
				::SetMenuDefaultItem(hSubMenu, 0, TRUE);
				
				// Display the menu at the current mouse location. There's a "bug"
				// (Microsoft calls it a feature) in Windows 95 that requires calling
				// SetForegroundWindow. To find out more, search for Q135788 in MSDN.
				//
				POINT mouse;
				GetCursorPos(&mouse);
				::SetForegroundWindow(_this->m_nid.hWnd);
				::TrackPopupMenu(hSubMenu, 0, mouse.x, mouse.y, 0,
					_this->m_nid.hWnd, NULL);
				
			} 
			return 0;
		}
	case WM_TIMER:
		_this->CheckTrayIcon();
		return 0;
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	}
	
	return DefWindowProc(hwnd, iMsg, wParam, lParam);
}
/**
*  @brief
*    Called when a control event has occurred
*/
void Application60::OnControl(Control &cControl)
{
	// Check whether the escape key was pressed
	if (cControl.GetType() == ControlButton && cControl.GetName() == "KeyboardEscape")
		Exit(0); // Shut down the application
}
示例#13
0
void TabContainer::_input_event(const InputEvent& p_event) {

	if (p_event.type==InputEvent::MOUSE_BUTTON &&
	    p_event.mouse_button.pressed &&
	    p_event.mouse_button.button_index==BUTTON_LEFT) {

		// clicks
		Point2 pos( p_event.mouse_button.x, p_event.mouse_button.y );

		int top_margin = _get_top_margin();
		if (pos.y>top_margin)
			return; // no click (too far down)

		if (pos.x<tabs_ofs_cache)
			return; // no click (too far left)

		Ref<StyleBox> tab_bg = get_stylebox("tab_bg");
		Ref<StyleBox> tab_fg = get_stylebox("tab_fg");
		Ref<Font> font = get_font("font");
		Ref<Texture> incr = get_icon("increment");
		Ref<Texture> decr = get_icon("decrement");
		Ref<Texture> menu = get_icon("menu");
		Ref<Texture> menu_hl = get_icon("menu_hl");

		if (popup && pos.x>get_size().width-menu->get_width()) {


			emit_signal("pre_popup_pressed");
			Vector2 pp_pos = get_global_pos();
			pp_pos.x+=get_size().width;
			pp_pos.x-=popup->get_size().width;
			pp_pos.y+=menu->get_height();

			popup->set_global_pos( pp_pos );
			popup->popup();;
			return;
		}
		pos.x-=tabs_ofs_cache;

		int idx=0;
		int found=-1;
		bool rightroom=false;

		for(int i=0;i<get_child_count();i++) {

			Control *c = get_child(i)->cast_to<Control>();
			if (!c)
				continue;
			if (c->is_set_as_toplevel())
				continue;

			if (idx<tab_display_ofs) {
				idx++;
				continue;
			}

			if (idx>last_tab_cache) {
				rightroom=true;
				break;
			}

			String s = c->has_meta("_tab_name")?String(XL_MESSAGE(String(c->get_meta("_tab_name")))):String(c->get_name());
			int tab_width=font->get_string_size(s).width;

			if (c->has_meta("_tab_icon")) {
				Ref<Texture> icon = c->get_meta("_tab_icon");
				if (icon.is_valid()) {
					tab_width+=icon->get_width();
					if (s!="")
						tab_width+=get_constant("hseparation");

				}
			}

			if (idx==current) {

				tab_width+=tab_fg->get_minimum_size().width;
			} else {
				tab_width+=tab_bg->get_minimum_size().width;
			}

			if (pos.x < tab_width) {

				found=idx;
				break;
			}

			pos.x-=tab_width;
			idx++;
		}

		if (buttons_visible_cache) {

			if (p_event.mouse_button.x>get_size().width-incr->get_width()) {
				if (rightroom) {
					tab_display_ofs+=1;
					update();
				}
			} else if (p_event.mouse_button.x>get_size().width-incr->get_width()-decr->get_width()) {

				if (tab_display_ofs>0) {
					tab_display_ofs-=1;
					update();
				}

			}
		}


		if (found!=-1) {

			set_current_tab(found);
		}
	}

}
示例#14
0
void TabContainer::_notification(int p_what) {


	switch(p_what) {


		case NOTIFICATION_DRAW: {

			RID ci = get_canvas_item();
			Ref<StyleBox> panel = get_stylebox("panel");
			Size2 size = get_size();

			if (!tabs_visible) {

				panel->draw(ci, Rect2( 0, 0, size.width, size.height));
				return;
			}



			Ref<StyleBox> tab_bg = get_stylebox("tab_bg");
			Ref<StyleBox> tab_fg = get_stylebox("tab_fg");
			Ref<Texture> incr = get_icon("increment");
			Ref<Texture> incr_hl = get_icon("increment_hilite");
			Ref<Texture> decr = get_icon("decrement");
			Ref<Texture> decr_hl = get_icon("decrement_hilite");
			Ref<Texture> menu = get_icon("menu");
			Ref<Texture> menu_hl = get_icon("menu_hl");
			Ref<Font> font = get_font("font");
			Color color_fg = get_color("font_color_fg");
			Color color_bg = get_color("font_color_bg");

			int side_margin = get_constant("side_margin");
			int top_margin = _get_top_margin();

			int label_valign_fg = get_constant("label_valign_fg");
			int label_valign_bg = get_constant("label_valign_bg");


			Size2 top_size = Size2( size.width, top_margin );



			int w=0;
			int idx=0;
			Vector<int> offsets;
			Vector<Control*> controls;
			int from=0;
			int limit=get_size().width;
			if (popup) {
				top_size.width-=menu->get_width();
				limit-=menu->get_width();
			}

			bool notdone=false;
			last_tab_cache=-1;

			for(int i=0;i<get_child_count();i++) {

				Control *c = get_child(i)->cast_to<Control>();
				if (!c)
					continue;
				if (c->is_set_as_toplevel())
					continue;
				if (idx<tab_display_ofs) {
					idx++;
					from=idx;
					continue;
				}

				if (w>=get_size().width) {
					buttons_visible_cache=true;
					notdone=true;
					break;
				}

				offsets.push_back(w);
				controls.push_back(c);

				String s = c->has_meta("_tab_name")?String(XL_MESSAGE(String(c->get_meta("_tab_name")))):String(c->get_name());
				w+=font->get_string_size(s).width;
				if (c->has_meta("_tab_icon")) {
					Ref<Texture> icon = c->get_meta("_tab_icon");
					if (icon.is_valid()) {
						w+=icon->get_width();
						if (s!="")
						     w+=get_constant("hseparation");

					}
				}

				if (idx==current) {

					w+=tab_fg->get_minimum_size().width;
				} else {
					w+=tab_bg->get_minimum_size().width;
				}

				if (idx<tab_display_ofs) {

				}
				last_tab_cache=idx;

				idx++;
			}


			int ofs;

			switch(align) {

				case ALIGN_LEFT: ofs = side_margin; break;
				case ALIGN_CENTER: ofs = (int(limit) - w)/2; break;
				case ALIGN_RIGHT: ofs = int(limit) - w - side_margin; break;
			};

			tab_display_ofs=0;


			tabs_ofs_cache=ofs;
			idx=0;



			for(int i=0;i<controls.size();i++) {

				idx=i+from;
				if (current>=from && current<from+controls.size()-1) {
					//current is visible! draw it last.
					if (i==controls.size()-1) {
						idx=current;
					} else if (idx>=current) {
						idx+=1;
					}
				}

				Control *c = controls[idx-from];

				String s = c->has_meta("_tab_name")?String(c->get_meta("_tab_name")):String(c->get_name());
				int w=font->get_string_size(s).width;
				Ref<Texture> icon;
				if (c->has_meta("_tab_icon")) {
					icon = c->get_meta("_tab_icon");
					if (icon.is_valid()) {

						w+=icon->get_width();
						if (s!="")
							w+=get_constant("hseparation");

					}
				}


				Ref<StyleBox> sb;
				int va;
				Color col;

				if (idx==current) {

					sb=tab_fg;
					va=label_valign_fg;
					col=color_fg;
				} else {
					sb=tab_bg;
					va=label_valign_bg;
					col=color_bg;
				}

				int lofs = ofs + offsets[idx-from];

				Size2i sb_ms = sb->get_minimum_size();
				Rect2 sb_rect = Rect2( lofs, 0, w+sb_ms.width, top_margin);


				sb->draw(ci, sb_rect );

				Point2i lpos = sb_rect.pos;
				lpos.x+=sb->get_margin(MARGIN_LEFT);
				if (icon.is_valid()) {

					icon->draw(ci, Point2i( lpos.x, sb->get_margin(MARGIN_TOP)+((sb_rect.size.y-sb_ms.y)-icon->get_height())/2 ) );
					if (s!="")
						lpos.x+=icon->get_width()+get_constant("hseparation");

				}

				font->draw(ci, Point2i( lpos.x, sb->get_margin(MARGIN_TOP)+((sb_rect.size.y-sb_ms.y)-font->get_height())/2+font->get_ascent() ), s, col );
				//ofs+=sb_ms.x+w;

				/*
				int sb_mw = sb->get_minimum_size().width;
				int font_ofs = sb_mw / 2;

				Rect2i rect =Rect2( ofs, 0, w+sb_mw, top_margin);

				rect.size
				sb->draw(ci,rect);
				rect.y+=va;
				rect.height+=va;
				int font_y = (rect.height - font->get_height())/2;

				font->draw(ci, Point2( ofs+font_ofs, va+font_y ), s, col );

*/
				idx++;
			}


			if (buttons_visible_cache) {

				int vofs = (top_margin-incr->get_height())/2;
				decr->draw(ci,Point2(limit,vofs),Color(1,1,1,tab_display_ofs==0?0.5:1.0));
				incr->draw(ci,Point2(limit+incr->get_width(),vofs),Color(1,1,1,notdone?1.0:0.5));
			}

			if (popup) {
				int from = get_size().width-menu->get_width();

				if (mouse_x_cache > from)
					menu_hl->draw(get_canvas_item(),Size2(from,0));
				else
					menu->draw(get_canvas_item(),Size2(from,0));
			}

			panel->draw(ci, Rect2( 0, top_size.height, size.width, size.height-top_size.height));

		} break;
		case NOTIFICATION_READY:
		case NOTIFICATION_THEME_CHANGED: {

			call_deferred("set_current_tab",get_current_tab()); //wait until all changed theme
		} break;
	}
}
示例#15
0
/** BroadCast Mouse Move Event */
void EventMgr::MouseDown(unsigned short x, unsigned short y, unsigned short Button,
	unsigned short Mod)
{
	std::vector< int>::iterator t;
	std::vector< Window*>::iterator m;
	Control *ctrl;
	unsigned long thisTime;

	thisTime = GetTickCount();
	if (ClickMatch(x, y, thisTime)) {
		Button |= GEM_MB_DOUBLECLICK;
		dc_x = 0;
		dc_y = 0;
		dc_time = 0;
	} else {
		dc_x = x;
		dc_y = y;
		dc_time = thisTime+dc_delay;
	}
	MButtons |= Button;
	for (t = topwin.begin(); t != topwin.end(); ++t) {
		m = windows.begin();
		m += ( *t );
		if (( *m ) == NULL)
			continue;
		if (!( *m )->Visible)
			continue;
		if (( ( *m )->XPos <= x ) && ( ( *m )->YPos <= y )) {
			//Maybe we are on the window, let's check
			if (( ( *m )->XPos + ( *m )->Width >= x ) &&
				( ( *m )->YPos + ( *m )->Height >= y )) {
				//Yes, we are on the Window
				//Let's check if we have a Control under the Mouse Pointer
				ctrl = ( *m )->GetControl( x, y, true );
				if (!ctrl) {
					ctrl = ( *m )->GetControl( x, y, false);
				}
				last_win_mousefocused = *m;
				if (ctrl != NULL) {
					last_win_mousefocused->SetMouseFocused( ctrl );
					ctrl->OnMouseDown( x - last_win_mousefocused->XPos - ctrl->XPos, y - last_win_mousefocused->YPos - ctrl->YPos,
									  Button, Mod );
					if (!ctrl->WantsDragOperation()) {
						focusLock = ctrl;
					}
					if (last_win_mousefocused) {
						RefreshCursor(last_win_mousefocused->Cursor);
					}
					return;
				}
			}
		}
		if (( *m )->Visible == WINDOW_FRONT) //stop looking further
			break;
	}
	
	if ((Button == GEM_MB_SCRLUP || Button == GEM_MB_SCRLDOWN) && last_win_mousefocused) {
		ctrl = last_win_mousefocused->GetScrollControl();
		if (ctrl) {
			ctrl->OnMouseDown( x - last_win_mousefocused->XPos - ctrl->XPos, y - last_win_mousefocused->YPos - ctrl->YPos, Button, Mod );
		}
	}

	if (last_win_mousefocused) {
		last_win_mousefocused->SetMouseFocused(NULL);
	}
}
示例#16
0
Sprite * Controls::getControlSprite(int id)
{
    Control *pc = getControl(id);
    if (pc) return pc->getSprite();
    return 0; //nullptr
}
示例#17
0
/** Special Key Press Event */
void EventMgr::OnSpecialKeyPress(unsigned char Key)
{
	if (!last_win_focused) {
		return;
	}
	Control *ctrl = NULL;

	// tab shows tooltips
	if (Key == GEM_TAB) {
		if (last_win_over != NULL) {
			Control *ctrl = last_win_over->GetOver();
			if (ctrl != NULL) {
				ctrl->DisplayTooltip();
			}
		}
	}
	//the default control will get only GEM_RETURN
	else if (Key == GEM_RETURN) {
		ctrl = last_win_focused->GetDefaultControl(0);
	}
	//the default cancel control will get only GEM_ESCAPE
	else if (Key == GEM_ESCAPE) {
		ctrl = last_win_focused->GetDefaultControl(1);
	} else if (Key >= GEM_FUNCTION1 && Key <= GEM_FUNCTION16) {
		if (function_bar) {
			ctrl = function_bar->GetFunctionControl(Key-GEM_FUNCTION1);
		} else {
			ctrl = last_win_focused->GetFunctionControl(Key-GEM_FUNCTION1);
		}
	}

	//if there was no default button set, then the current focus will get it (except function keys)
	if (!ctrl) {
		if (Key<GEM_FUNCTION1 || Key > GEM_FUNCTION16) {
			ctrl = last_win_focused->GetFocus();
		}
	}
	//if one is under focus, use the default scroll focus
	if (!ctrl) {
		if (Key == GEM_UP || Key == GEM_DOWN) {
			ctrl = last_win_focused->GetScrollControl();
		}
	}
	if (ctrl) {
		switch (ctrl->ControlType) {
			//scrollbars will receive only mousewheel events
			case IE_GUI_SCROLLBAR:
				if (Key != GEM_UP && Key != GEM_DOWN) {
					return;
				}
				break;
			//buttons will receive only GEM_RETURN
			case IE_GUI_BUTTON:
				if (Key >= GEM_FUNCTION1 && Key <= GEM_FUNCTION16) {
					//fake mouse button
					ctrl->OnMouseDown(0,0,GEM_MB_ACTION,0);
					ctrl->OnMouseUp(0,0,GEM_MB_ACTION,0);
					return;
				}
				if (Key != GEM_RETURN && Key!=GEM_ESCAPE) {
					return;
				}
				break;
				// shouldnt be any harm in sending these events to any control
		}
		ctrl->OnSpecialKeyPress( Key );
	}
}
示例#18
0
TileMapEditor::TileMapEditor(EditorNode *p_editor) {

	node=NULL;
	canvas_item_editor=NULL;
	editor=p_editor;
	undo_redo = editor->get_undo_redo();

	int mw = EDITOR_DEF("tile_map/palette_min_width",80);
	Control *ec = memnew( Control);
	ec->set_custom_minimum_size(Size2(mw,0));
	add_child(ec);

	HBoxContainer *hb = memnew( HBoxContainer );
	add_child(hb);
	hb->set_h_size_flags(SIZE_EXPAND_FILL);
	hb->add_spacer(true);

	button_thumbnail = memnew( ToolButton );
	button_thumbnail->set_toggle_mode(true);
	button_thumbnail->set_pressed(true);
	button_thumbnail->set_icon(p_editor->get_gui_base()->get_icon("FileThumbnail","EditorIcons"));
	hb->add_child(button_thumbnail);
	button_thumbnail->connect("pressed", this, "_set_display_mode", varray(DISPLAY_THUMBNAIL));

	button_list = memnew( ToolButton );
	button_list->set_toggle_mode(true);
	button_list->set_pressed(false);
	button_list->set_icon(p_editor->get_gui_base()->get_icon("FileList","EditorIcons"));
	hb->add_child(button_list);
	button_list->connect("pressed", this, "_set_display_mode", varray(DISPLAY_LIST));

	// Add tile palette
	palette = memnew( ItemList );
	palette->set_v_size_flags(SIZE_EXPAND_FILL);
	add_child(palette);

	// Add menu items
	canvas_item_editor_hb = memnew( HBoxContainer );
	CanvasItemEditor::get_singleton()->add_control_to_menu_panel(canvas_item_editor_hb);
	canvas_item_editor_hb->add_child( memnew( VSeparator ));
	transpose = memnew( ToolButton );
	transpose->set_toggle_mode(true);
	transpose->set_tooltip("Transpose");
	transpose->set_focus_mode(FOCUS_NONE);
	transpose->connect("pressed", this, "_update_transform_buttons", make_binds(transpose));
	canvas_item_editor_hb->add_child(transpose);
	mirror_x = memnew( ToolButton );
	mirror_x->set_toggle_mode(true);
	mirror_x->set_tooltip("Mirror X (A)");
	mirror_x->set_focus_mode(FOCUS_NONE);
	mirror_x->connect("pressed", this, "_update_transform_buttons", make_binds(mirror_x));
	canvas_item_editor_hb->add_child(mirror_x);
	mirror_y = memnew( ToolButton );
	mirror_y->set_toggle_mode(true);
	mirror_y->set_tooltip("Mirror Y (S)");
	mirror_y->set_focus_mode(FOCUS_NONE);
	mirror_y->connect("pressed", this, "_update_transform_buttons", make_binds(mirror_y));
	canvas_item_editor_hb->add_child(mirror_y);
	canvas_item_editor_hb->add_child(memnew(VSeparator));
	rotate_0 = memnew( ToolButton );
	rotate_0->set_toggle_mode(true);
	rotate_0->set_tooltip("Rotate 0 degrees");
	rotate_0->set_focus_mode(FOCUS_NONE);
	rotate_0->connect("pressed", this, "_update_transform_buttons", make_binds(rotate_0));
	canvas_item_editor_hb->add_child(rotate_0);
	rotate_90 = memnew( ToolButton );
	rotate_90->set_toggle_mode(true);
	rotate_90->set_tooltip("Rotate 90 degrees");
	rotate_90->set_focus_mode(FOCUS_NONE);
	rotate_90->connect("pressed", this, "_update_transform_buttons", make_binds(rotate_90));
	canvas_item_editor_hb->add_child(rotate_90);
	rotate_180 = memnew( ToolButton );
	rotate_180->set_toggle_mode(true);
	rotate_180->set_tooltip("Rotate 180 degrees");
	rotate_180->set_focus_mode(FOCUS_NONE);
	rotate_180->connect("pressed", this, "_update_transform_buttons", make_binds(rotate_180));
	canvas_item_editor_hb->add_child(rotate_180);
	rotate_270 = memnew( ToolButton );
	rotate_270->set_toggle_mode(true);
	rotate_270->set_tooltip("Rotate 270 degrees");
	rotate_270->set_focus_mode(FOCUS_NONE);
	rotate_270->connect("pressed", this, "_update_transform_buttons", make_binds(rotate_270));
	canvas_item_editor_hb->add_child(rotate_270);
	canvas_item_editor_hb->hide();

	rotate_0->set_pressed(true);
	tool=TOOL_NONE;
	selection_active=false;
	mouse_over=false;
}
void CBitmapControl::Paint(HDC hDC, const UiRect& rcPaint)
{
	try
	{
		if( !::IntersectRect( &m_rcPaint, &rcPaint, &m_rcItem ) ) 
			return;
		Control::Paint(hDC, rcPaint);
		//paint bitmap
		if (width_ * height_ > 0)
		{
			int item_w = m_rcItem.right-m_rcItem.left;
			int item_h = m_rcItem.bottom-m_rcItem.top;
			int item_x = m_rcItem.left;
			int item_y = m_rcItem.top;
			int source_w = width_;
			int source_h = height_;
			if (source_w > 0 && source_h > 0 && parent_wnd_)
			{
				//居中
				item_x += (item_w - source_w) / 2;
				item_y += (item_h - source_h) / 2;
				UiRect rcClient;
				::GetClientRect(parent_wnd_->GetHWND(), &rcClient);
				int width = rcClient.right - rcClient.left;
				int height = rcClient.bottom - rcClient.top;

				//计算实际绘制区域坐标
				int draw_x = max(rcPaint.left, item_x);
				draw_x = max(m_rcItem.left, draw_x);
				int draw_y = max(rcPaint.top, item_y);
				draw_y = max(m_rcItem.top, draw_y);
				int draw_h = min(rcPaint.bottom - draw_y, min(item_y + source_h, m_rcItem.bottom) - draw_y);
				draw_h = max(draw_h, 0);
				int src_x = draw_x - item_x;
				int src_y = draw_y - item_y;
				int src_w = min(rcPaint.right - draw_x, min(item_x + source_w, m_rcItem.right) - draw_x);
				src_w = max(src_w, 0);

				int dest_byte_width = width * 4;
				int src_byte_width = source_w * 4;
				int paint_byte_width = src_w * 4;
				char* dest_data = (char*)parent_wnd_->GetBits();
				int bottom = height - draw_y - 1;
				dest_data += bottom * dest_byte_width + draw_x * 4;
				char* src_data = (char*)data_.c_str();
				src_data += src_y * src_byte_width + src_x * 4;
				for (int i = 0; i < draw_h; ++i)
				{
					memcpy(dest_data, src_data, paint_byte_width);
					dest_data -= dest_byte_width;
					src_data += src_byte_width;
				}
			}
		}
		//绘制子控件
		for( auto it = m_items.begin(); it != m_items.end(); it++ )
		{
			Control* pControl = *it;
			if( !pControl->IsVisible() ) continue;
			UiRect controlPos = pControl->GetPos();
			if( !::IntersectRect( &m_rcPaint, &rcPaint, &controlPos ) ) continue;
			pControl->AlphaPaint( hDC, rcPaint );
		}
	}
	catch (...)
	{
		throw "CBitmapControl::DoPaint";
	}
}
示例#20
0
void Container::draw(SpriteBatch* spriteBatch, const Rectangle& clip, bool needsClear, bool cleared, float targetHeight)
{
    if (needsClear)
    {
        GL_ASSERT( glEnable(GL_SCISSOR_TEST) );
        GL_ASSERT( glClearColor(0, 0, 0, 0) );
        float clearY = targetHeight - _clearBounds.y - _clearBounds.height;
        GL_ASSERT( glScissor(_clearBounds.x, clearY,
            _clearBounds.width, _clearBounds.height) );
        GL_ASSERT( glClear(GL_COLOR_BUFFER_BIT) );
        GL_ASSERT( glDisable(GL_SCISSOR_TEST) );

        needsClear = false;
        cleared = true;
    }
    else if (!cleared)
    {
        needsClear = true;
    }

    spriteBatch->begin();
    Control::drawBorder(spriteBatch, clip);
    spriteBatch->end();

    std::vector<Control*>::const_iterator it;
    Rectangle boundsUnion = Rectangle::empty();
    for (it = _controls.begin(); it < _controls.end(); it++)
    {
        Control* control = *it;
        GP_ASSERT(control);
        if (!needsClear || control->isDirty() || control->_clearBounds.intersects(boundsUnion))
        {
            control->draw(spriteBatch, _viewportClipBounds, needsClear, cleared, targetHeight);
            Rectangle::combine(control->_clearBounds, boundsUnion, &boundsUnion);
        }
    }

    if (_scroll != SCROLL_NONE && (_scrollBarOpacity > 0.0f))
    {
        // Draw scroll bars.
        Rectangle clipRegion(_viewportClipBounds);

        spriteBatch->begin();

        if (_scrollBarBounds.height > 0)
        {
            const Rectangle& topRegion = _scrollBarTopCap->getRegion();
            const Theme::UVs& topUVs = _scrollBarTopCap->getUVs();
            Vector4 topColor = _scrollBarTopCap->getColor();
            topColor.w *= _scrollBarOpacity * _opacity;

            const Rectangle& verticalRegion = _scrollBarVertical->getRegion();
            const Theme::UVs& verticalUVs = _scrollBarVertical->getUVs();
            Vector4 verticalColor = _scrollBarVertical->getColor();
            verticalColor.w *= _scrollBarOpacity * _opacity;

            const Rectangle& bottomRegion = _scrollBarBottomCap->getRegion();
            const Theme::UVs& bottomUVs = _scrollBarBottomCap->getUVs();
            Vector4 bottomColor = _scrollBarBottomCap->getColor();
            bottomColor.w *= _scrollBarOpacity * _opacity;

            clipRegion.width += verticalRegion.width;

            Rectangle bounds(_viewportBounds.x + _viewportBounds.width - verticalRegion.width,
                             _viewportBounds.y + _scrollBarBounds.y,
                             topRegion.width, topRegion.height);
            spriteBatch->draw(bounds.x, bounds.y, bounds.width, bounds.height, topUVs.u1, topUVs.v1, topUVs.u2, topUVs.v2, topColor, clipRegion);

            bounds.y += topRegion.height;
            bounds.height = _scrollBarBounds.height - topRegion.height - bottomRegion.height;
            spriteBatch->draw(bounds.x, bounds.y, bounds.width, bounds.height, verticalUVs.u1, verticalUVs.v1, verticalUVs.u2, verticalUVs.v2, verticalColor, clipRegion);

            bounds.y += bounds.height;
            bounds.height = bottomRegion.height;
            spriteBatch->draw(bounds.x, bounds.y, bounds.width, bounds.height, bottomUVs.u1, bottomUVs.v1, bottomUVs.u2, bottomUVs.v2, bottomColor, clipRegion);
        }

        if (_scrollBarBounds.width > 0)
        {
            const Rectangle& leftRegion = _scrollBarLeftCap->getRegion();
            const Theme::UVs& leftUVs = _scrollBarLeftCap->getUVs();
            Vector4 leftColor = _scrollBarLeftCap->getColor();
            leftColor.w *= _scrollBarOpacity * _opacity;

            const Rectangle& horizontalRegion = _scrollBarHorizontal->getRegion();
            const Theme::UVs& horizontalUVs = _scrollBarHorizontal->getUVs();
            Vector4 horizontalColor = _scrollBarHorizontal->getColor();
            horizontalColor.w *= _scrollBarOpacity * _opacity;

            const Rectangle& rightRegion = _scrollBarRightCap->getRegion();
            const Theme::UVs& rightUVs = _scrollBarRightCap->getUVs();
            Vector4 rightColor = _scrollBarRightCap->getColor();
            rightColor.w *= _scrollBarOpacity * _opacity;

            clipRegion.height += horizontalRegion.height;
        
            Rectangle bounds(_viewportBounds.x + _scrollBarBounds.x,
                             _viewportBounds.y + _viewportBounds.height - horizontalRegion.height,
                             leftRegion.width, leftRegion.height);
            spriteBatch->draw(bounds.x, bounds.y, bounds.width, bounds.height, leftUVs.u1, leftUVs.v1, leftUVs.u2, leftUVs.v2, leftColor, clipRegion);

            bounds.x += leftRegion.width;
            bounds.width = _scrollBarBounds.width - leftRegion.width - rightRegion.width;
            spriteBatch->draw(bounds.x, bounds.y, bounds.width, bounds.height, horizontalUVs.u1, horizontalUVs.v1, horizontalUVs.u2, horizontalUVs.v2, horizontalColor, clipRegion);

            bounds.x += bounds.width;
            bounds.width = rightRegion.width;
            spriteBatch->draw(bounds.x, bounds.y, bounds.width, bounds.height, rightUVs.u1, rightUVs.v1, rightUVs.u2, rightUVs.v2, rightColor, clipRegion);
        }

        spriteBatch->end();

        if (_scrollingVelocity.isZero())
        {
            _dirty = false;
        }
    }
    else
    {
        _dirty = false;
    }
}
示例#21
0
void HouseRenderer::initialize() {
	houseRendererForm = Form::create("res/menu/houseRenderer.form");
	Control* mainMenuButton = houseRendererForm->getControl("mainMenuButton");
	mainMenuButton->addListener(this, Control::Listener::CLICK);
	Control* refreshButton = houseRendererForm->getControl("refreshButton");
	refreshButton->addListener(this, Control::Listener::CLICK);
	Control* clearButton = houseRendererForm->getControl("clearButton");
	clearButton->addListener(this, Control::Listener::CLICK);
	Control* floorUpButton = houseRendererForm->getControl("floorUpButton");
	floorUpButton->addListener(this, Control::Listener::CLICK);
	Control* floorDownButton = houseRendererForm->getControl("floorDownButton");
	floorDownButton->addListener(this, Control::Listener::CLICK);
	Control* roomTypesWheel = houseRendererForm->getControl("roomTypesWheel");
	roomTypesWheel->addListener(this, Control::Listener::CLICK);

    scene = Scene::create("HouseScene");
    zoomLevel = 1;
    curTranslate = new Vector3();
    
    Camera* camera = Camera::createOrthographic(0, 0, 0, 0.25, 600);
    
    Node* cameraNode = scene->addNode();
    cameraNode->setCamera(camera);
	scene->setActiveCamera(camera);
	cameraNode->translateForward(-100);
    
    SAFE_RELEASE(camera);
    
    cameraNode->rotateZ(MATH_PI / 4);
    cameraNode->rotateX(MATH_PI / 4);
    
    resize();
    
    createHouse(false, true);
}
示例#22
0
bool Container::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
{
    if (!isEnabled())
    {
        return false;
    }

    bool eventConsumed = false;
    const Theme::Border& border = getBorder(_state);
    const Theme::Padding& padding = getPadding();
    float xPos = border.left + padding.left;
    float yPos = border.top + padding.top;

    Vector2* offset = NULL;
    if (_scroll != SCROLL_NONE)
    {
        offset = &_scrollPosition;
    }

    std::vector<Control*>::const_iterator it;
    for (it = _controls.begin(); it < _controls.end(); it++)
    {
        Control* control = *it;
        GP_ASSERT(control);
        if (!control->isEnabled())
        {
            continue;
        }

        const Rectangle& bounds = control->getBounds();
        float boundsX = bounds.x;
        float boundsY = bounds.y;
        if (offset)
        {
            boundsX += offset->x;
            boundsY += offset->y;
        }

        if (control->getState() != Control::NORMAL ||
            (evt == Touch::TOUCH_PRESS &&
                x >= xPos + boundsX &&
                x <= xPos + boundsX + bounds.width &&
                y >= yPos + boundsY &&
                y <= yPos + boundsY + bounds.height))
        {
            // Pass on the event's clip relative to the control.
            eventConsumed |= control->touchEvent(evt, x - xPos - boundsX, y - yPos - boundsY, contactIndex);
        }
    }

    if (!isEnabled())
    {
        return (_consumeTouchEvents | eventConsumed);
    }

    switch (evt)
    {
    case Touch::TOUCH_PRESS:
        setState(Control::FOCUS);
        break;
    case Touch::TOUCH_RELEASE:
        setState(Control::NORMAL);
        break;
    }

    if (!eventConsumed && _scroll != SCROLL_NONE)
    {
        if (touchEventScroll(evt, x - xPos, y - yPos, contactIndex))
        {
            _dirty = true;
        }
    }

    return (_consumeTouchEvents | eventConsumed);
}
示例#23
0
void
MapNodeHelper::parse(MapNode*             mapNode,
                     osg::ArgumentParser& args,
                     osgViewer::View*     view,
                     osg::Group*          root,
                     Container*           userContainer ) const
{
    if ( !root )
        root = mapNode;

    // options to use for the load
    osg::ref_ptr<osgDB::Options> dbOptions = Registry::instance()->cloneOrCreateOptions();

    // parse out custom example arguments first:
    bool useSky        = args.read("--sky");
    bool useOcean      = args.read("--ocean");
    bool useMGRS       = args.read("--mgrs");
    bool useDMS        = args.read("--dms");
    bool useDD         = args.read("--dd");
    bool useCoords     = args.read("--coords") || useMGRS || useDMS || useDD;
    bool useOrtho      = args.read("--ortho");
    bool useAutoClip   = args.read("--autoclip");
    bool useShadows    = args.read("--shadows");
    bool animateSky    = args.read("--animate-sky");
    bool showActivity  = args.read("--activity");
    bool useLogDepth   = args.read("--logdepth");
    bool useLogDepth2  = args.read("--logdepth2");
    bool kmlUI         = args.read("--kmlui");
    bool inspect       = args.read("--inspect");

    if (args.read("--verbose"))
        osgEarth::setNotifyLevel(osg::INFO);
    
    if (args.read("--quiet"))
        osgEarth::setNotifyLevel(osg::FATAL);

    float ambientBrightness = 0.2f;
    args.read("--ambientBrightness", ambientBrightness);

    std::string kmlFile;
    args.read( "--kml", kmlFile );

    std::string imageFolder;
    args.read( "--images", imageFolder );

    std::string imageExtensions;
    args.read("--image-extensions", imageExtensions);
    
    // animation path:
    std::string animpath;
    if ( args.read("--path", animpath) )
    {
        view->setCameraManipulator( new osgGA::AnimationPathManipulator(animpath) );
    }

    // Install a new Canvas for our UI controls, or use one that already exists.
    ControlCanvas* canvas = ControlCanvas::getOrCreate( view );

    Container* mainContainer;
    if ( userContainer )
    {
        mainContainer = userContainer;
    }
    else
    {
        mainContainer = new VBox();
        mainContainer->setAbsorbEvents( true );
        mainContainer->setBackColor( Color(Color::Black, 0.8) );
        mainContainer->setHorizAlign( Control::ALIGN_LEFT );
        mainContainer->setVertAlign( Control::ALIGN_BOTTOM );
    }
    canvas->addControl( mainContainer );


    // look for external data in the map node:
    const Config& externals = mapNode->externalConfig();

    const Config& skyConf         = externals.child("sky");
    const Config& oceanConf       = externals.child("ocean");
    const Config& annoConf        = externals.child("annotations");
    const Config& declutterConf   = externals.child("decluttering");

    // some terrain effects.
    // TODO: Most of these are likely to move into extensions.
    const Config& lodBlendingConf = externals.child("lod_blending");
    const Config& vertScaleConf   = externals.child("vertical_scale");
    const Config& contourMapConf  = externals.child("contour_map");

    // Adding a sky model:
    if ( useSky || !skyConf.empty() )
    {
        SkyOptions options(skyConf);
        if ( options.getDriver().empty() )
        {
            if ( mapNode->getMapSRS()->isGeographic() )
                options.setDriver("simple");
            else
                options.setDriver("gl");
        }

        SkyNode* sky = SkyNode::create(options, mapNode);
        if ( sky )
        {
            sky->attach( view, 0 );
            if ( mapNode->getNumParents() > 0 )
            {
                osgEarth::insertGroup(sky, mapNode->getParent(0));
            }
            else
            {
                sky->addChild( mapNode );
                root = sky;
            }
                
            Control* c = SkyControlFactory().create(sky, view);
            if ( c )
                mainContainer->addControl( c );

            if (animateSky)
            {
                sky->setUpdateCallback( new AnimateSkyUpdateCallback() );
            }

        }
    }

    // Adding an ocean model:
    if ( useOcean || !oceanConf.empty() )
    {
        OceanNode* ocean = OceanNode::create(OceanOptions(oceanConf), mapNode);
        if ( ocean )
        {
            // if there's a sky, we want to ocean under it
            osg::Group* parent = osgEarth::findTopMostNodeOfType<SkyNode>(root);
            if ( !parent ) parent = root;
            parent->addChild( ocean );

            Control* c = OceanControlFactory().create(ocean);
            if ( c )
                mainContainer->addControl(c);
        }
    }

    // Shadowing.
    if ( useShadows )
    {
        ShadowCaster* caster = new ShadowCaster();
        caster->setLight( view->getLight() );
        caster->getShadowCastingGroup()->addChild( mapNode->getModelLayerGroup() );
        if ( mapNode->getNumParents() > 0 )
        {
            insertGroup(caster, mapNode->getParent(0));
        }
        else
        {
            caster->addChild(mapNode);
            root = caster;
        }
    }

    // Loading KML from the command line:
    if ( !kmlFile.empty() )
    {
        KMLOptions kml_options;
        kml_options.declutter() = true;

        // set up a default icon for point placemarks:
        IconSymbol* defaultIcon = new IconSymbol();
        defaultIcon->url()->setLiteral(KML_PUSHPIN_URL);
        kml_options.defaultIconSymbol() = defaultIcon;

        osg::Node* kml = KML::load( URI(kmlFile), mapNode, kml_options );
        if ( kml )
        {
            if (kmlUI)
            {
                Control* c = AnnotationGraphControlFactory().create(kml, view);
                if ( c )
                {
                    c->setVertAlign( Control::ALIGN_TOP );
                    canvas->addControl( c );
                }
            }
            root->addChild( kml );
        }
        else
        {
            OE_NOTICE << "Failed to load " << kmlFile << std::endl;
        }
    }

    // Annotations in the map node externals:
    if ( !annoConf.empty() )
    {
        osg::Group* annotations = 0L;
        AnnotationRegistry::instance()->create( mapNode, annoConf, dbOptions.get(), annotations );
        if ( annotations )
        {
            mapNode->addChild( annotations );
            //root->addChild( annotations );
        }
    }

    // Configure the de-cluttering engine for labels and annotations:
    if ( !declutterConf.empty() )
    {
        Decluttering::setOptions( DeclutteringOptions(declutterConf) );
    }

    // Configure the mouse coordinate readout:
    if ( useCoords )
    { 
        LabelControl* readout = new LabelControl();
        readout->setBackColor( Color(Color::Black, 0.8) );
        readout->setHorizAlign( Control::ALIGN_RIGHT );
        readout->setVertAlign( Control::ALIGN_BOTTOM );

        Formatter* formatter = 
            useMGRS ? (Formatter*)new MGRSFormatter(MGRSFormatter::PRECISION_1M, 0L, MGRSFormatter::USE_SPACES) :
            useDMS  ? (Formatter*)new LatLongFormatter(LatLongFormatter::FORMAT_DEGREES_MINUTES_SECONDS) :
            useDD   ? (Formatter*)new LatLongFormatter(LatLongFormatter::FORMAT_DECIMAL_DEGREES) :
            0L;

        MouseCoordsTool* mcTool = new MouseCoordsTool( mapNode );
        mcTool->addCallback( new MouseCoordsLabelCallback(readout, formatter) );
        view->addEventHandler( mcTool );

        canvas->addControl( readout );
    }

    // Configure for an ortho camera:
    if ( useOrtho )
    {
        view->getCamera()->setProjectionMatrixAsOrtho(-1, 1, -1, 1, 0, 1);
        //EarthManipulator* manip = dynamic_cast<EarthManipulator*>(view->getCameraManipulator());
        //if ( manip )
        //{
        //    manip->getSettings()->setCameraProjection( EarthManipulator::PROJ_ORTHOGRAPHIC );
        //}
    }

    // activity monitor (debugging)
    if ( showActivity )
    {
        VBox* vbox = new VBox();
        vbox->setBackColor( Color(Color::Black, 0.8) );
        vbox->setHorizAlign( Control::ALIGN_RIGHT );
        vbox->setVertAlign( Control::ALIGN_BOTTOM );
        view->addEventHandler( new ActivityMonitorTool(vbox) );
        canvas->addControl( vbox );
    }

    // Install an auto clip plane clamper
    if ( useAutoClip )
    {
        mapNode->addCullCallback( new AutoClipPlaneCullCallback(mapNode) );
    }

    // Install logarithmic depth buffer on main camera
    if ( useLogDepth )
    {
        OE_INFO << LC << "Activating logarithmic depth buffer (vertex-only) on main camera" << std::endl;
        osgEarth::Util::LogarithmicDepthBuffer logDepth;
        logDepth.setUseFragDepth( false );
        logDepth.install( view->getCamera() );
    }

    else if ( useLogDepth2 )
    {
        OE_INFO << LC << "Activating logarithmic depth buffer (precise) on main camera" << std::endl;
        osgEarth::Util::LogarithmicDepthBuffer logDepth;
        logDepth.setUseFragDepth( true );
        logDepth.install( view->getCamera() );
    }

    // Scan for images if necessary.
    if ( !imageFolder.empty() )
    {
        std::vector<std::string> extensions;
        if ( !imageExtensions.empty() )
            StringTokenizer( imageExtensions, extensions, ",;", "", false, true );
        if ( extensions.empty() )
            extensions.push_back( "tif" );

        OE_INFO << LC << "Loading images from " << imageFolder << "..." << std::endl;
        ImageLayerVector imageLayers;
        DataScanner scanner;
        scanner.findImageLayers( imageFolder, extensions, imageLayers );

        if ( imageLayers.size() > 0 )
        {
            mapNode->getMap()->beginUpdate();
            for( ImageLayerVector::iterator i = imageLayers.begin(); i != imageLayers.end(); ++i )
            {
                mapNode->getMap()->addImageLayer( i->get() );
            }
            mapNode->getMap()->endUpdate();
        }
        OE_INFO << LC << "...found " << imageLayers.size() << " image layers." << std::endl;
    }

    // Install elevation morphing
    if ( !lodBlendingConf.empty() )
    {
        mapNode->getTerrainEngine()->addEffect( new LODBlending(lodBlendingConf) );
    }

    // Install vertical scaler
    if ( !vertScaleConf.empty() )
    {
        mapNode->getTerrainEngine()->addEffect( new VerticalScale(vertScaleConf) );
    }

    // Install a contour map effect.
    if ( !contourMapConf.empty() )
    {
        mapNode->getTerrainEngine()->addEffect( new ContourMap(contourMapConf) );
    }

    // Generic named value uniform with min/max.
    VBox* uniformBox = 0L;
    while( args.find( "--uniform" ) >= 0 )
    {
        std::string name;
        float minval, maxval;
        if ( args.read( "--uniform", name, minval, maxval ) )
        {
            if ( uniformBox == 0L )
            {
                uniformBox = new VBox();
                uniformBox->setBackColor(0,0,0,0.5);
                uniformBox->setAbsorbEvents( true );
                canvas->addControl( uniformBox );
            }
            osg::Uniform* uniform = new osg::Uniform(osg::Uniform::FLOAT, name);
            uniform->set( minval );
            root->getOrCreateStateSet()->addUniform( uniform, osg::StateAttribute::OVERRIDE );
            HBox* box = new HBox();
            box->addControl( new LabelControl(name) );
            HSliderControl* hs = box->addControl( new HSliderControl(minval, maxval, minval, new ApplyValueUniform(uniform)));
            hs->setHorizFill(true, 200);
            box->addControl( new LabelControl(hs) );
            uniformBox->addControl( box );
            OE_INFO << LC << "Installed uniform controller for " << name << std::endl;
        }
    }

    if ( inspect )
    {
        mapNode->addExtension( Extension::create("mapinspector", ConfigOptions()) );
    }
    

    // Process extensions.
    for(std::vector<osg::ref_ptr<Extension> >::const_iterator eiter = mapNode->getExtensions().begin();
        eiter != mapNode->getExtensions().end();
        ++eiter)
    {
        Extension* e = eiter->get();

        // Check for a View interface:
        ExtensionInterface<osg::View>* viewIF = ExtensionInterface<osg::View>::get( e );
        if ( viewIF )
            viewIF->connect( view );

        // Check for a Control interface:
        ExtensionInterface<Control>* controlIF = ExtensionInterface<Control>::get( e );
        if ( controlIF )
            controlIF->connect( mainContainer );
    }

    root->addChild( canvas );
}
示例#24
0
void Container::updateScroll()
{
    // Update Time.
    static long lastFrameTime = Game::getGameTime();
    long frameTime = Game::getGameTime();
    long elapsedTime = (frameTime - lastFrameTime);
    lastFrameTime = frameTime;

    const Theme::Border& containerBorder = getBorder(_state);
    const Theme::Padding& containerPadding = getPadding();

    // Calculate total width and height.
    float totalWidth = 0;
    float totalHeight = 0;
    std::vector<Control*> controls = getControls();
    unsigned int controlsCount = controls.size();
    for (unsigned int i = 0; i < controlsCount; i++)
    {
        Control* control = controls.at(i);

        const Rectangle& bounds = control->getBounds();
        const Theme::Margin& margin = control->getMargin();

        float newWidth = bounds.x + bounds.width;
        if (newWidth > totalWidth)
        {
            totalWidth = newWidth;
        }

        float newHeight = bounds.y + bounds.height;
        if (newHeight > totalHeight)
        {
            totalHeight = newHeight;
        }
    }

    float vWidth = getImageRegion("verticalScrollBar", _state).width;
    float hHeight = getImageRegion("horizontalScrollBar", _state).height;
    float clipWidth = _bounds.width - containerBorder.left - containerBorder.right - containerPadding.left - containerPadding.right - vWidth;
    float clipHeight = _bounds.height - containerBorder.top - containerBorder.bottom - containerPadding.top - containerPadding.bottom - hHeight;

    // Apply and dampen inertia.
    if (!_scrolling && !_scrollingVelocity.isZero())
    {
        // Calculate the time passed since last update.
        float elapsedSecs = (float)elapsedTime * 0.001f;

        _scrollPosition.x += _scrollingVelocity.x * elapsedSecs;
        _scrollPosition.y += _scrollingVelocity.y * elapsedSecs;

        float dampening = 1.0f - _scrollingFriction * SCROLL_FRICTION_FACTOR * elapsedSecs;
        _scrollingVelocity.x *= dampening;
        _scrollingVelocity.y *= dampening;

        if (fabs(_scrollingVelocity.x) < 100.0f)
            _scrollingVelocity.x = 0.0f;
        if (fabs(_scrollingVelocity.y) < 100.0f)
            _scrollingVelocity.y = 0.0f;
    }

    // Stop scrolling when the far edge is reached.
    if (-_scrollPosition.x > totalWidth - clipWidth)
    {
        _scrollPosition.x = -(totalWidth - clipWidth);
        _scrollingVelocity.x = 0;
    }
    
    if (-_scrollPosition.y > totalHeight - clipHeight)
    {
        _scrollPosition.y = -(totalHeight - clipHeight);
        _scrollingVelocity.y = 0;
    }

    if (_scrollPosition.x > 0)
    {
        _scrollPosition.x = 0;
        _scrollingVelocity.x = 0;
    }

    if (_scrollPosition.y > 0)
    {
        _scrollPosition.y = 0;
        _scrollingVelocity.y = 0;
    }

    float scrollWidth = 0;
    if (clipWidth < totalWidth)
        scrollWidth = (clipWidth / totalWidth) * clipWidth;

    float scrollHeight = 0;
    if (clipHeight < totalHeight)
        scrollHeight = (clipHeight / totalHeight) * clipHeight;

    _scrollBarBounds.set(((-_scrollPosition.x) / totalWidth) * clipWidth,
                         ((-_scrollPosition.y) / totalHeight) * clipHeight,
                         scrollWidth, scrollHeight);

    // If scroll velocity is 0 and scrollbars are not always visible, trigger fade-out animation.
    if (!_scrolling && _scrollingVelocity.isZero() && _scrollBarsAutoHide && _scrollBarOpacity == 1.0f)
    {
        float to = 0;
        _scrollBarOpacity = 0.99f;
        Animation* animation = createAnimationFromTo("scrollbar-fade-out", ANIMATE_OPACITY, &_scrollBarOpacity, &to, Curve::QUADRATIC_IN_OUT, 500L);
        _scrollBarOpacityClip = animation->getClip();
        _scrollBarOpacityClip->play();
    }

    // Position controls within scroll area.
    _layout->update(this, _scrollPosition);
}
	// mouse Listeners
    void InputControlSystem::mouseMoved(const SFO::MouseMotionEvent& evt)
	{
		if(mActive)
		{
			if(!mDetectingBindingControl)
			{
				if(mXmouseAxisBinded && evt.xrel)
				{
					ControlAxisBinderItem mouseBinderItem = mControlsMouseAxisBinderMap[ /*NamedAxis::*/X ];
					Control* ctrl = mouseBinderItem.control;
					ctrl->setIgnoreAutoReverse(true);
					if(mouseBinderItem.direction == Control::INCREASE)
					{
						ctrl->setValue( float( (evt.x) / float(mClientWidth) ) );
					}
					else if(mouseBinderItem.direction == Control::DECREASE)
					{
						ctrl->setValue( 1 - float( evt.x / float(mClientWidth) ) );
					}
				}

				if(mYmouseAxisBinded && evt.yrel)
				{
					ControlAxisBinderItem mouseBinderItem = mControlsMouseAxisBinderMap[ /*NamedAxis::*/Y ];
					Control* ctrl = mouseBinderItem.control;
					ctrl->setIgnoreAutoReverse(true);
					if(mouseBinderItem.direction == Control::INCREASE)
					{
						ctrl->setValue( float( (evt.y) / float(mClientHeight) ) );
					}
					else if(mouseBinderItem.direction == Control::DECREASE)
					{
						ctrl->setValue( 1 - float( evt.y / float(mClientHeight) ) );
					}
				}

				//! @todo Whats the range of the Z axis?
				/*if(evt.state.Z.rel)
				{
					ControlAxisBinderItem mouseBinderItem = mControlsAxisBinderMap[ NamedAxis::Z ];
					Control* ctrl = mouseBinderItem.control;
					ctrl->setIgnoreAutoReverse(true);
					if(mouseBinderItem.direction == Control::INCREASE)
					{
						ctrl->setValue( float( (evt.state.Z.abs) / float(evt.state.¿width?) ) );
					}
					else if(mouseBinderItem.direction == Control::DECREASE)
					{
						ctrl->setValue( float( (1 - evt.state.Z.abs) / float(evt.state.¿width?) ) );
					}
				}*/
			}
			else if(mDetectingBindingListener)
			{
				if(mDetectingBindingControl->isAxisBindable())
				{
					if(mMouseAxisBindingInitialValues[0] == ICS_MOUSE_AXIS_BINDING_NULL_VALUE)
					{
						mMouseAxisBindingInitialValues[0] = 0;
						mMouseAxisBindingInitialValues[1] = 0;
						mMouseAxisBindingInitialValues[2] = 0;
					}

					mMouseAxisBindingInitialValues[0] += evt.xrel;
					mMouseAxisBindingInitialValues[1] += evt.yrel;
					mMouseAxisBindingInitialValues[2] += evt.zrel;

					if( abs(mMouseAxisBindingInitialValues[0]) > ICS_MOUSE_BINDING_MARGIN )
					{
						mDetectingBindingListener->mouseAxisBindingDetected(this,
							mDetectingBindingControl, X, mDetectingBindingDirection);
					}
					else if( abs(mMouseAxisBindingInitialValues[1]) > ICS_MOUSE_BINDING_MARGIN )
					{
						mDetectingBindingListener->mouseAxisBindingDetected(this,
							mDetectingBindingControl, Y, mDetectingBindingDirection);
					}
					else if( abs(mMouseAxisBindingInitialValues[2]) > ICS_MOUSE_BINDING_MARGIN )
					{
						mDetectingBindingListener->mouseAxisBindingDetected(this,
							mDetectingBindingControl, Z, mDetectingBindingDirection);		
					}
				}
			}
		}
	}
示例#26
0
void Container::addControls(Theme* theme, Properties* properties)
{
    GP_ASSERT(theme);
    GP_ASSERT(properties);

    // Add all the controls to this container.
    Properties* controlSpace = properties->getNextNamespace();
    while (controlSpace != NULL)
    {
        Control* control = NULL;

        const char* controlStyleName = controlSpace->getString("style");
        Theme::Style* controlStyle = NULL;
        if (controlStyleName)
        {
            controlStyle = theme->getStyle(controlStyleName);
        }
        else
        {
            Theme::Style::Overlay* overlay = Theme::Style::Overlay::create();
            controlStyle = new Theme::Style(theme, "", 1.0f / theme->_texture->getWidth(), 1.0f / theme->_texture->getHeight(),
                Theme::Margin::empty(), Theme::Border::empty(), overlay, overlay, overlay, overlay);
        }

        std::string controlName(controlSpace->getNamespace());
        std::transform(controlName.begin(), controlName.end(), controlName.begin(), (int(*)(int))toupper);
        if (controlName == "LABEL")
        {
            control = Label::create(controlStyle, controlSpace);
        }
        else if (controlName == "BUTTON")
        {
            control = Button::create(controlStyle, controlSpace);
        }
        else if (controlName == "CHECKBOX")
        {
            control = CheckBox::create(controlStyle, controlSpace);
        }
        else if (controlName == "RADIOBUTTON")
        {
            control = RadioButton::create(controlStyle, controlSpace);
        }
        else if (controlName == "CONTAINER")
        {
            control = Container::create(controlStyle, controlSpace, theme);
        }
        else if (controlName == "SLIDER")
        {
            control = Slider::create(controlStyle, controlSpace);
        }
        else if (controlName == "TEXTBOX")
        {
            control = TextBox::create(controlStyle, controlSpace);
        }
        else if (controlName == "JOYSTICK")
        {
            control = Joystick::create(controlStyle, controlSpace);
        }
        else
        {
            GP_ERROR("Failed to create control; unrecognized control name '%s'.", controlName.c_str());
        }

        // Add the new control to the form.
        if (control)
        {
            addControl(control);

            if (control->getZIndex() == -1)
            {
                control->setZIndex(_zIndexDefault++);
            }
        }

        // Get the next control.
        controlSpace = properties->getNextNamespace();
    }

    // Sort controls by Z-Order.
    std::sort(_controls.begin(), _controls.end(), &sortControlsByZOrder);
}
示例#27
0
void ScrollContainer::_notification(int p_what) {

	if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {

		call_deferred("_update_scrollbar_pos");
	};

	if (p_what == NOTIFICATION_SORT_CHILDREN) {

		child_max_size = Size2(0, 0);
		Size2 size = get_size();
		if (h_scroll->is_visible_in_tree())
			size.y -= h_scroll->get_minimum_size().y;

		if (v_scroll->is_visible_in_tree())
			size.x -= h_scroll->get_minimum_size().x;

		for (int i = 0; i < get_child_count(); i++) {

			Control *c = get_child(i)->cast_to<Control>();
			if (!c)
				continue;
			if (c->is_set_as_toplevel())
				continue;
			if (c == h_scroll || c == v_scroll)
				continue;
			Size2 minsize = c->get_combined_minimum_size();
			child_max_size.x = MAX(child_max_size.x, minsize.x);
			child_max_size.y = MAX(child_max_size.y, minsize.y);

			Rect2 r = Rect2(-scroll, minsize);
			if (!scroll_h || (!h_scroll->is_visible_in_tree() && c->get_h_size_flags() & SIZE_EXPAND)) {
				r.position.x = 0;
				if (c->get_h_size_flags() & SIZE_EXPAND)
					r.size.width = MAX(size.width, minsize.width);
				else
					r.size.width = minsize.width;
			}
			if (!scroll_v || (!v_scroll->is_visible_in_tree() && c->get_v_size_flags() & SIZE_EXPAND)) {
				r.position.y = 0;
				r.size.height = size.height;
				if (c->get_v_size_flags() & SIZE_EXPAND)
					r.size.height = MAX(size.height, minsize.height);
				else
					r.size.height = minsize.height;
			}
			fit_child_in_rect(c, r);
		}
		update();
	};

	if (p_what == NOTIFICATION_DRAW) {

		update_scrollbars();
	}

	if (p_what == NOTIFICATION_FIXED_PROCESS) {

		if (drag_touching) {

			if (drag_touching_deaccel) {

				Vector2 pos = Vector2(h_scroll->get_value(), v_scroll->get_value());
				pos += drag_speed * get_fixed_process_delta_time();

				bool turnoff_h = false;
				bool turnoff_v = false;

				if (pos.x < 0) {
					pos.x = 0;
					turnoff_h = true;
				}
				if (pos.x > (h_scroll->get_max() - h_scroll->get_page())) {
					pos.x = h_scroll->get_max() - h_scroll->get_page();
					turnoff_h = true;
				}

				if (pos.y < 0) {
					pos.y = 0;
					turnoff_v = true;
				}
				if (pos.y > (v_scroll->get_max() - v_scroll->get_page())) {
					pos.y = v_scroll->get_max() - v_scroll->get_page();
					turnoff_v = true;
				}

				if (scroll_h)
					h_scroll->set_value(pos.x);
				if (scroll_v)
					v_scroll->set_value(pos.y);

				float sgn_x = drag_speed.x < 0 ? -1 : 1;
				float val_x = Math::abs(drag_speed.x);
				val_x -= 1000 * get_fixed_process_delta_time();

				if (val_x < 0) {
					turnoff_h = true;
				}

				float sgn_y = drag_speed.y < 0 ? -1 : 1;
				float val_y = Math::abs(drag_speed.y);
				val_y -= 1000 * get_fixed_process_delta_time();

				if (val_y < 0) {
					turnoff_v = true;
				}

				drag_speed = Vector2(sgn_x * val_x, sgn_y * val_y);

				if (turnoff_h && turnoff_v) {
					set_fixed_process(false);
					drag_touching = false;
					drag_touching_deaccel = false;
				}

			} else {

				if (time_since_motion == 0 || time_since_motion > 0.1) {

					Vector2 diff = drag_accum - last_drag_accum;
					last_drag_accum = drag_accum;
					drag_speed = diff / get_fixed_process_delta_time();
				}

				time_since_motion += get_fixed_process_delta_time();
			}
		}
	}
};
//
// NOTE: run this sample from the repo/tests directory.
//
int main(int argc, char** argv)
{
    osg::ArgumentParser arguments(&argc,argv);

    osgViewer::Viewer viewer(arguments);
    s_viewer = &viewer;

    // Start by creating the map:
    s_mapNode = MapNode::load(arguments);
    if ( !s_mapNode )
    {
        Map* map = new Map();

        // Start with a basemap imagery layer; we'll be using the GDAL driver
        // to load a local GeoTIFF file:
        GDALOptions basemapOpt;
        basemapOpt.url() = "../data/world.tif";
        map->addImageLayer( new ImageLayer( ImageLayerOptions("basemap", basemapOpt) ) );

        // That's it, the map is ready; now create a MapNode to render the Map:
        MapNodeOptions mapNodeOptions;
        mapNodeOptions.enableLighting() = false;

        s_mapNode = new MapNode( map, mapNodeOptions );
    }
    s_mapNode->setNodeMask( 0x01 );    

        
    // Define a style for the feature data.
    Style style = buildStyle( Color::Yellow, 2.0f );    

    //LineString* line = new LineString();    
    Geometry* geom = GeometryUtils::geometryFromWKT("POLYGON((191.026667 87.63333,114.75 78,89.5 77.333336,81.833336 75.333336,70.683334 74.5,70.916664 73.666664,68.666664 73.666664,66.291664 71.505,57.65 71.166664,58 73.9,48.616665 73,49.198334 71.43,49.5 70.5,43.266666 68.666664,32.083332 71.5,32.083332 74,35 74,35 81,32 81,32 90,191.026667 87.63333))");
    OE_NOTICE << "Geometry " << GeometryUtils::geometryToWKT(geom) << std::endl;
    Feature* feature = new Feature(geom, s_mapNode->getMapSRS(), Style(), s_fid++);
    s_featureNode = new FeatureNode( s_mapNode, feature );    
    s_featureNode->setStyle( style );
    
    s_editorsRoot = new osg::Group;

    s_root = new osg::Group;
    s_root->addChild( s_mapNode.get() );
    s_root->addChild( s_featureNode.get() );
    s_root->addChild( s_editorsRoot.get() );


    //Setup the controls
    ControlCanvas* canvas = ControlCanvas::getOrCreate( &viewer );
    s_root->addChild( canvas );
    Grid *toolbar = createToolBar( );
    canvas->addControl( toolbar );
    canvas->setNodeMask( 0x1 << 1 );

    int col = 0;
    LabelControl* addVerts = new LabelControl("Add Verts");
    toolbar->setControl(col++, 0, addVerts );    
    addVerts->addEventHandler( new AddVertsModeHandler());
    
    LabelControl* edit = new LabelControl("Edit");
    toolbar->setControl(col++, 0, edit );    
    edit->addEventHandler(new EditModeHandler());

    unsigned int row = 0;
    Grid *styleBar = createToolBar( );
    styleBar->setPosition(0, 50);
    canvas->addControl( styleBar );
    
    //Make a list of styles
    styleBar->setControl(0, row++, new LabelControl("Styles") );    

    unsigned int numStyles = 8;
    for (unsigned int i = 0; i < numStyles; ++i)
    {
        float w = 50;
        osg::Vec4 color = randomColor();

        float widths[3] = {2, 4, 8};

        unsigned int r = row++;
        for (unsigned int j = 0; j < 3; j++) 
        {
            Control* l = new Control();            
            l->setBackColor( color );
            l->addEventHandler(new ChangeStyleHandler(buildStyle( color, widths[j] ) ));
            l->setSize(w,5 * widths[j]);
            styleBar->setControl(j, r, l);
        }
    }
   
    
    viewer.setSceneData( s_root.get() );
    viewer.setCameraManipulator( new EarthManipulator() );

    if ( s_mapNode )
        viewer.getCamera()->addCullCallback( new osgEarth::Util::AutoClipPlaneCullCallback(s_mapNode) );

    // add some stock OSG handlers:
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());
    viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()));

    return viewer.run();
}
示例#29
0
文件: mirror.cpp 项目: 2asoft/xray
void MirrorMod::Rotate(TimeValue t, Matrix3& partm, Matrix3& tmAxis, Quat& val, BOOL localOrigin)
	{
	SetXFormPacket pckt(val,localOrigin,partm,tmAxis);
	tmControl->SetValue(t,&pckt,TRUE,CTRL_RELATIVE);
	}
示例#30
0
void myMouseCB(int button, int state, int x, int y)
{
	control.mouseCB(button,state,x,y);
}