Пример #1
0
/* submenu for changing numeric values */
static void value_submenu(menu_t *menu, unsigned int itemid) {
  mark_value(menu, itemid, MENUMARKER_LEFT);

  while (1) {
    /* wait for input */
    while (!pad_buttons) ;

    unsigned int curbtns = pad_buttons;

    /* value change */
    if (curbtns & PAD_LEFT) {
      update_value(menu, itemid, UPDATE_DECREMENT);
      pad_clear(PAD_LEFT | PAD_UP | PAD_DOWN); // prioritize left/right
    }

    if (curbtns & PAD_RIGHT) {
      update_value(menu, itemid, UPDATE_INCREMENT);
      pad_clear(PAD_RIGHT | PAD_UP | PAD_DOWN); // prioritize left/right
    }

    /* exit with X/Y */
    if (curbtns & (PAD_X | PAD_Y))
      break;

    /* video mode change is ignored */
  }
  pad_clear(PAD_START | PAD_X | PAD_Y |
            PAD_LEFT | PAD_RIGHT | PAD_UP | PAD_DOWN |
            PAD_Z | PAD_L | PAD_R | PAD_A | PAD_B);

  mark_value(menu, itemid, ' ');
}
Пример #2
0
void	do_setenv(char **t, t_env *env)
{
  t_env_node	*node;
  char	*value;
  int	i;

  if (t[1] == NULL || t[2] == NULL)
    return;
  i = 3;
  value = my_strdup(t[2]);
  while (t[i] != NULL)
  {
    value = my_strcat(value, my_strdup(" "));
    value = my_strcat(value, my_strdup(t[i++]));
  }
  value = trim_quote(value);
  node = find_node(env->list, t[1]);
  if (node == NULL)
    node = append_new(env->list, t[1], value);
  else
    update_value(env->list, t[1], value);
  if (env->list == NULL)
    env->list = node;
  clean_wordtab(env->environ);
  env->environ = convert_to_tab(env->list);
  free(value);
}
Пример #3
0
DensityGrid get_rasterized_fast(const Gaussian3Ds &gmm, const Floats &weights,
                                double cell_width, const BoundingBox3D &bb, double factor) {
  DensityGrid ret(cell_width, bb, 0);
  for (unsigned int ng = 0; ng < gmm.size(); ng++) {
    Eigen::Matrix3d covar = get_covariance(gmm[ng]);
    Eigen::Matrix3d inverse = Eigen::Matrix3d::Zero(3, 3);

    double determinant;
    bool invertible;
    covar.computeInverseAndDetWithCheck(inverse, determinant, invertible);
    IMP_INTERNAL_CHECK((invertible && determinant > 0),
                       "Tried to invert Gaussian, but it's not proper matrix");
    double pre(get_gaussian_eval_prefactor(determinant));
    Eigen::Vector3d evals = covar.eigenvalues().real();
    double maxeval = sqrt(evals.maxCoeff());
    double cutoff = factor * maxeval;
    double cutoff2 = cutoff * cutoff;
    Vector3D c = gmm[ng].get_center();
    Vector3D lower = c - Vector3D(cutoff, cutoff, cutoff);
    Vector3D upper = c + Vector3D(cutoff, cutoff, cutoff);
    GridIndex3D lowerindex = ret.get_nearest_index(lower);
    GridIndex3D upperindex = ret.get_nearest_index(upper);
    Eigen::Vector3d center(c.get_data());
    IMP_INTERNAL_CHECK(invertible, "matrix wasn't invertible! uh oh!");
    IMP_GRID3D_FOREACH_SMALLER_EXTENDED_INDEX_RANGE(ret, upperindex, lowerindex,
                                                    upperindex, {
      GridIndex3D i(voxel_index[0], voxel_index[1], voxel_index[2]);
      Eigen::Vector3d r(get_vec_from_center(i, ret, center));
      if (r.squaredNorm() < cutoff2) {
        update_value(&ret, i, r, inverse, pre, weights[ng]);
      }
    })
  }
  return ret;
}
Пример #4
0
static int
pointer_event(glw_t *w, const glw_pointer_event_t *gpe)
{
  glw_root_t *gr = w->glw_root;
  glw_slider_t *s = (glw_slider_t *)w;
  int hitpos = 0;
  float v0 = w->glw_class == &glw_slider_x ? gpe->x : -gpe->y;
  float v = 0;
  float knob_pos;
  float knob_size = (float)s->knob_size_px / s->slider_size_px;
  int how = PROP_SET_NORMAL;

  if(w->glw_class == &glw_slider_x) {
    knob_pos = -1 + 2.0 * (float)s->knob_pos_px  / s->slider_size_px;
  } else {
    knob_pos =  1 - 2.0 * (float)s->knob_pos_px  / s->slider_size_px;
  }

  if(v0 < knob_pos - knob_size)
    hitpos = -1;
  else if(v0 > knob_pos + knob_size)
    hitpos = 1;
  
  switch(gpe->type) {
  case GLW_POINTER_LEFT_PRESS:
    if(w->glw_flags2 & GLW2_ALWAYS_GRAB_KNOB) {
      v = GLW_RESCALE(v0 + s->grab_delta,
		      -1.0 + knob_size, 1.0 - knob_size);
      gr->gr_pointer_grab = w;
    } else if(hitpos == 0) {
      s->grab_delta = knob_pos - v0;
      gr->gr_pointer_grab = w;
      v = s->value;
    } else {
      update_value_delta(s, hitpos * knob_size);
      return 0;
    }
    how = PROP_SET_TENTATIVE;
    break;

  case GLW_POINTER_FOCUS_MOTION:
    if(knob_size == 1.0)
      break;
    v = GLW_RESCALE(v0 + s->grab_delta, 
		    -1.0 + knob_size, 1.0 - knob_size);
    how = PROP_SET_TENTATIVE;
    break;

  case GLW_POINTER_LEFT_RELEASE:
    v = s->value;
    how = PROP_SET_COMMIT;
    break;

  default:
    return 0;
  }
  update_value(s, v, how);
  return 0;
}
Пример #5
0
// ----------------------------------------------------------------------------
// -- Function    : public Draw(cr)
// --
// -- Takes       : cr = a cairo context
// --
// -- Purpose     : This is called by our parent, and it signals that we need to
//                  update our value and redraw ourselves.
void BarWidget::Draw(Cairo::RefPtr<Cairo::Context> cr)
{
    // First, update our internal value
    update_value();
    // Then draw our bg and border (Parent method)
    draw_bg_and_border(cr);
    // Then draw our bar
    draw_bar(cr);
}
Пример #6
0
void CCalcEdit::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
	//TRACE("xxxx0 OnKeyD: sel = %x\r\n", GetSel());
	in_edit_ = true;
	ASSERT(pp_ != NULL && pp_->IsVisible());

	// Clear any result (unless arrows etc pressed)
	clear_result((nFlags & 0x100) == 0 && isprint(nChar));

	// If editing an integer then make allowances for separator char
	if (pp_->state_ == CALCINTLIT)
	{
		CString ss;                         // Text from the window (edit control)
		int start, end;                     // Current selection in the edit control

		// Set selection so that arrows/Del work OK in presence of separator chars
		GetWindowText(ss);
		GetSel(start, end);

		char sep_char = ' ';
		if (pp_->radix_ == 10) sep_char = theApp.dec_sep_char_;

		// If no selection and character to delete is separator ...
		if (nChar == VK_DELETE && start == end && start < ss.GetLength() - 1 && ss[start+1] == sep_char)
		{
			// Set selection so that the separator and following digit is deleted
			SetSel(start, start+2);
		}
		else if (nChar == VK_LEFT && start == end && start > 0 && ss[start-1] == sep_char)
		{
			// Move cursor back one so we skip over the separator (else add_sep below makes the caret stuck)
			SetSel(start-1, start-1);
		}
		else if (nChar == VK_RIGHT && start == end && start < ss.GetLength() - 1 && ss[start+1] == sep_char)
		{
			// Move cursor back one so we skip over the separator (else add_sep below makes the caret stuck)
			SetSel(start+1, start+1);
		}
	}

	CEdit::OnKeyDown(nChar, nRepCnt, nFlags);

	if (nChar == VK_DELETE)
	{
		// This is handled similarly to OnChar since Del key changes the text
		get();
		pp_->state_ = update_value(false);
		pp_->check_for_error();
		add_sep();
		get();
		pp_->set_right();
		pp_->inedit(km_user_str);
		pp_->ctl_calc_bits_.RedrawWindow();
	}
	in_edit_ = false;
	//TRACE("xxxx1 OnKeyD: sel = %x\r\n", GetSel());
}
Пример #7
0
ledcalc::ledcalc(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ledcalc)
{
    ui->setupUi(this);
    QList <QPushButton *> widgets=this->findChildren<QPushButton *>();
    foreach (QPushButton * widget, widgets) {
        widget->setCheckable(1);
        connect(widget,SIGNAL(clicked()),this,SLOT(update_value()));
    }
Пример #8
0
static void client_timer(evutil_socket_t fd, short event, void* arg) {
  struct client* client = arg;
  struct enabled_mod* lm = client->mods;
  while (lm) {
    char databuf[BUFSIZ];
    if (update_value(lm->module, databuf, sizeof(databuf), client))
      client_send_data(client, "%s: %s", lm->module->name, databuf);
    lm = lm->next;
  };
};
Пример #9
0
int mdhim_mysql_batch_put(void *dbh, void **keys, int32_t *key_lens, 
			    void **data, int32_t *data_lens, int num_records) {
	struct MDI *x = (struct MDI *)(dbh);
	MYSQL *db = (MYSQL *) x->msqdb;
	 if (db == NULL) 
	  {
	      fprintf(stderr, "%s\n", mysql_error(db));
	      return MDHIM_DB_ERROR;
	  }
	int i;
	struct timeval start, end;
		gettimeofday(&start, NULL);	
	char *table_name = x->table;
	char *query=NULL;
	//Insert X amount of Keys and Values
	printf("Number records: %d\n", num_records);
	for (i = 0; i < num_records; i++) {
		query = put_value(db, keys[i], key_lens[i], data[i], data_lens[i], table_name, x->msqkt);
	printf("\nThis is the query: \n%s\n", query);

	    if  (mysql_real_query(db, query, sizeof(char)*strlen(query)))  {
			int check_er = mysql_errno(db);
		    //printf("\nThis is the error number: %d\n", check_er);
			if (check_er == 1062){
				memset(query, 0, sizeof(char)*strlen(query));
				query = update_value(db, keys[i], key_lens[i], data[i], data_lens[i], table_name, x->msqkt);
				//printf("\nThis is the query: \n%s\n", query);

			if  (mysql_real_query(db, query, sizeof(char)*strlen(query)))  {
				//printf("This is the query: %s\n", query);
		   		mlog(MDHIM_SERVER_CRIT, "Error updating key/value in mysql\n");
		    		fprintf(stderr, "%s\n", mysql_error(db));
			return MDHIM_DB_ERROR;
					}
			//else printf("Sucessfully updated key/value in mdhim\n");
			}
		else {
		mlog(MDHIM_SERVER_CRIT, "Error putting key/value in mysql\n");
		    fprintf(stderr, "%s\n", mysql_error(db));
			return MDHIM_DB_ERROR;
			}
	    }

		memset(query, 0, sizeof(query));
	}

	//Report timing
	gettimeofday(&end, NULL);
	mlog(MDHIM_SERVER_DBG, "Took: %d seconds to put %d records", 
	     (int) (end.tv_sec - start.tv_sec), num_records);
	return MDHIM_SUCCESS; 
} 
Пример #10
0
/**
 * mdhim_mysql_put
 * Stores a single key in the data store
 *
 * @param dbh         in   pointer to the mysql struct which points to the handle
 * @param key         in   void * to the key to store
 * @param key_len     in   length of the key
 * @param data        in   void * to the value of the key
 * @param data_len    in   length of the value data 
 * @param mstore_opts in   additional options for the data store layer 
 * 
 * @return MDHIM_SUCCESS on success or MDHIM_DB_ERROR on failure
 */
int mdhim_mysql_put(void *dbh, void *key, int key_len, void *data, int32_t data_len) {
	
	struct timeval start, end;
	//printf("In put function\n");
	struct MDI *x = (struct MDI *)(dbh);
	MYSQL *db = x->msqdb;
	 if (db == NULL) 
	  {
	      fprintf(stderr, "%s\n", mysql_error(db));
	      return MDHIM_DB_ERROR;
	  }
	char *table_name;
		table_name = x->table;

	gettimeofday(&start, NULL);
	char *query;    
	//Insert key and value into table
	query = put_value(db, key, key_len, data, data_len, table_name, x->msqkt);
	//printf("\nThis is the query: \n%s\n", query);

    if  (mysql_real_query(db, query, sizeof(char)*strlen(query)))  {
		int check_er = mysql_errno(db);
	    //printf("\nThis is the error number: %d\n", check_er);
		if (check_er == 1062){
			memset(query, 0, sizeof(char)*strlen(query));
			query = update_value(db, key, key_len, data, data_len, table_name, x->msqkt);
		//printf("\nThis is the query: \n%s\n", query);


		if  (mysql_real_query(db, query, sizeof(char)*strlen(query)))  {
			//printf("This is the query: %s\n", query);
	   		mlog(MDHIM_SERVER_CRIT, "Error updating key/value in mysql\n");
	    		fprintf(stderr, "%s\n", mysql_error(db));
		return MDHIM_DB_ERROR;
				}
		//else printf("Sucessfully updated key/value in mdhim\n");
		}
	else {
		mlog(MDHIM_SERVER_CRIT, "Error putting key/value in mysql\nHere is the command:%s\n",query);
		    fprintf(stderr, "%s\n", mysql_error(db));
			return MDHIM_DB_ERROR;
			}
    }
	//Report timing
   	gettimeofday(&end, NULL);
    	mlog(MDHIM_SERVER_DBG, "Took: %d seconds to put the record", 
	(int) (end.tv_sec - start.tv_sec));
    return MDHIM_SUCCESS;
}
Пример #11
0
// When the edit box is displaying a result (eg, state_ == CALCINTRES etc)
// this changes the state_ to allow editing (eg CALCINTLIT) and also gives the 
// option to clear the edit box in preparation for a new value being entered.
void CCalcEdit::clear_result(bool clear /* = true */)
{
	if (pp_->state_ < CALCINTLIT || pp_->state_ >= CALCOTHRES)
	{
		if (clear)
		{
			TRACE("++++++ Clr: CLEARED RESULT FROM EDIT BOX\r\n");
			SetWindowText("");
		}

		TRACE("++++++ Now: editable <%s>\r\n", pp_->state_ < CALCINTLIT ? "int" : "");
		if (pp_->state_ < CALCINTLIT)
			pp_->state_ = CALCINTLIT;
		else if (pp_->state_ >= CALCOTHRES)
			pp_->state_ = update_value(false);
	}
}
Пример #12
0
void CCalcEdit::OnEnChange()
{
	if (!in_edit_)
	{
		// Update internals (state_, current_ etc) from the current edit box text
		get();
		pp_->state_ = update_value(false);
		pp_->check_for_error();
		add_sep();        // fix display of integers in edit box

		// Update the expression to be displayed
		get();
		pp_->set_right();
		pp_->ctl_calc_bits_.RedrawWindow();  // bit display

		pp_->inedit(km_user_str);            // macro
	}
}
Пример #13
0
int udhcpc_main(int argc, char **argv)
{
	if (check_action() != ACT_IDLE)
		return -1;

	if (!argv[1])
		return EINVAL;
	else if (strstr(argv[1], "deconfig"))
		return deconfig();
	else if (strstr(argv[1], "bound"))
		return bound();
	else if (strstr(argv[1], "renew"))
		return renew();
	else if (strstr(argv[1], "update"))
		return update_value();
	else
		return EINVAL;
}
Пример #14
0
void CCalcEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
	//TRACE("xxxx0 OnChar: sel = %x\r\n", GetSel());
	in_edit_ = true;
	ASSERT(pp_ != NULL && pp_->IsVisible());
	clear_result();					// Clear text if previous result is displayed

	// If editing an integer then make allowances for separator char
	if (pp_->state_ == CALCINTLIT)
	{
		CString ss;                         // Text from the window (edit control)
		int start, end;                     // Current selection in the edit control

		// Set selection so that arrows/Del work OK in presence of separator chars
		GetWindowText(ss);
		GetSel(start, end);

		char sep_char = ' ';
		if (pp_->radix_ == 10) sep_char = theApp.dec_sep_char_;

		if (nChar == '\b' && start > 1 && start == end && ss[start-1] == sep_char)
		{
			// If deleting 1st char of group then also delete preceding sep_char
			SetSel(start-2, end);
		}
	}
	
	CEdit::OnChar(nChar, nRepCnt, nFlags);

	// Update internals (state_, current_ etc) from the current edit box text
	get();
	pp_->state_ = update_value(false);
	pp_->check_for_error();
	add_sep();        // fix display of integers in edit box

	// Update the expression to be displayed
	get();
	pp_->set_right();

	pp_->inedit(km_user_str);
	pp_->ctl_calc_bits_.RedrawWindow();
	in_edit_ = false;
	//TRACE("xxxx1 OnChar: sel = %x\r\n", GetSel());
}
Пример #15
0
/**
 * \brief Remove the value in the selected field.
 */
void bf::item_field_edit::delete_selected_field()
{
  long index = GetFocusedItem();

  if ( index != wxNOT_FOUND )
    {
      std::string name;

      if ( get_field_name(index, name) )
        {
          m_last_edited_field = name;
          delete_item_field_event event
            ( name, delete_item_field_event::delete_field_event_type, GetId() );
          event.SetEventObject(this);

          if ( ProcessEvent(event) )
            update_value(index);
        }
    }
} // item_field_edit::delete_selected_field()
Пример #16
0
void zoom_out()
{
	char buf[16];
	if (reflow_mode)
	{
		rscale = (rscale > 200) ? rscale - 100 : rscale - 50;
		if (rscale < 150) rscale = 500;
		out_page(1);
		return;
	}
	int ssc = scale;
	update_value(&scale, -1, SC_DIRECT);
	if (ssc >= 200)
	{
		offx = (offx * scale) / ssc;
		offy = (offy * scale) / ssc;
	}
	sprintf(buf, "%i%%", scale);
	draw_jump_info(buf);
	SetHardTimer("ZOOM", zoom_timer, 1000);
}
Пример #17
0
DensityGrid get_rasterized(const Gaussian3Ds &gmm, const Floats &weights,
                           double cell_width, const BoundingBox3D &bb) {
  DensityGrid ret(cell_width, bb, 0);
  for (unsigned int ng = 0; ng < gmm.size(); ng++) {
    Eigen::Matrix3d covar = get_covariance(gmm[ng]);
    Eigen::Matrix3d inverse = Eigen::Matrix3d::Zero(3, 3);

    double determinant;
    bool invertible;
    covar.computeInverseAndDetWithCheck(inverse, determinant, invertible);
    IMP_INTERNAL_CHECK((invertible && determinant > 0),
                       "Tried to invert Gaussian, but it's not proper matrix");
    double pre(get_gaussian_eval_prefactor(determinant));
    Eigen::Vector3d center(gmm[ng].get_center().get_data());
    IMP_INTERNAL_CHECK(invertible, "matrix wasn't invertible! uh oh!");
    IMP_FOREACH(const DensityGrid::Index & i, ret.get_all_indexes()) {
      Eigen::Vector3d r(get_vec_from_center(i, ret, center));
      update_value(&ret, i, r, inverse, pre, weights[ng]);
    }
  }
  return ret;
}
Пример #18
0
void update_value(UBYTE mode, UBYTE line, UWORD value)
{
  if(mode == 0) {
    switch(line)
      {
      case 0: /* global_On_Off */
	soundReg->control.global_On_Off = value;
	NR52_REG = ((UBYTE *)soundReg)[0x16];
	break;
      case 1: /* Vin_SO1 */
	soundReg->control.Vin_SO1 = value;
	NR50_REG = ((UBYTE *)soundReg)[0x14];
	break;
      case 2: /* Vin_SO2 */
	soundReg->control.Vin_SO2 = value;
	NR50_REG = ((UBYTE *)soundReg)[0x14];
	break;
      case 3: /* SO1_OutputLevel */
	soundReg->control.SO1_OutputLevel = value;
	NR50_REG = ((UBYTE *)soundReg)[0x14];
	break;
      case 4: /* SO2_OutputLevel */
	soundReg->control.SO2_OutputLevel = value;
	NR50_REG = ((UBYTE *)soundReg)[0x14];
	break;
      case FREQUENCY:
	update_value(1, FREQUENCY, value);
	update_value(2, FREQUENCY, value);
	update_value(3, FREQUENCY, value);
	break;
      case PLAY: /* restart */
	update_value(1, FREQUENCY, current_value(1, FREQUENCY));
	update_value(2, FREQUENCY, current_value(2, FREQUENCY));
	update_value(3, FREQUENCY, current_value(3, FREQUENCY));
	soundReg->mode1.restart = value;
	soundReg->mode2.restart = value;
	soundReg->mode3.restart = value;
	soundReg->mode4.restart = value;
	NR14_REG = ((UBYTE *)soundReg)[0x04];
	NR24_REG = ((UBYTE *)soundReg)[0x09];
	NR34_REG = ((UBYTE *)soundReg)[0x0E];
	NR44_REG = ((UBYTE *)soundReg)[0x13];
	soundReg->mode1.restart = 0;
	soundReg->mode2.restart = 0;
	soundReg->mode3.restart = 0;
	soundReg->mode4.restart = 0;
	break;
      }
  } else if(mode == 1) {
    switch(line)
      {
      case 0: /* sweepTime */
	soundReg->mode1.sweepTime = value;
	NR10_REG = ((UBYTE *)soundReg)[0x00];
	break;
      case 1: /* sweepMode */
	soundReg->mode1.sweepMode = value;
	NR10_REG = ((UBYTE *)soundReg)[0x00];
	break;
      case 2: /* sweepShifts */
	soundReg->mode1.sweepShifts = value;
	NR10_REG = ((UBYTE *)soundReg)[0x00];
	break;
      case 3: /* patternDuty */
	soundReg->mode1.patternDuty = value;
	NR11_REG = ((UBYTE *)soundReg)[0x01];
	break;
      case 4: /* soundLength */
	soundReg->mode1.soundLength = value;
	NR11_REG = ((UBYTE *)soundReg)[0x01];
	break;
      case 5: /* envInitialValue */
	soundReg->mode1.envInitialValue = value;
	NR12_REG = ((UBYTE *)soundReg)[0x02];
	break;
      case 6: /* envMode */
	soundReg->mode1.envMode = value;
	NR12_REG = ((UBYTE *)soundReg)[0x02];
	break;
      case 7: /* envNbSweep */
	soundReg->mode1.envNbSweep = value;
	NR12_REG = ((UBYTE *)soundReg)[0x02];
	break;
      case 8: /* frequency */
      case FREQUENCY:
	soundReg->mode1.frequencyHigh = value >> 8;
	soundReg->mode1.frequencyLow  = value;
	NR13_REG = ((UBYTE *)soundReg)[0x03];
	NR14_REG = ((UBYTE *)soundReg)[0x04];
	break;
      case 9: /* counter_ConsSel */
	soundReg->mode1.counter_ConsSel = value;
	NR14_REG = ((UBYTE *)soundReg)[0x04];
	break;
      case 10: /* Sound1_To_SO1 */
	soundReg->control.Sound1_To_SO1 = value;
	NR51_REG = ((UBYTE *)soundReg)[0x15];
	break;
      case 11: /* Sound1_To_SO2 */
	soundReg->control.Sound1_To_SO2 = value;
	NR51_REG = ((UBYTE *)soundReg)[0x15];
	break;
      case 12: /* Sound1_On_Off */
	soundReg->control.Sound1_On_Off = value;
	NR52_REG = ((UBYTE *)soundReg)[0x16];
	break;
      case PLAY: /* restart */
	update_value(mode, FREQUENCY, current_value(mode, FREQUENCY));
	soundReg->mode1.restart = value;
	NR14_REG = ((UBYTE *)soundReg)[0x04];
	soundReg->mode1.restart = 0;
	break;
      }
  } else if(mode == 2) {
Пример #19
0
void FrTextSpan::updateScore(double amount, FrTextSpan_Operation op)
{
   setScore(update_value(op,score(),amount)) ;
}
bool humidity_sensor_hal::is_data_ready(bool wait)
{
	bool ret;
	ret = update_value(wait);
	return ret;
}
Пример #21
0
int menu_exec(menu_t *menu, unsigned int initial_item) {
  const menuitem_t *items = menu->items;
  unsigned int cur_item = initial_item;

  /* ensure the initial item is valid */
  while (items[cur_item].flags & MENU_FLAG_DISABLED) {
    cur_item++;
    if (cur_item >= menu->entries)
      cur_item = 0;
  }

  /* mark initial menuitem */
  osd_setattr(true, false);
  mark_item(menu, cur_item, MENUMARKER_LEFT);

  /* wait until all buttons are released */
  while (pad_buttons & PAD_ALL) ;

  /* handle input */
  while (1) {
    /* wait for input */
    while (!pad_buttons) ;

    unsigned int curbtns = pad_buttons;

    /* selection movement with up/down */
    if (curbtns & PAD_UP) {
      mark_item(menu, cur_item, ' ');

      do {
        if (cur_item > 0)
          cur_item--;
        else
          cur_item = menu->entries - 1;
      } while (items[cur_item].flags & MENU_FLAG_DISABLED);

      mark_item(menu, cur_item, MENUMARKER_LEFT);

      pad_clear(PAD_UP | PAD_LEFT | PAD_RIGHT); // prioritize up/down over left/right
    }

    if (curbtns & PAD_DOWN) {
      mark_item(menu, cur_item, ' ');

      do {
        cur_item++;
        if (cur_item >= menu->entries)
          cur_item = 0;
      } while (items[cur_item].flags & MENU_FLAG_DISABLED);

      mark_item(menu, cur_item, MENUMARKER_LEFT);

      pad_clear(PAD_DOWN | PAD_LEFT | PAD_RIGHT); // prioritize up/down over left/right
    }

    /* value change with left/right */
    if ((curbtns & PAD_LEFT) && items[cur_item].value) {
      update_value(menu, cur_item, UPDATE_DECREMENT);
      pad_clear(PAD_LEFT);
    }

    if ((curbtns & PAD_RIGHT) && items[cur_item].value) {
      update_value(menu, cur_item, UPDATE_INCREMENT);
      pad_clear(PAD_RIGHT);
    }

    /* selection with X */
    if (curbtns & PAD_X) {
      pad_clear(PAD_X);
      if (!items[cur_item].value) {
        /* no value attached, can exit from here */
        mark_item(menu, cur_item, ' ');
        return cur_item;

      } else {
        /* modify value */
        valueitem_t *vi = items[cur_item].value;

        switch (vi->type) {
        case VALTYPE_BOOL:
        case VALTYPE_EVENODD:
          update_value(menu, cur_item, UPDATE_INCREMENT); // bool always toggles
          break;

        case VALTYPE_BYTE:
        case VALTYPE_SBYTE:
          mark_item(menu, cur_item, ' ');
          value_submenu(menu, cur_item);
          mark_item(menu, cur_item, MENUMARKER_LEFT);
          break;
        }
      }
    }

    /* abort with Y */
    if (curbtns & PAD_Y) {
      pad_clear(PAD_Y);
      mark_item(menu, cur_item, ' ');
      return MENU_ABORT;
    }

    /* exit on video mode change (simplifies things) */
    if (curbtns & PAD_VIDEOCHANGE)
      return MENU_ABORT;

    /* clear unused buttons */
    pad_clear(PAD_START | PAD_Z | PAD_L | PAD_R | PAD_A | PAD_B);
  }
}
Пример #22
0
int main(int argc, char *argv[])
{
    int out_fd, base_raster;
    char *infile, *outmap;
    int percent;
    double zrange_min, zrange_max, d_tmp;
    double irange_min, irange_max;
    unsigned long estimated_lines;

    RASTER_MAP_TYPE rtype, base_raster_data_type;
    struct History history;
    char title[64];
    SEGMENT base_segment;
    struct PointBinning point_binning;
    void *base_array;
    void *raster_row;
    struct Cell_head region;
    struct Cell_head input_region;
    int rows, last_rows, row0, cols;		/* scan box size */
    int row;		/* counters */

    int pass, npasses;
    unsigned long line, line_total;
    unsigned int counter;
    unsigned long n_invalid;
    char buff[BUFFSIZE];
    double x, y, z;
    double intensity;
    int arr_row, arr_col;
    unsigned long count, count_total;
    int point_class;

    double zscale = 1.0;
    double iscale = 1.0;
    double res = 0.0;

    struct BinIndex bin_index_nodes;
    bin_index_nodes.num_nodes = 0;
    bin_index_nodes.max_nodes = 0;
    bin_index_nodes.nodes = 0;

    struct GModule *module;
    struct Option *input_opt, *output_opt, *percent_opt, *type_opt, *filter_opt, *class_opt;
    struct Option *method_opt, *base_raster_opt;
    struct Option *zrange_opt, *zscale_opt;
    struct Option *irange_opt, *iscale_opt;
    struct Option *trim_opt, *pth_opt, *res_opt;
    struct Option *file_list_opt;
    struct Flag *print_flag, *scan_flag, *shell_style, *over_flag, *extents_flag;
    struct Flag *intens_flag, *intens_import_flag;
    struct Flag *set_region_flag;
    struct Flag *base_rast_res_flag;
    struct Flag *only_valid_flag;

    /* LAS */
    LASReaderH LAS_reader;
    LASHeaderH LAS_header;
    LASSRSH LAS_srs;
    LASPointH LAS_point;
    int return_filter;

    const char *projstr;
    struct Cell_head cellhd, loc_wind;

    unsigned int n_filtered;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("import"));
    G_add_keyword(_("LIDAR"));
    G_add_keyword(_("statistics"));
    G_add_keyword(_("conversion"));
    G_add_keyword(_("aggregation"));
    G_add_keyword(_("binning"));
    module->description =
	_("Creates a raster map from LAS LiDAR points using univariate statistics.");

    input_opt = G_define_standard_option(G_OPT_F_BIN_INPUT);
    input_opt->required = NO;
    input_opt->label = _("LAS input file");
    input_opt->description = _("LiDAR input files in LAS format (*.las or *.laz)");
    input_opt->guisection = _("Input");

    output_opt = G_define_standard_option(G_OPT_R_OUTPUT);
    output_opt->required = NO;
    output_opt->guisection = _("Output");

    file_list_opt = G_define_standard_option(G_OPT_F_INPUT);
    file_list_opt->key = "file";
    file_list_opt->label = _("File containing names of LAS input files");
    file_list_opt->description = _("LiDAR input files in LAS format (*.las or *.laz)");
    file_list_opt->required = NO;
    file_list_opt->guisection = _("Input");

    method_opt = G_define_option();
    method_opt->key = "method";
    method_opt->type = TYPE_STRING;
    method_opt->required = NO;
    method_opt->description = _("Statistic to use for raster values");
    method_opt->options =
	"n,min,max,range,sum,mean,stddev,variance,coeff_var,median,percentile,skewness,trimmean";
    method_opt->answer = "mean";
    method_opt->guisection = _("Statistic");
    G_asprintf((char **)&(method_opt->descriptions),
               "n;%s;"
               "min;%s;"
               "max;%s;"
               "range;%s;"
               "sum;%s;"
               "mean;%s;"
               "stddev;%s;"
               "variance;%s;"
               "coeff_var;%s;"
               "median;%s;"
               "percentile;%s;"
               "skewness;%s;"
               "trimmean;%s",
               _("Number of points in cell"),
               _("Minimum value of point values in cell"),
               _("Maximum value of point values in cell"),
               _("Range of point values in cell"),
               _("Sum of point values in cell"),
               _("Mean (average) value of point values in cell"),
               _("Standard deviation of point values in cell"),
               _("Variance of point values in cell"),
               _("Coefficient of variance of point values in cell"),
               _("Median value of point values in cell"),
               _("pth (nth) percentile of point values in cell"),
               _("Skewness of point values in cell"),
               _("Trimmed mean of point values in cell"));

    type_opt = G_define_standard_option(G_OPT_R_TYPE);
    type_opt->required = NO;
    type_opt->answer = "FCELL";

    base_raster_opt = G_define_standard_option(G_OPT_R_INPUT);
    base_raster_opt->key = "base_raster";
    base_raster_opt->required = NO;
    base_raster_opt->label =
        _("Subtract raster values from the Z coordinates");
    base_raster_opt->description =
        _("The scale for Z is applied beforehand, the range filter for"
          " Z afterwards");
    base_raster_opt->guisection = _("Transform");

    zrange_opt = G_define_option();
    zrange_opt->key = "zrange";
    zrange_opt->type = TYPE_DOUBLE;
    zrange_opt->required = NO;
    zrange_opt->key_desc = "min,max";
    zrange_opt->description = _("Filter range for Z data (min,max)");
    zrange_opt->guisection = _("Selection");

    zscale_opt = G_define_option();
    zscale_opt->key = "zscale";
    zscale_opt->type = TYPE_DOUBLE;
    zscale_opt->required = NO;
    zscale_opt->answer = "1.0";
    zscale_opt->description = _("Scale to apply to Z data");
    zscale_opt->guisection = _("Transform");

    irange_opt = G_define_option();
    irange_opt->key = "intensity_range";
    irange_opt->type = TYPE_DOUBLE;
    irange_opt->required = NO;
    irange_opt->key_desc = "min,max";
    irange_opt->description = _("Filter range for intensity values (min,max)");
    irange_opt->guisection = _("Selection");

    iscale_opt = G_define_option();
    iscale_opt->key = "intensity_scale";
    iscale_opt->type = TYPE_DOUBLE;
    iscale_opt->required = NO;
    iscale_opt->answer = "1.0";
    iscale_opt->description = _("Scale to apply to intensity values");
    iscale_opt->guisection = _("Transform");

    percent_opt = G_define_option();
    percent_opt->key = "percent";
    percent_opt->type = TYPE_INTEGER;
    percent_opt->required = NO;
    percent_opt->answer = "100";
    percent_opt->options = "1-100";
    percent_opt->description = _("Percent of map to keep in memory");

    /* I would prefer to call the following "percentile", but that has too
     * much namespace overlap with the "percent" option above */
    pth_opt = G_define_option();
    pth_opt->key = "pth";
    pth_opt->type = TYPE_INTEGER;
    pth_opt->required = NO;
    pth_opt->options = "1-100";
    pth_opt->description = _("pth percentile of the values");
    pth_opt->guisection = _("Statistic");

    trim_opt = G_define_option();
    trim_opt->key = "trim";
    trim_opt->type = TYPE_DOUBLE;
    trim_opt->required = NO;
    trim_opt->options = "0-50";
    trim_opt->label = _("Discard given percentage of the smallest and largest values");
    trim_opt->description =
	_("Discard <trim> percent of the smallest and <trim> percent of the largest observations");
    trim_opt->guisection = _("Statistic");

    res_opt = G_define_option();
    res_opt->key = "resolution";
    res_opt->type = TYPE_DOUBLE;
    res_opt->required = NO;
    res_opt->description =
	_("Output raster resolution");
    res_opt->guisection = _("Output");

    filter_opt = G_define_option();
    filter_opt->key = "return_filter";
    filter_opt->type = TYPE_STRING;
    filter_opt->required = NO;
    filter_opt->label = _("Only import points of selected return type");
    filter_opt->description = _("If not specified, all points are imported");
    filter_opt->options = "first,last,mid";
    filter_opt->guisection = _("Selection");

    class_opt = G_define_option();
    class_opt->key = "class_filter";
    class_opt->type = TYPE_INTEGER;
    class_opt->multiple = YES;
    class_opt->required = NO;
    class_opt->label = _("Only import points of selected class(es)");
    class_opt->description = _("Input is comma separated integers. "
                               "If not specified, all points are imported.");
    class_opt->guisection = _("Selection");

    print_flag = G_define_flag();
    print_flag->key = 'p';
    print_flag->description =
	_("Print LAS file info and exit");

    extents_flag = G_define_flag();
    extents_flag->key = 'e';
    extents_flag->label =
        _("Use the extent of the input for the raster extent");
    extents_flag->description =
        _("Set internally computational region extents based on the"
          " point cloud");
    extents_flag->guisection = _("Output");

    set_region_flag = G_define_flag();
    set_region_flag->key = 'n';
    set_region_flag->label =
        _("Set computation region to match the new raster map");
    set_region_flag->description =
        _("Set computation region to match the 2D extent and resolution"
          " of the newly created new raster map");
    set_region_flag->guisection = _("Output");

    over_flag = G_define_flag();
    over_flag->key = 'o';
    over_flag->label =
	_("Override projection check (use current location's projection)");
    over_flag->description =
	_("Assume that the dataset has same projection as the current location");

    scan_flag = G_define_flag();
    scan_flag->key = 's';
    scan_flag->description = _("Scan data file for extent then exit");

    shell_style = G_define_flag();
    shell_style->key = 'g';
    shell_style->description =
	_("In scan mode, print using shell script style");

    intens_flag = G_define_flag();
    intens_flag->key = 'i';
    intens_flag->label =
        _("Use intensity values rather than Z values");
    intens_flag->description =
        _("Uses intensity values everywhere as if they would be Z"
          " coordinates");

    intens_import_flag = G_define_flag();
    intens_import_flag->key = 'j';
    intens_import_flag->description =
        _("Use Z values for filtering, but intensity values for statistics");

    base_rast_res_flag = G_define_flag();
    base_rast_res_flag->key = 'd';
    base_rast_res_flag->label =
        _("Use base raster resolution instead of computational region");
    base_rast_res_flag->description =
        _("For getting values from base raster, use its actual"
          " resolution instead of computational region resolution");

    only_valid_flag = G_define_flag();
    only_valid_flag->key = 'v';
    only_valid_flag->label = _("Use only valid points");
    only_valid_flag->description =
        _("Points invalid according to APSRS LAS specification will be"
          " filtered out");
    only_valid_flag->guisection = _("Selection");

    G_option_required(input_opt, file_list_opt, NULL);
    G_option_exclusive(input_opt, file_list_opt, NULL);
    G_option_required(output_opt, print_flag, scan_flag, shell_style, NULL);
    G_option_exclusive(intens_flag, intens_import_flag, NULL);
    G_option_requires(base_rast_res_flag, base_raster_opt, NULL);

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    int only_valid = FALSE;
    n_invalid = 0;
    if (only_valid_flag->answer)
        only_valid = TRUE;

    /* we could use rules but this gives more info and allows continuing */
    if (set_region_flag->answer && !(extents_flag->answer || res_opt->answer)) {
        G_warning(_("Flag %c makes sense only with %s option or -%c flag"),
                  set_region_flag->key, res_opt->key, extents_flag->key);
        /* avoid the call later on */
        set_region_flag->answer = '\0';
    }

    struct StringList infiles;

    if (file_list_opt->answer) {
        if (access(file_list_opt->answer, F_OK) != 0)
            G_fatal_error(_("File <%s> does not exist"), file_list_opt->answer);
        string_list_from_file(&infiles, file_list_opt->answer);
    }
    else {
        string_list_from_one_item(&infiles, input_opt->answer);
    }

    /* parse input values */
    outmap = output_opt->answer;

    if (shell_style->answer && !scan_flag->answer) {
	scan_flag->answer = 1; /* pointer not int, so set = shell_style->answer ? */
    }

    /* check zrange and extent relation */
    if (scan_flag->answer || extents_flag->answer) {
        if (zrange_opt->answer)
            G_warning(_("zrange will not be taken into account during scan"));
    }

    Rast_get_window(&region);
    /* G_get_window seems to be unreliable if the location has been changed */
    G_get_set_window(&loc_wind);        /* TODO: v.in.lidar uses G_get_default_window() */

    estimated_lines = 0;
    int i;
    for (i = 0; i < infiles.num_items; i++) {
        infile = infiles.items[i];
        /* don't if file not found */
        if (access(infile, F_OK) != 0)
            G_fatal_error(_("Input file <%s> does not exist"), infile);
        /* Open LAS file*/
        LAS_reader = LASReader_Create(infile);
        if (LAS_reader == NULL)
            G_fatal_error(_("Unable to open file <%s> as a LiDAR point cloud"),
                          infile);
        LAS_header = LASReader_GetHeader(LAS_reader);
        if  (LAS_header == NULL) {
            G_fatal_error(_("Unable to read LAS header of <%s>"), infile);
        }

        LAS_srs = LASHeader_GetSRS(LAS_header);

        /* print info or check projection if we are actually importing */
        if (print_flag->answer) {
            /* print filename when there is more than one file */
            if (infiles.num_items > 1)
                fprintf(stdout, "File: %s\n", infile);
            /* Print LAS header */
            print_lasinfo(LAS_header, LAS_srs);
        }
        else {
            /* report that we are checking more files */
            if (i == 1)
                G_message(_("First file's projection checked,"
                            " checking projection of the other files..."));
            /* Fetch input map projection in GRASS form. */
            projstr = LASSRS_GetWKT_CompoundOK(LAS_srs);
            /* we are printing the non-warning messages only for first file */
            projection_check_wkt(cellhd, loc_wind, projstr, over_flag->answer,
                                 shell_style->answer || i);
            /* if there is a problem in some other file, first OK message
             * is printed but than a warning, this is not ideal but hopefully
             * not so confusing when importing multiple files */
        }
        if (scan_flag->answer || extents_flag->answer) {
            /* we assign to the first one (i==0) but update for the rest */
            scan_bounds(LAS_reader, shell_style->answer, extents_flag->answer, i,
                        zscale, &region);
        }
        /* number of estimated point across all files */
        /* TODO: this should be ull which won't work with percent report */
        estimated_lines += LASHeader_GetPointRecordsCount(LAS_header);
        /* We are closing all again and we will be opening them later,
         * so we don't have to worry about limit for open files. */
        LASSRS_Destroy(LAS_srs);
        LASHeader_Destroy(LAS_header);
        LASReader_Destroy(LAS_reader);
    }
    /* if we are not importing, end */
    if (print_flag->answer || scan_flag->answer)
        exit(EXIT_SUCCESS);

    return_filter = LAS_ALL;
    if (filter_opt->answer) {
	if (strcmp(filter_opt->answer, "first") == 0)
	    return_filter = LAS_FIRST;
	else if (strcmp(filter_opt->answer, "last") == 0)
	    return_filter = LAS_LAST;
	else if (strcmp(filter_opt->answer, "mid") == 0)
	    return_filter = LAS_MID;
	else
	    G_fatal_error(_("Unknown filter option <%s>"), filter_opt->answer);
    }
    struct ReturnFilter return_filter_struct;
    return_filter_struct.filter = return_filter;
    struct ClassFilter class_filter;
    class_filter_create_from_strings(&class_filter, class_opt->answers);

    percent = atoi(percent_opt->answer);
    /* TODO: we already used zscale */
    /* TODO: we don't report intensity range */
    if (zscale_opt->answer)
        zscale = atof(zscale_opt->answer);
    if (iscale_opt->answer)
        iscale = atof(iscale_opt->answer);

    /* parse zrange */
    if (zrange_opt->answer != NULL) {
	if (zrange_opt->answers[0] == NULL)
	    G_fatal_error(_("Invalid zrange"));

	sscanf(zrange_opt->answers[0], "%lf", &zrange_min);
	sscanf(zrange_opt->answers[1], "%lf", &zrange_max);

	if (zrange_min > zrange_max) {
	    d_tmp = zrange_max;
	    zrange_max = zrange_min;
	    zrange_min = d_tmp;
	}
    }
    /* parse irange */
    if (irange_opt->answer != NULL) {
        if (irange_opt->answers[0] == NULL)
            G_fatal_error(_("Invalid %s"), irange_opt->key);

        sscanf(irange_opt->answers[0], "%lf", &irange_min);
        sscanf(irange_opt->answers[1], "%lf", &irange_max);

        if (irange_min > irange_max) {
            d_tmp = irange_max;
            irange_max = irange_min;
            irange_min = d_tmp;
        }
    }

    point_binning_set(&point_binning, method_opt->answer, pth_opt->answer,
                      trim_opt->answer, FALSE);

    base_array = NULL;

    if (strcmp("CELL", type_opt->answer) == 0)
	rtype = CELL_TYPE;
    else if (strcmp("DCELL", type_opt->answer) == 0)
	rtype = DCELL_TYPE;
    else
	rtype = FCELL_TYPE;

    if (point_binning.method == METHOD_N)
	rtype = CELL_TYPE;

    if (res_opt->answer) {
	/* align to resolution */
	res = atof(res_opt->answer);

	if (!G_scan_resolution(res_opt->answer, &res, region.proj))
	    G_fatal_error(_("Invalid input <%s=%s>"), res_opt->key, res_opt->answer);

	if (res <= 0)
	    G_fatal_error(_("Option '%s' must be > 0.0"), res_opt->key);
	
	region.ns_res = region.ew_res = res;

	region.north = ceil(region.north / res) * res;
	region.south = floor(region.south / res) * res;
	region.east = ceil(region.east / res) * res;
	region.west = floor(region.west / res) * res;

	G_adjust_Cell_head(&region, 0, 0);
    }
    else if (extents_flag->answer) {
	/* align to current region */
	Rast_align_window(&region, &loc_wind);
    }
    Rast_set_output_window(&region);

    rows = last_rows = region.rows;
    npasses = 1;
    if (percent < 100) {
	rows = (int)(region.rows * (percent / 100.0));
	npasses = region.rows / rows;
	last_rows = region.rows - npasses * rows;
	if (last_rows)
	    npasses++;
	else
	    last_rows = rows;

    }
    cols = region.cols;

    G_debug(2, "region.n=%f  region.s=%f  region.ns_res=%f", region.north,
	    region.south, region.ns_res);
    G_debug(2, "region.rows=%d  [box_rows=%d]  region.cols=%d", region.rows,
	    rows, region.cols);

    /* using row-based chunks (used for output) when input and output
     * region matches and using segment library when they don't */
    int use_segment = 0;
    int use_base_raster_res = 0;
    /* TODO: see if the input region extent is smaller than the raster
     * if yes, the we need to load the whole base raster if the -e
     * flag was defined (alternatively clip the regions) */
    if (base_rast_res_flag->answer)
        use_base_raster_res = 1;
    if (base_raster_opt->answer && (res_opt->answer || use_base_raster_res
                                    || extents_flag->answer))
        use_segment = 1;
    if (base_raster_opt->answer && !use_segment) {
        /* TODO: do we need to test existence first? mapset? */
        base_raster = Rast_open_old(base_raster_opt->answer, "");
        base_raster_data_type = Rast_get_map_type(base_raster);
        base_array = G_calloc((size_t)rows * (cols + 1), Rast_cell_size(base_raster_data_type));
    }
    if (base_raster_opt->answer && use_segment) {
        if (use_base_raster_res) {
            /* read raster actual extent and resolution */
            Rast_get_cellhd(base_raster_opt->answer, "", &input_region);
            /* TODO: make it only as small as the output is or points are */
            Rast_set_input_window(&input_region);  /* we have split window */
        } else {
            Rast_get_input_window(&input_region);
        }
        rast_segment_open(&base_segment, base_raster_opt->answer, &base_raster_data_type);
    }

    if (!scan_flag->answer) {
        if (!check_rows_cols_fit_to_size_t(rows, cols))
		G_fatal_error(_("Unable to process the hole map at once. "
                        "Please set the '%s' option to some value lower than 100."),
				percent_opt->key);
        point_binning_memory_test(&point_binning, rows, cols, rtype);
	}

    /* open output map */
    out_fd = Rast_open_new(outmap, rtype);

    /* allocate memory for a single row of output data */
    raster_row = Rast_allocate_output_buf(rtype);

    G_message(_("Reading data ..."));

    count_total = line_total = 0;

    /* main binning loop(s) */
    for (pass = 1; pass <= npasses; pass++) {

	if (npasses > 1)
	    G_message(_("Pass #%d (of %d) ..."), pass, npasses);

	/* figure out segmentation */
	row0 = (pass - 1) * rows;
	if (pass == npasses) {
	    rows = last_rows;
	}

        if (base_array) {
            G_debug(2, "filling base raster array");
            for (row = 0; row < rows; row++) {
                Rast_get_row(base_raster, base_array + ((size_t) row * cols * Rast_cell_size(base_raster_data_type)), row, base_raster_data_type);
            }
        }

	G_debug(2, "pass=%d/%d  rows=%d", pass, npasses, rows);

    point_binning_allocate(&point_binning, rows, cols, rtype);

	line = 0;
	count = 0;
	counter = 0;
	G_percent_reset();

        /* loop of input files */
        for (i = 0; i < infiles.num_items; i++) {
            infile = infiles.items[i];
            /* we already know file is there, so just do basic checks */
            LAS_reader = LASReader_Create(infile);
            if (LAS_reader == NULL)
                G_fatal_error(_("Unable to open file <%s>"), infile);

            while ((LAS_point = LASReader_GetNextPoint(LAS_reader)) != NULL) {
                line++;
                counter++;

                if (counter == 100000) {        /* speed */
                    if (line < estimated_lines)
                        G_percent(line, estimated_lines, 3);
                    counter = 0;
                }

                /* We always count them and report because behavior
                 * changed in between 7.0 and 7.2 from undefined (but skipping
                 * invalid points) to filtering them out only when requested. */
                if (!LASPoint_IsValid(LAS_point)) {
                    n_invalid++;
                    if (only_valid)
                        continue;
                }

                x = LASPoint_GetX(LAS_point);
                y = LASPoint_GetY(LAS_point);
                if (intens_flag->answer)
                    /* use intensity as z here to allow all filters (and
                     * modifications) below to be applied for intensity */
                    z = LASPoint_GetIntensity(LAS_point);
                else
                    z = LASPoint_GetZ(LAS_point);

                int return_n = LASPoint_GetReturnNumber(LAS_point);
                int n_returns = LASPoint_GetNumberOfReturns(LAS_point);
                if (return_filter_is_out(&return_filter_struct, return_n, n_returns)) {
                    n_filtered++;
                    continue;
                }
                point_class = (int) LASPoint_GetClassification(LAS_point);
                if (class_filter_is_out(&class_filter, point_class))
                    continue;

                if (y <= region.south || y > region.north) {
                    continue;
                }
                if (x < region.west || x >= region.east) {
                    continue;
                }

                /* find the bin in the current array box */
		arr_row = (int)((region.north - y) / region.ns_res) - row0;
		if (arr_row < 0 || arr_row >= rows)
		    continue;
                arr_col = (int)((x - region.west) / region.ew_res);

                z = z * zscale;

                if (base_array) {
                    double base_z;
                    if (row_array_get_value_row_col(base_array, arr_row, arr_col,
                                                    cols, base_raster_data_type,
                                                    &base_z))
                        z -= base_z;
                    else
                        continue;
                }
                else if (use_segment) {
                    double base_z;
                    if (rast_segment_get_value_xy(&base_segment, &input_region,
                                                  base_raster_data_type, x, y,
                                                  &base_z))
                        z -= base_z;
                    else
                        continue;
                }

                if (zrange_opt->answer) {
                    if (z < zrange_min || z > zrange_max) {
                        continue;
                    }
                }

                if (intens_import_flag->answer || irange_opt->answer) {
                    intensity = LASPoint_GetIntensity(LAS_point);
                    intensity *= iscale;
                    if (irange_opt->answer) {
                        if (intensity < irange_min || intensity > irange_max) {
                            continue;
                        }
                    }
                    /* use intensity for statistics */
                    if (intens_import_flag->answer)
                        z = intensity;
                }

                count++;
                /*          G_debug(5, "x: %f, y: %f, z: %f", x, y, z); */

                update_value(&point_binning, &bin_index_nodes, cols,
                             arr_row, arr_col, rtype, x, y, z);
            }                        /* while !EOF of one input file */
            /* close input LAS file */
            LASReader_Destroy(LAS_reader);
        }           /* end of loop for all input files files */

	G_percent(1, 1, 1);	/* flush */
	G_debug(2, "pass %d finished, %lu coordinates in box", pass, count);
	count_total += count;
	line_total += line;

	/* calc stats and output */
	G_message(_("Writing to map ..."));
	for (row = 0; row < rows; row++) {
        /* potentially vector writing can be independent on the binning */
        write_values(&point_binning, &bin_index_nodes, raster_row, row,
            cols, rtype, NULL);
	    /* write out line of raster data */
        Rast_put_row(out_fd, raster_row, rtype);
	}

	/* free memory */
	point_binning_free(&point_binning, &bin_index_nodes);
    }				/* passes loop */
    if (base_array)
        Rast_close(base_raster);
    if (use_segment)
        Segment_close(&base_segment);

    G_percent(1, 1, 1);		/* flush */
    G_free(raster_row);

    /* close raster file & write history */
    Rast_close(out_fd);

    sprintf(title, "Raw X,Y,Z data binned into a raster grid by cell %s",
            method_opt->answer);
    Rast_put_cell_title(outmap, title);

    Rast_short_history(outmap, "raster", &history);
    Rast_command_history(&history);
    Rast_set_history(&history, HIST_DATSRC_1, infile);
    Rast_write_history(outmap, &history);

    /* set computation region to the new raster map */
    /* TODO: should be in the done message */
    if (set_region_flag->answer)
        G_put_window(&region);

    if (n_invalid && only_valid)
        G_message(_("%lu input points were invalid and filtered out"),
                  n_invalid);
    if (n_invalid && !only_valid)
        G_message(_("%lu input points were invalid, use -%c flag to filter"
                    " them out"), n_invalid, only_valid_flag->key);
    if (infiles.num_items > 1) {
        sprintf(buff, _("Raster map <%s> created."
                        " %lu points from %d files found in region."),
                outmap, count_total, infiles.num_items);
    }
    else {
        sprintf(buff, _("Raster map <%s> created."
                        " %lu points found in region."),
                outmap, count_total);
    }

    G_done_msg("%s", buff);
    G_debug(1, "Processed %lu points.", line_total);

    string_list_free(&infiles);

    exit(EXIT_SUCCESS);

}
Пример #23
0
int _pf_get_value (Param_File_Type *p, Param_Type *pf, unsigned int ormode)
{
   int perform_query;
   unsigned int mode;

   if (pf->type == PF_COMMENT_TYPE)
     return 0;

   mode = _pf_get_effective_mode (p, pf);
   perform_query = ((0 == (pf->flags & PF_CURRENT_VALUE))
		    && (mode & PF_QUERY_MODE));
   mode |= ormode;
   if (perform_query == 0)
     perform_query = ormode & PF_QUERY_MODE;   /* explicit requested */

   if (-1 == _pf_get_current_value (p, pf))
     {
	if ((PF_Errno != PF_NUMBER_FORMAT_BAD)
	    && (PF_Errno != PF_INDIRECT_ERROR))
	  return -1;
	/* reset error and force a query */
	pf_error ("Error occured while examining %s from %s.",
		  pf->name, p->input_filename);
	PF_Errno = 0;
	perform_query = 1;
     }

   if (pf->flags & PF_CURRENT_VALUE)
     {
	if (-1 == range_check (p, pf))
	  {
	     pf_error ("Range error occured while looking at parameter %s.",
		       pf->name);
	     if (PF_Errno != PF_RANGE_ERROR)
	       return -1;

	     /* Force query. */
	     perform_query = 1;
	  }
     }
   else perform_query = 1;

   while (perform_query)
     {
	if (-1 == _pf_query_current_value (p, pf))
	  return -1;

	if (0 == range_check (p, pf)) break;
	if (PF_Errno != PF_RANGE_ERROR)
	  return -1;
	pf_error ("Value is out of range.");
     }

   if ((mode & PF_LEARN_MODE) && (pf->flags & PF_PARAM_DIRTY))
     {
	p->flags |= PFILE_DIRTY;
	if (-1 == update_value (pf))
	  return -1;
     }
   return 0;
}
Пример #24
0
int main (int argc, char * argv[])
{
	int rank, size;
	
	MPI_Init (&argc, &argv);
	MPI_Comm_rank (MPI_COMM_WORLD, &rank);
  	MPI_Comm_size (MPI_COMM_WORLD, &size);
	
	if (argc < 4)
	{
		printf("UŻYCIE: size, iteration_no\n");
		return(1);
	}
	
	int sizeM = atoi(argv[1]);
	int iteration_no = atoi(argv[2]);
	float temp = atof(argv[3]);
	int part_size_y = sizeM / size;

	// printf("RANK: %d, WORLD: %d", rank, size);

	// allocate own matrix
	double **matrix = (double **)malloc(sizeM * sizeof(double*));	
	int x,y;
	for(x = 0; x < sizeM; x++){
		matrix[x] = (double *)malloc(part_size_y * sizeof(double));
	}
	
	for (x = 0; x < sizeM; x++){
		for(y = 0; y < part_size_y; y++){
			matrix[x][y] = 0.0;
		}
	}

	//set temperature
	if( rank == 0 ){
		for (x=0; x < sizeM; x++){
			matrix[x][0] = temp;
		}
	}
	
	struct timeval  start_time, end_time;
	if (rank == 0){		
		gettimeofday(&start_time, NULL); 
	}

	int i;
	for(i = 0; i < iteration_no; i++){		
		double *my_row = (double *)malloc(sizeM * sizeof(double));
		double *answer_row = (double *)malloc(sizeM * sizeof(double));

		//exchange bottom of own matrix
		for (x = 0; x < sizeM; x++){
			my_row[x] = matrix[x][part_size_y - 1];
		}		
		if (rank == 0){
			if (size > 1){
				MPI_Send(my_row, sizeM, MPI_DOUBLE, (rank + 1), 0, MPI_COMM_WORLD);
			}				
			for (x = 0; x < sizeM; x++){
				answer_row[x] = 0.0;
			}
		} else if ((rank == size - 1) && (rank > 0)){
			MPI_Recv(answer_row, sizeM, MPI_DOUBLE, (rank - 1), 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);		
		} else {		
			MPI_Recv(answer_row, sizeM, MPI_DOUBLE, (rank - 1), 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);		
			MPI_Send(my_row, sizeM, MPI_DOUBLE, (rank + 1), 0, MPI_COMM_WORLD);			
		}	

		if (rank != 0){
			for (x = 1; x < sizeM-1; x++){		
				update_value(x, 0, matrix, answer_row[x], matrix[x][1]);
			}
		}

		for (y = 1; y < part_size_y - 1; y++){
			for (x = 1; x < sizeM-1; x++){
				update_value(x, y, matrix, matrix[x][y-1], matrix[x][y+1]);
			}
		}

		//exchange up of own matrix
		for (x = 0; x < sizeM; x++){
			my_row[x] = matrix[x][0];
		}
		if (rank == size - 1 && rank > 0){
			if (size > 1){
				MPI_Send(my_row, sizeM, MPI_DOUBLE, (rank - 1), 0, MPI_COMM_WORLD);
			}
			for (x = 0; x < sizeM; x++){
				answer_row[x] = 0.0;
			}
		} else if (rank == 0){
			if (size > 1){
				MPI_Recv(answer_row, sizeM, MPI_DOUBLE, (rank + 1), 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);	
			}				
			for (x = 0; x < sizeM; x++){
				answer_row[x] = 0.0;
			}		
		} else {
			MPI_Recv(answer_row, sizeM, MPI_DOUBLE, (rank + 1), 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);			
			MPI_Send(my_row, sizeM, MPI_DOUBLE, (rank - 1), 0, MPI_COMM_WORLD);					
		}

		if (rank != size - 1){
			for (x = 1; x < sizeM-1; x++){
				update_value(x, part_size_y - 1, matrix, matrix[x][part_size_y-2], answer_row[x]);
			}
		}
		

		MPI_Barrier(MPI_COMM_WORLD);
	}

	if (rank == 0){
		gettimeofday(&end_time, NULL);
		double s_time = (start_time.tv_sec) * 1000 + (start_time.tv_usec) / 1000;
		double e_time = (end_time.tv_sec) * 1000 + (end_time.tv_usec) / 1000;
		double total_time = e_time - s_time;  
		printf("%d %F\n", size, total_time);
		//printf("X = %d, Y = %d, SIZE = %d, ITERATION_NO = %d, TOTAL_TIME = %d\n\n", sizeM, size, iteration_no, (int)total_time);		
		//printf("MACIERZ:\n");
	}
	
 //  	for (i = 0; i < size; i++){
	// 	MPI_Barrier(MPI_COMM_WORLD);
	// 	if (rank == i){
	// 		for (y = 0; y < part_size_y; y++){
	// 			printf("[");
	// 			for(x = 0; x < sizeM; x++){
	// 				printf("%.2f ", matrix[x][y]);
	// 			}
	// 			printf("]\n");
	// 		}

	// 	}
	// }
	
	MPI_Finalize();
	return 0;
}	
Пример #25
0
// Put the current value into the edit box
// - from current_ if state_ <= CALCINTLIT,
// - else from current_str_
//   Note that state_/current_/current_str_ may be updated to reflect what current_str_ contained.
void CCalcEdit::put()
{
	ASSERT(pp_ != NULL);
	ASSERT(pp_->radix_ > 1 && pp_->radix_ <= 36);

	if (theApp.refresh_off_ || !pp_->IsVisible())
		return;

	if (pp_->state_ <= CALCERROR)
	{
		if (pp_->current_str_.IsEmpty())
			SetWindowText("ERROR");
		else
			::SetWindowTextW(m_hWnd, (LPCWSTR)pp_->current_str_);
		TRACE("++++++ Put: error\r\n");
		return;
	}
	else if (pp_->state_ <= CALCINTLIT)
	{
		// Get value from current_ (integer)
		mpz_class val = pp_->get_norm(pp_->current_);

		// Get a buffer large enough to hold the text (may be big)
		int len = mpz_sizeinbase(val.get_mpz_t(), pp_->radix_) + 2 + 1;
		char *buf = new char[len];
		buf[len-1] = '\xCD';

		// Get the number as a string and add it to the text box
		mpz_get_str(buf, theApp.hex_ucase_? -pp_->radix_ : pp_->radix_, val.get_mpz_t());
		ASSERT(buf[len-1] == '\xCD');
		bool handled = false;
		if (len > 1000)
		{
			CString ss;
			ss.Format("The result of the operation has been calculated and has %d "
			          "digits which may be too large for the Windows text box to handle.\n\n"
			          "You may open the result in a text file, or copy it to the clipboard, or "
			          "simply select \"Cancel\" to attempt to display it normally.", len-3);
			CAvoidableDialog dlg(IDS_CALC_TOO_BIG, ss, "", MLCBF_CANCEL_BUTTON);
			dlg.AddButton(47, "Open in File");
			dlg.AddButton(48, "Copy to Clipboard");

			switch (dlg.DoModal())
			{
			case 47:
				theApp.FileFromString(buf);
				handled = true;
				break;
			case 48:
				if (!OpenClipboard())
					AfxMessageBox("The clipboard is in use!");
				else
				{
					HANDLE hh;                              // Windows handle for memory
					char *pp;

					if (!::EmptyClipboard() ||
						(hh = ::GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, DWORD(len-1))) == NULL ||
						(pp = reinterpret_cast<char *>(::GlobalLock(hh))) == NULL)
					{
						AfxMessageBox("Not enough memory to add to clipboard");
						::CloseClipboard();
						break;
					}
					memcpy(pp, buf, len-1);
					::SetClipboardData(CF_TEXT, hh);
					::CloseClipboard();
					theApp.ClipBoardAdd(len-1);   // allow temp cb file to be deleted and keep track of large cb allocs so we can check if they should be deleted on close
					SetWindowText("");            // Clear text box to avoid confusion
					handled = true;
				}
				break;
			case IDCANCEL:
				break;
			default:
				ASSERT(0);
			}

		}

		if (!handled)
		{
			SetWindowText(buf);
			SetSel(len, -1, FALSE);     // move caret to end
		}
		delete[] buf;
	}
	else
	{
		// Get value from current_str_ (expression (possibly integer), non-int literal, or something else)
		//SetWindowText(pp_->current_str_);
		// Put as Unicode as an expression can contain a Unicode string
		::SetWindowTextW(m_hWnd, (LPCWSTR)pp_->current_str_);
		SetSel(pp_->current_str_.GetLength(), -1, FALSE);     // move caret to end
		TRACE("++++++ Put: expr %s\r\n", (const char *)CString(pp_->current_str_));

#if 0 // I don't think this is necessary and makes other code more complicated
		// Finally we need to make sure that state_ etc match what the string contains.
		// Eg current_str_ may actually be an integer literal, in which case we update state_/current_
		pp_->state_ = update_value(false);
#endif
	}

	add_sep();

	// xxx do this in idle processing???
	if (pp_->ctl_calc_bits_.m_hWnd != 0)
		pp_->ctl_calc_bits_.RedrawWindow();
}
Пример #26
0
int process_line(struct client* client, char* line, size_t len) {
  DEBUG(255, "Raw line: %s", line);
  char buf[65];
  double double_number;
  int number;
  struct timeval tv = { 0, 0 };
  if (strcmp(line, "MODULES") == 0)
    send_loaded_modules_info(client);
  else if (sscanf(line, "ENABLE %64s", buf) == 1) {
    struct module* module = get_module(buf);
    if (module) {
      struct enabled_mod* em = malloc(sizeof(struct enabled_mod));
      em->module = module;
      em->id = 0;
      em->next = NULL;
      if (!client->mods) {
        client->mods = em;
        if (em->module->array_length == 1)
          client_send_data(client, "LOADED: %s %s ID %d", module_type_to_string(em->module->type), buf, em->id);
        else
          client_send_data(client, "LOADED: %s %s ID %d WITH %d ITEMS", module_type_to_string(em->module->type), buf, em->id, em->module->array_length);
      } else {
        em->id++;
        struct enabled_mod* lm = client->mods;
        if (lm->module == em->module) {
          client_send_data(client, "ERROR: ALREADY LOADED %s WITH ID %d", em->module->name, em->id);
          free(em);
        } else {
          while (lm) {
            if (lm->module == em->module) {
              client_send_data(client, "ERROR: ALREADY LOADED %s WITH ID %d", em->module->name, em->id);
              free(em);
              return 0;
            }
            em->id = lm->id + 1;
            if (!lm->next)
              break;
            lm = lm->next;
          };
          lm->next = em;
          if (em->module->array_length == 1)
          client_send_data(client, "LOADED: %s %s ID %d", module_type_to_string(em->module->type), buf, em->id);
        else
          client_send_data(client, "LOADED: %s %s ID %d WITH %d ITEMS", module_type_to_string(em->module->type), buf, em->id, em->module->array_length);
        }
      }
    } else
      client_send_data(client, "ERROR: UNABLE TO LOAD %s", buf);
  } else if (sscanf(line, "DISABLE %64s", buf) == 1) {
    struct module* module = get_module(buf);
    if (module) {
      struct enabled_mod* lm = client->mods;
      if (lm->module == module) {
        client->mods = lm->next;
        client_send_data(client, "DISABLED: %s WITH ID %d", buf, lm->id);
        free(lm);
      } else {
        while (lm->next) {
          if (lm->next->module == module) {
            struct enabled_mod* to_free = lm->next;
            lm->next = lm->next->next;
            client_send_data(client, "DISABLED: %s WITH ID %d", buf, to_free->id);
            free(to_free);
            break;
          }
          lm = lm->next;
        };
      }
    } else
      client_send_data(client, "ERROR: MODULE %s DOESN'T EXIST", buf);
  } else if (sscanf(line, "PULL %64s", buf) == 1) {
    struct module* module = get_module(buf);
    if (module) {
      char databuf[BUFSIZ];
      if (update_value(module, databuf, sizeof(databuf), client))
        client_send_data(client, "%s: %s", module->name, databuf);
    };
  } else if (sscanf(line, "ITEMNAMES %64s", buf) == 1) {
    struct module* module = get_module(buf);
    if (module) {
      char databuf[BUFSIZ];
      if (get_module_item_names(module, databuf, sizeof(databuf)))
        client_send_data(client, "%s: %s", module->name, databuf);
    };
  } else if (sscanf(line, "INTERVAL %lf", &double_number) == 1) {
    if (client->timer)
      event_free(client->timer);
    if (double_number < 0) {
      client->timer = NULL;
      return 0;
    }
    tv.tv_sec = (long) double_number;
    tv.tv_usec = (long) ((double_number - (double) tv.tv_sec) * 1000000.0) ;
    client->timer = event_new(bufferevent_get_base(client->bev), -1, EV_PERSIST, client_timer, client);
    event_add(client->timer, &tv);
  } else if (sscanf(line, "PRECISION %d", &number) == 1) {
    if (number >= 0 && number <= 255)
      client->precision = number;
    else
      client_send_data(client, "ERROR: Precision %d is out of the valid range (0-255)", number);
  } else if ((!client->websocket || !client->websocket->connected) && handle_handshake(client, line, len))
    return 0;
  else {
    switch (++client->unknown_command) {
    case 1:
      client_send_data(client, "ERROR: This is not a valid command...");
      return 0;
    case 2:
      client_send_data(client, "ERROR: I'm warning you, stop that.");
      return 0;
    case 3:
      client_eventcb(client->bev, BEV_ERROR, client);
      return 1;
    }
  }
  client->unknown_command = 0;
  return 0;
};
Пример #27
0
void FrTextSpan::updateWeight(double amount, FrTextSpan_Operation op)
{
   setWeight(update_value(op,weight(),amount)) ;
}
	bool code (PrologElement * parameters, PrologResolution * resolution) {
		if (parameters -> isPair ()) {
			PrologElement * v = parameters -> getLeft ();
			PrologElement * o = 0;
			if (v -> isNumber () || v -> isPair () || v -> isEarth () || v -> isVar ()) {
				integrated_phobos * ph = (integrated_phobos *) module;
				PrologElement * path = parameters -> getRight ();
				if (path -> isPair () && path -> getLeft () -> isVar ()) {o = path -> getLeft (); path = path -> getRight ();}
				PrologElement * se;
				PrologAtom * sa;
				if (path -> isPair ()) {
					se = path -> getLeft ();
					if (se -> isAtom ()) {
						sa = se -> getAtom ();
						if (sa == core_atom) {
							path = path -> getRight ();
							if (path -> isPair ()) {
								se = path -> getLeft ();
								if (se -> isAtom ()) {
									sa = se -> getAtom ();
									if (sa == volume) return update_value (& ph -> volume . gateway, v, o, 1);
									if (sa == pan) return update_value (& ph -> pan_ctrl, v, o, 1);
									if (sa == chorus) {
										path = path -> getRight ();
										if (path -> isPair ()) {
											se = path -> getLeft ();
											if (se -> isAtom ()) {
												sa = se -> getAtom ();
												if (sa == level) return update_value (& ph -> chorus . level, v, o, 1);
												if (sa == time) return update_value (& ph -> chorus . time, v, o, 1);
												if (sa == bias) return update_value (& ph -> chorus . bias, v, o, 1);
												if (sa == speed) return update_value (& ph -> chorus . speed, v, o, 1);
												if (sa == phase) return update_value (& ph -> chorus . phase, v, o, 1);
												if (sa == amp) return update_value (& ph -> chorus . amp, v, o, 1);
											}
										}
										return false;
									}
									if (sa == delay) {
										path = path -> getRight ();
										if (path -> isPair ()) {
											se = path -> getLeft ();
											if (se -> isAtom ()) {
												sa = se -> getAtom ();
												if (sa == balance) return update_value (& ph -> dry_wet . balance, v, o, 1);
												if (sa == feedback) return update_value (& ph -> delay . feedback, v, o, 1);
												if (sa == time) return update_value (& ph -> delay . time, v, o, 4);
												if (sa == highdamp) return update_value (& ph -> delay . high_damp, v, o, 1);
											}
										}
										return false;
									}
									if (sa == X) return update_value (& ph -> X, v, o, 1);
									if (sa == Y) return update_value (& ph -> Y, v, o, 1);
									if (sa == pitch) return update_value (& ph -> pitch, v, o, 1);
									if (sa == auto_atom) return update_value (& ph -> auto_ctrl, v, o, 1);
								}
							}
							return false;
						}
						if (sa == arpeggiator) {
							path = path -> getRight ();
							if (path -> isPair ()) {
								se = path -> getLeft ();
								if (se -> isAtom ()) {
									sa = se -> getAtom ();
									if (sa == speed) return update_value (& ph -> arp . tempo, v, o, 1);
									if (sa == subdivision) return update_value (& ph -> arp . division, v, o, 1);
									if (sa == active) return update_value (& ph -> arp . active, v, o, 5);
									if (sa == algo) return update_value (& ph -> arp . current_algo, v, o, 1);
									if (sa == hold) return update_value (& ph -> arp . hold, v, o, 5);
								}
							}
							return false;
						}
						if (sa == lfo) {
							path = path -> getRight ();
							if (path -> isPair ()) {
								se = path -> getLeft ();
								if (! se -> isInteger ()) return false;
								int ind = se -> getInteger ();
								if (ind == 1) {
									path = path -> getRight ();
									if (path -> isPair ()) {
										se = path -> getLeft ();
										if (se -> isAtom ()) {
											sa = se -> getAtom ();
											if (sa == speed) return update_value (& ph -> lfo1 . speed, v, o, 1);
											if (sa == wave) return update_value (& ph -> lfo1 . wave, v, o, 6);
											if (sa == pulse) return update_value (& ph -> lfo1 . pulse, v, o, 1);
											if (sa == phase) return update_value (& ph -> lfo1 . phase, v, o, 1);
											if (sa == sync) return update_value (& ph -> lfo1 . sync, v, o, 5);
											if (sa == vibrato) return update_value (& ph -> lfo1 . vibrato, v, o, 1);
										}
									}
									return false;
								}
								if (ind == 2) {
									path = path -> getRight ();
									if (path -> isPair ()) {
										se = path -> getLeft ();
										if (se -> isAtom ()) {
											sa = se -> getAtom ();
											if (sa == speed) return update_value (& ph -> lfo2 . speed, v, o, 1);
											if (sa == wave) return update_value (& ph -> lfo2 . wave, v, o, 6);
											if (sa == pulse) return update_value (& ph -> lfo2 . pulse, v, o, 1);
											if (sa == phase) return update_value (& ph -> lfo2 . phase, v, o, 1);
											if (sa == sync) return update_value (& ph -> lfo2 . sync, v, o, 5);
											if (sa == vibrato) return update_value (& ph -> lfo2 . vibrato, v, o, 1);
											if (sa == tremolo) return update_value (& ph -> lfo2 . tremolo, v, o, 1);
											if (sa == wahwah) return update_value (& ph -> lfo2 . wahwah, v, o, 1);
											if (sa == pan) return update_value (& ph -> lfo2 . pan, v, o, 1);
										}
									}
									return false;
								}
							}
							return false;
						}
						if (sa == operator_atom) {
							path = path -> getRight ();
							if (path -> isPair ()) {
								se = path -> getLeft ();
								if (se -> isAtom ()) {sa = se -> getAtom (); if (sa == algo) return update_value (& ph -> operator_algo, v, o, 8); return false;}
								if (se -> isInteger ()) {
									int ind = se -> getInteger () - 1;
									if (ind < 0 || ind > 3) return false;
									path = path -> getRight ();
									if (path -> isPair ()) {
										se = path -> getLeft ();
										if (se -> isAtom ()) {
											sa = se -> getAtom ();
											if (sa == freq) return update_value (& ph -> operators [ind] . freq, v, o, 2);
											if (sa == amp) return update_value (& ph -> operators [ind] . amp, v, o, 3);
											if (sa == ratio) return update_value (& ph -> operators [ind] . ratio, v, o, 7);
											if (sa == feedback) return update_value (& ph -> operators [ind] . feedback, v, o, 1);
											if (sa == eg) {
												path = path -> getRight ();
												if (path -> isPair ()) {
													se = path -> getLeft ();
													if (se -> isAtom ()) {
														sa = se -> getAtom ();
														if (sa == time1) return update_value (& ph -> operators [ind] . eg . time [0], v, o, 4);
														if (sa == time2) return update_value (& ph -> operators [ind] . eg . time [1], v, o, 4);
														if (sa == time3) return update_value (& ph -> operators [ind] . eg . time [2], v, o, 4);
														if (sa == time4) return update_value (& ph -> operators [ind] . eg . time [3], v, o, 4);
														if (sa == level1) return update_value (& ph -> operators [ind] . eg . level [0], v, o, 1);
														if (sa == level2) return update_value (& ph -> operators [ind] . eg . level [1], v, o, 1);
														if (sa == level3) return update_value (& ph -> operators [ind] . eg . level [2], v, o, 1);
														if (sa == level4) return update_value (& ph -> operators [ind] . eg . level [3], v, o, 1);
														if (sa == egscal) {
															path = path -> getRight ();
															if (path -> isPair ()) {
																se = path -> getLeft ();
																if (se -> isAtom ()) {
																	sa = se -> getAtom ();
																	if (sa == BP) return update_value (& ph -> operators [ind] . eg . egscal . BP, v, o, 1);
																	if (sa == left) return update_value (& ph -> operators [ind] . eg . egscal . left, v, o, 1);
																	if (sa == right) return update_value (& ph -> operators [ind] . eg . egscal . right, v, o, 1);
																}
															}
															return false;
														}
													}
												}
												return false;
											}
											if (sa == vector) {
												path = path -> getRight ();
												if (path -> isPair ()) {
													se = path -> getLeft ();
													if (se -> isAtom ()) {
														sa = se -> getAtom ();
														if (sa == A) return update_value (& ph -> operators [ind] . vector [0], v, o, 1);
														if (sa == B) return update_value (& ph -> operators [ind] . vector [1], v, o, 1);
														if (sa == C) return update_value (& ph -> operators [ind] . vector [2], v, o, 1);
														if (sa == D) return update_value (& ph -> operators [ind] . vector [3], v, o, 1);
													}
												}
												return false;
											}
											if (sa == sens) {
												path = path -> getRight ();
												if (path -> isPair ()) {
													se = path -> getLeft ();
													if (se -> isAtom ()) {
														sa = se -> getAtom ();
														if (sa == freq) {
															path = path -> getRight ();
															if (path -> isPair ()) {
																se = path -> getLeft ();
																if (se -> isAtom ()) {
																	sa = se -> getAtom ();
																	if (sa == key) {
																		path = path -> getRight ();
																		if (path -> isPair ()) {
																			se = path -> getLeft ();
																			if (se -> isAtom ()) {
																				sa = se -> getAtom ();
																				if (sa == BP) return update_value (& ph -> operators [ind] . sens . freq . key . BP, v, o, 1);
																				if (sa == left) return update_value (& ph -> operators [ind] . sens . freq . key . left, v, o, 1);
																				if (sa == right) return update_value (& ph -> operators [ind] . sens . freq . key . right, v, o, 1);
																			}
																		}
																		return false;
																	}
																	if (sa == eg)  return update_value (& ph -> operators [ind] . sens . freq . eg, v, o, 1);
																	if (sa == pitch) return update_value (& ph -> operators [ind] . sens . freq . pitch, v, o, 1);
																	if (sa == lfo) {
																		path = path -> getRight ();
																		if (path -> isPair ()) {
																			se = path -> getLeft ();
																			if (se -> isInteger ()) {
																				int li = se -> getInteger () - 1;
																				if (li < 0 || li > 1) return false;
																				return update_value (& ph -> operators [ind] . sens . freq . lfo [li], v, o, 1);
																			}
																		}
																		return false;
																	}
																}
															}
															return false;
														}
														if (sa == amp) {
															path = path -> getRight ();
															if (path -> isPair ()) {
																se = path -> getLeft ();
																if (se -> isAtom ()) {
																	sa = se -> getAtom ();
																	if (sa == key) {
																		path = path -> getRight ();
																		if (path -> isPair ()) {
																			se = path -> getLeft ();
																			if (se -> isAtom ()) {
																				sa = se -> getAtom ();
																				if (sa == BP) return update_value (& ph -> operators [ind] . sens . amp . key . BP, v, o, 1);
																				if (sa == left) return update_value (& ph -> operators [ind] . sens . amp . key . left, v, o, 1);
																				if (sa == right) return update_value (& ph -> operators [ind] . sens . amp . key . right, v, o, 1);
																			}
																		}
																		return false;
																	}
																	if (sa == velocity) {
																		path = path -> getRight ();
																		if (path -> isPair ()) {
																			se = path -> getLeft ();
																			if (se -> isAtom ()) {
																				sa = se -> getAtom ();
																				if (sa == BP) return update_value (& ph -> operators [ind] . sens . amp . velocity . BP, v, o, 1);
																				if (sa == left) return update_value (& ph -> operators [ind] . sens . amp . velocity . left, v, o, 1);
																				if (sa == right) return update_value (& ph -> operators [ind] . sens . amp . velocity . right, v, o, 1);
																			}
																		}
																		return false;
																	}
																	if (sa == lfo) return update_value (& ph -> operators [ind] . sens . amp . lfo, v, o, 1);
																}
															}
															return false;
														}
													}
												}
												return false;
											}
										}
									}
								}
							}
							return false;
						}
						if (sa == noise) {
							path = path -> getRight ();
							if (path -> isPair ()) {
								se = path -> getLeft ();
								if (se -> isAtom ()) {
									sa = se -> getAtom ();
									if (sa == amp) return update_value (& ph -> noise . amp, v, o, 3);
									if (sa == time1) return update_value (& ph -> noise . time [0], v, o, 4);
									if (sa == time2) return update_value (& ph -> noise . time [1], v, o, 4);
									if (sa == time3) return update_value (& ph -> noise . time [2], v, o, 4);
									if (sa == time4) return update_value (& ph -> noise . time [3], v, o, 4);
									if (sa == level1) return update_value (& ph -> noise . level [0], v, o, 1);
									if (sa == level2) return update_value (& ph -> noise . level [1], v, o, 1);
									if (sa == level3) return update_value (& ph -> noise . level [2], v, o, 1);
									if (sa == level4) return update_value (& ph -> noise . level [3], v, o, 1);
								}
							}
							return false;
						}
						if (sa == filter) {
							path = path -> getRight ();
							if (path -> isPair ()) {
								se = path -> getLeft ();
								if (se -> isAtom ()) {
									sa = se -> getAtom ();
									if (sa == freq) return update_value (& ph -> filter . freq, v, o, 2);
									if (sa == resonance) return update_value (& ph -> filter . resonance, v, o, 1);
									if (sa == amp) return update_value (& ph -> filter . amp, v, o, 3);
									if (sa == sens) {
										path = path -> getRight ();
										if (path -> isPair ()) {
											se = path -> getLeft ();
											if (se -> isAtom ()) {
												sa = se -> getAtom ();
												if (sa == eg) return update_value (& ph -> filter . sens . eg, v, o, 1);
												if (sa == key) {
													path = path -> getRight ();
													if (path -> isPair ()) {
														se = path -> getLeft ();
														if (se -> isAtom ()) {
															sa = se -> getAtom ();
															if (sa == BP) return update_value (& ph -> filter . sens . key . BP, v, o, 1);
															if (sa == left) return update_value (& ph -> filter . sens . key . left, v, o, 1);
															if (sa == right) return update_value (& ph -> filter . sens . key . right, v, o, 1);
														}
													}
													return false;
												}
												if (sa == pitch) return update_value (& ph -> filter . sens . pitch, v, o, 1);
												if (sa == lfo) {
													path = path -> getRight ();
													if (path -> isPair ()) {
														se = path -> getLeft ();
														if (se -> isInteger ()) {
															int li = se -> getInteger () - 1;
															if (li < 0 || li > 1) return false;
															return update_value (& ph -> filter . sens . lfo [li], v, o, 1);
														}
													}
													return false;
												}
											}
										}
										return false;
									}
								}
							}
							return false;
						}
						if (sa == adsr) {
							path = path -> getRight ();
							if (path -> isPair ()) {
								se = path -> getLeft ();
								if (se -> isAtom ()) {
									sa = se -> getAtom ();
									if (sa == amp) {
										path = path -> getRight ();
										if (path -> isPair ()) {
											se = path -> getLeft ();
											if (se -> isAtom ()) {
												sa = se -> getAtom ();
												if (sa == attack) return update_value (& ph -> adsr . amp . attack, v, o, 4);
												if (sa == decay) return update_value (& ph -> adsr . amp . decay, v, o, 4);
												if (sa == sustain) return update_value (& ph -> adsr . amp . sustain, v, o, 3);
												if (sa == release) return update_value (& ph -> adsr . amp . release, v, o, 4);
												if (sa == egscal) {
													path = path -> getRight ();
													if (path -> isPair ()) {
														se = path -> getLeft ();
														if (se -> isAtom ()) {
															sa = se -> getAtom ();
															if (sa == BP) return update_value (& ph -> adsr . amp . egscal . BP, v, o, 1);
															if (sa == left) return update_value (& ph -> adsr . amp . egscal . left, v, o, 1);
															if (sa == right) return update_value (& ph -> adsr . amp . egscal . right, v, o, 1);
														}
													}
													return false;
												}
											}
										}
										return false;
									}
									if (sa == freq) {
										path = path -> getRight ();
										if (path -> isPair ()) {
											se = path -> getLeft ();
											if (se -> isAtom ()) {
												sa = se -> getAtom ();
												if (sa == time1) return update_value (& ph -> adsr . freq . time [0], v, o, 4);
												if (sa == time2) return update_value (& ph -> adsr . freq . time [1], v, o, 4);
												if (sa == time3) return update_value (& ph -> adsr . freq . time [2], v, o, 4);
												if (sa == time4) return update_value (& ph -> adsr . freq . time [3], v, o, 4);
												if (sa == level1) return update_value (& ph -> adsr . freq . level [0], v, o, 1);
												if (sa == level2) return update_value (& ph -> adsr . freq . level [1], v, o, 1);
												if (sa == level3) return update_value (& ph -> adsr . freq . level [2], v, o, 1);
												if (sa == level4) return update_value (& ph -> adsr . freq . level [3], v, o, 1);
												if (sa == egscal) {
													path = path -> getRight ();
													if (path -> isPair ()) {
														se = path -> getLeft ();
														if (se -> isAtom ()) {
															sa = se -> getAtom ();
															if (sa == BP) return update_value (& ph -> adsr . freq . egscal . BP, v, o, 1);
															if (sa == left) return update_value (& ph -> adsr . freq . egscal . left, v, o, 1);
															if (sa == right) return update_value (& ph -> adsr . freq . egscal . right, v, o, 1);
														}
													}
													return false;
												}
											}
										}
										return false;
									}
								}
							}
							return false;
						}
						if (sa == portamento) {
							path = path -> getRight ();
							if (path -> isPair ()) {
								se = path -> getLeft ();
								if (se -> isAtom ()) {
									sa = se -> getAtom ();
									if (sa == porta) return update_value (& ph -> portamento . porta, v, o, 5);
									if (sa == time) return update_value (& ph -> portamento . time, v, o, 4);
									if (sa == legato) return update_value (& ph -> portamento . legato, v, o, 5);
									if (sa == hold) return update_value (& ph -> portamento . hold, v, o, 5);
								}
							}
							return false;
						}
						if (sa == vector) {
							path = path -> getRight ();
							if (path -> isPair ()) {
								se = path -> getLeft ();
								if (se -> isAtom ()) {
									sa = se -> getAtom ();
									if (sa == X) {
										if (v -> isVar ()) return ph -> X_data . return_content (v);
										if (v -> isPair ()) return ph -> X_data . read_content (v);
										return false;
									}
									if (sa == Y) {
										if (v -> isVar ()) return ph -> Y_data . return_content (v);
										if (v -> isPair ()) return ph -> Y_data . read_content (v);
										return false;
									}
								}
							}
							return true;
						}
						if (sa == key_map) {
							if (v -> isVar ()) return ph -> key_map . return_content (v);
							if (v -> isPair ()) return ph -> key_map . read_content (v);
							return false;
						}
					}
					return false;
				}
			}
		}
		return native_moonbase :: code (parameters, resolution);
	}
Пример #29
0
/**
 * \brief Get the value of all fields of the current item.
 */
void bf::item_field_edit::update_values()
{
  for ( long i=0; i!=GetItemCount(); ++i )
    update_value(i);
} // item_field_edit::update_values()
Пример #30
0
static void find_best(struct file *a, struct file *b,
		      int alo, int ahi,
		      int blo, int bhi, struct best *best)
{
	int klo, khi, k;
	int f;

	struct v *valloc = xmalloc(sizeof(struct v)*((ahi-alo)+(bhi-blo)+5));
	struct v *v = valloc + (bhi-alo+2);

	k = klo = khi = alo-blo;
	f = alo+blo; /* front that moves forward */
	v[k].val = 0;
	v[k].c = -1;

	while (f < ahi+bhi) {
		int x, y;

		f++;
		for (k = klo+1; k <= khi-1 ; k += 2) {
			struct v vnew, vnew2;
			x = (k+f)/2;
			y = x-k;
			/* first consider the diagonal - if possible
			 * it is always preferred
			 */
			if (match(&a->list[x-1], &b->list[y-1])) {
				vnew = v[k];
				update_value(&v[k], 0, k, x);
				if (v[k].c < 0)
					abort();
				if (v[k].val > best[v[k].c].val) {
					int chunk = v[k].c;
					best[chunk].xlo = v[k].x;
					best[chunk].ylo = v[k].y;
					best[chunk].xhi = x;
					best[chunk].yhi = y;
					best[chunk].val = v[k].val;
				}
			} else {
				/* First consider a y-step: adding a
				 * symbol from B */
				vnew = v[k+1];
				update_value(&vnew, -1, k, x);
				/* might cross a chunk boundary */
				if (b->list[y-1].len && b->list[y-1].start[0] == 0) {
					vnew.c = atoi(b->list[y-1].start+1);
					vnew.val = 0;
				}

				/* Not consider an x-step: deleting
				 * a symbol.  This cannot be a chunk
				 * boundary as there aren't any in 'A'
				 */
				vnew2 = v[k-1];
				update_value(&vnew2, 1, k, x);

				/* Now choose the best. */
				if (vnew2.val > vnew.val)
					v[k] = vnew2;
				else
					v[k] = vnew;
			}
		}
		/* extend or contract range */
		klo--;
		v[klo] = v[klo+1];
		x = (klo+f)/2; y = x-klo;
		update_value(&v[klo], -1, klo, x);
		if (y <= bhi && b->list[y-1].len && b->list[y-1].start[0] == 0) {
			v[klo].c = atoi(b->list[y-1].start+1);
			v[klo].val = 0;
		}
		while (klo+2 < (ahi-bhi) &&
		       (y > bhi ||
			(best_val(&v[klo], min(ahi-x, bhi-y)) < best[v[klo].c].val &&
			 best_val(&v[klo+1], min(ahi-x, bhi-y+1)) < best[v[klo+1].c].val
				)
			       )) {
			klo += 2;
			x = (klo+f)/2; y = x-klo;
		}

		khi++;
		v[khi] = v[khi-1];
		x = (khi+f)/2; y = x - khi;
		update_value(&v[khi], -1, khi, x);
		while (khi-2 > (ahi-bhi) &&
		       (x > ahi ||
			(v[khi].c >= 0 &&
			 best_val(&v[khi], min(ahi-x, bhi-y)) < best[v[khi].c].val &&
			 best_val(&v[khi-1], min(ahi-x+1, bhi-y)) < best[v[khi].c].val
				)
			       )) {
			khi -= 2;
			x = (khi+f)/2; y = x - khi;
		}

	}
	free(valloc);
}