コード例 #1
0
ファイル: wksp_initial_setting.cpp プロジェクト: s861114/OpCd
void WKSP::initial_read_setting(void)
{
	FILE* fp = fopen("setup.set","r");
	char dump[100];
	char dump1[100];
	/*while(!feof(fp))
	{
		fgets(dump,100,fp);
		printf("%s",dump);
	}*/
	fgets(dump,100,fp);	sscanf(dump,"%s  %d\n",dump1,&N_radial);
	fgets(dump,100,fp);	sscanf(dump,"%s  %lf\n",dump1,&kc);		
	fgets(dump,100,fp);	sscanf(dump,"%s  %d\n",dump1,&N_theta);	
	fgets(dump,100,fp);	sscanf(dump,"%s  %lf\n",dump1,&kf);		
	fgets(dump,100,fp);	sscanf(dump,"%s  %lf\n",dump1,&alpha);
	fgets(dump,100,fp);	sscanf(dump,"%s  %lf\n",dump1,&Ef);
	fgets(dump,100,fp);	sscanf(dump,"%s  %lf\n",dump1,&nB);
	fgets(dump,100,fp);	sscanf(dump,"%s  %lf\n",dump1,&nT);
	nB=nB*1e+16;
	nT=nT*1e+16;

	set_alpha(alpha);
	h_radial = kc / N_radial;
	h_theta = 2.0*M_PI/ N_theta;
	c_theta = 1.0/N_theta;	

}
コード例 #2
0
ファイル: SurfaceOperations.cpp プロジェクト: Valtis/sdl_gui
void set_color(SDL_Surface *surface, int x, int y, SDL_Color color)
{
	set_red(surface, x, y, color.r);
	set_green(surface, x, y, color.g);
	set_blue(surface, x, y, color.g);
	set_alpha(surface, x, y, color.a);
}
コード例 #3
0
ファイル: cmdoptions.cpp プロジェクト: kimwalisch/primecount
CmdOptions parseOptions(int argc, char* argv[])
{
  CmdOptions opts;
  vector<maxint_t> numbers;

  for (int i = 1; i < argc; i++)
  {
    Option opt = makeOption(argv[i]);

    switch (optionMap[opt.opt])
    {
      case OPTION_ALPHA:   set_alpha(stod(opt.val)); break;
      case OPTION_NUMBER:  numbers.push_back(opt.to<maxint_t>()); break;
      case OPTION_THREADS: set_num_threads(opt.to<int>()); break;
      case OPTION_PHI:     opts.a = opt.to<int64_t>(); opts.option = OPTION_PHI; break;
      case OPTION_HELP:    help(); break;
      case OPTION_STATUS:  optionStatus(opt, opts); break;
      case OPTION_TIME:    opts.time = true; break;
      case OPTION_TEST:    test(); break;
      case OPTION_VERSION: version(); break;
      default:             opts.option = optionMap[opt.opt];
    }
  }

  if (numbers.empty())
    throw primecount_error("missing x number");
  else
    opts.x = numbers[0];

  return opts;
}
コード例 #4
0
ファイル: test.cpp プロジェクト: kgori/pllpy
int main(int argc, char const *argv[])
{
    std::string FILE="/homes/kgori/scratch/basic_pll/GGPS1.phy";
    std::string PART="/homes/kgori/scratch/basic_pll/GGPS1.partitions.txt";
    std::string TREE="/homes/kgori/scratch/basic_pll/GGPS1.tree";

    auto inst = make_unique<pll>(FILE, PART, TREE, 1, 123);
    std::cout << inst->get_likelihood() << std::endl;
    std::cout << inst->get_partition_name(0) << std::endl;
    std::cout << inst->get_model_name(0) << std::endl;
    std::cout << inst->get_epsilon() << std::endl;
    std::cout << inst->get_alpha(0) << std::endl;
    std::cout << inst->get_number_of_partitions() << std::endl;
    std::cout << inst->get_tree() << std::endl;
    std::cout << inst->get_frac_change() << std::endl;
    inst->set_tree("((Ptro:0.00147084048849247711,Ppan:0.00106294370976534763):0.00444598321816729036,(Cjac:0.05157798212603657839,(Csab:0.00440006365327790666,(Mmul:0.00652936575529242547,Panu:0.00101047194512476272):0.00381049900890796569):0.01359968787254225639):0.01375788728353777995,Hsap:0.00674547067186638278):0.0;");
    inst->set_epsilon(0.001);
    inst->set_alpha(2, 0, true);
    auto ef = inst->get_empirical_frequencies();

    inst->optimise(true, true, true, true);
    inst->optimise_tree_search(true);
    std::cout << inst->get_likelihood() << std::endl;
    std::cout << inst->get_tree() << std::endl;
    return 0;
}
コード例 #5
0
ファイル: animator.c プロジェクト: codyd51/axle
void finalize_animation(Window* window, ca_animation* anim) {
	//ensure property is set to final state
	//(just in case there was an issue with timing)
	switch (anim->type) {
		case ALPHA_ANIM:
			set_alpha((View*)window, anim->alpha_to);
			break;
		case POS_ANIM:
			window->frame.origin = anim->pos_to;
			break;
		case COLOR_ANIM:
		default:
			window->content_view->background_color = anim->color_to;
			break;
	}

	//remove anim _before_ calling finalize handler
	//finalize handler may destroy window so we need to do this first
	lock(mutex);
	array_m_remove(window->animations, array_m_index(window->animations, anim));
	unlock(mutex);
	
	event_handler finished = anim->finished_handler;
	if (finished) {
		printf("calling finished_handler %x for win %x\n", finished, window);
		finished(window, NULL);
	}

	kfree(anim);

	mark_needs_redraw((View*)window);
}
コード例 #6
0
ファイル: wksp_initial_setting.cpp プロジェクト: s861114/OpCd
void WKSP::initial_define_constant(void)
{

	gamma0=3; // 3eV
	gamma1=0.37;//0.3eV
	esq = 14.39966058372; // eV*angstrom
	// e= 4.803205e-10 statC
	// (1statC)^2 = 1 erg cm
	// 1 erg = 6.241509e+11 eV
	a=2.46; // lattice constant 2.46 angstrom
	reala=2.46e-10;
	d=3.35; // distance between layers 3.35 angstrom
	hv_a = 0.5*sqrt(3)*gamma0; // eV
	esq_a=esq/a;  // eV
	alpha0=esq_a/hv_a; // e^2/(hbar v0) epsilon=1  alpha<=alpha0;
	dbar = d/a;
	epsilon=8.85418e-12;
	slf_const=1.602e-19*0.334e-9/(2*epsilon);
	set_alpha(1);

	// tot_th means num of logical CPU.
	//  = physical CPU # * 2 (hyperthreading)
	#pragma omp parallel
	{
		tot_th = omp_get_num_threads();
	}
}
コード例 #7
0
ファイル: Style.cpp プロジェクト: potassco/ginkgo
const Style Style::styleGTK(Glib::RefPtr<Gtk::StyleContext> styleContext)
{
	const auto colorPositive = styleContext->get_color();
	auto colorPositiveLight = colorPositive;
	colorPositiveLight.set_alpha(0.5);

	return
		{
			true,
			true,
			1.0,
			styleContext->get_background_color(),
			colorPositive,
			colorPositiveLight,
			Gdk::RGBA("#3080e9"),
			Gdk::RGBA("#505050"),
			Gdk::RGBA("#606060"),
			288.0,
			60.0,
			30.0,
			20.0,
			5.0,
			3.0,
			18.0
		};
}
コード例 #8
0
ファイル: Particle.cpp プロジェクト: octol/libsdlc
void Particle::update(const Timer& timer)
{
    // Update position
    set_x(x() + (x_vel()  * timer.frame_time()));
    set_y(y() + (y_vel()  * timer.frame_time()));

    // Update alpha
    set_alpha(alpha() - (fade_speed() * timer.frame_time()));
}
コード例 #9
0
ファイル: cmmenu.c プロジェクト: nasa/QuIP
static COMMAND_FUNC( do_setalpha )
{
	int index,val;

	index=(int)HOW_MANY("index");
	val=(int)HOW_MANY("alpha value");
	CHECK_DPYP("do_setalpha")
	set_alpha(index,val);
}
コード例 #10
0
ファイル: model_e3.cpp プロジェクト: dimalit/ode-env
E3Config::E3Config(){
	set_m(1000);
	set_n(1.0);
	set_theta_e(0);
	set_gamma_0_2(0.0);
	set_delta_e(0);
	set_r_e(0.0);
	set_alpha(0.0);
}
コード例 #11
0
ファイル: Color.cpp プロジェクト: Holygitzdq/ElVis
 std::unique_ptr<ElVis::Serialization::Color> Color::Serialize() const
 {
   auto pResult = std::unique_ptr<ElVis::Serialization::Color>(new ElVis::Serialization::Color());
   pResult->set_red(m_red);
   pResult->set_green(m_green);
   pResult->set_blue(m_blue);
   pResult->set_alpha(m_alpha);
   return pResult;
 }
コード例 #12
0
ファイル: colorsel.cpp プロジェクト: bb-generation/gobby
void Gobby::ColorButton::on_clicked()
{
	ColorSelectionDialog dlg(m_config_entry);
	dlg.get_colorsel()->set_current_color(get_color() );
	dlg.get_colorsel()->set_current_alpha(get_alpha() );

	if(dlg.run() == Gtk::RESPONSE_OK)
	{
		set_color(dlg.get_colorsel()->get_current_color() );
		set_alpha(dlg.get_colorsel()->get_current_alpha() );
	}
}
コード例 #13
0
ファイル: test.c プロジェクト: tlively/cs51-final
void test_colors() {
  printf("testing colors\n");
  int r = 25;
  int g = 225;
  int b = 200;
  int a = 255;
  color c = get_color(r,g,b,a);
  assert(c == 0x19E1C8FF);
  assert(get_red(c) == r);
  assert(get_green(c) == g);
  assert(get_blue(c) == b);
  assert(get_alpha(c) == a);
  assert(set_red(c,0xAA) == 0xAAE1C8FF);
  assert(set_green(c,0xAA) == 0x19AAC8FF);
  assert(set_blue(c,0xAA) == 0x19E1AAFF);
  assert(set_alpha(c,0xAA) == 0x19E1C8AA);
}
コード例 #14
0
ファイル: varH.c プロジェクト: shivupa/VarHy
void read_basis(){
  FILE *myfile;
  float val;
  char i;

  myfile=fopen("basis.txt", "r");
  printf("READING BASIS FROM basis.txt\n");
  printf("Basis: \n");
  for(i = 0; i <4; i++)
  {
    fscanf(myfile,"%f",&val);
    printf("%f ",val);
    printf("\n");
    set_alpha(i,val);
  }

  fclose(myfile);
}
コード例 #15
0
ファイル: l2r_l1hinge_spdc.cpp プロジェクト: husk214/rp-velb
Eigen::VectorXd l2r_l1hinge_spdc::train_warm_start(const Eigen::VectorXd &alp) {
  set_alpha(alp);
  alpha_ = Eigen::VectorXd::Constant(num_ins_, C);
  // set_w_by_alpha(alpha_);
  double alpha_old = 0.0;
  std::default_random_engine g;
  std::uniform_int_distribution<> uni_dist(0, num_ins_ - 1);
  const auto ins_is_begin_it = std::begin(active_index_);
  w_ = Eigen::VectorXd::Zero(num_fea_);
  spdc_w_ = w_;
  auto random_it = std::next(ins_is_begin_it, uni_dist(g));
  gamma_ = 0.1;
  double tau_ = std::sqrt(gamma_ / (1.0 * (1.0 / C))) / R_;
  double sigma_ = std::sqrt(((1.0 / C) * 1.0) / gamma_) / R_;
  double theta_ =
      1.0 - 1.0 / ((1.0 / C) + R_ * std::sqrt((1.0 / C) / (1.0 * gamma_)));
  // double tau_ = std::sqrt(1.0) / (2.0 * R_);
  // double sigma_ = std::sqrt(1.0 / 1.0) / (2.0 * R_);
  // double theta_ = 1.0 - 1.0 / (1.0 + (R_ / gamma_) * std::sqrt(1.0 / 1.0));
  const double sig_gam = -sigma_ * gamma_ - 1.0;

  int i = 0, itr_ = 0;
  double delta_alpha_i = 0.0, yi = 0.0, beta_i = 0.0, alpha_i_new = 0.0,
         eta = 0.0;
  Eigen::VectorXd delta_v(num_fea_), w_new(num_fea_);
  calculate_duality_gap(true, true);
  std::cout << tau_ << " " << sigma_ << " " << theta_ << " " << R_ << std::endl;
  std::cout << " start optimization " << max_iteration << std::endl;
  for (itr_ = 1; itr_ < max_iteration && duality_gap_ > 1e-6; ++itr_) {
    for (int ir = 0; ir < num_ins_; ++ir) {
      random_it = std::next(ins_is_begin_it, uni_dist(g));
      i = *random_it;
      yi = y_[i];
      // beta_i = -(sigma_ * (yi * (x_.row(i) * spdc_w_)(0) - 1.0)) + alpha_[i];
      beta_i = (sigma_ * (yi * (x_.row(i) * spdc_w_)(0) - 1.0) - alpha_[i]) /
               (sig_gam);
      alpha_i_new = std::min(C, std::max(0.0, beta_i));
      delta_alpha_i = alpha_i_new - alpha_[i];
      alpha_[i] = alpha_i_new;
      delta_v = (yi * delta_alpha_i) * x_.row(i);
      // w_new = (1.0 / (1.0 + tau_)) * (w_ - tau_ * (za_ - delta_v));
      for (int j = 0; j < num_fea_; ++j) {
        eta = (1.0 / (1.0 + tau_)) * (w_[j] + tau_ * (za_[j] + delta_v[j]));
        spdc_w_[j] = eta + theta_ * (eta - w_[j]);
        w_[j] = eta;
      }
      // spdc_w_ = w_new + theta_ * (w_new - w_);
      // w_ = w_new;
      // for (srm_iit it(x_, i); it; ++it)
      //   za_[it.index()] += delta_v[it.index()];
      za_ += delta_v;
    }
    // if (itr_) {
    calculate_duality_gap(true, true);
    std::cout << itr_ << " optimization end gap : " << duality_gap_ << " "
              << primal_obj_value_ << " " << dual_obj_value_ << std::endl;
  }
  std::cout << itr_ << " optimization end gap : " << duality_gap_ << " "
            << primal_obj_value_ << " " << dual_obj_value_ << std::endl;
  std::cout << w_.transpose() << std::endl;
  return w_;
}
コード例 #16
0
ファイル: render_preview.c プロジェクト: OldBrunet/BGERTPS
static void icon_preview_startjob(void *customdata, short *stop, short *do_update)
{
	ShaderPreview *sp= customdata;
	ID *id= sp->id;
	short idtype= GS(id->name);

	if(idtype == ID_IM) {
		Image *ima= (Image*)id;
		ImBuf *ibuf= NULL;
		ImageUser iuser= {NULL};

		/* ima->ok is zero when Image cannot load */
		if(ima==NULL || ima->ok==0)
			return;

		/* setup dummy image user */
		iuser.ok= iuser.framenr= 1;
		iuser.scene= sp->scene;
		
		/* elubie: this needs to be changed: here image is always loaded if not
		   already there. Very expensive for large images. Need to find a way to 
		   only get existing ibuf */
		ibuf = BKE_image_get_ibuf(ima, &iuser);
		if(ibuf==NULL || ibuf->rect==NULL)
			return;
		
		icon_copy_rect(ibuf, sp->sizex, sp->sizey, sp->pr_rect);

		*do_update= 1;
	}
	else if(idtype == ID_BR) {
		Brush *br= (Brush*)id;

		br->icon_imbuf= get_brush_icon(br);

		memset(sp->pr_rect, 0x888888, sp->sizex*sp->sizey*sizeof(unsigned int));

		if(!(br->icon_imbuf) || !(br->icon_imbuf->rect))
			return;

		icon_copy_rect(br->icon_imbuf, sp->sizex, sp->sizey, sp->pr_rect);

		*do_update= 1;
	}
	else {
		/* re-use shader job */
		shader_preview_startjob(customdata, stop, do_update);

		/* world is rendered with alpha=0, so it wasn't displayed 
		   this could be render option for sky to, for later */
		if(idtype == ID_WO) {
			set_alpha((char*)sp->pr_rect, sp->sizex, sp->sizey, 255);
		}
		else if(idtype == ID_MA) {
			Material* ma = (Material*)id;

			if(ma->material_type == MA_TYPE_HALO)
				set_alpha((char*)sp->pr_rect, sp->sizex, sp->sizey, 255);
		}
	}
}
コード例 #17
0
ファイル: sgtree.hpp プロジェクト: CasparCG/Client
 alpha_holder()
    : max_tree_size_()
 {  set_alpha(0.70711f);   } // ~1/sqrt(2)
コード例 #18
0
// -----------------------------------------------------------------------
// Constructor.
// -----------------------------------------------------------------------
t_combat_area_shader::t_combat_area_shader( t_battlefield & battlefield )
    : t_abstract_combat_object( &battlefield)
{
    set_alpha( battlefield, 5 );
}
コード例 #19
0
ファイル: l2r_l1hinge_spdc.cpp プロジェクト: husk214/rp-velb
void l2r_l1hinge_spdc::train_warm_start_inexact_shrinking(
    const Eigen::VectorXd &alp) {
  set_alpha(alp);
  set_w_by_alpha(alpha_);
  active_size_ = num_ins_;
  int index;
  double alpha_old = 0.0, pg = 0.0;

  // main loop
  for (now_iteration = 1; now_iteration <= max_iteration; ++now_iteration) {
    pg_max_new_ = -inf;
    pg_min_new_ = inf;
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::shuffle(std::begin(active_index_), std::end(active_index_),
                 std::default_random_engine(seed));

    for (int s = 0; s < active_size_; ++s) {
      index = active_index_[s];
      grad_[index] = (y_[index] * (x_.row(index) * w_)(0)) - 1.0;
      if (alpha_[index] == 0.0) {
        if (grad_[index] > pg_max_old_) {
          active_size_--;
          std::iter_swap(std::begin(active_index_) + s,
                         std::begin(active_index_) + active_size_);
          s--;
          continue;
        } else {
          pg = std::min(grad_[index], 0.0);
        }
      } else if (alpha_[index] == C) {
        if (grad_[index] < pg_min_old_) {
          active_size_--;
          std::iter_swap(std::begin(active_index_) + s,
                         std::begin(active_index_) + active_size_);
          s--;
          continue;
        } else {
          pg = std::max(grad_[index], 0.0);
        }
      } else {
        pg = grad_[index];
      }
      pg_max_new_ = std::max(pg_max_new_, pg);
      pg_min_new_ = std::min(pg_min_new_, pg);
      if (fabs(pg) > 1e-12) {
        alpha_old = alpha_[index];
        alpha_[index] = std::min(
            std::max(alpha_[index] - grad_[index] / x_sqnorm_[index], 0.0), C);
        w_ +=
            y_[index] * (alpha_[index] - alpha_old) * x_.row(index).transpose();
      }
    }
    // if (now_iteration % num_ins_ == 0) {
    //   // primal_func_val = get_primal_func(w_);
    //   // dual_func_val = get_dual_func(alpha_);
    //   // duality_gap = primal_func_val - dual_func_val;
    //   std::cout
    //       << "outer_iter: " << now_iteration // << ", max_violation: " <<
    //       max_violation
    //       // << ", f: " << get_primal_func(w_)
    //       // << ", d: " << get_dual_func(alpha_) << ", gap : " <<
    //       duality_gap
    //       << ", active_size_ : " << active_size_ << std::endl;
    // }
    if (pg_max_new_ - pg_min_new_ < stopping_criterion) {
      if (active_size_ == num_ins_) {
        // std::cout << "dcdm shrinking outer iteration : " << now_iteration
        // << std::endl;
        break;
      } else {
        active_size_ = num_ins_;
        pg_max_old_ = inf;
        pg_min_old_ = -inf;
        continue;
      }
    }
    pg_max_old_ = pg_max_new_;
    pg_min_old_ = pg_min_new_;
    if (pg_max_old_ <= 0)
      pg_max_old_ = inf;
    if (pg_min_old_ >= 0)
      pg_min_old_ = -inf;
  }
}
コード例 #20
0
ファイル: mask_image.cpp プロジェクト: BestRCH/magicseteditor
void AlphaMask::setAlpha(Image& img) const {
	if (!alpha) return;
	set_alpha(img, alpha, size);
}
コード例 #21
0
ファイル: sampler.cpp プロジェクト: NetBUG/topicmod
  // Sets hyperparameters from vector containing logs of hyperparameters
void Sampler::SetHyperparameters(const vector<double>& hyperparameters) {
  assert(hyperparameters.size() == 2);
  set_alpha(exp(hyperparameters[0]));
  set_lambda(exp(hyperparameters[1]));
}
コード例 #22
0
widget::widget(const variant& v, game_logic::formula_callable* e) 
	: environ_(e), w_(0), h_(0), x_(0), y_(0), zorder_(0), 
	true_x_(0), true_y_(0), disabled_(false), disabled_opacity_(v["disabled_opacity"].as_int(127)),
	tooltip_displayed_(false), id_(v["id"].as_string_default()), align_h_(HALIGN_LEFT), align_v_(VALIGN_TOP),
	tooltip_display_delay_(v["tooltip_delay"].as_int(500)), tooltip_ticks_(INT_MAX),
	resolution_(v["frame_size"].as_int(0)), display_alpha_(v["alpha"].as_int(256)),
	pad_w_(0), pad_h_(0), claim_mouse_events_(v["claim_mouse_events"].as_bool(true)),
	draw_with_object_shader_(v["draw_with_object_shader"].as_bool(true))
{
	set_alpha(display_alpha_ < 0 ? 0 : (display_alpha_ > 256 ? 256 : display_alpha_));
	if(v.has_key("width")) {
		w_ = v["width"].as_int();
	} 
	if(v.has_key("height")) {
		h_ = v["height"].as_int();
	} 
	if(v.has_key("wh")) {
		std::vector<int> iv = v["wh"].as_list_int();
		ASSERT_LOG(iv.size() == 2, "WH attribute must be 2 integer elements.");
		w_ = iv[0];
		h_ = iv[1];
	}
	if(v.has_key("rect")) {
		std::vector<int> r = v["rect"].as_list_int();
		ASSERT_LOG(r.size() == 4, "Four values must be supplied to the rect attribute");
		set_loc(r[0], r[1]);
		set_dim(r[2], r[3]);
	} 
	if(v.has_key("draw_area")) {
		std::vector<int> r = v["draw_area"].as_list_int();
		ASSERT_LOG(r.size() == 4, "Four values must be supplied to the rect attribute");
		set_loc(r[0], r[1]);
		set_dim(r[2], r[3]);
	} 
	if(v.has_key("x")) {
		true_x_ = x_ = v["x"].as_int();
	} 
	if(v.has_key("y")) {
		true_y_ = y_ = v["y"].as_int();
	}
	if(v.has_key("xy")) {
		std::vector<int> iv = v["xy"].as_list_int();
		ASSERT_LOG(iv.size() == 2, "XY attribute must be 2 integer elements.");
		true_x_ = x_ = iv[0];
		true_y_ = y_ = iv[1];
	}
	zorder_ = v["zorder"].as_int(0);
	if(v.has_key("on_process")) {
		on_process_ = boost::bind(&widget::process_delegate, this);
		ffl_on_process_ = get_environment()->create_formula(v["on_process"]);
	}
	if(v.has_key("tooltip")) {
		if(v["tooltip"].is_string()) {
			SDL_Color color = v.has_key("tooltip_color") ? graphics::color(v["tooltip_color"]).as_sdl_color() : graphics::color_yellow();
			set_tooltip(v["tooltip"].as_string(), v["tooltip_size"].as_int(18), color, v["tooltip_font"].as_string_default());
		} else if(v["tooltip"].is_map()) {
			SDL_Color color = v["tooltip"].has_key("color") ? graphics::color(v["tooltip"]["color"]).as_sdl_color() : graphics::color_yellow();
			set_tooltip(v["tooltip"]["text"].as_string(), v["tooltip"]["size"].as_int(18), color, v["tooltip"]["font"].as_string_default());
		} else {
			ASSERT_LOG(false, "Specify the tooltip as a string, e.g. \"tooltip\":\"Text to display on mouseover\", "
				"or a map, e.g. \"tooltip\":{\"text\":\"Text to display.\", \"size\":14}");
		}
	}
	visible_ = v["visible"].as_bool(true);
	if(v.has_key("align_h")) {
		std::string align = v["align_h"].as_string();
		if(align == "left") {
			align_h_ = HALIGN_LEFT;
		} else if(align == "middle" || align == "center" || align == "centre") {
			align_h_ = HALIGN_CENTER;
		} else if(align == "right") {
			align_h_ = HALIGN_RIGHT;
		} else {
			ASSERT_LOG(false, "Invalid align_h attribute given: " << align);
		}
	}
	if(v.has_key("align_v")) {
		std::string align = v["align_v"].as_string();
		if(align == "top") {
			align_v_ = VALIGN_TOP;
		} else if(align == "middle" || align == "center" || align == "centre") {
			align_v_ = VALIGN_CENTER;
		} else if(align == "bottom") {
			align_v_ = VALIGN_BOTTOM;
		} else {
			ASSERT_LOG(false, "Invalid align_v attribute given: " << align);
		}
	}
	disabled_ = !v["enabled"].as_bool(true);
	if(v.has_key("frame")) {
		set_frame_set(v["frame"].as_string());
	}
	if(v.has_key("frame_padding")) {
		ASSERT_LOG(v["frame_padding"].is_list() && v["frame_padding"].num_elements() == 2, "'pad' must be two element list");
		set_padding(v["frame_padding"][0].as_int(), v["frame_padding"][1].as_int());
	} 
	if(v.has_key("frame_pad_width")) {
		set_padding(v["frame_pad_width"].as_int(), get_pad_height());
	}
	if(v.has_key("frame_pad_height")) {
		set_padding(get_pad_width(), v["frame_pad_height"].as_int());
	}
	recalc_loc();
}
コード例 #23
0
ファイル: KinectDataRenderer.cpp プロジェクト: OpenGP/htrack
void KinectDataRenderer::init(Camera *camera)
{
    this->camera = camera;

    ///--- Create vertex array object
    if(!vao.isCreated()){
        bool success = vao.create();
        assert(success);
        vao.bind();
    }
    
    ///--- Load/compile shaders
    if (!program.isLinked()) {
        const char* vshader = ":/KinectDataRenderer/KinectDataRenderer_vshader.glsl";
        const char* fshader = ":/KinectDataRenderer/KinectDataRenderer_fshader.glsl";
        bool vok = program.addShaderFromSourceFile(QGLShader::Vertex, vshader);
        bool fok = program.addShaderFromSourceFile(QGLShader::Fragment, fshader);
        bool lok = program.link ();
        assert(lok && vok && fok);
        bool success = program.bind();
        assert(success); 
    }
    
    ///--- Used to create connectivity
    Grid grid(camera->width(),camera->height());
    
    ///--- Create vertex buffer/attributes "position"
    {
        bool success = vertexbuffer.create();
        assert(success);
        vertexbuffer.setUsagePattern( QGLBuffer::StaticDraw );
        success = vertexbuffer.bind();
        assert(success);
        vertexbuffer.allocate( grid.vertices.data(), grid.vertices.size() * sizeof(GLfloat) );
        program.setAttributeBuffer("vpoint", GL_FLOAT, 0, 2 );
        program.enableAttributeArray("vpoint");
    }
    
    ///--- Create vertex buffer/attributes "uv"
    {
        bool success = uvbuffer.create();
        assert(success);
        uvbuffer.setUsagePattern( QGLBuffer::StaticDraw );
        success = uvbuffer.bind();
        assert(success);
        uvbuffer.allocate( grid.texcoords.data(), grid.texcoords.size() * sizeof(GLfloat) );
        program.setAttributeBuffer("uv", GL_FLOAT, 0, 2 );
        program.enableAttributeArray("uv");
    }
    
    ///--- Create the index "triangle" buffer
    {
        bool success = indexbuffer.create();
        assert(success);
        indexbuffer.setUsagePattern( QGLBuffer::StaticDraw ); 
        success = indexbuffer.bind();
        assert(success);
        indexbuffer.allocate( grid.indices.data(), grid.indices.size() * sizeof(unsigned int) );
    }   
    
    ///--- Create texture to colormap the point cloud
    {
        // const int sz=2; GLfloat tex[3*sz] = {/*green*/ 0.000, 1.000, 0, /*red*/ 1.000, 0.000, 0,};
        // const int sz=2; GLfloat tex[3*sz] = {/*gray*/ .1, .1, .1, /*black*/ 0.8, 0.8, 0.8};
        const int sz=3; GLfloat tex[3*sz] = {/*red*/ 1.000, 0.000, 0, /*yellow*/ 1.0, 1.0, 0.0, /*green*/ 0.000, 1.000, 0};
        glActiveTexture(GL_TEXTURE2);
        glGenTextures(1, &texture_id_cmap);
        glBindTexture(GL_TEXTURE_1D, texture_id_cmap);
        glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB, sz, 0, GL_RGB, GL_FLOAT, tex);
        glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        program.setUniformValue("colormap", 2 /*GL_TEXTURE2*/);
    }
    
    ///--- @todo upload data to do inverse projection
    set_uniform("inv_proj_matrix",camera->inv_projection_matrix());
    
    ///--- upload near/far planes
    set_zNear(camera->zNear());
    set_zFar(camera->zFar());
    // set_alpha(1.0); ///< default no alpha blending
    set_alpha(.7); ///< default no alpha blending
    set_discard_cosalpha_th(.3);  ///< default sideface clipping
    
    ///--- save for glDrawElements
    num_indexes = grid.indices.size();
    num_vertices = grid.vertices.size();
    
    ///--- Avoid pollution
    program.release();
    vao.release();
}
コード例 #24
0
ファイル: l2r_l1hinge_spdc.cpp プロジェクト: husk214/rp-velb
Eigen::VectorXd
l2r_l1hinge_spdc::train_warm_start_inexact(const Eigen::VectorXd &alp,
                                           const double inexact_level) {
  // Eigen::VectorXd alpha_ = Eigen::VectorXd::Zero(num_ins_); // alp;
  set_alpha(alp);
  set_w_by_alpha(alpha_);

  active_size_ = num_ins_;
  int index;
  double alpha_old = 0.0, pg = 0.0;
  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();

  // main loop
  for (int iter = 1; iter <= max_iteration; ++iter) {
    pg_max_new_ = -inf;
    pg_min_new_ = inf;
    std::shuffle(std::begin(active_index_), std::end(active_index_),
                 std::default_random_engine(seed));

    for (int s = 0; s < active_size_; ++s) {
      index = active_index_[s];
      grad_[index] = (y_[index] * (x_.row(index) * w_)(0)) - 1.0;
      pg = 0.0;
      if (alpha_[index] == 0.0) {
        if (grad_[index] > pg_max_old_) {
          active_size_--;
          std::iter_swap(std::begin(active_index_) + s,
                         std::begin(active_index_) + active_size_);
          s--;
          continue;
        } else {
          pg = std::min(grad_[index], 0.0);
        }
      } else if (alpha_[index] == C) {
        if (grad_[index] < pg_min_old_) {
          active_size_--;
          std::iter_swap(std::begin(active_index_) + s,
                         std::begin(active_index_) + active_size_);
          s--;
          continue;
        } else {
          pg = std::max(grad_[index], 0.0);
        }
      } else {
        pg = grad_[index];
      }
      pg_max_new_ = std::max(pg_max_new_, pg);
      pg_min_new_ = std::min(pg_min_new_, pg);
      if (fabs(pg) > 1e-12) {
        alpha_old = alpha_[index];
        alpha_[index] = std::min(
            std::max(alpha_[index] - grad_[index] / x_sqnorm_[index], 0.0), C);
        w_ +=
            y_[index] * (alpha_[index] - alpha_old) * x_.row(index).transpose();
      }
    }
    if (pg_max_new_ - pg_min_new_ < stopping_criterion) {
      if (active_size_ == num_ins_) {
        break;
      } else {
        active_size_ = num_ins_;
        pg_max_old_ = inf;
        pg_min_old_ = -inf;
        continue;
      }
    }
    pg_max_old_ = pg_max_new_;
    pg_min_old_ = pg_min_new_;
    if (pg_max_old_ <= 0)
      pg_max_old_ = inf;
    if (pg_min_old_ >= 0)
      pg_min_old_ = -inf;
  }
  return w_;
}
コード例 #25
0
bool me::WindowManager::handle_pointer_event(MirPointerEvent const* pev)
{
    bool handled = false;

    geometry::Point cursor{mir_pointer_event_axis_value(pev, mir_pointer_axis_x),
                           mir_pointer_event_axis_value(pev, mir_pointer_axis_y)};
    auto action = mir_pointer_event_action(pev);
    auto modifiers = mir_pointer_event_modifiers(pev);
    auto vscroll = mir_pointer_event_axis_value(pev, mir_pointer_axis_vscroll);
    auto primary_button_pressed = mir_pointer_event_button_state(pev, mir_pointer_button_primary);
    auto tertiary_button_pressed = mir_pointer_event_button_state(pev, mir_pointer_button_tertiary);

    float new_zoom_mag = 0.0f;  // zero means unchanged

   if (modifiers & mir_input_event_modifier_meta &&
       action == mir_pointer_action_motion)
   {
        zoom_exponent += vscroll;

        // Negative exponents do work too, but disable them until
        // there's a clear edge to the desktop.
        if (zoom_exponent < 0)
            zoom_exponent = 0;
    
        new_zoom_mag = powf(1.2f, zoom_exponent);
        handled = true;
    }

    me::DemoCompositor::for_each(
        [new_zoom_mag,&cursor](me::DemoCompositor& c)
        {
            if (new_zoom_mag > 0.0f)
                c.zoom(new_zoom_mag);
            c.on_cursor_movement(cursor);
        });

    if (zoom_exponent || new_zoom_mag)
        force_redraw();

    auto const surf = focus_controller->focused_surface();
    if (surf &&
        (modifiers & mir_input_event_modifier_alt) && (primary_button_pressed || tertiary_button_pressed))
    {
        // Start of a gesture: When the latest finger/button goes down
        if (action == mir_pointer_action_button_down)
        {
            click = cursor;
            save_edges(*surf, click);
            handled = true;
        }
        else if (action == mir_pointer_action_motion)
        {
            geometry::Displacement drag = cursor - old_cursor;

            if (tertiary_button_pressed)
            {  // Resize by mouse middle button
                resize(*surf, cursor);
            }
            else
            {
                surf->move_to(old_pos + drag);
            }

            handled = true;
        }

        old_pos = surf->top_left();
        old_size = surf->size();
    }

    if (surf && 
        (modifiers & mir_input_event_modifier_alt) &&
        action == mir_pointer_action_motion &&
        vscroll)
    {
        float alpha = surf->alpha();
        alpha += 0.1f * vscroll;
        if (alpha < 0.0f)
            alpha = 0.0f;
        else if (alpha > 1.0f)
            alpha = 1.0f;
        surf->set_alpha(alpha);
        handled = true;
    }

    old_cursor = cursor;
    return handled;
}
コード例 #26
0
ファイル: visualizer.cpp プロジェクト: sjt85/software
int main(int argc, char **argv) {
  std::string model_filename;
  if (argc < 2) {
    model_filename = getBinDir() + BIN2CONFIG + DEFAULT_CONFIG;
  }
  else {
    model_filename = argv[1];
  }

  shm_init();
  glfwSetErrorCallback(error_callback);
  if (!glfwInit()) {
    return -1;
  }

  glfwWindowHint(GLFW_SAMPLES, 4); // TODO how many samples?
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  GLFWwindow *window = glfwCreateWindow(DEFAULT_WIDTH, DEFAULT_HEIGHT,
                                      "CUAUV Visualizer " VERSION, NULL, NULL);
  if (!window) {
    fprintf(stderr, "ERROR: Failed to create window.\n");
    return -1;
  }

  glfwMakeContextCurrent(window);

  if (init_engine(true, true)) {
    fprintf(stderr, "ERROR: Failed to initalize graphics engine.\n");
    return -1;
  }

  cam.direction = NORTH;
  cam.up = UP;
  cam.width = DEFAULT_WIDTH;
  cam.height = DEFAULT_HEIGHT;
  cam.fov = 1.0;

  libconfig::Config config;
  config.setOptions(libconfig::Setting::OptionAutoConvert);
  try {
    config.readFile(model_filename.c_str());
  }
  catch (libconfig::ParseException &pe) {
    fprintf(stderr, "ERROR parsing config file %s:%d %s\n",
            pe.getFile(), pe.getLine(), pe.getError());
    return -1;
  }

  std::unordered_map<std::string, GLuint> texture_map;

  auto &objects = config.lookup("objects");
  for (const auto &object : objects) {
    std::string name("Poor nameless object");
    object.lookupValue("name", name);

    std::unique_ptr<SceneObject> scene_object;

    bool is_sub = (object.exists("sub") && ((bool)object.lookup("sub")) == true)
                  || objects.getLength() == 1;
    if (!object.exists("model")) {
      scene_object = std::make_unique<SceneObject>();
      if (!scene_object) {
        fprintf(stderr, "ERROR: Could not allocate memory for SceneObject!\n");
        continue;
      }

      load_axes(scene_object.get());
    }

    else {
      auto mesh_object = std::make_unique<MeshObject>();
      if (!mesh_object) {
        fprintf(stderr, "ERROR: Could not allocate memory for MeshObject!\n");
        continue;
      }
      std::string mesh_name = object.lookup("model");

      auto get_file_name = [] (const std::string &filename, const char *folder) {
        if (filename[0] == '/') {
          return filename;
        }
        return getBinDir() + folder + filename;
      };

      if (load_model(get_file_name(mesh_name, BIN2DATA), mesh_object.get())) {
        fprintf(stderr, "ERROR: failed to make model \"%s\".\n", mesh_name.c_str());
      }

      if (object.exists("texture")) {
        std::string texture = object.lookup("texture");
        if (texture_map.find(texture) == texture_map.end()) {
          GLuint texture_ind;
          if (load_texture(get_file_name(texture, BIN2TEXTURES), texture_ind)) {
            fprintf(stderr, "WARNING: texture \"%s\" failed to load.\n", texture.c_str());
          }

          texture_map[texture] = texture_ind;
        }

        mesh_object->set_texture(texture_map[texture]);
      }

      if (object.exists("alpha")) {
        mesh_object->set_alpha(object.lookup("alpha"));
      }

      scene_object = std::move(mesh_object);
    }

    auto grab_vec = [&object, &name] (const std::string &att_name, glm::vec3 id_v) -> std::function<glm::vec3()> {
      auto id = [id_v] { return id_v; };
      if (object.exists(att_name)) {
        auto &att = object.lookup(att_name);
        if (att.getLength() == 3) {
          glm::vec3 vec(att[0], att[1], att[2]);
          return [vec] { return vec; };
        }
        std::string att_s = att;
        if (att_s == "kalman") {
          return get_sub_position;
        }
        else {
          fprintf(stderr, "ERROR: Invalid %s for object \"%s\".\n", att_name.c_str(), name.c_str());
        }
      }
      else {
        return id;
      }
      return id;
    };

    auto grab_orientation = [&object, &name] (const std::string &att_prefix) -> std::function<glm::fquat()> {
      auto id = [] { return quat_from_hpr(0, 0, 0); };
      if (object.exists(att_prefix + "_hpr")) {
        auto &att = object.lookup(att_prefix + "_hpr");
        if (att.getLength() == 3) {
          glm::fquat q = quat_from_hpr(att[0], att[1], att[2]);
          return [q] { return q; };
        }
        std::string att_s = att;
        if (att_s == "desires") {
          return get_desire_quat;
        }
        else {
          fprintf(stderr, "ERROR: Invalid orientation_hpr for object \"%s\".\n", name.c_str());
        }
      }
      else if (object.exists(att_prefix + "_q")) {
        std::string att_s = object.lookup(att_prefix + "_q");
        if (att_s == "kalman") {
          return get_sub_quat;
        }
        else {
          fprintf(stderr, "ERROR: Invalid orientation_q for object \"%s\".\n", name.c_str());
        }
      }

      return id;
    };

    scene_object->get_position = grab_vec("position", glm::vec3(0, 0, 0));

    auto orient_f = grab_orientation("orientation");
    scene_object->get_orientation = [orient_f] () {
      return orient_f();
    };
    auto mesh_f = grab_orientation("mesh_offset");
    scene_object->mesh_offset = mesh_f();

    scene_object->get_scale = grab_vec("scale", glm::vec3(1, 1, 1));

    if (object.exists("exclude_renders")) {
      auto &excludes = object.lookup("exclude_renders");
      for (const auto &render : excludes) {
        std::unordered_map<std::string, char> value_map = {
          {"main", RENDER_MAIN},
          {"offscreen", RENDER_OFFSCREEN},
          {"shadow", RENDER_SHADOW}
        };

        if (value_map.find(render) == value_map.end()) {
          std::string s;
          for (const auto &pair : value_map) {
            s += pair.first + " ";
          }

          fprintf(stderr, "WARNING: Invalid exclude_renders for object \"%s\". "
                          "Possible values are: %s\n", name.c_str(), s.c_str());
        }
        else {
          scene_object->exclude |= value_map[render];
        }
      }
    }

    if (object.exists("camera_attachments")) {
      if (!load_vision_link_lib()) {
        auto &cams = object.lookup("camera_attachments");
        for (const auto &cam : cams) {
          auto &pos = cam.lookup("pos");
          auto &orient = cam.lookup("orientation");

          unsigned int width = DEFAULT_WIDTH;
          unsigned int height = DEFAULT_HEIGHT;
          float fov = 1.0;
          cam.lookupValue("width", width);
          cam.lookupValue("height", height);
          cam.lookupValue("fov", fov);

          add_sub_camera(cam.lookup("name"), width, height, fov,
                         glm::vec3(pos[0], pos[1], pos[2]),
                         quat_from_hpr(orient[0], orient[1], orient[2]));
        }
      }
      else {
        fprintf(stderr, "WARNING: Loading vision link library failed; "
                        "vision output unavailable.\n");
      }
    }

    if (is_sub) {
      sub = scene_object.get();
    }

    scene_objects.push_back(std::move(scene_object));
  }

  if (!sub) {
    fprintf(stderr, "WARNING: no sub designated; sub follow mode will not work.\n");
  }

  add_light(&light1);
  add_light(&light2);

  glfwSetFramebufferSizeCallback(window, reshape_callback);
  glfwSetKeyCallback(window, key_callback);
  glfwSetCursorPosCallback(window, [] (GLFWwindow *w, double x, double y) {
    mouse_handlers[mouse_state](w, x, y);
  });

  glClearColor(0.0, 0.0, 0.0, 1.0);
  glClearDepth(1.0);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
  glEnable(GL_TEXTURE_2D);
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  mouse_move_mode_off(window);

  mouse_handlers[MOUSE] = handle_mouse_move;
  mouse_handlers[FIXED] = [] (GLFWwindow *w, int x, int y) {};
  register_action(GLFW_KEY_M, [window] {
    if (mouse_state == MOUSE) {
      mouse_move_mode_off(window);
    }
    else {
      mouse_move_mode_on(window);
    }
  });

  register_action(GLFW_KEY_F, [] {
    if (sub) {
      sub_follow = !sub_follow;
      if (sub_follow) {
        cam.up = UP;
      }
    }
  });
  register_action(GLFW_KEY_H, [] {
    heading_lock = !heading_lock;
    if (heading_lock) {
      cam_angle = 0.0;
    }
  });

  register_action(GLFW_KEY_X, toggle_skybox);
  register_action(GLFW_KEY_Z, toggle_shadows);
  register_action(GLFW_KEY_V, toggle_offscreen_rendering);
  register_action(GLFW_KEY_ESCAPE, [window] () { mouse_move_mode_off(window); });

  int width, height;
  glfwGetFramebufferSize(window, &width, &height);
  reshape_callback(window, width, height);

  draw_loop(window);

  glfwDestroyWindow(window);
  glfwTerminate();
  return 0;
}
コード例 #27
0
static void icon_preview_startjob(void *customdata, short *stop, short *do_update)
{
	ShaderPreview *sp = customdata;

	if (sp->pr_method == PR_ICON_DEFERRED) {
		PreviewImage *prv = sp->owner;
		ImBuf *thumb;
		char *deferred_data = PRV_DEFERRED_DATA(prv);
		int source =  deferred_data[0];
		char *path = &deferred_data[1];

//		printf("generating deferred %d×%d preview for %s\n", sp->sizex, sp->sizey, path);

		thumb = IMB_thumb_manage(path, THB_LARGE, source);

		if (thumb) {
			/* PreviewImage assumes premultiplied alhpa... */
			IMB_premultiply_alpha(thumb);

			icon_copy_rect(thumb, sp->sizex, sp->sizey, sp->pr_rect);
			IMB_freeImBuf(thumb);
		}
	}
	else {
		ID *id = sp->id;
		short idtype = GS(id->name);

		if (idtype == ID_IM) {
			Image *ima = (Image *)id;
			ImBuf *ibuf = NULL;
			ImageUser iuser = {NULL};

			/* ima->ok is zero when Image cannot load */
			if (ima == NULL || ima->ok == 0)
				return;

			/* setup dummy image user */
			iuser.ok = iuser.framenr = 1;
			iuser.scene = sp->scene;

			/* elubie: this needs to be changed: here image is always loaded if not
			 * already there. Very expensive for large images. Need to find a way to
			 * only get existing ibuf */
			ibuf = BKE_image_acquire_ibuf(ima, &iuser, NULL);
			if (ibuf == NULL || ibuf->rect == NULL) {
				BKE_image_release_ibuf(ima, ibuf, NULL);
				return;
			}

			icon_copy_rect(ibuf, sp->sizex, sp->sizey, sp->pr_rect);

			*do_update = true;

			BKE_image_release_ibuf(ima, ibuf, NULL);
		}
		else if (idtype == ID_BR) {
			Brush *br = (Brush *)id;

			br->icon_imbuf = get_brush_icon(br);

			memset(sp->pr_rect, 0x88, sp->sizex * sp->sizey * sizeof(unsigned int));

			if (!(br->icon_imbuf) || !(br->icon_imbuf->rect))
				return;

			icon_copy_rect(br->icon_imbuf, sp->sizex, sp->sizey, sp->pr_rect);

			*do_update = true;
		}
		else {
			/* re-use shader job */
			shader_preview_startjob(customdata, stop, do_update);

			/* world is rendered with alpha=0, so it wasn't displayed
			 * this could be render option for sky to, for later */
			if (idtype == ID_WO) {
				set_alpha((char *)sp->pr_rect, sp->sizex, sp->sizey, 255);
			}
			else if (idtype == ID_MA) {
				Material *ma = (Material *)id;

				if (ma->material_type == MA_TYPE_HALO)
					set_alpha((char *)sp->pr_rect, sp->sizex, sp->sizey, 255);
			}
		}
	}
}
コード例 #28
0
 alpha_holder() : max_tree_size_(0)
 {  set_alpha(0.7f);   }
コード例 #29
0
ファイル: model_e42m.cpp プロジェクト: dimalit/ode-env
E42mConfig::E42mConfig(){
	set_n(1000);
	set_delta_0(0);
	set_alpha(0);
}