Пример #1
0
unsigned int
encode_vbind (char *oid_string, char oid_asntype, union t_val *value,
	      unsigned char *out_buffer, size_t out_size)
{
  oid var_name[MAX_OID_LEN];
  size_t name_len = MAX_OID_LEN;
  oid oid_value[MAX_OID_LEN];
  size_t oid_value_len = MAX_OID_LEN;
  unsigned char *data_ptr;
  unsigned char buf[SPRINT_MAX_LEN];
  unsigned int ltmp;
  struct tree *tp;
  struct range_list *rp;
  long len=0;
  int rv;
  long longval;
  unsigned long ulongval;

  memset (buf, 0, SPRINT_MAX_LEN);
  if (!get_node (oid_string, var_name, &name_len))
    {
      if (!read_objid (oid_string, var_name, &name_len))
	{
	  /* enable random access */
	  if (!netsnmp_ds_get_boolean
	      (NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_RANDOM_ACCESS))
	    {
	      netsnmp_ds_toggle_boolean (NETSNMP_DS_LIBRARY_ID,
					 NETSNMP_DS_LIB_RANDOM_ACCESS);
	    }

	  if (!get_node (oid_string, var_name, &name_len))
	    {
	      /* Not found, try UCD style OID access */
	      netsnmp_ds_toggle_boolean (NETSNMP_DS_LIBRARY_ID,
					 NETSNMP_DS_LIB_READ_UCD_STYLE_OID);
	      if (!netsnmp_ds_get_boolean
		  (NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_READ_UCD_STYLE_OID))
		{
		  netsnmp_ds_toggle_boolean (NETSNMP_DS_LIBRARY_ID,
					     NETSNMP_DS_LIB_READ_UCD_STYLE_OID);
		}

	      if (!read_objid (oid_string, var_name, &name_len))
		{

		  /* Hmm, still not found, go back to net-snmp-style OID and try regex access */
		  netsnmp_ds_toggle_boolean (NETSNMP_DS_LIBRARY_ID,
					     NETSNMP_DS_LIB_READ_UCD_STYLE_OID);

		  if (!netsnmp_ds_get_boolean
		      (NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_REGEX_ACCESS))
		    {
		      netsnmp_ds_toggle_boolean (NETSNMP_DS_LIBRARY_ID,
						 NETSNMP_DS_LIB_REGEX_ACCESS);
		    }

		  if (!get_wild_node (oid_string, var_name, &name_len))
		    {
		      /* Ran out of ideas. */
		      fprintf(stderr, "/* Error: Can't find oid %s at line %d */\n",
			      oid_string, line);
		      snmp_perror ("encode_vbind");
		      return 0;
		    }
		}
	    }
	}
    }

  switch (oid_asntype)
    {
    case 'i':
      longval = value->intval;
      data_ptr = _docsis_snmp_build_var_op (out_buffer,
				    var_name,
				    &name_len,
				    ASN_INTEGER,
				    sizeof (long),
				    (unsigned char *) &longval,
				    &out_size);
      return data_ptr - out_buffer;
      break;
      ;;
    case 'g':
      ulongval = value->intval;
      data_ptr = _docsis_snmp_build_var_op (out_buffer,
				    var_name,
				    &name_len,
				    ASN_GAUGE,
				    sizeof (unsigned long),
				    (unsigned char *) &ulongval,
				    &out_size);
      return data_ptr - out_buffer;
      break;
      ;;
    case 'c':
      ulongval = value->intval;
      data_ptr = _docsis_snmp_build_var_op (out_buffer,
				    var_name,
				    &name_len,
				    ASN_COUNTER,
				    sizeof (unsigned long),
				    (unsigned char *) &ulongval,
				    &out_size);
      return data_ptr - out_buffer;
      break;
      ;;
    case 'u':
      ulongval = value->intval;
      data_ptr = _docsis_snmp_build_var_op (out_buffer,
				    var_name,
				    &name_len,
				    ASN_GAUGE,
				    sizeof (unsigned long),
				    (unsigned char *) &ulongval,
				    &out_size);
      return data_ptr - out_buffer;
      break;
      ;;
    case 't':
      ulongval = value->intval;
      data_ptr = _docsis_snmp_build_var_op (out_buffer,
                                    var_name,
                                    &name_len,
                                    ASN_TIMETICKS,
                                    sizeof (unsigned long),
                                    (unsigned char *) &ulongval,
                                    &out_size);
      return data_ptr - out_buffer;
      break;
      ;;
    case 's':
    case 'x':
    case 'd':
      if (oid_asntype == 'd')
	{
	  /* ltmp = ascii_to_binary(value->strval, buf);
	     strncpy((char*)buf, value, SPRINT_MAX_BUF);
	     ltmp = strlen((char*)buf); */
	}
      else if (oid_asntype == 's')
	{
	  strncpy ((char *) buf, value->strval, SPRINT_MAX_LEN);
	  len = strlen ((char *) buf);
	}
      else if (oid_asntype == 'x')
	{
	  if ((rv = hexadecimal_to_binary (value->strval, buf)) == -1)
	    {
	      fprintf(stderr, "Invalid hexadecimal string at line %d\n", line);
	      return 0;
	    }
	  ltmp = (unsigned int) rv;
	  len = ltmp;
	}

      if (len < 0 || len > SPRINT_MAX_LEN - 1)
	{
	  fprintf(stderr, "String too long at line %d, max allowed %d\n", line,
		  SPRINT_MAX_LEN);
	  return 0;
	  break;
	}
      tp = get_tree (var_name, name_len, get_tree_head ());
      if (tp && tp->ranges
	  && !netsnmp_ds_get_boolean (NETSNMP_DS_LIBRARY_ID,
				      NETSNMP_DS_LIB_DONT_CHECK_RANGE))
	{
	  rp = tp->ranges;
	  while (rp)
	    {
	      if (rp->low <= len && len <= rp->high)
		break;
	      rp = rp->next;
	    }
	  if (!rp)
	    {
	      fprintf(stderr, "Value too long at line %d\n", line);
	      return 0;
	      break;
	    }
	}
      /* If length is more than 127, won't fit into a 1-byte quantity */
      if (len+name_len+8 < 0x7f ) {
     		data_ptr = _docsis_snmp_build_var_op (out_buffer,
                                    var_name,
                                    &name_len,
                                    ASN_OCTET_STR,
                                    len, (unsigned char *) buf,
                                    &out_size);
      } else {
      		data_ptr = snmp_build_var_op (out_buffer,
				    var_name,
				    &name_len,
				    ASN_OCTET_STR,
				    len, (unsigned char *) buf,
				    &out_size);
      }
#ifdef DEBUG
      fprintf (stderr, "encoded len %ld var_len %d leftover %ud difference %d\n", len, name_len, out_size, (data_ptr - out_buffer) );
#endif
      return data_ptr - out_buffer;
      break;
      ;;
    case 'a':
      if (!inet_aton (value->strval, (struct in_addr *) &ltmp))
	{
	  fprintf(stderr, "Invalid IP address %s at line %d\n", value->strval, line);
	  return 0;
	}
      data_ptr = _docsis_snmp_build_var_op (out_buffer,
				    var_name,
				    &name_len,
				    ASN_IPADDRESS,
				    sizeof (struct in_addr),
				    (unsigned char *) &ltmp, &out_size);
      return data_ptr - out_buffer;
      break;
      ;;
    case 'o':

	strncpy ((char *) buf, value->strval, SPRINT_MAX_LEN);
	len = strlen ((char *) buf);

	if (!read_objid ((char *) buf, oid_value, &oid_value_len))
	  {
		fprintf(stderr, "Can't find oid %s at line %d\n", buf, line);
		return 0;
    	  }

	data_ptr = _docsis_snmp_build_var_op (out_buffer,
                                    var_name,
                                    &name_len,
                                    ASN_OBJECT_ID,
                                    oid_value_len*sizeof(oid),
                                    (unsigned char *) &oid_value, &out_size);
	return data_ptr - out_buffer;
	break;
	;;

    default:
      fprintf(stderr, "Variable type %s not supported yet\n", &oid_asntype);
      return 0;
      ;;
    }
/* NOTREACHED */
}
Пример #2
0
void insert_line(tree_node *tree, int new_key, char *new_line){
	//Inserts the line before the line of the number `new_key`, if such
	//a line exists, to `new_line` , renumbering all lines after that line.
	//If no such line exists, it `appends(new_line)` as last line.

	tree_node *temp_node;
	int finished;

	if(tree->left == NULL){
		//empty tree. no children
		tree->left = (tree_node *) new_line;
		//tree->key = new_key;
		tree->key +=1;
		tree->height = 0;
		tree->right = NULL;
	}

	if(tree->key == 1){
		//the root has one child
		tree_node *left_child, *right_child;
		
		left_child = get_node();
		right_child = get_node();

		left_child->left = tree->left;
		left_child->key = tree->key;

		right_child->left = (tree_node *) new_line;
		right_child->key += 1;

		tree->left = left_child;
		tree->right = right_child;
		tree->key += 1;
	}

	if (tree->key < new_key){
		//go to the left branch
		append_line(tree, new_line);
	}
	else{
		//go to the right branch
		tree_node *stack[STACK_MAX];
		int stack_ptr = 0;
		temp_node = tree;

		while(temp_node->right != NULL){
			stack[stack_ptr++] = temp_node;
			temp_node->key += 1;
			if (new_key <= temp_node->left->key){
				temp_node = temp_node->left;
			}
			else{
				new_key -= temp_node->left->key;
				temp_node = temp_node->right;
			}
		}

		tree_node *left_child, *right_child;
		left_child = get_node();
		right_child = get_node();

		left_child->left = temp_node->left;
		left_child->key = temp_node->key;

		right_child->left = (tree_node *) new_line;
		right_child->key += 1;

		temp_node->left = left_child;
		temp_node->right = right_child;
		temp_node->key += 1;
		temp_node->height = 1;

		//rebalance tree
		finished = 0;
		while(stack_ptr > 0  && !finished){
			int temp_height , old_height;
			temp_node = stack[--stack_ptr];
			old_height = temp_node->height;

			if(temp_node->left->height - temp_node->right->height == 2){

				if (temp_node->left->left->height - temp_node->right->height == 1){
					right_rotation(temp_node);
					temp_node->right->height = temp_node->right->left->height + 1;
					temp_node->height = temp_node->right->height + 1;
				}
				else{
					left_rotation(temp_node->left);
					right_rotation(temp_node);
					temp_height = temp_node->left->left->height;
					temp_node->left->height = temp_height + 1;
					temp_node->right->height = temp_height + 1;
					temp_node->height = temp_height + 2;
				}

			}
			else if (temp_node->left->height - temp_node->right->height == -2){

				if (temp_node->right->right->height - temp_node->left->height == 1){
					left_rotation(temp_node);
					temp_node->left->height = temp_node->left->right->height + 1;
					temp_node->height = temp_node->left->height + 1;
				}
				else{
					right_rotation(temp_node->right);
					left_rotation(temp_node);
					temp_height = temp_node->right->right->height;
					temp_node->left->height = temp_height + 1;
					temp_node->right->height = temp_height + 1;
					temp_node->height = temp_height + 2;
				}

			}
			else{
				//if no rotation needed, update height
				if (temp_node->left->height > temp_node->right->height){
					temp_node->height = temp_node->left->height + 1;
				}
				else{
					temp_node->height = temp_node->right->height + 1;
				}

			}

			if (temp_node->height == old_height){
				finished = 1;
			}
		}

	}
}
int pqrs_xml_compiler_get_preferences_number_node_tree_step(const pqrs_xml_compiler_preferences_number_node_tree* p) {
  auto node_tree = cast_to_preferences_number_node_tree(p);
  if (!node_tree) return 0;

  return (node_tree->get_node()).get_step();
}
Пример #4
0
void AnimationPlayer::_generate_node_caches(AnimationData *p_anim) {

	Node *parent = get_node(root);

	ERR_FAIL_COND(!parent);

	Animation *a = p_anim->animation.operator->();

	p_anim->node_cache.resize(a->get_track_count());

	for (int i = 0; i < a->get_track_count(); i++) {

		p_anim->node_cache[i] = NULL;
		RES resource;
		Node *child = parent->get_node_and_resource(a->track_get_path(i), resource);
		if (!child) {
			ERR_EXPLAIN("On Animation: '" + p_anim->name + "', couldn't resolve track:  '" + String(a->track_get_path(i)) + "'");
		}
		ERR_CONTINUE(!child); // couldn't find the child node
		uint32_t id = resource.is_valid() ? resource->get_instance_id() : child->get_instance_id();
		int bone_idx = -1;

		if (a->track_get_path(i).get_property() && Object::cast_to<Skeleton>(child)) {

			bone_idx = Object::cast_to<Skeleton>(child)->find_bone(a->track_get_path(i).get_property());
			if (bone_idx == -1) {

				continue;
			}
		}

		{
			if (!child->is_connected("tree_exited", this, "_node_removed"))
				child->connect("tree_exited", this, "_node_removed", make_binds(child), CONNECT_ONESHOT);
		}

		TrackNodeCacheKey key;
		key.id = id;
		key.bone_idx = bone_idx;

		if (node_cache_map.has(key)) {

			p_anim->node_cache[i] = &node_cache_map[key];
		} else {

			node_cache_map[key] = TrackNodeCache();

			p_anim->node_cache[i] = &node_cache_map[key];
			p_anim->node_cache[i]->path = a->track_get_path(i);
			p_anim->node_cache[i]->node = child;
			p_anim->node_cache[i]->resource = resource;
			p_anim->node_cache[i]->node_2d = Object::cast_to<Node2D>(child);
			if (a->track_get_type(i) == Animation::TYPE_TRANSFORM) {
				// special cases and caches for transform tracks

				// cache spatial
				p_anim->node_cache[i]->spatial = Object::cast_to<Spatial>(child);
				// cache skeleton
				p_anim->node_cache[i]->skeleton = Object::cast_to<Skeleton>(child);
				if (p_anim->node_cache[i]->skeleton) {

					StringName bone_name = a->track_get_path(i).get_property();
					if (bone_name.operator String() != "") {

						p_anim->node_cache[i]->bone_idx = p_anim->node_cache[i]->skeleton->find_bone(bone_name);
						if (p_anim->node_cache[i]->bone_idx < 0) {
							// broken track (nonexistent bone)
							p_anim->node_cache[i]->skeleton = NULL;
							p_anim->node_cache[i]->spatial = NULL;
							printf("bone is %ls\n", String(bone_name).c_str());
							ERR_CONTINUE(p_anim->node_cache[i]->bone_idx < 0);
						} else {
						}
					} else {
						// no property, just use spatialnode
						p_anim->node_cache[i]->skeleton = NULL;
					}
				}
			}
		}

		if (a->track_get_type(i) == Animation::TYPE_VALUE) {

			StringName property = a->track_get_path(i).get_property();
			if (!p_anim->node_cache[i]->property_anim.has(property)) {

				TrackNodeCache::PropertyAnim pa;
				pa.prop = property;
				pa.object = resource.is_valid() ? (Object *)resource.ptr() : (Object *)child;
				pa.special = SP_NONE;
				pa.owner = p_anim->node_cache[i];
				if (false && p_anim->node_cache[i]->node_2d) {

					if (pa.prop == SceneStringNames::get_singleton()->transform_pos)
						pa.special = SP_NODE2D_POS;
					else if (pa.prop == SceneStringNames::get_singleton()->transform_rot)
						pa.special = SP_NODE2D_ROT;
					else if (pa.prop == SceneStringNames::get_singleton()->transform_scale)
						pa.special = SP_NODE2D_SCALE;
				}
				p_anim->node_cache[i]->property_anim[property] = pa;
			}
		}
	}
}
Пример #5
0
void AnimationTree::_process_graph(float p_delta) {

	_update_properties(); //if properties need updating, update them

	//check all tracks, see if they need modification

	root_motion_transform = Transform();

	if (!root.is_valid()) {
		ERR_PRINT("AnimationTree: root AnimationNode is not set, disabling playback.");
		set_active(false);
		cache_valid = false;
		return;
	}

	if (!has_node(animation_player)) {
		ERR_PRINT("AnimationTree: no valid AnimationPlayer path set, disabling playback");
		set_active(false);
		cache_valid = false;
		return;
	}

	AnimationPlayer *player = Object::cast_to<AnimationPlayer>(get_node(animation_player));

	ObjectID current_animation_player = 0;

	if (player) {
		current_animation_player = player->get_instance_id();
	}

	if (last_animation_player != current_animation_player) {

		if (last_animation_player) {
			Object *old_player = ObjectDB::get_instance(last_animation_player);
			if (old_player) {
				old_player->disconnect("caches_cleared", this, "_clear_caches");
			}
		}

		if (player) {
			player->connect("caches_cleared", this, "_clear_caches");
		}

		last_animation_player = current_animation_player;
	}

	if (!player) {
		ERR_PRINT("AnimationTree: path points to a node not an AnimationPlayer, disabling playback");
		set_active(false);
		cache_valid = false;
		return;
	}

	if (!cache_valid) {
		if (!_update_caches(player)) {
			return;
		}
	}

	{ //setup

		process_pass++;

		state.valid = true;
		state.invalid_reasons = "";
		state.animation_states.clear(); //will need to be re-created
		state.valid = true;
		state.player = player;
		state.last_pass = process_pass;
		state.tree = this;

		// root source blends

		root->blends.resize(state.track_count);
		float *src_blendsw = root->blends.ptrw();
		for (int i = 0; i < state.track_count; i++) {
			src_blendsw[i] = 1.0; //by default all go to 1 for the root input
		}
	}

	//process

	{

		if (started) {
			//if started, seek
			root->_pre_process(SceneStringNames::get_singleton()->parameters_base_path, NULL, &state, 0, true, Vector<StringName>());
			started = false;
		}

		root->_pre_process(SceneStringNames::get_singleton()->parameters_base_path, NULL, &state, p_delta, false, Vector<StringName>());
	}

	if (!state.valid) {
		return; //state is not valid. do nothing.
	}
	//apply value/transform/bezier blends to track caches and execute method/audio/animation tracks

	{

		bool can_call = is_inside_tree() && !Engine::get_singleton()->is_editor_hint();

		for (List<AnimationNode::AnimationState>::Element *E = state.animation_states.front(); E; E = E->next()) {

			const AnimationNode::AnimationState &as = E->get();

			Ref<Animation> a = as.animation;
			float time = as.time;
			float delta = as.delta;
			bool seeked = as.seeked;

			for (int i = 0; i < a->get_track_count(); i++) {

				NodePath path = a->track_get_path(i);

				ERR_CONTINUE(!track_cache.has(path));

				TrackCache *track = track_cache[path];
				if (track->type != a->track_get_type(i)) {
					continue; //may happen should not
				}

				track->root_motion = root_motion_track == path;

				ERR_CONTINUE(!state.track_map.has(path));
				int blend_idx = state.track_map[path];

				ERR_CONTINUE(blend_idx < 0 || blend_idx >= state.track_count);

				float blend = (*as.track_blends)[blend_idx];

				if (blend < CMP_EPSILON)
					continue; //nothing to blend

				switch (track->type) {

					case Animation::TYPE_TRANSFORM: {

						TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);

						if (track->root_motion) {

							if (t->process_pass != process_pass) {

								t->process_pass = process_pass;
								t->loc = Vector3();
								t->rot = Quat();
								t->rot_blend_accum = 0;
								t->scale = Vector3(1, 1, 1);
							}

							float prev_time = time - delta;
							if (prev_time < 0) {
								if (!a->has_loop()) {
									prev_time = 0;
								} else {
									prev_time = a->get_length() + prev_time;
								}
							}

							Vector3 loc[2];
							Quat rot[2];
							Vector3 scale[2];

							if (prev_time > time) {

								Error err = a->transform_track_interpolate(i, prev_time, &loc[0], &rot[0], &scale[0]);
								if (err != OK) {
									continue;
								}

								a->transform_track_interpolate(i, a->get_length(), &loc[1], &rot[1], &scale[1]);

								t->loc += (loc[1] - loc[0]) * blend;
								t->scale += (scale[1] - scale[0]) * blend;
								Quat q = Quat().slerp(rot[0].normalized().inverse() * rot[1].normalized(), blend).normalized();
								t->rot = (t->rot * q).normalized();

								prev_time = 0;
							}

							Error err = a->transform_track_interpolate(i, prev_time, &loc[0], &rot[0], &scale[0]);
							if (err != OK) {
								continue;
							}

							a->transform_track_interpolate(i, time, &loc[1], &rot[1], &scale[1]);

							t->loc += (loc[1] - loc[0]) * blend;
							t->scale += (scale[1] - scale[0]) * blend;
							Quat q = Quat().slerp(rot[0].normalized().inverse() * rot[1].normalized(), blend).normalized();
							t->rot = (t->rot * q).normalized();

							prev_time = 0;

						} else {
							Vector3 loc;
							Quat rot;
							Vector3 scale;

							Error err = a->transform_track_interpolate(i, time, &loc, &rot, &scale);
							//ERR_CONTINUE(err!=OK); //used for testing, should be removed

							if (t->process_pass != process_pass) {

								t->process_pass = process_pass;
								t->loc = loc;
								t->rot = rot;
								t->rot_blend_accum = 0;
								t->scale = scale;
							}

							if (err != OK)
								continue;

							t->loc = t->loc.linear_interpolate(loc, blend);
							if (t->rot_blend_accum == 0) {
								t->rot = rot;
								t->rot_blend_accum = blend;
							} else {
								float rot_total = t->rot_blend_accum + blend;
								t->rot = rot.slerp(t->rot, t->rot_blend_accum / rot_total).normalized();
								t->rot_blend_accum = rot_total;
							}
							t->scale = t->scale.linear_interpolate(scale, blend);
						}

					} break;
					case Animation::TYPE_VALUE: {

						TrackCacheValue *t = static_cast<TrackCacheValue *>(track);

						Animation::UpdateMode update_mode = a->value_track_get_update_mode(i);

						if (update_mode == Animation::UPDATE_CONTINUOUS || update_mode == Animation::UPDATE_CAPTURE) { //delta == 0 means seek

							Variant value = a->value_track_interpolate(i, time);

							if (value == Variant())
								continue;

							if (t->process_pass != process_pass) {
								t->value = value;
								t->process_pass = process_pass;
							}

							Variant::interpolate(t->value, value, blend, t->value);

						} else if (delta != 0) {

							List<int> indices;
							a->value_track_get_key_indices(i, time, delta, &indices);

							for (List<int>::Element *F = indices.front(); F; F = F->next()) {

								Variant value = a->track_get_key_value(i, F->get());
								t->object->set_indexed(t->subpath, value);
							}
						}

					} break;
					case Animation::TYPE_METHOD: {

						if (delta == 0) {
							continue;
						}
						TrackCacheMethod *t = static_cast<TrackCacheMethod *>(track);

						List<int> indices;

						a->method_track_get_key_indices(i, time, delta, &indices);

						for (List<int>::Element *F = indices.front(); F; F = F->next()) {

							StringName method = a->method_track_get_name(i, F->get());
							Vector<Variant> params = a->method_track_get_params(i, F->get());

							int s = params.size();

							ERR_CONTINUE(s > VARIANT_ARG_MAX);
							if (can_call) {
								t->object->call_deferred(
										method,
										s >= 1 ? params[0] : Variant(),
										s >= 2 ? params[1] : Variant(),
										s >= 3 ? params[2] : Variant(),
										s >= 4 ? params[3] : Variant(),
										s >= 5 ? params[4] : Variant());
							}
						}

					} break;
					case Animation::TYPE_BEZIER: {

						TrackCacheBezier *t = static_cast<TrackCacheBezier *>(track);

						float bezier = a->bezier_track_interpolate(i, time);

						if (t->process_pass != process_pass) {
							t->value = bezier;
							t->process_pass = process_pass;
						}

						t->value = Math::lerp(t->value, bezier, blend);

					} break;
					case Animation::TYPE_AUDIO: {

						TrackCacheAudio *t = static_cast<TrackCacheAudio *>(track);

						if (seeked) {
							//find whathever should be playing
							int idx = a->track_find_key(i, time);
							if (idx < 0)
								continue;

							Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx);
							if (!stream.is_valid()) {
								t->object->call("stop");
								t->playing = false;
								playing_caches.erase(t);
							} else {
								float start_ofs = a->audio_track_get_key_start_offset(i, idx);
								start_ofs += time - a->track_get_key_time(i, idx);
								float end_ofs = a->audio_track_get_key_end_offset(i, idx);
								float len = stream->get_length();

								if (start_ofs > len - end_ofs) {
									t->object->call("stop");
									t->playing = false;
									playing_caches.erase(t);
									continue;
								}

								t->object->call("set_stream", stream);
								t->object->call("play", start_ofs);

								t->playing = true;
								playing_caches.insert(t);
								if (len && end_ofs > 0) { //force a end at a time
									t->len = len - start_ofs - end_ofs;
								} else {
									t->len = 0;
								}

								t->start = time;
							}

						} else {
							//find stuff to play
							List<int> to_play;
							a->track_get_key_indices_in_range(i, time, delta, &to_play);
							if (to_play.size()) {
								int idx = to_play.back()->get();

								Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx);
								if (!stream.is_valid()) {
									t->object->call("stop");
									t->playing = false;
									playing_caches.erase(t);
								} else {
									float start_ofs = a->audio_track_get_key_start_offset(i, idx);
									float end_ofs = a->audio_track_get_key_end_offset(i, idx);
									float len = stream->get_length();

									t->object->call("set_stream", stream);
									t->object->call("play", start_ofs);

									t->playing = true;
									playing_caches.insert(t);
									if (len && end_ofs > 0) { //force a end at a time
										t->len = len - start_ofs - end_ofs;
									} else {
										t->len = 0;
									}

									t->start = time;
								}
							} else if (t->playing) {

								bool loop = a->has_loop();

								bool stop = false;

								if (!loop && time < t->start) {
									stop = true;
								} else if (t->len > 0) {
									float len = t->start > time ? (a->get_length() - t->start) + time : time - t->start;

									if (len > t->len) {
										stop = true;
									}
								}

								if (stop) {
									//time to stop
									t->object->call("stop");
									t->playing = false;
									playing_caches.erase(t);
								}
							}
						}

						float db = Math::linear2db(MAX(blend, 0.00001));
						if (t->object->has_method("set_unit_db")) {
							t->object->call("set_unit_db", db);
						} else {
							t->object->call("set_volume_db", db);
						}
					} break;
					case Animation::TYPE_ANIMATION: {

						TrackCacheAnimation *t = static_cast<TrackCacheAnimation *>(track);

						AnimationPlayer *player2 = Object::cast_to<AnimationPlayer>(t->object);

						if (!player2)
							continue;

						if (delta == 0 || seeked) {
							//seek
							int idx = a->track_find_key(i, time);
							if (idx < 0)
								continue;

							float pos = a->track_get_key_time(i, idx);

							StringName anim_name = a->animation_track_get_key_animation(i, idx);
							if (String(anim_name) == "[stop]" || !player2->has_animation(anim_name))
								continue;

							Ref<Animation> anim = player2->get_animation(anim_name);

							float at_anim_pos;

							if (anim->has_loop()) {
								at_anim_pos = Math::fposmod(time - pos, anim->get_length()); //seek to loop
							} else {
								at_anim_pos = MAX(anim->get_length(), time - pos); //seek to end
							}

							if (player2->is_playing() || seeked) {
								player2->play(anim_name);
								player2->seek(at_anim_pos);
								t->playing = true;
								playing_caches.insert(t);
							} else {
								player2->set_assigned_animation(anim_name);
								player2->seek(at_anim_pos, true);
							}
						} else {
							//find stuff to play
							List<int> to_play;
							a->track_get_key_indices_in_range(i, time, delta, &to_play);
							if (to_play.size()) {
								int idx = to_play.back()->get();

								StringName anim_name = a->animation_track_get_key_animation(i, idx);
								if (String(anim_name) == "[stop]" || !player2->has_animation(anim_name)) {

									if (playing_caches.has(t)) {
										playing_caches.erase(t);
										player2->stop();
										t->playing = false;
									}
								} else {
									player2->play(anim_name);
									t->playing = true;
									playing_caches.insert(t);
								}
							}
						}

					} break;
				}
			}
		}
	}

	{
		// finally, set the tracks
		const NodePath *K = NULL;
		while ((K = track_cache.next(K))) {
			TrackCache *track = track_cache[*K];
			if (track->process_pass != process_pass)
				continue; //not processed, ignore

			switch (track->type) {

				case Animation::TYPE_TRANSFORM: {

					TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);

					Transform xform;
					xform.origin = t->loc;

					xform.basis.set_quat_scale(t->rot, t->scale);

					if (t->root_motion) {

						root_motion_transform = xform;

						if (t->skeleton && t->bone_idx >= 0) {
							root_motion_transform = (t->skeleton->get_bone_rest(t->bone_idx) * root_motion_transform) * t->skeleton->get_bone_rest(t->bone_idx).affine_inverse();
						}
					} else if (t->skeleton && t->bone_idx >= 0) {

						t->skeleton->set_bone_pose(t->bone_idx, xform);

					} else {

						t->spatial->set_transform(xform);
					}

				} break;
				case Animation::TYPE_VALUE: {

					TrackCacheValue *t = static_cast<TrackCacheValue *>(track);

					t->object->set_indexed(t->subpath, t->value);

				} break;
				case Animation::TYPE_BEZIER: {

					TrackCacheBezier *t = static_cast<TrackCacheBezier *>(track);

					t->object->set_indexed(t->subpath, t->value);

				} break;
				default: {
				} //the rest don't matter
			}
		}
	}
}
Пример #6
0
void GraphEdit::_top_layer_input(const Ref<InputEvent> &p_ev) {

	Ref<InputEventMouseButton> mb = p_ev;
	if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT && mb->is_pressed()) {

		Ref<Texture> port = get_icon("port", "GraphNode");
		Vector2 mpos(mb->get_position().x, mb->get_position().y);
		for (int i = get_child_count() - 1; i >= 0; i--) {

			GraphNode *gn = Object::cast_to<GraphNode>(get_child(i));
			if (!gn)
				continue;

			for (int j = 0; j < gn->get_connection_output_count(); j++) {

				Vector2 pos = gn->get_connection_output_position(j) + gn->get_position();
				if (is_in_hot_zone(pos, mpos)) {

					if (valid_left_disconnect_types.has(gn->get_connection_output_type(j))) {
						//check disconnect
						for (List<Connection>::Element *E = connections.front(); E; E = E->next()) {

							if (E->get().from == gn->get_name() && E->get().from_port == j) {

								Node *to = get_node(String(E->get().to));
								if (Object::cast_to<GraphNode>(to)) {

									connecting_from = E->get().to;
									connecting_index = E->get().to_port;
									connecting_out = false;
									connecting_type = Object::cast_to<GraphNode>(to)->get_connection_input_type(E->get().to_port);
									connecting_color = Object::cast_to<GraphNode>(to)->get_connection_input_color(E->get().to_port);
									connecting_target = false;
									connecting_to = pos;
									just_disconnected = true;

									emit_signal("disconnection_request", E->get().from, E->get().from_port, E->get().to, E->get().to_port);
									to = get_node(String(connecting_from)); //maybe it was erased
									if (Object::cast_to<GraphNode>(to)) {
										connecting = true;
									}
									return;
								}
							}
						}
					}

					connecting = true;
					connecting_from = gn->get_name();
					connecting_index = j;
					connecting_out = true;
					connecting_type = gn->get_connection_output_type(j);
					connecting_color = gn->get_connection_output_color(j);
					connecting_target = false;
					connecting_to = pos;
					just_disconnected = false;
					return;
				}
			}

			for (int j = 0; j < gn->get_connection_input_count(); j++) {

				Vector2 pos = gn->get_connection_input_position(j) + gn->get_position();
				if (is_in_hot_zone(pos, mpos)) {

					if (right_disconnects || valid_right_disconnect_types.has(gn->get_connection_input_type(j))) {
						//check disconnect
						for (List<Connection>::Element *E = connections.front(); E; E = E->next()) {

							if (E->get().to == gn->get_name() && E->get().to_port == j) {

								Node *fr = get_node(String(E->get().from));
								if (Object::cast_to<GraphNode>(fr)) {

									connecting_from = E->get().from;
									connecting_index = E->get().from_port;
									connecting_out = true;
									connecting_type = Object::cast_to<GraphNode>(fr)->get_connection_output_type(E->get().from_port);
									connecting_color = Object::cast_to<GraphNode>(fr)->get_connection_output_color(E->get().from_port);
									connecting_target = false;
									connecting_to = pos;
									just_disconnected = true;

									emit_signal("disconnection_request", E->get().from, E->get().from_port, E->get().to, E->get().to_port);
									fr = get_node(String(connecting_from)); //maybe it was erased
									if (Object::cast_to<GraphNode>(fr)) {
										connecting = true;
									}
									return;
								}
							}
						}
					}

					connecting = true;
					connecting_from = gn->get_name();
					connecting_index = j;
					connecting_out = false;
					connecting_type = gn->get_connection_input_type(j);
					connecting_color = gn->get_connection_input_color(j);
					connecting_target = false;
					connecting_to = pos;
					just_disconnected = true;

					return;
				}
			}
		}
	}

	Ref<InputEventMouseMotion> mm = p_ev;
	if (mm.is_valid() && connecting) {

		connecting_to = mm->get_position();
		connecting_target = false;
		top_layer->update();

		Ref<Texture> port = get_icon("port", "GraphNode");
		Vector2 mpos = mm->get_position();
		for (int i = get_child_count() - 1; i >= 0; i--) {

			GraphNode *gn = Object::cast_to<GraphNode>(get_child(i));
			if (!gn)
				continue;

			if (!connecting_out) {
				for (int j = 0; j < gn->get_connection_output_count(); j++) {

					Vector2 pos = gn->get_connection_output_position(j) + gn->get_position();
					int type = gn->get_connection_output_type(j);
					if ((type == connecting_type || valid_connection_types.has(ConnType(type, connecting_type))) && is_in_hot_zone(pos, mpos)) {

						connecting_target = true;
						connecting_to = pos;
						connecting_target_to = gn->get_name();
						connecting_target_index = j;
						return;
					}
				}
			} else {

				for (int j = 0; j < gn->get_connection_input_count(); j++) {

					Vector2 pos = gn->get_connection_input_position(j) + gn->get_position();
					int type = gn->get_connection_input_type(j);
					if ((type == connecting_type || valid_connection_types.has(ConnType(type, connecting_type))) && is_in_hot_zone(pos, mpos)) {
						connecting_target = true;
						connecting_to = pos;
						connecting_target_to = gn->get_name();
						connecting_target_index = j;
						return;
					}
				}
			}
		}
	}

	if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT && !mb->is_pressed()) {

		if (connecting && connecting_target) {

			String from = connecting_from;
			int from_slot = connecting_index;
			String to = connecting_target_to;
			int to_slot = connecting_target_index;

			if (!connecting_out) {
				SWAP(from, to);
				SWAP(from_slot, to_slot);
			}
			emit_signal("connection_request", from, from_slot, to, to_slot);

		} else if (!just_disconnected) {
			String from = connecting_from;
			int from_slot = connecting_index;
			Vector2 ofs = Vector2(mb->get_position().x, mb->get_position().y);
			emit_signal("connection_to_empty", from, from_slot, ofs);
		}
		connecting = false;
		top_layer->update();
		update();
		connections_layer->update();
	}
}
Пример #7
0
int ex_cvt_nodes_to_sides(int exoid, void_int *num_elem_per_set, void_int *num_nodes_per_set,
                          void_int *side_sets_elem_index, /* unused */
                          void_int *side_sets_node_index, /* unused */
                          void_int *side_sets_elem_list, void_int *side_sets_node_list,
                          void_int *side_sets_side_list)
{
  size_t    i, j, k, n;
  int       num_side_sets, num_elem_blks;
  int64_t   tot_num_elem = 0, tot_num_ss_elem = 0, elem_num = 0, ndim;
  void_int *elem_blk_ids     = NULL;
  void_int *connect          = NULL;
  void_int *ss_elem_ndx      = NULL;
  void_int *ss_elem_node_ndx = NULL;
  void_int *ss_parm_ndx      = NULL;
  size_t    elem_ctr, node_ctr, elem_num_pos;
  int       num_nodes_per_elem, num_node_per_side;

  int *same_elem_type = NULL;
  int  el_type        = 0;

  int int_size;
  int ids_size;

  struct elem_blk_parm *elem_blk_parms = NULL;

  int err_stat = EX_NOERR;

  /* node to side translation tables -
     These tables are used to look up the side number based on the
     first and second node in the side/face list. The side node order
     is found in the original Exodus document, SAND87-2997. The element
     node order is found in the ExodusII document, SAND92-2137. These
     tables were generated by following the right-hand rule for determining
     the outward normal. Note: Only the more complex 3-D shapes require
     these tables, the simple shapes are trivial - the first node found
     is also the side number.
  */

  /*    1     2   3    4                                          node 1 */
  static int shell_table[2][8] = {
      {2, 4, 3, 1, 4, 2, 1, 3}, /* node 2 */
      {1, 2, 1, 2, 1, 2, 1, 2}  /* side # */
  };

  /*    1     2   3    4                                          node 1 */
  static int shell_edge_table[2][8] = {
      {2, 4, 3, 1, 4, 2, 1, 3}, /* node 2 */
      {3, 6, 4, 3, 5, 4, 6, 5}  /* side # */
  };

  /*    1     2   3                                               node 1 */
  static int trishell_table[2][6] = {
      {2, 3, 3, 1, 1, 2}, /* node 2 */
      {1, 2, 1, 2, 1, 2}  /* side # */
  };

  /*     1      2      3      4                                   node 1 */
  static int tetra_table[2][12] = {
      {2, 3, 4, 1, 3, 4, 4, 1, 2, 1, 2, 3}, /* node 2 */
      {1, 4, 3, 4, 2, 1, 2, 3, 4, 1, 2, 3}  /* side # */
  };

#if 0
  static int wedge_table[2][18]  = {
    /*     1      2      3      4      5      6                     node 1 */
    {2,4,3, 5,1,3, 6,1,2, 1,6,5, 6,2,4, 4,3,5},              /* node 2 */
    {1,3,4, 1,4,2, 2,3,4, 1,3,5, 5,2,1, 5,3,2}               /* side # */
  };
#endif

  static int hex_table[2][24] = {
      /*     1      2      3      4      5      6      7      8       node 1 */
      {4, 2, 5, 1, 3, 6, 7, 4, 2, 3, 1, 8, 6, 8, 1, 5, 2, 7, 8, 6, 3, 7, 5, 4}, /* node 2 */
      {5, 1, 4, 5, 2, 1, 2, 3, 5, 5, 4, 3, 6, 4, 1, 1, 2, 6, 6, 2, 3, 3, 6, 4}  /* side # */
  };

  char errmsg[MAX_ERR_LENGTH];

  ex_check_valid_file_id(exoid);

  exerrval = 0; /* clear error code */

  /* first check if any side sets are specified */
  /* inquire how many side sets have been stored */

  num_side_sets = ex_inquire_int(exoid, EX_INQ_SIDE_SETS);
  if (num_side_sets < 0) {
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get number of side sets in file id %d",
             exoid);
    ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
    return (EX_FATAL);
  }

  if (num_side_sets == 0) {
    snprintf(errmsg, MAX_ERR_LENGTH, "Warning: no side sets defined in file id %d", exoid);
    ex_err("ex_cvt_nodes_to_sides", errmsg, EX_WARN);
    return (EX_WARN);
  }

  num_elem_blks = ex_inquire_int(exoid, EX_INQ_ELEM_BLK);
  if (num_elem_blks < 0) {
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get number of element blocks in file id %d",
             exoid);
    ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
    return (EX_FATAL);
  }

  tot_num_elem = ex_inquire_int(exoid, EX_INQ_ELEM);
  if (tot_num_elem < 0) {
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get total number of elements in file id %d",
             exoid);
    ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
    return (EX_FATAL);
  }

  /* get the dimensionality of the coordinates;  this is necessary to
     distinguish between 2d TRIs and 3d TRIs */
  ndim = ex_inquire_int(exoid, EX_INQ_DIM);

  int_size = sizeof(int);
  if (ex_int64_status(exoid) & EX_BULK_INT64_API) {
    int_size = sizeof(int64_t);
  }

  /* First count up # of elements in the side sets*/
  if (ex_int64_status(exoid) & EX_BULK_INT64_API) {
    for (i = 0; i < num_side_sets; i++) {
      tot_num_ss_elem += ((int64_t *)num_elem_per_set)[i];
    }
  }
  else {
    for (i = 0; i < num_side_sets; i++) {
      tot_num_ss_elem += ((int *)num_elem_per_set)[i];
    }
  }

  /* Allocate space for the ss element index array */
  if (!(ss_elem_ndx = malloc(tot_num_ss_elem * int_size))) {
    exerrval = EX_MEMFAIL;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to allocate space for side set elem sort "
                                     "array for file id %d",
             exoid);
    ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
    err_stat = EX_FATAL;
    goto cleanup;
  }

  if (int_size == sizeof(int64_t)) {
    /* Sort side set element list into index array  - non-destructive */
    int64_t *elems = (int64_t *)ss_elem_ndx;
    for (i = 0; i < tot_num_ss_elem; i++) {
      elems[i] = i; /* init index array to current position */
    }
    ex_iqsort64(side_sets_elem_list, elems, tot_num_ss_elem);
  }
  else {
    /* Sort side set element list into index array  - non-destructive */
    int *elems = (int *)ss_elem_ndx;
    for (i = 0; i < tot_num_ss_elem; i++) {
      elems[i] = i; /* init index array to current position */
    }
    ex_iqsort(side_sets_elem_list, elems, tot_num_ss_elem);
  }

  /* Allocate space for the element block ids */
  ids_size = sizeof(int);
  if (ex_int64_status(exoid) & EX_IDS_INT64_API) {
    ids_size = sizeof(int64_t);
  }

  if (!(elem_blk_ids = malloc(num_elem_blks * ids_size))) {
    exerrval = EX_MEMFAIL;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to allocate space for element block ids for file id %d", exoid);
    ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
    err_stat = EX_FATAL;
    goto cleanup;
  }

  if (ex_get_ids(exoid, EX_ELEM_BLOCK, elem_blk_ids)) {
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get element block ids in file id %d", exoid);
    ex_err("ex_cvt_nodes_to_sides", errmsg, EX_MSG);
    err_stat = EX_FATAL;
    goto cleanup;
  }

  /* Allocate space for the element block params */
  if (!(elem_blk_parms = malloc(num_elem_blks * sizeof(struct elem_blk_parm)))) {
    exerrval = EX_MEMFAIL;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to allocate space for element block params "
                                     "for file id %d",
             exoid);
    ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
    err_stat = EX_FATAL;
    goto cleanup;
  }
  elem_ctr = 0;
  for (i = 0; i < num_elem_blks; i++) {
    ex_entity_id id;
    if (ex_int64_status(exoid) & EX_IDS_INT64_API) {
      id = ((int64_t *)elem_blk_ids)[i];
    }
    else {
      id = ((int *)elem_blk_ids)[i];
    }

    err_stat = ex_int_get_block_param(exoid, id, ndim, &elem_blk_parms[i]);
    if (err_stat != EX_NOERR) {
      goto cleanup;
    }

    elem_ctr += elem_blk_parms[i].num_elem_in_blk;
    elem_blk_parms[i].elem_ctr = elem_ctr; /* save elem number max */
  }

  /* Allocate space for the ss element to element block parameter index array */
  if (!(ss_parm_ndx = malloc(tot_num_ss_elem * int_size))) {
    exerrval = EX_MEMFAIL;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to allocate space for side set elem parms "
                                     "index for file id %d",
             exoid);
    ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
    err_stat = EX_FATAL;
    goto cleanup;
  }

  /* Allocate space for the ss element to node list index array */
  if (!(ss_elem_node_ndx = malloc((tot_num_ss_elem + 1) * int_size))) {
    exerrval = EX_MEMFAIL;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to allocate space for side set elem to node "
                                     "index for file id %d",
             exoid);
    ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
    err_stat = EX_FATAL;
    goto cleanup;
  }

  /* determine if each side set has uniform element types; this will
     be used to help determine the stride through the node list
  */

  /* Allocate space for same element type flag array*/
  if (!(same_elem_type = malloc(num_side_sets * sizeof(int)))) {
    exerrval = EX_MEMFAIL;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to allocate space for element type flag "
                                     "array for file id %d",
             exoid);
    ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
    err_stat = EX_FATAL;
    goto cleanup;
  }

  same_elem_type[0] = EX_TRUE;
  if (ex_int64_status(exoid) & EX_BULK_INT64_API) {
    elem_ctr = ((int64_t *)num_elem_per_set)[0];
    for (i = 0, k = 0; i < tot_num_ss_elem; i++) {
      int64_t elem = ((int64_t *)side_sets_elem_list)[i];
      for (j = 0; j < num_elem_blks; j++) {
        if (elem <= elem_blk_parms[j].elem_ctr) {
          break;
        }
      }

      if (j >= num_elem_blks) {
        exerrval = EX_INTERNAL;
        snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: internal logic error for file id %d", exoid);
        ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
        err_stat = EX_FATAL;
        goto cleanup;
      }

      if (i == 0) {
        el_type = elem_blk_parms[j].elem_type_val;
      }

      /* determine which side set this element is in; assign to kth side set */
      if (i >= elem_ctr) {
        elem_ctr += ((int64_t *)num_elem_per_set)[++k];

        el_type           = elem_blk_parms[j].elem_type_val;
        same_elem_type[k] = EX_TRUE;
      }

      if (el_type != elem_blk_parms[j].elem_type_val) {
        same_elem_type[k] = EX_FALSE;
      }
    }

    /* Build side set element to node list index and side set element
       parameter index.
    */
    node_ctr = 0;
    elem_ctr = ((int64_t *)num_elem_per_set)[0];
    for (i = 0, k = 0; i < tot_num_ss_elem; i++) {
      int64_t elem = ((int64_t *)side_sets_elem_list)[i];

      for (j = 0; j < num_elem_blks; j++) {
        if (elem <= elem_blk_parms[j].elem_ctr) {
          break;
        }
      }
      if (j >= num_elem_blks) {
        exerrval = EX_INTERNAL;
        snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: internal logic error for file id %d", exoid);
        ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
        err_stat = EX_FATAL;
        goto cleanup;
      }

      ((int64_t *)ss_parm_ndx)[i]      = j;        /* assign parameter block index */
      ((int64_t *)ss_elem_node_ndx)[i] = node_ctr; /* assign node list index */

      /* determine which side set this element is in; assign to kth side set */
      if (i >= elem_ctr) {
        /* skip over NULL side sets */
        while (((int64_t *)num_elem_per_set)[++k] == 0) {
          ;
        }
        elem_ctr += ((int64_t *)num_elem_per_set)[k];
      }

      /* determine number of nodes per side */
      if (((((int64_t *)num_nodes_per_set)[k] % ((int64_t *)num_elem_per_set)[k]) == 0) &&
          (same_elem_type[k] == EX_TRUE)) { /* all side set elements are same type */
        node_ctr += ((int64_t *)num_nodes_per_set)[k] / ((int64_t *)num_elem_per_set)[k];
      }
      else {
        node_ctr += elem_blk_parms[j].num_nodes_per_side[0];
      }
    }
    ((int64_t *)ss_elem_node_ndx)[i] = node_ctr; /* assign node list index */
  }
  else {
    elem_ctr = ((int *)num_elem_per_set)[0];
    for (i = 0, k = 0; i < tot_num_ss_elem; i++) {
      int elem = ((int *)side_sets_elem_list)[i];

      for (j = 0; j < num_elem_blks; j++) {
        if (elem <= elem_blk_parms[j].elem_ctr) {
          break;
        }
      }

      if (j >= num_elem_blks) {
        exerrval = EX_INTERNAL;
        snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: internal logic error for file id %d", exoid);
        ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
        err_stat = EX_FATAL;
        goto cleanup;
      }

      if (i == 0) {
        el_type = elem_blk_parms[j].elem_type_val;
      }

      /* determine which side set this element is in; assign to kth side set */
      if (i >= elem_ctr) {
        elem_ctr += ((int *)num_elem_per_set)[++k];

        el_type           = elem_blk_parms[j].elem_type_val;
        same_elem_type[k] = EX_TRUE;
      }

      if (el_type != elem_blk_parms[j].elem_type_val) {
        same_elem_type[k] = EX_FALSE;
      }
    }

    /* Build side set element to node list index and side set element
       parameter index.
    */
    node_ctr = 0;
    elem_ctr = ((int *)num_elem_per_set)[0];
    for (i = 0, k = 0; i < tot_num_ss_elem; i++) {
      int elem = ((int *)side_sets_elem_list)[i];

      for (j = 0; j < num_elem_blks; j++) {
        if (elem <= elem_blk_parms[j].elem_ctr) {
          break;
        }
      }
      if (j >= num_elem_blks) {
        exerrval = EX_INTERNAL;
        snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: internal logic error for file id %d", exoid);
        ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
        err_stat = EX_FATAL;
        goto cleanup;
      }

      ((int *)ss_parm_ndx)[i]      = j;        /* assign parameter block index */
      ((int *)ss_elem_node_ndx)[i] = node_ctr; /* assign node list index */

      /* determine which side set this element is in; assign to kth side set */
      if (i >= elem_ctr) {
        /* skip over NULL side sets */
        while (((int *)num_elem_per_set)[++k] == 0) {
          ;
        }
        elem_ctr += ((int *)num_elem_per_set)[k];
      }

      /* determine number of nodes per side */
      if (((((int *)num_nodes_per_set)[k] % ((int *)num_elem_per_set)[k]) == 0) &&
          (same_elem_type[k])) { /* all side set elements are same type */
        node_ctr += ((int *)num_nodes_per_set)[k] / ((int *)num_elem_per_set)[k];
      }
      else {
        node_ctr += elem_blk_parms[j].num_nodes_per_side[0];
      }
    }
    ((int *)ss_elem_node_ndx)[i] = node_ctr; /* assign node list index */
  }

  /* All setup, ready to go ... */

  elem_ctr = 0;

  for (j = 0; j < tot_num_ss_elem; j++) {
    int64_t elem;
    int64_t idx;
    int64_t ss_node0, ss_node1;
    int64_t p_ndx;
    if (int_size == sizeof(int64_t)) {
      idx      = ((int64_t *)ss_elem_ndx)[j];
      elem     = ((int64_t *)side_sets_elem_list)[idx];
      ss_node0 = ((int64_t *)side_sets_node_list)[((int64_t *)ss_elem_node_ndx)[idx]];
      ss_node1 = ((int64_t *)side_sets_node_list)[((int64_t *)ss_elem_node_ndx)[idx] + 1];
      p_ndx    = ((int64_t *)ss_parm_ndx)[idx];
    }
    else {
      idx      = ((int *)ss_elem_ndx)[j];
      elem     = ((int *)side_sets_elem_list)[idx];
      ss_node0 = ((int *)side_sets_node_list)[((int *)ss_elem_node_ndx)[idx]];
      ss_node1 = ((int *)side_sets_node_list)[((int *)ss_elem_node_ndx)[idx] + 1];
      p_ndx    = ((int *)ss_parm_ndx)[idx];
    }
    elem_num = elem - 1;

    if (elem > elem_ctr) {
      /* release connectivity array space and get next one */
      if (elem_ctr > 0) {
        free(connect);
      }

      /* Allocate space for the connectivity array for new element block */
      if (!(connect = malloc(elem_blk_parms[p_ndx].num_elem_in_blk *
                             elem_blk_parms[p_ndx].num_nodes_per_elem * int_size))) {
        exerrval = EX_MEMFAIL;
        snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to allocate space for connectivity "
                                         "array for file id %d",
                 exoid);
        ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
        err_stat = EX_FATAL;
        goto cleanup;
      }

      /* get connectivity array */
      if (ex_get_conn(exoid, EX_ELEM_BLOCK, elem_blk_parms[p_ndx].elem_blk_id, connect, NULL,
                      NULL) == -1) {
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "ERROR: failed to get connectivity array for elem blk %" PRId64 " for file id %d",
                 elem_blk_parms[p_ndx].elem_blk_id, exoid);
        ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
        err_stat = EX_FATAL;
        goto cleanup;
      }
      elem_ctr = elem_blk_parms[p_ndx].elem_ctr;
    }
    /*  For the first node of each side in side set, using a linear search
        (of up to num_nodes_per_elem) of the connectivity array,
        locate the node position in the element. The first node position
        and the second node position are used with a element type specific
        table to determine the side. */

    if (connect == NULL) {
      snprintf(errmsg, MAX_ERR_LENGTH,
               "ERROR: logic error. Connect pointer is null for elem blk %" PRId64
               " for file id %d",
               elem_blk_parms[p_ndx].elem_blk_id, exoid);
      ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
      err_stat = EX_FATAL;
      goto cleanup;
    }

    /* calculate the relative element number position in it's block*/
    elem_num_pos =
        elem_num - (elem_blk_parms[p_ndx].elem_ctr - elem_blk_parms[p_ndx].num_elem_in_blk);
    /* calculate the beginning of the node list for this element by
       using the ss_elem_node_ndx index into the side_sets_node_index
       and adding the element number position * number of nodes per elem */

    num_nodes_per_elem = elem_blk_parms[p_ndx].num_nodes_per_elem;

    for (n = 0; n < num_nodes_per_elem; n++) {
      /* find node in connectivity array that matches first node in side set */
      if (((int_size == sizeof(int64_t)) &&
           (ss_node0 == ((int64_t *)connect)[num_nodes_per_elem * (elem_num_pos) + n])) ||
          ((int_size == sizeof(int)) &&
           (ss_node0 == ((int *)connect)[num_nodes_per_elem * (elem_num_pos) + n]))) {
        switch (elem_blk_parms[p_ndx].elem_type_val) {
        case EX_EL_CIRCLE:
        case EX_EL_SPHERE: {
          /* simple case: 1st node number is same as side # */
          put_side(side_sets_side_list, idx, n + 1, int_size);
          break;
        }
        case EX_EL_QUAD:
        case EX_EL_TRIANGLE:
        case EX_EL_TRUSS:
        case EX_EL_BEAM: {
          /* simple case: 1st node number is same as side # */
          put_side(side_sets_side_list, idx, n + 1, int_size);
          break;
        }
        case EX_EL_TRISHELL: {
          /* use table to find which node to compare to next */
          if (ss_node1 == get_node(connect, num_nodes_per_elem * (elem_num_pos) +
                                                (trishell_table[0][2 * n] - 1),
                                   int_size)) {
            /* Assume only front or back, no edges... */
            put_side(side_sets_side_list, idx, trishell_table[1][2 * n], int_size);
          }
          else if (ss_node1 == get_node(connect, num_nodes_per_elem * (elem_num_pos) +
                                                     (trishell_table[0][2 * n + 1] - 1),
                                        int_size)) {
            /* Assume only front or back, no edges... */
            put_side(side_sets_side_list, idx, trishell_table[1][2 * n + 1], int_size);
          }
          else if (ss_node1 == get_node(connect, num_nodes_per_elem * (elem_num_pos) +
                                                     (trishell_table[0][2 * n + 2] - 1),
                                        int_size)) {
            /* Assume only front or back, no edges... */
            put_side(side_sets_side_list, idx, trishell_table[1][2 * n + 2], int_size);
          }
          else {
            exerrval = EX_BADPARAM;
            snprintf(errmsg, MAX_ERR_LENGTH,
                     "ERROR: failed to find TRIANGULAR SHELL element %" PRId64 ", node %" PRId64
                     " in connectivity array %" PRId64 " for file id %d",
                     elem_num + 1, ss_node1, elem_blk_parms[p_ndx].elem_blk_id, exoid);
            ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
            err_stat = EX_FATAL;
            goto cleanup;
          }
          break;
        }
        case EX_EL_SHELL: {
          /* use table to find which node to compare to next */

          if (ex_int64_status(exoid) & EX_BULK_INT64_API) {
            num_node_per_side =
                ((int64_t *)ss_elem_node_ndx)[idx + 1] - ((int64_t *)ss_elem_node_ndx)[idx];
          }
          else {
            num_node_per_side = ((int *)ss_elem_node_ndx)[idx + 1] - ((int *)ss_elem_node_ndx)[idx];
          }

          if (ss_node1 ==
              get_node(connect, num_nodes_per_elem * (elem_num_pos) + (shell_table[0][2 * n] - 1),
                       int_size)) {
            if (num_node_per_side >= 4) {
              /* 4- or 8-node side (front or back face) */
              put_side(side_sets_side_list, idx, shell_table[1][2 * n], int_size);
            }
            else {
              /* 2- or 3-node side (edge of shell) */
              put_side(side_sets_side_list, idx, shell_edge_table[1][2 * n], int_size);
            }
          }
          else if (ss_node1 == get_node(connect, num_nodes_per_elem * (elem_num_pos) +
                                                     (shell_table[0][2 * n + 1] - 1),
                                        int_size)) {
            if (num_node_per_side >= 4) {
              /* 4- or 8-node side (front or back face) */
              put_side(side_sets_side_list, idx, shell_table[1][2 * n + 1], int_size);
            }
            else {
              /* 2- or 3-node side (edge of shell) */
              put_side(side_sets_side_list, idx, shell_edge_table[1][2 * n + 1], int_size);
            }
          }
          else if (ss_node1 == get_node(connect, num_nodes_per_elem * (elem_num_pos) +
                                                     (shell_table[0][2 * n + 2] - 1),
                                        int_size)) {
            if (num_node_per_side >= 4) {
              /* 4- or 8-node side (front or back face) */
              put_side(side_sets_side_list, idx, shell_table[1][2 * n + 2], int_size);
            }
            else {
              /* 2- or 3-node side (edge of shell) */
              put_side(side_sets_side_list, idx, shell_edge_table[1][2 * n + 2], int_size);
            }
          }
          else {
            exerrval = EX_BADPARAM;
            snprintf(errmsg, MAX_ERR_LENGTH,
                     "ERROR: failed to find SHELL element %" PRId64 ", node %" PRId64
                     " in connectivity array %" PRId64 " for file id %d",
                     elem_num + 1, ss_node1, elem_blk_parms[p_ndx].elem_blk_id, exoid);
            ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
            err_stat = EX_FATAL;
            goto cleanup;
          }
          break;
        }
        case EX_EL_HEX: {
          /* use table to find which node to compare to next */

          if (ss_node1 == get_node(connect,
                                   num_nodes_per_elem * (elem_num_pos) + (hex_table[0][3 * n] - 1),
                                   int_size)) {
            put_side(side_sets_side_list, idx, hex_table[1][3 * n], int_size);
          }
          else if (ss_node1 == get_node(connect, num_nodes_per_elem * (elem_num_pos) +
                                                     (hex_table[0][3 * n + 1] - 1),
                                        int_size)) {
            put_side(side_sets_side_list, idx, hex_table[1][3 * n + 1], int_size);
          }
          else if (ss_node1 == get_node(connect, num_nodes_per_elem * (elem_num_pos) +
                                                     (hex_table[0][3 * n + 2] - 1),
                                        int_size)) {
            put_side(side_sets_side_list, idx, hex_table[1][3 * n + 2], int_size);
          }
          else {
            exerrval = EX_BADPARAM;
            snprintf(errmsg, MAX_ERR_LENGTH,
                     "ERROR: failed to find HEX element %" PRId64 ", node %" PRId64
                     " in connectivity array %" PRId64 " for file id %d",
                     elem_num + 1, ss_node1, elem_blk_parms[p_ndx].elem_blk_id, exoid);
            ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
            err_stat = EX_FATAL;
            goto cleanup;
          }
          break;
        }
        case EX_EL_TETRA: {
          /* use table to find which node to compare to next */

          if (ss_node1 ==
              get_node(connect, num_nodes_per_elem * (elem_num_pos) + (tetra_table[0][3 * n] - 1),
                       int_size)) {
            put_side(side_sets_side_list, idx, tetra_table[1][3 * n], int_size);
          }
          else if (ss_node1 == get_node(connect, num_nodes_per_elem * (elem_num_pos) +
                                                     (tetra_table[0][3 * n + 1] - 1),
                                        int_size)) {
            put_side(side_sets_side_list, idx, tetra_table[1][3 * n + 1], int_size);
          }
          else if (ss_node1 == get_node(connect, num_nodes_per_elem * (elem_num_pos) +
                                                     (tetra_table[0][3 * n + 2] - 1),
                                        int_size)) {
            put_side(side_sets_side_list, idx, tetra_table[1][3 * n + 2], int_size);
          }
          else {
            exerrval = EX_BADPARAM;
            snprintf(errmsg, MAX_ERR_LENGTH,
                     "ERROR: failed to find TETRA element %" PRId64 ", node %" PRId64
                     " in connectivity array %" PRId64 " for file id %d",
                     elem_num + 1, ss_node1, elem_blk_parms[p_ndx].elem_blk_id, exoid);
            ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
            err_stat = EX_FATAL;
            goto cleanup;
          }
          break;
        }
        case EX_EL_PYRAMID: {
          /* NOTE: PYRAMID elements in side set node lists are currently not
           * supported */
          exerrval = EX_BADPARAM;
          snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: unsupported PYRAMID element found in side "
                                           "set node list in file id %d",
                   exoid);
          ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
          err_stat = EX_FATAL;
          goto cleanup;
        }
        case EX_EL_WEDGE: {
          /* NOTE: WEDGE elements in side set node lists are currently not
           * supported */
          exerrval = EX_BADPARAM;
          snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: unsupported WEDGE element found in side set "
                                           "node list in file id %d",
                   exoid);
          ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
          err_stat = EX_FATAL;
          goto cleanup;
        }
        default: {
          exerrval = EX_BADPARAM;
          snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: %s is an unsupported element type",
                   elem_blk_parms[p_ndx].elem_type);
          ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
          err_stat = EX_FATAL;
          goto cleanup;
        }
        }
        break; /* done with this element */
      }
    }
    if (n >= num_nodes_per_elem) /* did we find the node? */
    {
      exerrval = EX_BADPARAM;
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to find element %" PRId64 ", node %" PRId64
                                       " in element block %" PRId64 " for file id %d",
               elem_num + 1, ss_node0, elem_blk_parms[p_ndx].elem_blk_id, exoid);
      ex_err("ex_cvt_nodes_to_sides", errmsg, exerrval);
      err_stat = EX_FATAL;
      goto cleanup;
    }
  }

/* All done: release connectivity array space, element block ids array,
   element block parameters array, and side set element index array */
cleanup:
  free(connect);
  free(ss_elem_node_ndx);
  free(ss_parm_ndx);
  free(elem_blk_parms);
  free(elem_blk_ids);
  free(ss_elem_ndx);
  free(same_elem_type);

  return (err_stat);
}
Пример #8
0
	textctrl_pad(cfg_location&& _loc, wxTextCtrl*& ptr)
		: cfg_adapter(std::move(_loc))
		, ptr(ptr)
	{
		ptr->SetValue(fmt::FromUTF8(get_node(loaded).Scalar()));
	}
Пример #9
0
	void save() override
	{
		get_node(saved) = fmt::ToUTF8(ptr->GetValue());
	}
Пример #10
0
	checkbox_pad(cfg_location&& _loc, wxCheckBox*& ptr)
		: cfg_adapter(std::move(_loc))
		, ptr(ptr)
	{
		ptr->SetValue(get_node(loaded).as<bool>(false));
	}
Пример #11
0
	void save() override
	{
		get_node(saved) = ptr->GetValue() ? "true" : "false";
	}
Пример #12
0
	void save() override
	{
		get_node(saved) = get_cfg().to_list()[ptr->GetSelection()];
	}
Пример #13
0
struct rect_list_t *get_rect_list_node()
{  return( ( struct rect_list_t *) get_node() );
}
Пример #14
0
struct seg_tree_2d_t *rect_list_to_tree_list(struct rect_list_t *rect_list, int x) {
  int keys[1000000];
  int prev_key;
  int i = 0;
  int j,t;
  int *tmpob;
  struct rect_list_t *tmp_list = rect_list;
  struct seg_tree_2d_t *list, *tmp, *seg_tree;

  if (x == 1) {
  	//build x seg tree
  	while (tmp_list != NULL) {
	    keys[2*i] = tmp_list->x_min;
	    keys[2*i+1] = tmp_list->x_max;
	    rect_intv[i].x_min = tmp_list->x_min;
	    rect_intv[i].x_max = tmp_list->x_max;
	    rect_intv[i].y_min = tmp_list->y_min;
	    rect_intv[i].y_max = tmp_list->y_max;
	    tmp_list = tmp_list->next;
	    i++;
	}
	rect_total_number = i;

  }else {
  	// rect_intv_y init to 0;
  	for(t=0; t < rect_total_number_y; t++) {
  		rect_intv_y[t].x_min = rect_intv_y[t].x_max = 0;
  		rect_intv_y[t].y_min = rect_intv_y[t].y_max = 0;
  	}

  	//build y tree
	while (tmp_list != NULL) {
	    keys[2*i] = tmp_list->y_min;
	    keys[2*i+1] = tmp_list->y_max;
	    // need to switch y and x
	    rect_intv_y[i].x_min = tmp_list->y_min;
	    rect_intv_y[i].x_max = tmp_list->y_max;
	    rect_intv_y[i].y_min = tmp_list->x_min;
	    rect_intv_y[i].y_max = tmp_list->x_max;
	    tmp_list = tmp_list->next;
	    i++;
	}
	rect_total_number_y = i;
  }

   qsort(keys, 2*i, sizeof( int ), compint );
  printf("  the keys, sorted in increasing order, are \n");
   //struct seg_tree_2d_t *list, *tmp, *seg_tree;
   list = get_node();
   list->right = NULL;
   prev_key = list->key = keys[2*i-1];
   tmpob  = (int *) malloc(sizeof(int));
   *tmpob = 42;
   list->left = (struct seg_tree_2d_t *) tmpob;
   for( j = 2*i-2; j>= 0; j-- )
   {  if( keys[j] != prev_key )
      { tmp = get_node();
        prev_key = tmp->key = keys[j];
        tmp->right = list;
        tmpob  = (int *) malloc(sizeof(int));
        *tmpob = 42;
        tmp->left = (struct seg_tree_2d_t *) tmpob;
        list = tmp;
      }
   }
   tmp = get_node();
   tmp->key = -1000;
   tmp->right = list;
   tmpob  = (int *) malloc(sizeof(int));
   *tmpob = 42;
   tmp->left = (struct seg_tree_2d_t *) tmpob;
   list = tmp;
   printf("Built sorted list from keys\n");
   tmp = list;
   while (tmp != NULL )
   { printf("%d ", tmp->key );
     tmp = tmp->right;
   }
   printf("\n");
   return list;
}
Пример #15
0
void LegIKController::_ready() {
	global_leg_ik_enabled_changed();
	global_leg_ik_feet_reposition_rate_changed();
	global_leg_ik_body_reposition_rate_changed();

	//Ignore player collision hull
	ray_exclusion_array = Set<RID>();

	CollisionObject *collision_object = static_cast<CollisionObject *>(get_node(NodePath("..")));
	if (collision_object)
		ray_exclusion_array.insert(collision_object->get_rid());

	skeleton = static_cast<Skeleton *>(get_node(skeleton_path));

	if (skeleton != NULL) {
		root_bone = skeleton->find_bone(root_bone_name);
		pelvis = skeleton->find_bone(pelvis_name);

		left_leg = skeleton->find_bone(left_leg_name);
		left_knee = skeleton->find_bone(left_knee_name);
		left_ankle = skeleton->find_bone(left_ankle_name);
		left_toe = skeleton->find_bone(left_toe_name);

		right_leg = skeleton->find_bone(right_leg_name);
		right_knee = skeleton->find_bone(right_knee_name);
		right_ankle = skeleton->find_bone(right_ankle_name);
		right_toe = skeleton->find_bone(right_toe_name);

		if (root_bone != -1 && pelvis != -1 &&
			left_leg != -1 && left_knee != -1 && left_ankle != -1 &&
			right_leg != -1 && right_knee != -1 && right_ankle != -1 &&
			left_toe != -1 && right_toe != -1) {

			left_thigh_length = skeleton->get_bone_global_pose(left_leg).origin.distance_to(skeleton->get_bone_global_pose(left_knee).origin);
			left_calf_length = skeleton->get_bone_global_pose(left_knee).origin.distance_to(skeleton->get_bone_global_pose(left_ankle).origin);
			left_leg_full_length = left_thigh_length + left_calf_length;

			right_thigh_length = skeleton->get_bone_global_pose(right_leg).origin.distance_to(skeleton->get_bone_global_pose(right_knee).origin);
			right_calf_length = skeleton->get_bone_global_pose(right_knee).origin.distance_to(skeleton->get_bone_global_pose(right_ankle).origin);
			right_leg_full_length = right_thigh_length + right_calf_length;

			prev_target_height = skeleton->get_bone_global_pose(root_bone).origin.y;

			Transform left_foot_local_transform = skeleton->get_bone_global_pose(left_ankle);
			Transform right_foot_local_transform = skeleton->get_bone_global_pose(right_ankle);

			Transform left_foot_transform = skeleton->get_global_transform() * left_foot_local_transform;
			Transform right_foot_transform = skeleton->get_global_transform() * right_foot_local_transform;

			targeted_left_ground = left_foot_transform.origin;
			targeted_right_ground = right_foot_transform.origin;

			prev_left_ground = left_foot_local_transform.origin;
			prev_right_ground = right_foot_local_transform.origin;

			ik_valid = true;
		}
		else {
			ik_valid = false;
		}
	}
}
Пример #16
0
	static YAML::Node get_node(YAML::Node node, cfg_location::const_iterator begin, cfg_location::const_iterator end)
	{
		return begin == end ? node : get_node(node[*begin], begin + 1, end); // TODO
	}
Пример #17
0
void LegIKController::solve_leg_ik(const float p_delta) {
	
	if(skeleton == NULL)
		return;
	
	Transform root_bone_transform = skeleton->get_global_transform() * skeleton->get_bone_global_pose(root_bone);
	
	if (ik_on && ik_valid) {
		if(dss == NULL) {
			if (root == NULL) {
				root = static_cast<Spatial *>(get_node(NodePath("..")));
				if (root == NULL)
					return;
			}

			dss = PhysicsServer::get_singleton()->space_get_direct_state(root->get_world()->get_space());
			if(dss == NULL);
				return;
		};
				
		root_global_transform = root->get_global_transform();
				
		Transform skeleton_affine_inverse = skeleton->get_global_transform().affine_inverse();

		Transform left_foot_local_transform = skeleton->get_bone_global_pose(left_ankle);
		Transform right_foot_local_transform = skeleton->get_bone_global_pose(right_ankle);
		
		Transform left_foot_transform = skeleton->get_global_transform() * left_foot_local_transform;
		Transform right_foot_transform = skeleton->get_global_transform() * right_foot_local_transform;
		
		Transform left_calf_transform = skeleton->get_global_transform() * skeleton->get_bone_global_pose(left_knee);
		Transform right_calf_transform = skeleton->get_global_transform() * skeleton->get_bone_global_pose(right_knee);
		
		Transform left_thigh_transform = skeleton->get_global_transform() * skeleton->get_bone_global_pose(left_leg);
		Transform right_thigh_transform = skeleton->get_global_transform() * skeleton->get_bone_global_pose(right_leg);
		
		root_offset = root_bone_transform.origin.y - root_global_transform.origin.y;
		ankle_height_L = left_foot_transform.origin.y - root_global_transform.origin.y;
		ankle_height_R = right_foot_transform.origin.y - root_global_transform.origin.y;
		
		targeted_left_ground.y += (left_foot_local_transform.origin.y - prev_left_ground.y);
		targeted_right_ground.y += (right_foot_local_transform.origin.y - prev_right_ground.y);
					
		prev_left_ground = left_foot_local_transform.origin;
		prev_right_ground = right_foot_local_transform.origin;
		
		// Default feet targets.
		Vector3 left_ground = left_foot_transform.origin;
		Vector3 right_ground = right_foot_transform.origin;
		Vector3 original_left_ground = left_foot_transform.origin;
		Vector3 original_right_ground = right_foot_transform.origin;
		
		float animation_delta = left_ground.y - right_ground.y;
		if (animation_delta < -animation_offset) {
			left_foot_down = true;
			right_foot_down = false;
		} else if (animation_delta > animation_offset) {
			left_foot_down = false;
			right_foot_down = true;
		} else {
			left_foot_down = true;
			right_foot_down = true;
		}
		
		float ray_distance = 0.0;
	 
		if ((!left_foot_down) && (right_foot_down)) {
			ray_distance = left_calf_length + ankle_height_L;
		} else {
			ray_distance = left_calf_length + left_leg_full_length;
		}

		// Left
		if (ray_distance > 0) {
			Vector3 from = left_foot_transform.origin + Vector3(0, left_calf_length, 0);
			Vector3 to = from + (-Vector3(0, 1, 0) * ray_distance);
			
			PhysicsDirectSpaceState::RayResult result_foot;
			if (dss->intersect_ray(from, to, result_foot, ray_exclusion_array, 1, 15)) {
				Transform left_toe_transform = skeleton->get_global_transform() * skeleton->get_bone_global_pose(left_toe);
				
				float original_y = from.y;
				from = left_toe_transform.origin + Vector3(0, left_calf_length, 0);
				from.y = original_y;
				to = from + (-Vector3(0, 1, 0) * ray_distance);
				
				PhysicsDirectSpaceState::RayResult result_toe;
				if (dss->intersect_ray(from, to, result_toe, ray_exclusion_array, 1, 15)) {
					if (result_toe.position.y - result_foot.position.y > 0.001) {
						left_ground = result_toe.position + Vector3(0, ankle_height_L, 0);
					} else {
						left_ground = result_foot.position + Vector3(0, ankle_height_L, 0);
					}
				} else {
					left_ground = result_foot.position + Vector3(0, ankle_height_L, 0);
				}
			}
		}

		if ((left_foot_down) && (!right_foot_down)) {
			ray_distance = right_calf_length + ankle_height_R;
		} else {
			ray_distance = right_calf_length + right_leg_full_length;
		}
		
		// Right
		if (ray_distance > 0) {
			Vector3 from = right_foot_transform.origin + Vector3(0, right_calf_length, 0);
			Vector3 to = from + (-Vector3(0, 1, 0) * ray_distance);
			
			PhysicsDirectSpaceState::RayResult result_foot;
			if (dss->intersect_ray(from, to, result_foot, ray_exclusion_array, 1, 15)) {
				Transform right_toe_transform = skeleton->get_global_transform() * skeleton->get_bone_global_pose(right_toe);

				float original_y = from.y;
				from = right_toe_transform.origin + Vector3(0, right_calf_length, 0);
				from.y = original_y;
				to = from + (-Vector3(0, 1, 0) * ray_distance);

				PhysicsDirectSpaceState::RayResult result_toe;
				if (dss->intersect_ray(from, to, result_toe, ray_exclusion_array, 1, 15)) {
					if (result_toe.position.y - result_foot.position.y > 0.001) {
						right_ground = result_toe.position + Vector3(0, ankle_height_R, 0);
					} else {
						right_ground = result_foot.position + Vector3(0, ankle_height_R, 0);
					}
				} else {
					right_ground = result_foot.position + Vector3(0, ankle_height_R, 0);
				}
			}
		}

		if (left_ground.y < right_ground.y) {
			target_height = left_ground.y - ankle_height_L + root_offset;
		} else {
			target_height = right_ground.y - ankle_height_R + root_offset;
		}
		
		target_height = Math::lerp(prev_target_height, target_height, p_delta * ik_body_reposition_rate);
		
		float height_diff = target_height - root_bone_transform.origin.y;
		
		root_bone_transform.origin.y = target_height;
		skeleton->set_bone_global_pose(root_bone, skeleton_affine_inverse * root_bone_transform);
		
		prev_target_height = root_bone_transform.origin.y;

		if((!left_foot_down) && (right_foot_down) && (left_ground == original_left_ground))
			left_ground.y += height_diff;
		
		if((left_foot_down) && (!right_foot_down) && (right_ground == original_right_ground))
			right_ground.y += height_diff;
		
		targeted_left_ground.x = left_ground.x;
		targeted_left_ground.z = left_ground.z;
		
		targeted_right_ground.x = right_ground.x;
		targeted_right_ground.z = right_ground.z;
		
		targeted_left_ground.y = Math::lerp(targeted_left_ground.y, left_ground.y, p_delta * ik_feet_reposition_rate);
		targeted_right_ground.y = Math::lerp(targeted_right_ground.y, right_ground.y, p_delta * ik_feet_reposition_rate);

		LegIK::solve_leg_ik(skeleton, left_leg, left_knee, left_ankle, targeted_left_ground);
		LegIK::solve_leg_ik(skeleton, right_leg, right_knee, right_ankle, targeted_right_ground);
	} else {
		prev_target_height = root_bone_transform.origin.y;
	}
}
Пример #18
0
	YAML::Node get_node(YAML::Node root) const
	{
		return get_node(root, location.cbegin(), location.cend());
	}
Пример #19
0
void UAVCAN_sniffer::loop(void)
{
    auto *node = get_node();
    node->spin(uavcan::MonotonicDuration::fromMSec(1));
}
Пример #20
0
void ScrollBar::_notification(int p_what) {

	if (p_what == NOTIFICATION_DRAW) {

		RID ci = get_canvas_item();

		Ref<Texture> decr = highlight == HIGHLIGHT_DECR ? get_icon("decrement_highlight") : get_icon("decrement");
		Ref<Texture> incr = highlight == HIGHLIGHT_INCR ? get_icon("increment_highlight") : get_icon("increment");
		Ref<StyleBox> bg = has_focus() ? get_stylebox("scroll_focus") : get_stylebox("scroll");

		Ref<StyleBox> grabber;
		if (drag.active)
			grabber = get_stylebox("grabber_pressed");
		else if (highlight == HIGHLIGHT_RANGE)
			grabber = get_stylebox("grabber_highlight");
		else
			grabber = get_stylebox("grabber");

		Point2 ofs;

		VisualServer *vs = VisualServer::get_singleton();

		vs->canvas_item_add_texture_rect(ci, Rect2(Point2(), decr->get_size()), decr->get_rid());

		if (orientation == HORIZONTAL)
			ofs.x += decr->get_width();
		else
			ofs.y += decr->get_height();

		Size2 area = get_size();

		if (orientation == HORIZONTAL)
			area.width -= incr->get_width() + decr->get_width();
		else
			area.height -= incr->get_height() + decr->get_height();

		bg->draw(ci, Rect2(ofs, area));

		if (orientation == HORIZONTAL)
			ofs.width += area.width;
		else
			ofs.height += area.height;

		vs->canvas_item_add_texture_rect(ci, Rect2(ofs, decr->get_size()), incr->get_rid());
		Rect2 grabber_rect;

		if (orientation == HORIZONTAL) {

			grabber_rect.size.width = get_grabber_size();
			grabber_rect.size.height = get_size().height;
			grabber_rect.position.y = 0;
			grabber_rect.position.x = get_grabber_offset() + decr->get_width() + bg->get_margin(MARGIN_LEFT);
		} else {

			grabber_rect.size.width = get_size().width;
			grabber_rect.size.height = get_grabber_size();
			grabber_rect.position.y = get_grabber_offset() + decr->get_height() + bg->get_margin(MARGIN_TOP);
			grabber_rect.position.x = 0;
		}

		grabber->draw(ci, grabber_rect);
	}

	if (p_what == NOTIFICATION_ENTER_TREE) {

		if (has_node(drag_slave_path)) {
			Node *n = get_node(drag_slave_path);
			drag_slave = n->cast_to<Control>();
		}

		if (drag_slave) {
			drag_slave->connect("gui_input", this, "_drag_slave_input");
			drag_slave->connect("tree_exited", this, "_drag_slave_exit", varray(), CONNECT_ONESHOT);
		}
	}
	if (p_what == NOTIFICATION_EXIT_TREE) {

		if (drag_slave) {
			drag_slave->disconnect("gui_input", this, "_drag_slave_input");
			drag_slave->disconnect("tree_exited", this, "_drag_slave_exit");
		}

		drag_slave = NULL;
	}

	if (p_what == NOTIFICATION_FIXED_PROCESS) {

		if (scrolling) {
			if (get_value() != target_scroll) {
				double target = target_scroll - get_value();
				double dist = sqrt(target * target);
				double vel = ((target / dist) * 500) * get_fixed_process_delta_time();

				if (vel >= dist) {
					set_value(target_scroll);
				} else {
					set_value(get_value() + vel);
				}
			} else {
				scrolling = false;
				set_fixed_process(false);
			}
		} else if (drag_slave_touching) {

			if (drag_slave_touching_deaccel) {

				Vector2 pos = Vector2(orientation == HORIZONTAL ? get_value() : 0, orientation == VERTICAL ? get_value() : 0);
				pos += drag_slave_speed * get_fixed_process_delta_time();

				bool turnoff = false;

				if (orientation == HORIZONTAL) {

					if (pos.x < 0) {
						pos.x = 0;
						turnoff = true;
					}

					if (pos.x > (get_max() - get_page())) {
						pos.x = get_max() - get_page();
						turnoff = true;
					}

					set_value(pos.x);

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

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

					drag_slave_speed.x = sgn_x * val_x;

				} else {

					if (pos.y < 0) {
						pos.y = 0;
						turnoff = true;
					}

					if (pos.y > (get_max() - get_page())) {
						pos.y = get_max() - get_page();
						turnoff = true;
					}

					set_value(pos.y);

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

					if (val_y < 0) {
						turnoff = true;
					}
					drag_slave_speed.y = sgn_y * val_y;
				}

				if (turnoff) {
					set_fixed_process(false);
					drag_slave_touching = false;
					drag_slave_touching_deaccel = false;
				}

			} else {

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

					Vector2 diff = drag_slave_accum - last_drag_slave_accum;
					last_drag_slave_accum = drag_slave_accum;
					drag_slave_speed = diff / get_fixed_process_delta_time();
				}

				time_since_motion += get_fixed_process_delta_time();
			}
		}
	}

	if (p_what == NOTIFICATION_MOUSE_EXIT) {

		highlight = HIGHLIGHT_NONE;
		update();
	}
}
Пример #21
0
static void extract_media(struct uae_prefs *p, unzFile uz, xmlNode *node)
{
  xmlNode *tmp = get_node(node, "media");
  if(tmp != NULL) 
  {
    for(xmlNode *curr_node = tmp; curr_node; curr_node = curr_node->next) 
    {
      int mediatype = -1;
      if (curr_node->type == XML_ELEMENT_NODE && strcmp((const char *)curr_node->name, _T("floppy")) == 0)
        mediatype = 0;
      else if (curr_node->type == XML_ELEMENT_NODE && strcmp((const char *)curr_node->name, _T("harddrive")) == 0)
        mediatype = 1;
      if(mediatype >= 0)
      {
        xmlChar *content = xmlNodeGetContent(curr_node);
        if(content != NULL) 
        {
          int priority = 0;
          xmlChar *attr = xmlGetProp(curr_node, (const xmlChar *) _T("priority"));
          if(attr != NULL) 
          {
            priority = atoi((const char *)attr);
            xmlFree(attr);
          }
        	
        	if (unzLocateFile (uz, (char *)content, 1) == UNZ_OK)
          {
            unz_file_info file_info;
            if (unzGetCurrentFileInfo (uz, &file_info, NULL, 0, NULL, 0, NULL, 0) == UNZ_OK)
            {
              void *buffer = malloc(file_info.uncompressed_size);
              if(buffer != NULL)
              {
                if (unzOpenCurrentFile (uz) == UNZ_OK)
                {
                  int readsize = unzReadCurrentFile(uz, buffer, file_info.uncompressed_size);
                  unzCloseCurrentFile(uz);
                  if(readsize == file_info.uncompressed_size)
                  {
                    char target_file[MAX_DPATH];
                    snprintf(target_file, MAX_DPATH, "%s%s", rp9tmp_path, content);
                    FILE *f = fopen(target_file, "wb");
                    if(f != NULL)
                    {
                      fwrite(buffer, 1, readsize, f);
                      fclose(f);
                      if(mediatype == 0)
                      {
                        // Add floppy
                        if(priority < 2)
                        {
                  	      strncpy(p->floppyslots[0].df, target_file, sizeof(p->floppyslots[0].df));
                  	      disk_insert(0, p->floppyslots[0].df);
                  	    }
                  	    else if(priority == 2 && p->nr_floppies > 1)
                	      {
                  	      strncpy(p->floppyslots[1].df, target_file, sizeof(p->floppyslots[1].df));
                  	      disk_insert(1, p->floppyslots[1].df);
                	      }
                  	    else if(priority == 3 && p->nr_floppies > 2)
                	      {
                  	      strncpy(p->floppyslots[2].df, target_file, sizeof(p->floppyslots[2].df));
                  	      disk_insert(2, p->floppyslots[2].df);
                	      }
                  	    else if(priority == 4 && p->nr_floppies > 3)
                	      {
                  	      strncpy(p->floppyslots[3].df, target_file, sizeof(p->floppyslots[3].df));
                  	      disk_insert(3, p->floppyslots[3].df);
                	      }
                        AddFileToDiskList(target_file, 1);
                      }
                      else
                      {
                        // Add hardfile
                        struct uaedev_config_info *uci;
                        char dhx[8];

                        sprintf(dhx, "DH%d", add_HDF_DHnum);
                        ++add_HDF_DHnum;
                        if(hardfile_testrdb (target_file))                        
                          uci = add_filesys_config(p, -1, dhx, 0, target_file, 0, 0, 0, 0, 512, 0, 0, 0, 0);
                        else
                          uci = add_filesys_config(p, -1, dhx, 0, target_file, 0, 32, 1, 2, 512, 0, 0, 0, 0);
                        if (uci)
    	                    hardfile_do_disk_change (uci, 1);
    	                  gui_force_rtarea_hdchange();
                      }
                      lstTmpRP9Files.push_back(target_file);
                    }
                  }
                }
                free(buffer);
              }
            }
          }
          
          xmlFree(content);
        }      
      }
    }
  }
}
Пример #22
0
/**
 * This function's previous recursive implementation was
 * easier to read, but was vulnerable to a smash-stacking
 * attack via maliciously-crafted bencoded data. (#667)
 */
int
tr_variantParseBenc (const void    * buf_in,
                     const void    * bufend_in,
                     tr_variant    * top,
                     const char   ** setme_end)
{
  int err = 0;
  const uint8_t * buf = buf_in;
  const uint8_t * bufend = bufend_in;
  tr_ptrArray stack = TR_PTR_ARRAY_INIT;
  tr_quark key = 0;

  tr_variantInit (top, 0);

  while (buf != bufend)
    {
      if (buf > bufend) /* no more text to parse... */
        err = EILSEQ;

      if (err)
        break;

      if (*buf == 'i') /* int */
        {
          int64_t val;
          const uint8_t * end;
          tr_variant * v;

          if ((err = tr_bencParseInt (buf, bufend, &end, &val)))
            break;
          buf = end;

          if ((v = get_node (&stack, &key, top, &err)))
            tr_variantInitInt (v, val);
        }
      else if (*buf == 'l') /* list */
        {
          tr_variant * v;

          ++buf;

          if ((v = get_node (&stack, &key, top, &err)))
            {
              tr_variantInitList (v, 0);
              tr_ptrArrayAppend (&stack, v);
            }
        }
      else if (*buf == 'd') /* dict */
        {
          tr_variant * v;

          ++buf;

          if ((v = get_node (&stack, &key, top, &err)))
            {
              tr_variantInitDict (v, 0);
              tr_ptrArrayAppend (&stack, v);
            }
        }
      else if (*buf == 'e') /* end of list or dict */
        {
          ++buf;

          if (tr_ptrArrayEmpty (&stack) || (key != 0))
            {
              err = EILSEQ;
              break;
            }
          else
            {
              tr_ptrArrayPop (&stack);
              if (tr_ptrArrayEmpty (&stack))
                break;
            }
        }
      else if (isdigit (*buf)) /* string? */
        {
          tr_variant * v;
          const uint8_t * end;
          const uint8_t * str;
          size_t str_len;

          if ((err = tr_bencParseStr (buf, bufend, &end, &str, &str_len)))
            break;
          buf = end;

          if (!key && !tr_ptrArrayEmpty(&stack) && tr_variantIsDict(tr_ptrArrayBack(&stack)))
            key = tr_quark_new (str, str_len);
          else if ((v = get_node (&stack, &key, top, &err)))
            tr_variantInitStr (v, str, str_len);
        }
      else /* invalid bencoded text... march past it */
        {
          ++buf;
        }

      if (tr_ptrArrayEmpty (&stack))
        break;
    }

  if (!err && (!top->type || !tr_ptrArrayEmpty(&stack)))
    err = EILSEQ;

  if (!err && setme_end)
    *setme_end = (const char*) buf;

  tr_ptrArrayDestruct (&stack, NULL);
  return err;
}
Пример #23
0
/*int	get_value_snmp(double *result,char *result_str,DB_ITEM *item,char *error, int max_error_len)*/
int	get_value_snmp(DB_ITEM *item, AGENT_RESULT *value)
{

	#define NEW_APPROACH

	struct snmp_session session, *ss;
	struct snmp_pdu *pdu;
	struct snmp_pdu *response;

#ifdef NEW_APPROACH
	char temp[MAX_STRING_LEN];
#endif

	oid anOID[MAX_OID_LEN];
	size_t anOID_len = MAX_OID_LEN;

	struct variable_list *vars;
	int status;

	char 	*p, *c;
	double dbl;

	unsigned char *ip;

	char error[MAX_STRING_LEN];

	int ret=SUCCEED;

	zabbix_log( LOG_LEVEL_DEBUG, "In get_value_SNMP()");

	init_result(value);

/*	assert((item->type == ITEM_TYPE_SNMPv1)||(item->type == ITEM_TYPE_SNMPv2c)); */
	assert((item->type == ITEM_TYPE_SNMPv1)||(item->type == ITEM_TYPE_SNMPv2c)||(item->type == ITEM_TYPE_SNMPv3));

	snmp_sess_init( &session );
/*	session.version = version;*/
	if(item->type == ITEM_TYPE_SNMPv1)
	{
		session.version = SNMP_VERSION_1;
	}
	else if(item->type == ITEM_TYPE_SNMPv2c)
	{
		session.version = SNMP_VERSION_2c;
	}
	else if(item->type == ITEM_TYPE_SNMPv3)
	{
		session.version = SNMP_VERSION_3;
	}
	else
	{
		zbx_snprintf(error,sizeof(error),"Error in get_value_SNMP. Wrong item type [%d]. Must be SNMP.",
			item->type);
		zabbix_log( LOG_LEVEL_ERR, "%s",
			error);
		SET_MSG_RESULT(value, strdup(error));

		return NOTSUPPORTED;
	}


	if(item->useip == 1)
	{
	#ifdef NEW_APPROACH
		zbx_snprintf(temp,sizeof(temp),"%s:%d",
			item->host_ip,
			item->snmp_port);
		session.peername = temp;
		session.remote_port = item->snmp_port;
	#else
		session.peername = item->host_ip;
		session.remote_port = item->snmp_port;
	#endif
	}
	else
	{
	#ifdef NEW_APPROACH
		zbx_snprintf(temp, sizeof(temp), "%s:%d",
			item->host_dns,
			item->snmp_port);
		session.peername = temp;
		session.remote_port = item->snmp_port;
	#else
		session.peername = item->host_dns;
		session.remote_port = item->snmp_port;
	#endif
	}

	if( (session.version == SNMP_VERSION_1) || (item->type == ITEM_TYPE_SNMPv2c))
	{
		session.community = (u_char *)item->snmp_community;
		session.community_len = strlen((void *)session.community);
		zabbix_log( LOG_LEVEL_DEBUG, "SNMP [%s@%s:%d]",
			session.community,
			session.peername,
			session.remote_port);
	}
	else if(session.version == SNMP_VERSION_3)
	{
		/* set the SNMPv3 user name */
		session.securityName = item->snmpv3_securityname;
		session.securityNameLen = strlen(session.securityName);

		/* set the security level to authenticated, but not encrypted */

		if(item->snmpv3_securitylevel == ITEM_SNMPV3_SECURITYLEVEL_NOAUTHNOPRIV)
		{
			session.securityLevel = SNMP_SEC_LEVEL_NOAUTH;
		}
		else if(item->snmpv3_securitylevel == ITEM_SNMPV3_SECURITYLEVEL_AUTHNOPRIV)
		{
			session.securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
			
			/* set the authentication method to MD5 */
			session.securityAuthProto = usmHMACMD5AuthProtocol;
			session.securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
			session.securityAuthKeyLen = USM_AUTH_KU_LEN;

			if (generate_Ku(session.securityAuthProto,
				session.securityAuthProtoLen,
				(u_char *) item->snmpv3_authpassphrase, strlen(item->snmpv3_authpassphrase),
				session.securityAuthKey,
				&session.securityAuthKeyLen) != SNMPERR_SUCCESS)
			{
				zbx_snprintf(error,sizeof(error),"Error generating Ku from authentication pass phrase.");

				zabbix_log( LOG_LEVEL_ERR, "%s", error);
				SET_MSG_RESULT(value, strdup(error));

				return NOTSUPPORTED;
			}
		}
		else if(item->snmpv3_securitylevel == ITEM_SNMPV3_SECURITYLEVEL_AUTHPRIV)
		{
			session.securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;

			/* set the authentication method to MD5 */
			session.securityAuthProto = usmHMACMD5AuthProtocol;
			session.securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
			session.securityAuthKeyLen = USM_AUTH_KU_LEN;

			if (generate_Ku(session.securityAuthProto,
				session.securityAuthProtoLen,
				(u_char *) item->snmpv3_authpassphrase, strlen(item->snmpv3_authpassphrase),
				session.securityAuthKey,
				&session.securityAuthKeyLen) != SNMPERR_SUCCESS)
			{
				zbx_snprintf(error,sizeof(error),"Error generating Ku from authentication pass phrase.");

				zabbix_log( LOG_LEVEL_ERR, "%s", error);
				SET_MSG_RESULT(value, strdup(error));

				return NOTSUPPORTED;
			}
			
			/* set the private method to DES */
			session.securityPrivProto = usmDESPrivProtocol;
    			session.securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
			session.securityPrivKeyLen = USM_PRIV_KU_LEN;
			
			if (generate_Ku(session.securityAuthProto,
				session.securityAuthProtoLen,
		                (u_char *) item->snmpv3_privpassphrase, strlen(item->snmpv3_privpassphrase),
				session.securityPrivKey,
				&session.securityPrivKeyLen) != SNMPERR_SUCCESS) 
			{
				zbx_snprintf(error,sizeof(error),"Error generating Ku from priv pass phrase.");

				zabbix_log( LOG_LEVEL_ERR, "%s", error);
				SET_MSG_RESULT(value, strdup(error));

				return NOTSUPPORTED;
			}
		}
		zabbix_log( LOG_LEVEL_DEBUG, "SNMPv3 [%s@%s:%d]",
			session.securityName,
			session.peername,
			session.remote_port);
	}
	else
	{
		zbx_snprintf(error,sizeof(error),"Error in get_value_SNMP. Unsupported session.version [%d]",
			(int)session.version);
		zabbix_log( LOG_LEVEL_ERR, "%s",
			error);
		SET_MSG_RESULT(value, strdup(error));
		
		return NOTSUPPORTED;
	}

	zabbix_log( LOG_LEVEL_DEBUG, "OID [%s]",
		item->snmp_oid);

	SOCK_STARTUP;
	ss = snmp_open(&session);

	if(ss == NULL)
	{
		SOCK_CLEANUP;

		zbx_snprintf(error,sizeof(error),"Error doing snmp_open()");
		zabbix_log( LOG_LEVEL_ERR, "%s",
			error);
		SET_MSG_RESULT(value, strdup(error));

		return NOTSUPPORTED;
	}
	zabbix_log( LOG_LEVEL_DEBUG, "In get_value_SNMP() 0.2");

	pdu = snmp_pdu_create(SNMP_MSG_GET);
/* Changed to snmp_parse_oid */
/* read_objid(item->snmp_oid, anOID, &anOID_len);*/
	snmp_parse_oid(item->snmp_oid, anOID, &anOID_len);

#if OTHER_METHODS
	get_node("sysDescr.0", anOID, &anOID_len);
	read_objid(".1.3.6.1.2.1.1.1.0", anOID, &anOID_len);
	read_objid("system.sysDescr.0", anOID, &anOID_len);
#endif

	snmp_add_null_var(pdu, anOID, anOID_len);
	zabbix_log( LOG_LEVEL_DEBUG, "In get_value_SNMP() 0.3");
  
	status = snmp_synch_response(ss, pdu, &response);
	zabbix_log( LOG_LEVEL_DEBUG, "Status send [%d]", status);
	zabbix_log( LOG_LEVEL_DEBUG, "In get_value_SNMP() 0.4");

	zabbix_log( LOG_LEVEL_DEBUG, "In get_value_SNMP() 1");

	if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR)
	{

	zabbix_log( LOG_LEVEL_DEBUG, "In get_value_SNMP() 2");
/*		for(vars = response->variables; vars; vars = vars->next_variable)
		{
			print_variable(vars->name, vars->name_length, vars);
		}*/

		for(vars = response->variables; vars; vars = vars->next_variable)
		{
			int count=1;
			zabbix_log( LOG_LEVEL_DEBUG, "AV loop(%d)", vars->type);

/*			if(	(vars->type == ASN_INTEGER) ||*/
			if(	(vars->type == ASN_UINTEGER)||
				(vars->type == ASN_COUNTER) ||
#ifdef OPAQUE_SPECIAL_TYPES
				(vars->type == ASN_UNSIGNED64) ||
#endif
				(vars->type == ASN_TIMETICKS) ||
				(vars->type == ASN_GAUGE)
			)
			{
/*				*result=(long)*vars->val.integer;*/
				/*
				 * This solves situation when large numbers are stored as negative values
				 * http://sourceforge.net/tracker/index.php?func=detail&aid=700145&group_id=23494&atid=378683
				 */ 
				/*zbx_snprintf(result_str,sizeof(result_str),"%ld",(long)*vars->val.integer);*/
/*				zbx_snprintf(result_str,sizeof(result_str),"%lu",(long)*vars->val.integer);*/

				/* Not correct. Returns huge values. */
/*				SET_UI64_RESULT(value, (zbx_uint64_t)*vars->val.integer);*/
				if (vars->type == ASN_GAUGE && *vars->val.integer >= 4294967294) {
					SET_UI64_RESULT(value, (unsigned long)0);
				}
				else {
					SET_UI64_RESULT(value, (unsigned long)*vars->val.integer);
				}

				zabbix_log( LOG_LEVEL_DEBUG, "OID [%s] Type [%d] UI64[" ZBX_FS_UI64 "]",
					    item->snmp_oid,
					    vars->type,
					    (zbx_uint64_t)*vars->val.integer);
				zabbix_log( LOG_LEVEL_DEBUG, "OID [%s] Type [%d] ULONG[%lu]",
					    item->snmp_oid,
					    vars->type,
					    (zbx_uint64_t)(unsigned long)*vars->val.integer);
			}
			else if(vars->type == ASN_COUNTER64)
			{
				/* Incorrect code for 32 bit platforms */
/*				SET_UI64_RESULT(value, ((vars->val.counter64->high)<<32)+(vars->val.counter64->low));*/
				SET_UI64_RESULT(value, (((zbx_uint64_t)vars->val.counter64->high)<<32)+((zbx_uint64_t)vars->val.counter64->low));
			}
			else if(vars->type == ASN_INTEGER
#define ASN_FLOAT           (ASN_APPLICATION | 8)
#define ASN_DOUBLE          (ASN_APPLICATION | 9)

#ifdef OPAQUE_SPECIAL_TYPES
				|| (vars->type == ASN_INTEGER64)
#endif
			)
			{
				/* Negative integer values are converted to double */
				if(*vars->val.integer<0)
				{
					SET_DBL_RESULT(value, (double)*vars->val.integer);
				}
				else
				{
					SET_UI64_RESULT(value, (zbx_uint64_t)*vars->val.integer);
				}
			}
#ifdef OPAQUE_SPECIAL_TYPES
			else if(vars->type == ASN_FLOAT)
			{
				SET_DBL_RESULT(value, *vars->val.floatVal);
			}
			else if(vars->type == ASN_DOUBLE)
			{
				SET_DBL_RESULT(value, *vars->val.doubleVal);
			}
#endif
			else if(vars->type == ASN_OCTET_STR)
			{
				if(item->value_type == ITEM_VALUE_TYPE_FLOAT)
				{
					p = malloc(vars->val_len+1);
					if(p)
					{
						memcpy(p, vars->val.string, vars->val_len);
						p[vars->val_len] = '\0';
						dbl = strtod(p, NULL);

						SET_DBL_RESULT(value, dbl);
					}
					else
					{
						zbx_snprintf(error,sizeof(error),"Cannot allocate required memory");
						zabbix_log( LOG_LEVEL_ERR, "%s", error);
						SET_MSG_RESULT(value, strdup(error));
					}
				}
				else if(item->value_type != ITEM_VALUE_TYPE_STR)
				{
					zbx_snprintf(error,sizeof(error),"Cannot store SNMP string value (ASN_OCTET_STR) in item having numeric type");
					zabbix_log( LOG_LEVEL_ERR, "%s",
						error);
					SET_MSG_RESULT(value, strdup(error));

					ret = NOTSUPPORTED;
				}
				else
				{
					zabbix_log( LOG_LEVEL_DEBUG, "ASN_OCTET_STR [%s]", vars->val.string);
					zabbix_log( LOG_LEVEL_DEBUG, "ASN_OCTET_STR [%d]", vars->val_len);
					
					p = malloc(1024);
					if(p)
					{
						memset(p,0,1024);
						snprint_value(p, 1023, vars->name, vars->name_length, vars);
						/* Skip STRING: and STRING_HEX: */
						c=strchr(p,':');
						if(c==NULL)
						{
							SET_STR_RESULT(value, strdup(p));
						}
						else
						{
							SET_STR_RESULT(value, strdup(c+1));
						}
						zabbix_log( LOG_LEVEL_DEBUG, "ASN_OCTET_STR [%s]", p);
						free(p);
					}
					else
					{
						zbx_snprintf(error,MAX_STRING_LEN-1,"Cannot allocate required memory");
						zabbix_log( LOG_LEVEL_ERR, "%s", error);
						SET_MSG_RESULT(value, strdup(error));
					}

/*					p = malloc(vars->val_len+1);
					if(p)
					{
						zabbix_log( LOG_LEVEL_WARNING, "Result [%s] len [%d]",vars->val.string,vars->val_len);
						memcpy(p, vars->val.string, vars->val_len);
						p[vars->val_len] = '\0';

						SET_STR_RESULT(value, p);
					}
					else
					{
						zbx_snprintf(error,sizeof(error),"Cannot allocate required memory");
						zabbix_log( LOG_LEVEL_ERR, "%s", error);
						SET_MSG_RESULT(value, strdup(error));
					}*/
				}
			}
			else if(vars->type == ASN_IPADDRESS)
			{
/*				ip = vars->val.string;
				zbx_snprintf(result_str,sizeof(result_str),"%d.%d.%d.%d",ip[0],ip[1],ip[2],ip[3]);*/
/*				if(item->type == 0)
				{
					ret = NOTSUPPORTED;
				}*/
				if(item->value_type != ITEM_VALUE_TYPE_STR)
				{
					zbx_snprintf(error,sizeof(error),"Cannot store SNMP string value (ASN_IPADDRESS) in item having numeric type");
					zabbix_log( LOG_LEVEL_ERR, "%s",
						error);
					SET_MSG_RESULT(value, strdup(error));
					ret = NOTSUPPORTED;
				}
				else
				{
					p = malloc(MAX_STRING_LEN);
					if(p)
					{
						ip = vars->val.string;
						zbx_snprintf(p,MAX_STRING_LEN-1,"%d.%d.%d.%d",
							ip[0],
							ip[1],
							ip[2],
							ip[3]);
						SET_STR_RESULT(value, p);
                                        }
					else
					{
						zbx_snprintf(error,MAX_STRING_LEN-1,"Cannot allocate required memory");
						zabbix_log( LOG_LEVEL_ERR, "%s",
							error);
						SET_MSG_RESULT(value, strdup(error));
					}
				}
			}
			else
			{
/* count is not really used. Has to be removed */ 
				count++;

				zbx_snprintf(error,sizeof(error),"OID [%s] value #%d has unknow type [%X]",
					item->snmp_oid,
					count,
					vars->type);

				zabbix_log( LOG_LEVEL_ERR, "%s",
					error);
				SET_MSG_RESULT(value, strdup(error));

				ret  = NOTSUPPORTED;
			}
		}
	}
	else
	{
		if (status == STAT_SUCCESS)
		{
			zabbix_log( LOG_LEVEL_WARNING, "SNMP error in packet. Reason: %s\n",
				snmp_errstring(response->errstat));
			if(response->errstat == SNMP_ERR_NOSUCHNAME)
			{
				zbx_snprintf(error,sizeof(error),"SNMP error [%s]",
					snmp_errstring(response->errstat));

				zabbix_log( LOG_LEVEL_ERR, "%s",
					error);
				SET_MSG_RESULT(value, strdup(error));

				ret=NOTSUPPORTED;
			}
			else
			{
				zbx_snprintf(error,sizeof(error),"SNMP error [%s]",
					snmp_errstring(response->errstat));

				zabbix_log( LOG_LEVEL_ERR, "%s",
					error);
				SET_MSG_RESULT(value, strdup(error));

				ret=NOTSUPPORTED;
			}
		}
		else if(status == STAT_TIMEOUT)
		{
			zbx_snprintf(error,sizeof(error),"Timeout while connecting to [%s]",
				session.peername);

/*			snmp_sess_perror("snmpget", ss);*/
			zabbix_log( LOG_LEVEL_ERR, "%s",
				error);
			SET_MSG_RESULT(value, strdup(error));

			ret = NETWORK_ERROR;
		}
		else
		{
			zbx_snprintf(error,sizeof(error),"SNMP error [%d]",
				status);

			zabbix_log( LOG_LEVEL_ERR, "%s",
				error);
			SET_MSG_RESULT(value, strdup(error));

			ret=NOTSUPPORTED;
		}
	}

	if (response)
	{
		snmp_free_pdu(response);
	}
	snmp_close(ss);

	SOCK_CLEANUP;
	return ret;
}
Пример #24
0
HRESULT get_elem_source_index(HTMLElement *elem, LONG *ret)
{
    elem_vector_t buf = {NULL, 0, 8};
    nsIDOMNode *parent_node, *iter;
    UINT16 parent_type;
    HTMLDOMNode *node;
    int i;
    nsresult nsres;
    HRESULT hres;

    iter = elem->node.nsnode;
    nsIDOMNode_AddRef(iter);

    /* Find document or document fragment parent. */
    while(1) {
        nsres = nsIDOMNode_GetParentNode(iter, &parent_node);
        nsIDOMNode_Release(iter);
        assert(nsres == NS_OK);
        if(!parent_node)
            break;

        nsres = nsIDOMNode_GetNodeType(parent_node, &parent_type);
        assert(nsres == NS_OK);

        if(parent_type != ELEMENT_NODE) {
            if(parent_type != DOCUMENT_NODE && parent_type != DOCUMENT_FRAGMENT_NODE)
                FIXME("Unexpected parent_type %d\n", parent_type);
            break;
        }

        iter = parent_node;
    }

    if(!parent_node) {
        *ret = -1;
        return S_OK;
    }

    hres = get_node(elem->node.doc, parent_node, TRUE, &node);
    nsIDOMNode_Release(parent_node);
    if(FAILED(hres))
        return hres;


    /* Create all children collection and find the element in it.
     * This could be optimized if we ever find the reason. */
    buf.buf = heap_alloc(buf.size*sizeof(*buf.buf));
    if(!buf.buf) {
        IHTMLDOMNode_Release(&node->IHTMLDOMNode_iface);
        return E_OUTOFMEMORY;
    }

    create_all_list(elem->node.doc, node, &buf);

    for(i=0; i < buf.len; i++) {
        if(buf.buf[i] == elem)
            break;
    }
    IHTMLDOMNode_Release(&node->IHTMLDOMNode_iface);
    heap_free(buf.buf);
    if(i == buf.len) {
        FIXME("The element is not in parent's child list?\n");
        return E_UNEXPECTED;
    }

    *ret = i;
    return S_OK;
}
Пример #25
0
int UavcanNode::run()
{

	get_node().setRestartRequestHandler(&restart_request_handler);

	while (init_indication_controller(get_node()) < 0) {
		::syslog(LOG_INFO, "UAVCAN: Indication controller init failed\n");
		::sleep(1);
	}

	while (init_sim_controller(get_node()) < 0) {
		::syslog(LOG_INFO, "UAVCAN: sim controller init failed\n");
		::sleep(1);
	}

	(void)pthread_mutex_lock(&_node_mutex);

	/*
	 * Set up the time synchronization
	 */

	const int slave_init_res = _time_sync_slave.start();

	if (slave_init_res < 0) {
		warnx("Failed to start time_sync_slave");
		_task_should_exit = true;
	}

	const unsigned PollTimeoutMs = 50;

	const int busevent_fd = ::open(uavcan_stm32::BusEvent::DevName, 0);

	if (busevent_fd < 0) {
		warnx("Failed to open %s", uavcan_stm32::BusEvent::DevName);
		_task_should_exit = true;
	}

	/* If we had an  RTC we would call uavcan_stm32::clock::setUtc()
	* but for now we use adjustUtc with a correction of 0
	*/
//        uavcan_stm32::clock::adjustUtc(uavcan::UtcDuration::fromUSec(0));

	_node.setModeOperational();

	/*
	 * This event is needed to wake up the thread on CAN bus activity (RX/TX/Error).
	 * Please note that with such multiplexing it is no longer possible to rely only on
	 * the value returned from poll() to detect whether actuator control has timed out or not.
	 * Instead, all ORB events need to be checked individually (see below).
	 */
	add_poll_fd(busevent_fd);

	uint32_t start_tick = clock_systimer();

	while (!_task_should_exit) {
		// Mutex is unlocked while the thread is blocked on IO multiplexing
		(void)pthread_mutex_unlock(&_node_mutex);

		const int poll_ret = ::poll(_poll_fds, _poll_fds_num, PollTimeoutMs);


		(void)pthread_mutex_lock(&_node_mutex);

		node_spin_once();  // Non-blocking


		// this would be bad...
		if (poll_ret < 0) {
			PX4_ERR("poll error %d", errno);
			continue;

		} else {
			// Do Something
		}

		if (clock_systimer() - start_tick > TICK_PER_SEC) {
			start_tick = clock_systimer();
			resources("Udate:");
			/*
			 *  Printing the slave status information once a second
			 */
			const bool active = _time_sync_slave.isActive();                      // Whether it can sync with a remote master

			const int master_node_id = _time_sync_slave.getMasterNodeID().get();  // Returns an invalid Node ID if (active == false)

			const long msec_since_last_adjustment = (_node.getMonotonicTime() - _time_sync_slave.getLastAdjustmentTime()).toMSec();
			const uavcan::UtcTime utc = uavcan_stm32::clock::getUtc();
			syslog(LOG_INFO, "Time:%lld\n"
			       "            Time sync slave status:\n"
			       "    Active: %d\n"
			       "    Master Node ID: %d\n"
			       "    Last clock adjustment was %ld ms ago\n",
			       utc .toUSec(), int(active), master_node_id, msec_since_last_adjustment);
			syslog(LOG_INFO, "UTC %lu sec   Rate corr: %fPPM   Jumps: %lu   Locked: %i\n\n",
			       static_cast<unsigned long>(utc.toMSec() / 1000),
			       static_cast<double>(uavcan_stm32::clock::getUtcRateCorrectionPPM()),
			       uavcan_stm32::clock::getUtcJumpCount(),
			       int(uavcan_stm32::clock::isUtcLocked()));
		}

	}

	teardown();
	warnx("exiting.");

	exit(0);
}
Пример #26
0
/* SOAP client calls this function to parse response from SOAP server */
bool parse_packet_soap(SoapClient *obj, const char *buffer,
                       int buffer_size,
                       std::shared_ptr<sdlFunction> fn, const char *fn_name,
                       Variant &return_value, Array& soap_headers) {
  char* envelope_ns = nullptr;
  xmlNodePtr trav, env, head, body, resp, cur, fault;
  xmlAttrPtr attr;
  int param_count = 0;
  int soap_version = SOAP_1_1;
  sdlSoapBindingFunctionHeaderMap *hdrs = nullptr;

  assert(return_value.asTypedValue()->m_type == KindOfUninit);
  return_value.asTypedValue()->m_type = KindOfNull;

  /* Response for one-way opearation */
  if (buffer_size == 0) {
    return true;
  }

  /* Parse XML packet */
  xmlDocPtr response = soap_xmlParseMemory(buffer, buffer_size);
  if (!response) {
    add_soap_fault(obj, "Client", "looks like we got no XML document");
    return false;
  }
  if (xmlGetIntSubset(response) != nullptr) {
    add_soap_fault(obj, "Client", "DTD are not supported by SOAP");
    xmlFreeDoc(response);
    return false;
  }

  /* Get <Envelope> element */
  env = nullptr;
  trav = response->children;
  while (trav != nullptr) {
    if (trav->type == XML_ELEMENT_NODE) {
      if (!env && node_is_equal_ex(trav,"Envelope", SOAP_1_1_ENV_NAMESPACE)) {
        env = trav;
        envelope_ns = SOAP_1_1_ENV_NAMESPACE;
        soap_version = SOAP_1_1;
      } else if (!env &&
                 node_is_equal_ex(trav, "Envelope", SOAP_1_2_ENV_NAMESPACE)) {
        env = trav;
        envelope_ns = SOAP_1_2_ENV_NAMESPACE;
        soap_version = SOAP_1_2;
      } else {
        add_soap_fault(obj, "VersionMismatch", "Wrong Version");
        xmlFreeDoc(response);
        return false;
      }
    }
    trav = trav->next;
  }
  if (env == nullptr) {
    add_soap_fault(obj, "Client",
                   "looks like we got XML without \"Envelope\" element");
    xmlFreeDoc(response);
    return false;
  }

  attr = env->properties;
  while (attr != nullptr) {
    if (attr->ns == nullptr) {
      add_soap_fault(obj, "Client",
                     "A SOAP Envelope element cannot have non Namespace "
                     "qualified attributes");
      xmlFreeDoc(response);
      return false;
    }
    if (attr_is_equal_ex(attr, "encodingStyle", SOAP_1_2_ENV_NAMESPACE)) {
      if (soap_version == SOAP_1_2) {
        add_soap_fault(obj, "Client",
                       "encodingStyle cannot be specified on the Envelope");
        xmlFreeDoc(response);
        return false;
      }
      if (strcmp((char*)attr->children->content, SOAP_1_1_ENC_NAMESPACE)) {
        add_soap_fault(obj, "Client", "Unknown data encoding style");
        xmlFreeDoc(response);
        return false;
      }
    }
    attr = attr->next;
  }

  /* Get <Header> element */
  head = nullptr;
  trav = env->children;
  while (trav != nullptr && trav->type != XML_ELEMENT_NODE) {
    trav = trav->next;
  }
  if (trav != nullptr && node_is_equal_ex(trav,"Header",envelope_ns)) {
    head = trav;
    trav = trav->next;
  }

  /* Get <Body> element */
  body = nullptr;
  while (trav != nullptr && trav->type != XML_ELEMENT_NODE) {
    trav = trav->next;
  }
  if (trav != nullptr && node_is_equal_ex(trav,"Body",envelope_ns)) {
    body = trav;
    trav = trav->next;
  }
  while (trav != nullptr && trav->type != XML_ELEMENT_NODE) {
    trav = trav->next;
  }
  if (body == nullptr) {
    add_soap_fault(obj, "Client", "Body must be present in a SOAP envelope");
    xmlFreeDoc(response);
    return false;
  }
  attr = body->properties;
  while (attr != nullptr) {
    if (attr->ns == nullptr) {
      if (soap_version == SOAP_1_2) {
        add_soap_fault(obj, "Client",
                       "A SOAP Body element cannot have non Namespace "
                       "qualified attributes");
        xmlFreeDoc(response);
        return false;
      }
    } else if (attr_is_equal_ex(attr,"encodingStyle",SOAP_1_2_ENV_NAMESPACE)) {
      if (soap_version == SOAP_1_2) {
        add_soap_fault(obj, "Client",
                       "encodingStyle cannot be specified on the Body");
        xmlFreeDoc(response);
        return false;
      }
      if (strcmp((char*)attr->children->content, SOAP_1_1_ENC_NAMESPACE)) {
        add_soap_fault(obj, "Client", "Unknown data encoding style");
        xmlFreeDoc(response);
        return false;
      }
    }
    attr = attr->next;
  }
  if (trav != nullptr && soap_version == SOAP_1_2) {
    add_soap_fault(obj, "Client",
                   "A SOAP 1.2 envelope can contain only Header and Body");
    xmlFreeDoc(response);
    return false;
  }

  if (head != nullptr) {
    attr = head->properties;
    while (attr != nullptr) {
      if (attr->ns == nullptr) {
        add_soap_fault(obj, "Client",
                       "A SOAP Header element cannot have non Namespace "
                       "qualified attributes");
        xmlFreeDoc(response);
        return false;
      }
      if (attr_is_equal_ex(attr, "encodingStyle", SOAP_1_2_ENV_NAMESPACE)) {
        if (soap_version == SOAP_1_2) {
          add_soap_fault(obj, "Client",
                         "encodingStyle cannot be specified on the Header");
          xmlFreeDoc(response);
          return false;
        }
        if (strcmp((char*)attr->children->content, SOAP_1_1_ENC_NAMESPACE)) {
          add_soap_fault(obj, "Client", "Unknown data encoding style");
          xmlFreeDoc(response);
          return false;
        }
      }
      attr = attr->next;
    }
  }

  /* Check if <Body> contains <Fault> element */
  fault = get_node_ex(body->children,"Fault",envelope_ns);
  if (fault != nullptr) {
    char *faultcode = nullptr;
    String faultstring, faultactor;
    Variant details;
    xmlNodePtr tmp;

    if (soap_version == SOAP_1_1) {
      tmp = get_node(fault->children, "faultcode");
      if (tmp != nullptr && tmp->children != nullptr) {
        faultcode = (char*)tmp->children->content;
      }

      tmp = get_node(fault->children, "faultstring");
      if (tmp != nullptr && tmp->children != nullptr) {
        Variant zv = master_to_zval(get_conversion(KindOfString), tmp);
        faultstring = zv.toString();
      }

      tmp = get_node(fault->children, "faultactor");
      if (tmp != nullptr && tmp->children != nullptr) {
        Variant zv = master_to_zval(get_conversion(KindOfString), tmp);
        faultactor = zv.toString();
      }

      tmp = get_node(fault->children, "detail");
      if (tmp != nullptr) {
        details = master_to_zval(encodePtr(), tmp);
      }
    } else {
      tmp = get_node(fault->children, "Code");
      if (tmp != nullptr && tmp->children != nullptr) {
        tmp = get_node(tmp->children, "Value");
        if (tmp != nullptr && tmp->children != nullptr) {
          faultcode = (char*)tmp->children->content;
        }
      }

      tmp = get_node(fault->children,"Reason");
      if (tmp != nullptr && tmp->children != nullptr) {
        /* TODO: lang attribute */
        tmp = get_node(tmp->children,"Text");
        if (tmp != nullptr && tmp->children != nullptr) {
          Variant zv = master_to_zval(get_conversion(KindOfString), tmp);
          faultstring = zv.toString();
        }
      }

      tmp = get_node(fault->children,"Detail");
      if (tmp != nullptr) {
        details = master_to_zval(encodePtr(), tmp);
      }
    }
    obj->m_soap_fault =
        SystemLib::AllocSoapFaultObject(String(faultcode, CopyString),
                                        faultstring,
                                        faultactor,
                                        details);
    xmlFreeDoc(response);
    return false;
  }

  /* Parse content of <Body> element */
  return_value = Array::Create();
  resp = body->children;
  while (resp != nullptr && resp->type != XML_ELEMENT_NODE) {
    resp = resp->next;
  }
  if (resp != nullptr) {
    if (fn && fn->binding && fn->binding->bindingType == BINDING_SOAP) {
      /* Function has WSDL description */
      sdlParamPtr h_param, param;
      xmlNodePtr val = nullptr;
      const char *name, *ns = nullptr;
      Variant tmp(Variant::NullInit{});
      sdlSoapBindingFunctionPtr fnb =
        (sdlSoapBindingFunctionPtr)fn->bindingAttributes;
      int res_count;

      hdrs = &fnb->output.headers;

      if (!fn->responseParameters.empty()) {
        res_count = fn->responseParameters.size();
        for (unsigned int i = 0; i < fn->responseParameters.size(); i++) {
          h_param = fn->responseParameters[i];
          param = h_param;
          if (fnb->style == SOAP_DOCUMENT) {
            if (param->element) {
              name = param->element->name.c_str();
              ns = param->element->namens.c_str();
/*
              name = param->encode->details.type_str;
              ns = param->encode->details.ns;
*/
            } else {
              name = param->paramName.c_str();
            }
          } else {
            name = fn->responseName.c_str();
            /* ns = ? */
          }

          /* Get value of parameter */
          cur = get_node_ex(resp, (char*)name, (char*)ns);
          if (!cur) {
            cur = get_node(resp, (char*)name);
            /* TODO: produce warning invalid ns */
          }
          if (!cur && fnb->style == SOAP_RPC) {
            cur = resp;
          }
          if (cur) {
            if (fnb->style == SOAP_DOCUMENT) {
              val = cur;
            } else {
              val = get_node(cur->children, (char*)param->paramName.c_str());
              if (res_count == 1) {
                if (val == nullptr) {
                  val = get_node(cur->children, "return");
                }
                if (val == nullptr) {
                  val = get_node(cur->children, "result");
                }
                if (val == nullptr && cur->children && !cur->children->next) {
                  val = cur->children;
                }
              }
            }
          }

          if (!val) {
            /* TODO: may be "nil" is not OK? */
/*
            add_soap_fault(obj, "Client", "Can't find response data");
            xmlFreeDoc(response);
            return false;
*/
          } else {
            /* Decoding value of parameter */
            if (param != nullptr) {
              tmp = master_to_zval(param->encode, val);
            } else {
              tmp = master_to_zval(encodePtr(), val);
            }
          }
          return_value.toArrRef().set(String(param->paramName), tmp);
          param_count++;
        }
      }
    } else {
      /* Function hasn't WSDL description */
      xmlNodePtr val;
      val = resp->children;
      while (val != nullptr) {
        while (val && val->type != XML_ELEMENT_NODE) {
          val = val->next;
        }
        if (val != nullptr) {
          if (!node_is_equal_ex(val,"result",RPC_SOAP12_NAMESPACE)) {
            Variant tmp = master_to_zval(encodePtr(), val);
            if (val->name) {
              String key((char*)val->name, CopyString);
              if (return_value.toCArrRef().exists(key)) {
                auto& lval = return_value.toArrRef().lvalAt(key);
                if (!lval.isArray()) lval = lval.toArray();
                lval.toArrRef().append(tmp);
              } else if (val->next && get_node(val->next, (char*)val->name)) {
                Array arr = Array::Create();
                arr.append(tmp);
                return_value.toArrRef().set(key, arr);
              } else {
                return_value.toArrRef().set(key, tmp);
              }
            } else {
              return_value.toArrRef().append(tmp);
            }
            ++param_count;
          }
          val = val->next;
        }
      }
    }
  }

  if (return_value.isArray()) {
    if (param_count == 0) {
      return_value = init_null();
    } else if (param_count == 1) {
      Array arr = return_value.toArray();
      ArrayIter iter(arr);
      return_value = iter.second();
    }
  }

  if (head) {
    trav = head->children;
    while (trav) {
      if (trav->type == XML_ELEMENT_NODE) {
        encodePtr enc;
        if (hdrs && !hdrs->empty()) {
          std::string key;
          if (trav->ns) {
            key += (char*)trav->ns->href;
            key += ':';
          }
          key += (char*)trav->name;
          sdlSoapBindingFunctionHeaderMap::const_iterator iter =
            hdrs->find(key);
          if (iter != hdrs->end()) {
            enc = iter->second->encode;
          }
        }
        soap_headers.set(String((char*)trav->name, CopyString),
                         master_to_zval(enc, trav));
      }
      trav = trav->next;
    }
  }

  xmlFreeDoc(response);
  return true;
}
Пример #27
0
void append_line(tree_node *tree, char *new_line){
	//appends `new_line` as a new last line
	tree_node *temp_node;
	int finished;

	if(tree->left == NULL){
		//empty tree
		tree->left = (tree_node *) new_line;
		tree->key += 1;
		tree->right = NULL;
		tree->height = 0;
	}
	else{
		temp_node = tree;
		tree_node *stack[STACK_MAX];
		int stack_ptr = 0;

		while (temp_node->right != NULL){
			stack[stack_ptr++] = temp_node;
			temp_node->key += 1;
			temp_node =  temp_node->right;
		}

		tree_node *left_child, *right_child;
		
		left_child = get_node();
		right_child = get_node();

		left_child->left = temp_node->left;
		left_child->key = temp_node->key;

		right_child->left = (tree_node *)new_line;
		right_child->key += 1;

		temp_node->left = left_child;
		temp_node->right = right_child;
		temp_node->key += 1;
		temp_node->height = 1;

		//rebalance tree
		finished = 0;

		while (stack_ptr > 0 && !finished){
			int temp_height, old_height;
			temp_node = stack[--stack_ptr];
			old_height = temp_node->height;

			if(temp_node->left->height - temp_node->right->height == 2){

				if (temp_node->left->left->height - temp_node->right->height == 1){
					right_rotation(temp_node);
					temp_node->right->height = temp_node->right->left->height + 1;
					temp_node->height = temp_node->right->height + 1;
				}
				else{
					left_rotation(temp_node->left);
					right_rotation(temp_node);
					temp_height = temp_node->left->left->height;
					temp_node->left->height = temp_height + 1;
					temp_node->right->height = temp_height + 1;
					temp_node->height = temp_height + 2;
				}

			}
			else if (temp_node->left->height - temp_node->right->height == -2){

				if (temp_node->right->right->height - temp_node->left->height == 1){
					left_rotation(temp_node);
					temp_node->left->height = temp_node->left->right->height + 1;
					temp_node->height = temp_node->left->height + 1;
				}
				else{
					right_rotation(temp_node->right);
					left_rotation(temp_node);
					temp_height = temp_node->right->right->height;
					temp_node->left->height = temp_height + 1;
					temp_node->right->height = temp_height + 1;
					temp_node->height = temp_height + 2;
				}

			}
			else{
				//if no rotation needed, update height
				if (temp_node->left->height > temp_node->right->height){
					temp_node->height = temp_node->left->height + 1;
				}
				else{
					temp_node->height = temp_node->right->height + 1;
				}

			}

			if (temp_node->height == old_height){
				finished = 1;
			}

		}
	}
}
Пример #28
0
void SceneTreeEditor::_cell_button_pressed(Object *p_item,int p_column,int p_id) {

	TreeItem *item=p_item->cast_to<TreeItem>();
	ERR_FAIL_COND(!item);

	NodePath np = item->get_metadata(0);

	Node *n=get_node(np);
	ERR_FAIL_COND(!n);

	if (p_id==BUTTON_SUBSCENE) {
		//open scene request
		Rect2 item_rect = tree->get_item_rect(item,0);
		item_rect.pos.y-=tree->get_scroll().y;
		item_rect.pos+=tree->get_global_pos();

		if (n==get_scene_node()) {
			inheritance_menu->set_pos(item_rect.pos+Vector2(0,item_rect.size.y));
			inheritance_menu->set_size(Vector2(item_rect.size.x,0));
			inheritance_menu->popup();
			instance_node=n->get_instance_ID();

		} else {
			instance_menu->set_pos(item_rect.pos+Vector2(0,item_rect.size.y));
			instance_menu->set_size(Vector2(item_rect.size.x,0));
			if (EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(n))
				instance_menu->set_item_checked(0,true);
			else
				instance_menu->set_item_checked(0,false);

			if (n->get_owner()==get_scene_node()) {
				instance_menu->set_item_checked(1,n->get_scene_instance_load_placeholder());
				instance_menu->set_item_disabled(1,false);
			} else {

				instance_menu->set_item_checked(1,false);
				instance_menu->set_item_disabled(1,true);
			}

			instance_menu->popup();
			instance_node=n->get_instance_ID();
		}
		//emit_signal("open",n->get_filename());
	} else if (p_id==BUTTON_SCRIPT) {
		RefPtr script=n->get_script();
		if (!script.is_null())
			emit_signal("open_script",script);

	} else if (p_id==BUTTON_VISIBILITY) {


		if (n->is_type("Spatial")) {

			Spatial *ci = n->cast_to<Spatial>();
			if (!ci->is_visible() && ci->get_parent_spatial() && !ci->get_parent_spatial()->is_visible()) {
				error->set_text(TTR("This item cannot be made visible because the parent is hidden. Unhide the parent first."));
				error->popup_centered_minsize();
				return;
			}

			bool v = !bool(n->call("is_hidden"));
			undo_redo->create_action(TTR("Toggle Spatial Visible"));
			undo_redo->add_do_method(n,"_set_visible_",!v);
			undo_redo->add_undo_method(n,"_set_visible_",v);
			undo_redo->commit_action();
		} else if (n->is_type("CanvasItem")) {

			CanvasItem *ci = n->cast_to<CanvasItem>();
			if (!ci->is_visible() && ci->get_parent_item() && !ci->get_parent_item()->is_visible()) {
				error->set_text(TTR("This item cannot be made visible because the parent is hidden. Unhide the parent first."));
				error->popup_centered_minsize();
				return;
			}
			bool v = !bool(n->call("is_hidden"));
			undo_redo->create_action(TTR("Toggle CanvasItem Visible"));
			undo_redo->add_do_method(n,v?"hide":"show");
			undo_redo->add_undo_method(n,v?"show":"hide");
			undo_redo->commit_action();
		}

	} else if (p_id==BUTTON_LOCK) {

		if (n->is_type("CanvasItem")) {
			n->set_meta("_edit_lock_", Variant());
			_update_tree();
			emit_signal("node_changed");
		}

	} else if (p_id==BUTTON_GROUP) {
		if (n->is_type("CanvasItem")) {
			n->set_meta("_edit_group_", Variant());
			_update_tree();
			emit_signal("node_changed");
		}
	} else if (p_id==BUTTON_WARNING) {

		String config_err = n->get_configuration_warning();
		if (config_err==String())
			return;
		config_err=config_err.word_wrap(80);
		warning->set_text(config_err);
		warning->popup_centered_minsize();

	} else if (p_id==BUTTON_SIGNALS) {

		editor_selection->clear();
		editor_selection->add_node(n);

		set_selected(n);

		NodeDock::singleton->get_parent()->call("set_current_tab",NodeDock::singleton->get_index());
		NodeDock::singleton->show_connections();

	} else if (p_id==BUTTON_GROUPS) {

		editor_selection->clear();
		editor_selection->add_node(n);

		set_selected(n);

		NodeDock::singleton->get_parent()->call("set_current_tab",NodeDock::singleton->get_index());
		NodeDock::singleton->show_groups();
	}
}
int pqrs_xml_compiler_get_preferences_checkbox_node_tree_name_line_count(const pqrs_xml_compiler_preferences_checkbox_node_tree* p) {
    auto node_tree = cast_to_preferences_checkbox_node_tree(p);
    if (!node_tree) return 0;

    return (node_tree->get_node()).get_name_line_count();
}
Пример #30
0
int
decode_vbind (unsigned char *data, unsigned int vb_len)
{
  unsigned char *var_val;
  oid var_name[MAX_OID_LEN];	/* To test the objid */
  size_t name_len = MAX_OID_LEN;	/* To test the objid */
  int badtype=0;
  size_t len;
  struct variable_list *vp;
  oid objid[MAX_OID_LEN];
  char _docsis_snmp_label[50];	/* To hold the 'name' of the type, i.e. Integer etc */
  char *enum_string = NULL;
  static char outbuf[16384];
  struct tree *subtree;
  struct enum_list *enums;

  memset (outbuf, 0, 16384);

  vp = (struct variable_list *) malloc (sizeof (struct variable_list));
  if (vp == NULL)
    {
      fprintf (stderr, "Out of memory\n");
      return 0;
    }
  memset (vp, 0, sizeof (struct variable_list));

  vp->next_variable = NULL;
  vp->val.string = NULL;
  vp->name_length = MAX_OID_LEN;
  vp->name = 0;
  data = snmp_parse_var_op (data, objid, &vp->name_length, &vp->type, &vp->val_len,
		       &var_val, (size_t *) & vb_len);

  if (data == NULL)
    return -1;
  if (snmp_set_var_objid (vp, objid, vp->name_length))
    return -1;

  len = PACKET_LENGTH;

  if (netsnmp_ds_get_boolean
      (NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_EXTENDED_INDEX))
    {
      netsnmp_ds_toggle_boolean (NETSNMP_DS_LIBRARY_ID,
                                 NETSNMP_DS_LIB_EXTENDED_INDEX);
    } /* Disable extended index format ... makes it harder to parse tokens in lex */
  if (!netsnmp_ds_get_boolean
      (NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM))
    {
      netsnmp_ds_toggle_boolean (NETSNMP_DS_LIBRARY_ID,
                                 NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM);
    } /* Enable printing numeric enums */
  if (netsnmp_ds_get_boolean
      (NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_ESCAPE_QUOTES))
    {
      netsnmp_ds_toggle_boolean (NETSNMP_DS_LIBRARY_ID,
                                 NETSNMP_DS_LIB_ESCAPE_QUOTES);
    } /* Disable escape quotes in string index output  */

  netsnmp_ds_set_int (NETSNMP_DS_LIBRARY_ID,
			      NETSNMP_DS_LIB_OID_OUTPUT_FORMAT,
			      NETSNMP_OID_OUTPUT_SUFFIX);

  if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_OID_OUTPUT_NUMERIC)) {
        netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT,
                                                  NETSNMP_OID_OUTPUT_NUMERIC);
  }

  snprint_objid (outbuf, 1023, vp->name, vp->name_length);

  if (!get_node (outbuf, var_name, &name_len))
    {
      if (!read_objid (outbuf, var_name, &name_len))
	{
	  fprintf (stderr,
		   "/* Hmm ... can't find oid %s at line %d ... perhaps the MIBs are not installed ? */\n",
		   outbuf, line);
	  /* temporarily set full output format */
	  netsnmp_ds_set_int (NETSNMP_DS_LIBRARY_ID,
			      NETSNMP_DS_LIB_OID_OUTPUT_FORMAT,
			      NETSNMP_OID_OUTPUT_FULL);
	  memset (outbuf, 0, 1024);
	  snprint_objid (outbuf, 1023, vp->name, vp->name_length);
	  /* Go back to suffix-mode for better readability */
	  netsnmp_ds_set_int (NETSNMP_DS_LIBRARY_ID,
			      NETSNMP_DS_LIB_OID_OUTPUT_FORMAT,
			      NETSNMP_OID_OUTPUT_SUFFIX);
	}
    }

  printf("%s", outbuf);

/* save the subtree - we need it later to show enums */
  subtree = get_tree (var_name, name_len, get_tree_head() );

/* This first switch is just for saving the type in the format we actually want
   to print. */

  switch ((short) vp->type)
    {
    case ASN_INTEGER:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "Integer");
      break;
    case ASN_COUNTER:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "Counter32");
      break;
    case ASN_GAUGE:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "Gauge32");
      break;
    case ASN_TIMETICKS:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "TimeTicks");
      break;
    case ASN_UINTEGER:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "Unsigned32");
      break;
#ifdef OPAQUE_SPECIAL_TYPES
    case ASN_OPAQUE_COUNTER64:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "OpaqueCounter64");
      break;
    case ASN_OPAQUE_U64:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "OpaqueU64");
      break;
#endif /* OPAQUE_SPECIAL_TYPES */
    case ASN_COUNTER64:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "Counter64");
      break;
#ifdef OPAQUE_SPECIAL_TYPES
    case ASN_OPAQUE_FLOAT:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "OpaqueFloat");
      break;
    case ASN_OPAQUE_DOUBLE:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "OpaqueDouble");
      break;
    case ASN_OPAQUE_I64:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "OpaqueI64");
      break;
#endif /* OPAQUE_SPECIAL_TYPES */
    case ASN_OCTET_STR:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "String");
      break;
    case ASN_IPADDRESS:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "IPAddress");
      break;
    case ASN_OPAQUE:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "Opaque");
      break;
    case ASN_NSAP:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "NSAP");
      break;
    case ASN_OBJECT_ID:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "ObjectID");
      break;
    case ASN_BIT_STR:
      memset (_docsis_snmp_label, 0, 50);
      sprintf (_docsis_snmp_label, "BitString");
      break;
    }

  switch ((short) vp->type)
    {
    case ASN_INTEGER:

      vp->val.integer = (long *) vp->buf;
      vp->val_len = sizeof (long);
      asn_parse_int (var_val, &len, &vp->type,
		     (long *) vp->val.integer, sizeof (vp->val.integer));

      break;
    case ASN_COUNTER:
    case ASN_GAUGE:
    case ASN_TIMETICKS:
    case ASN_UINTEGER:
      vp->val.integer = (long *) vp->buf;
      vp->val_len = sizeof (u_long);
      asn_parse_unsigned_int (var_val, &len, &vp->type,
			      (u_long *) vp->val.integer,
			      sizeof (vp->val.integer));

      break;

#ifdef OPAQUE_SPECIAL_TYPES
    case ASN_OPAQUE_COUNTER64:
    case ASN_OPAQUE_U64:
#endif /* OPAQUE_SPECIAL_TYPES */
    case ASN_COUNTER64:
      vp->val.counter64 = (struct counter64 *) vp->buf;
      vp->val_len = sizeof (struct counter64);
      asn_parse_unsigned_int64 (var_val, &len, &vp->type,
				(struct counter64 *) vp->val.counter64,
				sizeof (*vp->val.counter64));
      break;
#ifdef OPAQUE_SPECIAL_TYPES
    case ASN_OPAQUE_FLOAT:
      vp->val.floatVal = (float *) vp->buf;
      vp->val_len = sizeof (float);
      asn_parse_float (var_val, &len, &vp->type,
		       vp->val.floatVal, vp->val_len);
      break;
    case ASN_OPAQUE_DOUBLE:
      vp->val.doubleVal = (double *) vp->buf;
      vp->val_len = sizeof (double);
      asn_parse_double (var_val, &len, &vp->type,
			vp->val.doubleVal, vp->val_len);
      break;
    case ASN_OPAQUE_I64:
      vp->val.counter64 = (struct counter64 *) vp->buf;
      vp->val_len = sizeof (struct counter64);
      asn_parse_signed_int64 (var_val, &len, &vp->type,
			      (struct counter64 *) vp->val.counter64,
			      sizeof (*vp->val.counter64));

      break;
#endif /* OPAQUE_SPECIAL_TYPES */
    case ASN_OCTET_STR:
    case ASN_IPADDRESS:
    case ASN_OPAQUE:
    case ASN_NSAP:
      if (vp->val_len < sizeof (vp->buf))
	{
	  vp->val.string = (u_char *) vp->buf;
	}
      else
	{
	  vp->val.string = (u_char *) malloc ((unsigned) vp->val_len+1);
	  memset(vp->val.string, 0, vp->val_len+1);
	}
      asn_parse_string (var_val, &len, &vp->type, vp->val.string,
			&vp->val_len);
      break;
    case ASN_OBJECT_ID:
      vp->val_len = MAX_OID_LEN;
      asn_parse_objid (var_val, &len, &vp->type, objid, &vp->val_len);
      vp->val_len *= sizeof (oid);
      vp->val.objid = (oid *) malloc ((unsigned) vp->val_len);
      memmove (vp->val.objid, objid, vp->val_len);
      break;
    case SNMP_NOSUCHOBJECT:
    case SNMP_NOSUCHINSTANCE:
    case SNMP_ENDOFMIBVIEW:
    case ASN_NULL:
      break;
    case ASN_BIT_STR:
      vp->val.bitstring = (u_char *) malloc (vp->val_len);
      asn_parse_bitstring (var_val, &len, &vp->type,
			   vp->val.bitstring, &vp->val_len);
      break;
    default:
      fprintf(stderr, "Error: bad type returned (%x)\n", vp->type);
      badtype = 1;
      break;
    }

  if (!netsnmp_ds_get_boolean
      (NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_FULL_OID))
    {
      netsnmp_ds_toggle_boolean (NETSNMP_DS_LIBRARY_ID,
				 NETSNMP_DS_LIB_PRINT_FULL_OID);
    }
  if (!netsnmp_ds_get_boolean
      (NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_OIDS))
    {
      netsnmp_ds_toggle_boolean (NETSNMP_DS_LIBRARY_ID,
				 NETSNMP_DS_LIB_PRINT_NUMERIC_OIDS);
    }
  if (!netsnmp_ds_get_boolean
      (NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT))
    {
      netsnmp_ds_toggle_boolean (NETSNMP_DS_LIBRARY_ID,
				 NETSNMP_DS_LIB_QUICK_PRINT);
    }

  if (!strcmp (_docsis_snmp_label, "String"))	/* Strings need special treatment - see below  */
    {
      netsnmp_ds_toggle_boolean (NETSNMP_DS_LIBRARY_ID,
				 NETSNMP_DS_LIB_QUICK_PRINT);
      netsnmp_ds_toggle_boolean (NETSNMP_DS_LIBRARY_ID,
				 NETSNMP_DS_LIB_ESCAPE_QUOTES);
    }

  switch ((short) vp->type)
    {
    case ASN_OCTET_STR:
	if (str_isprint((char *) vp->val.string, vp->val_len))
		{
		 	snprintf(outbuf, vp->val_len+5, "\"%s\"", vp->val.string);
		} else {
			snprint_hexadecimal (outbuf, 16383, (char *) vp->val.string, vp->val_len);
      			memset (_docsis_snmp_label, 0, 50);
      			sprintf (_docsis_snmp_label, "HexString");
		}
	break;

    case ASN_BIT_STR:
		snprint_hexadecimal (outbuf, 1023, (char *) vp->val.bitstring, vp->val_len);
		break;
    case ASN_OBJECT_ID:
      		netsnmp_ds_set_int (NETSNMP_DS_LIBRARY_ID,
			  	NETSNMP_DS_LIB_OID_OUTPUT_FORMAT,
			  	NETSNMP_OID_OUTPUT_NUMERIC);
		snprint_value (outbuf, 1023, vp->name, vp->name_length, vp);
      		netsnmp_ds_set_int (NETSNMP_DS_LIBRARY_ID,
				NETSNMP_DS_LIB_OID_OUTPUT_FORMAT,
				NETSNMP_OID_OUTPUT_SUFFIX);
		break;

    default:
	snprint_value (outbuf, 1023, vp->name, vp->name_length, vp);

    }

    if ( subtree )
    {
   	enums = subtree->enums;
	   	for (; enums; enums = enums->next) {
			if (enums->value == *vp->val.integer) {
			enum_string = enums->label;
       			break;
			}
		}
    }
  if (enum_string)
	printf(" %s %s; /* %s */", _docsis_snmp_label, outbuf, enum_string);
  else
	printf(" %s %s;", _docsis_snmp_label, outbuf);


  snmp_free_var (vp);

  return badtype;
}