Example #1
0
/**
 * Find nearest vertex and/or edge and/or face, for each vertex (adapted from shrinkwrap.c).
 */
static void get_vert2geom_distance(int numVerts, float (*v_cos)[3],
                                   float *dist_v, float *dist_e, float *dist_f,
                                   DerivedMesh *target, const SpaceTransform *loc2trgt)
{
	Vert2GeomData data = {0};
	Vert2GeomDataChunk data_chunk = {{{0}}};

	BVHTreeFromMesh treeData_v = {NULL};
	BVHTreeFromMesh treeData_e = {NULL};
	BVHTreeFromMesh treeData_f = {NULL};

	if (dist_v) {
		/* Create a bvh-tree of the given target's verts. */
		bvhtree_from_mesh_verts(&treeData_v, target, 0.0, 2, 6);
		if (treeData_v.tree == NULL) {
			OUT_OF_MEMORY();
			return;
		}
	}
	if (dist_e) {
		/* Create a bvh-tree of the given target's edges. */
		bvhtree_from_mesh_edges(&treeData_e, target, 0.0, 2, 6);
		if (treeData_e.tree == NULL) {
			OUT_OF_MEMORY();
			return;
		}
	}
	if (dist_f) {
		/* Create a bvh-tree of the given target's faces. */
		bvhtree_from_mesh_looptri(&treeData_f, target, 0.0, 2, 6);
		if (treeData_f.tree == NULL) {
			OUT_OF_MEMORY();
			return;
		}
	}

	data.v_cos = v_cos;
	data.loc2trgt = loc2trgt;
	data.treeData[0] = &treeData_v;
	data.treeData[1] = &treeData_e;
	data.treeData[2] = &treeData_f;
	data.dist[0] = dist_v;
	data.dist[1] = dist_e;
	data.dist[2] = dist_f;

	BLI_task_parallel_range_ex(
	            0, numVerts, &data, &data_chunk, sizeof(data_chunk), vert2geom_task_cb, numVerts > 10000, false);

	if (dist_v)
		free_bvhtree_from_mesh(&treeData_v);
	if (dist_e)
		free_bvhtree_from_mesh(&treeData_e);
	if (dist_f)
		free_bvhtree_from_mesh(&treeData_f);
}
Example #2
0
inline void CMemoryBuffer::AllocSrcBuf( unsigned int len )
{
	SrcLen = len;
	SourceBuf = (unsigned char*) malloc(SrcLen);
	if (SourceBuf==NULL)
		OUT_OF_MEMORY();
}
Example #3
0
/* ------------------------------------------------------------------------- */
struct service_t*
service_create(struct plugin_t* plugin,
               const char* directory,
               const service_func exec,
               struct type_info_t* type_info)
{
    struct service_t* service;
    struct ptree_t* node;

    assert(plugin);
    assert(plugin->game);
    assert(directory);
    assert(exec);
    assert(type_info);

    /* allocate and initialise service object */
    if(!(service = (struct service_t*)MALLOC(sizeof(struct service_t))))
        OUT_OF_MEMORY("service_create()", NULL);
    memset(service, 0, sizeof(struct service_t));

    /* if anything fails, break */
    for(;;)
    {
        service->plugin = plugin;
        service->exec = exec;
        service->type_info = type_info;

        /* plugin object keeps track of all created services */
        if(!unordered_vector_push(&plugin->services, &service))
            break;

        /* copy directory */
        if(!(service->directory = malloc_string(directory)))
            break;

        /* create node in game's service directory - want to do this last
         * because ptree_remove_node uses malloc() */
        if(!(node = ptree_add_node(&plugin->game->services, directory, service)))
            break;

        /* NOTE: don't MALLOC() past this point ----------------------- */

        /* set the node's free function to service_free() to make deleting
         * nodes easier */
        ptree_set_free_func(node, (ptree_free_func)service_free);

        /* success! */
        return service;
    }

    /* something went wrong, clean up everything */

    /* remove from plugin's list of services */
    unordered_vector_erase_element(&plugin->services, &service);

    if(service->directory)
        free_string(service->directory);

    return NULL;
}
Example #4
0
DEFINEFN
void psyco_flog(char* msg, ...)
{
  va_list vargs;
  PyObject* s;
  PyObject* r;
  PyObject *etype, *evalue, *etb;
  extra_assert(psyco_logger != NULL);

  PyErr_Fetch(&etype, &evalue, &etb);
  
#ifdef HAVE_STDARG_PROTOTYPES
  va_start(vargs, msg);
#else
  va_start(vargs);
#endif
  s = PyString_FromFormatV(msg, vargs);
  va_end(vargs);

  if (s == NULL)
    OUT_OF_MEMORY();
  r = PyObject_CallFunction(psyco_logger, "O", s);
  if (r == NULL)
    PyErr_WriteUnraisable(psyco_logger);
  else
    Py_DECREF(r);
  Py_DECREF(s);

  PyErr_Restore(etype, evalue, etb);
}
Example #5
0
File: value.c Project: rgburke/wed
Status va_deep_copy_value(Value value, Value *new_val)
{
    if (!STR_BASED_VAL(value)) {
        *new_val = value;
        return STATUS_SUCCESS;
    }

    const char *curr_val = va_str_val(value);

    if (curr_val == NULL) {
        *new_val = value;
        return STATUS_SUCCESS;
    }

    char *str_val = strdup(curr_val);

    if (str_val == NULL) {
        return OUT_OF_MEMORY("Unable to copy value");
    }

    if (value.type == VAL_TYPE_STR) {
        *new_val = STR_VAL(str_val);
    } else if (value.type == VAL_TYPE_REGEX) {
        *new_val = REGEX_VAL(str_val, RVAL(value).modifiers);
    } else if (value.type == VAL_TYPE_SHELL_COMMAND) {
        *new_val = CMD_VAL(str_val);
    }

    return STATUS_SUCCESS;
}
Example #6
0
DEFINEFN
void vinfo_array_shrink(PsycoObject* po, vinfo_t* vi, int ncount)
{
  vinfo_array_t* array = vi->array;
  int i = array->count;
  if (i <= ncount)
    return;
  
  while (i > ncount)
    {
      vinfo_t* v1 = array->items[--i];
      if (v1 != NULL)
        {
          array->items[i] = NULL;
          vinfo_decref(v1, po);
        }
    }
  if (ncount == 0)
    array = NullArray;
  else
    {
      array = PyMem_REALLOC(array, sizeof(int) + ncount * sizeof(vinfo_t*));
      if (array == NULL)
        OUT_OF_MEMORY();
      array->count = ncount;
    }
  vi->array = array;
}
Example #7
0
Status ws_new_pattern(SyntaxPattern **syn_pattern_ptr, const Regex *regex,
                      SyntaxToken token)
{
    assert(syn_pattern_ptr != NULL);
    assert(regex != NULL);
    assert(!is_null_or_empty(regex->regex_pattern));

    SyntaxPattern *syn_pattern = malloc(sizeof(SyntaxPattern));

    if (syn_pattern == NULL) {
        return OUT_OF_MEMORY("Unable to allocate SyntaxPattern");
    }

    memset(syn_pattern, 0, sizeof(SyntaxPattern));

    Status status = ru_compile_custom_error_msg(&syn_pattern->regex, regex, 
                                                "pattern ");

    if (!STATUS_IS_SUCCESS(status)) {
        free(syn_pattern);
        return status; 
    }

    syn_pattern->token = token;
    *syn_pattern_ptr = syn_pattern;

    return STATUS_SUCCESS;
}
Example #8
0
static void set_ceval_hook(ceval_events_t* cev, int when,
			   ceval_event_fn fn, PyObject* arg)
{
	int n, i, allow;
	struct cevents_s* events;
	extra_assert(0 <= when && when < PyTrace_TOTAL);
	events = cev->events + when;
	n = events->count++;
	PyMem_RESIZE(events->items, struct cevent_s, events->count);
	if (events->items == NULL)
		OUT_OF_MEMORY();
	events->items[n].fn = fn;
	events->items[n].arg = arg;
	cev->events_total++;
	if (arg != NULL) {
		/* bound the total number of hooks by checking if there are
		   too many other hooks with the same 'fn' */
		allow = 8;
		for (i=n; --i >= 0; ) {
			if (events->items[i].fn == fn && !--allow) {
				/* too many! remove an arbitrary one */
				events->items[i].fn = &deleted_ceval_hook;
				cev->events_total--;
				break;
			}
		}
	}
}
Example #9
0
inline void CMemoryBuffer::AllocTgtBuf( unsigned int len )
{
	TgtLen = len;
	TargetBuf = (unsigned char*) malloc(len+6);
	if (TargetBuf==NULL)
		OUT_OF_MEMORY();
	TargetBuf += 3;
}
Example #10
0
DEFINEFN
void psyco_stats_reset(void)
{
	/* reset all stats */
	int i = 0;
	PyObject *key, *value, *d;
	stats_printf(("stats: reset\n"));

	/* reset the charge of all PyCodeStats, keep only the used ones */
        RECLIMIT_SAFE_ENTER();
	d = PyDict_New();
	if (d == NULL)
		OUT_OF_MEMORY();
	while (PyDict_Next(codestats_dict, &i, &key, &value)) {
		PyCodeStats* cs = (PyCodeStats*) key;
		if (cs->st_mergepoints) {
			/* clear the charge and keep alive */
			cs->st_charge = 0.0f;
			if (PyDict_SetItem(d, key, value))
				OUT_OF_MEMORY();
		}
	}
        RECLIMIT_SAFE_LEAVE();
	Py_DECREF(codestats_dict);
	codestats_dict = d;
	charge_total = 0.0;
	charge_prelimit = 0.0f;

	/* reset the time measure in all threads */
	{
#if MEASURE_ALL_THREADS
		PyInterpreterState* istate = PyThreadState_Get()->interp;
		PyThreadState* tstate;
		for (tstate=istate->tstate_head; tstate; tstate=tstate->next) {
			(void) get_measure(tstate);
		}
#else
		(void) get_measure(NULL);
#endif
	}
}
Example #11
0
DEFINEFN
void psyco_turbo_code(PyCodeObject* code, int recursion)
{
	PyCodeStats* cs = PyCodeStats_Get(code);
	if (cs->st_codebuf == NULL && cs->st_globals == NULL) {
		/* trigger compilation at the next occasion
		   by storing something non-NULL in st_globals */
		cs->st_globals = PyInt_FromLong(recursion);
		if (cs->st_globals == NULL)
			OUT_OF_MEMORY();
        }
}
Example #12
0
MIKTEXINTERNALFUNC(bool) ReportMiKTeXEvent(unsigned short eventType, unsigned long eventId, ...)
{
#if ! REPORT_EVENTS
  UNUSED_ALWAYS(eventType);
  UNUSED_ALWAYS(eventId);
  return false;
#else
  vector<const char *> vecStrings;
  va_list marker;
  va_start(marker, eventId);
  for (const char * lpsz = va_arg(marker, const char *);
  lpsz != nullptr;
    lpsz = va_arg(marker, const char *))
  {
    vecStrings.push_back(lpsz);
  }
  va_end(marker);

  HANDLE hEventSource = RegisterEventSource(0, SOURCE);
  if (hEventSource == nullptr)
  {
    return false;
  }

  PSID pSid = 0;
  size_t bufSize = 8192;
  AutoMemoryPointer pBuf(malloc(bufSize));
  if (pBuf.Get() == nullptr)
  {
    OUT_OF_MEMORY("malloc");
  }
  char szAccountName[BufferSizes::MaxPath];
  unsigned long n = BufferSizes::MaxPath;
  if (GetUserName(szAccountName, &n))
  {
    unsigned long sidSize = static_cast<unsigned long>(bufSize);
    pSid = reinterpret_cast<PSID>(pBuf.Get());
    char szDomainName[BufferSizes::MaxPath];
    unsigned long domainNameSize = BufferSizes::MaxPath;
    SID_NAME_USE use;
    if (!LookupAccountName(0, szAccountName, pSid, &sidSize, szDomainName, &domainNameSize, &use))
    {
      pSid = 0;
    }
  }
  BOOL done =
    ReportEvent(hEventSource, eventType, 0, eventId, pSid, static_cast<unsigned short>(vecStrings.size()), 0, &vecStrings[0], 0);
  DeregisterEventSource(hEventSource);

  return done ? true : false;
#endif
}
Example #13
0
/* ------------------------------------------------------------------------- */
struct event_t*
event_create(struct plugin_t* plugin,
             const char* directory,
             struct type_info_t* type_info)
{
    struct ptree_t* node;
    struct event_t* event;

    assert(plugin);
    assert(plugin->game);
    assert(directory);

    /* allocate and initialise event object */
    if(!(event = (struct event_t*)MALLOC(sizeof(struct event_t))))
        OUT_OF_MEMORY("event_create()", NULL);
    memset(event, 0, sizeof(struct event_t));

    for(;;)
    {
        event->plugin = plugin;
        event->type_info = type_info;
        unordered_vector_init_vector(&event->listeners, sizeof(struct event_listener_t));

        /* copy directory */
        if(!(event->directory = malloc_string(directory)))
            break;

        /* plugin object keeps track of all created events */
        if(!unordered_vector_push(&plugin->events, &event))
            break;

        /* create node in game's event directory and add event - do this last
         * because ptree_remove_node() uses malloc() */
        if(!(node = ptree_add_node(&plugin->game->events, directory, event)))
            break;

        /* NOTE: don't MALLOC() past this point ----------------------- */

        /* set the node's free function to event_free() to make deleting
         * nodes easier */
        ptree_set_free_func(node, (ptree_free_func)event_free);

        /* success! */
        return event;
    }

    /* something went wrong, clean up */
    if(event->directory)
        free_string(event->directory);

    return NULL;
}
Example #14
0
void CContainers::writeMemBuffers(int preprocFlag, int PPMDlib_order, int comprLevel, Encoder* PAQ_encoder, unsigned char* zlibBuffer,COutFileStream* outStream)
{
	std::map<std::string,CMemoryBuffer*>::iterator it;

	int fileLen=0;
	int len=0;
	int lenCompr=0;
	int allocated=0;

#ifdef USE_LZMA_LIBRARY
	if (IF_OPTION(OPTION_LZMA))
	{
		Byte **Data;
		size_t* Size;
		int count;
		
		count=(int)memmap.size();
		Size=new size_t[count];
		Data=(unsigned char**) malloc(sizeof(unsigned char*)*count);
		if (Data==NULL)
			OUT_OF_MEMORY();
	
		int i=0;
		for (it=memmap.begin(); it!=memmap.end(); it++)
		{
			CMemoryBuffer* b=it->second;
			fileLen=b->Size();
			
			if (fileLen>0)
			{
				Size[i]=fileLen;
				Data[i]=b->TargetBuf;
				i++;
				
				PUTC((int)it->first.size());
				for (int i=0; i<(int)it->first.size(); i++)
					PUTC(it->first[i]);
				
				PUTC(fileLen>>24);
				PUTC(fileLen>>16);
				PUTC(fileLen>>8);
				PUTC(fileLen);	
			}
		}
		
		PUTC(0);
		
		count=i;
		int last=LZMAlib_GetOutputFilePos(outStream);
		LZMAlib_EncodeSolidMemToFile(Data,Size,count,outStream);
		printStatus(0,LZMAlib_GetOutputFilePos(outStream)-last,true);
	}
Example #15
0
inline void CMemoryBuffer::ReallocTgtBuf(unsigned int len)
{
	unsigned char* NewTargetBuf = (unsigned char*) malloc(len+6);

	if (NewTargetBuf==NULL)
		OUT_OF_MEMORY();

	NewTargetBuf += 3;
	memcpy(NewTargetBuf,TargetBuf,min(TgtPtr,len));
	TgtLen = len;
	delete(TargetBuf-3);
	TargetBuf=NewTargetBuf;
}
Example #16
0
static ceval_events_t* new_cevents(PyThreadState* tstate)
{
	ceval_events_t* cev;
	PyObject* dict = tstate->dict;

        RECLIMIT_SAFE_ENTER();
	if (dict == NULL) {
		dict = tstate->dict = PyDict_New();
		if (dict == NULL)
			OUT_OF_MEMORY();
	}
	cev = PyCStruct_NEW(ceval_events_t, ceval_events_dealloc);
	/*cev->lock = PyThread_allocate_lock();*/
	memset(cev->events, 0, sizeof(cev->events));
	cev->tstate = tstate;
	cev->events_total = 0;
	cev->current_hook = 0;
	if (PyDict_SetItem(dict, ceval_events_key, (PyObject*) cev))
		OUT_OF_MEMORY();
        RECLIMIT_SAFE_LEAVE();
	Py_DECREF(cev);  /* one ref left in dict */
	return cev;
}
Example #17
0
DEFINEFN
vinfo_array_t* array_grow1(vinfo_array_t* array, int ncount)
{
  int i = array->count;
  extra_assert(ncount > i);
  if (i == 0)
    array = PyMem_MALLOC(sizeof(int) + ncount * sizeof(vinfo_t*));
  else
    array = PyMem_REALLOC(array, sizeof(int) + ncount * sizeof(vinfo_t*));
  if (array == NULL)
    OUT_OF_MEMORY();
  array->count = ncount;
  while (i<ncount)
    array->items[i++] = NULL;
  return array;
}
Example #18
0
static Status pc_complete_buffer(const Session *sess, List *suggestions,
                                 const char *str, size_t str_len)
{
    const Buffer *buffer = sess->buffers;
    const char *buffer_path;
    PromptSuggestion *suggestion;
    SuggestionRank rank;

    while (buffer != NULL) {
        rank = SR_NO_MATCH;

        if (fi_has_file_path(&buffer->file_info)) {
            buffer_path = buffer->file_info.rel_path;
        } else {
            buffer_path = buffer->file_info.file_name;
        }

        if (strcmp(buffer_path, str) == 0) {
            rank = SR_EXACT_MATCH;
        } else if (strncmp(buffer_path, str, str_len) == 0) {
            rank = SR_STARTS_WITH;
        } else if (strstr(buffer_path, str) != NULL) {
            rank = SR_CONTAINS;
        }

        if (rank != SR_NO_MATCH) {
            suggestion = pc_new_suggestion(buffer_path, rank, buffer);
            
            if (suggestion == NULL || !list_add(suggestions, suggestion)) {
                free(suggestion);
                return OUT_OF_MEMORY("Unable to allocated suggested buffer");
            }
        }

        buffer = buffer->next;
    }

    return STATUS_SUCCESS;
}
Example #19
0
DEFINEFN
PyCodeStats* PyCodeStats_Get(PyCodeObject* co)
{
	PyCodeStats* cs;
	RECLIMIT_SAFE_ENTER();
	cs = (PyCodeStats*) PyCStruct_DictGet(codestats_dict, (PyObject*) co);
	if (cs == NULL) {
		cs = PyCStruct_NEW(PyCodeStats, PyCodeStats_dealloc);

		Py_INCREF(co);
		cs->cs_key = (PyObject*) co;
		cs->st_charge = 0.0f;
		cs->st_mergepoints = NULL;
                cs->st_codebuf = NULL;
                cs->st_globals = NULL;

		if (PyDict_SetItem(codestats_dict, (PyObject*) cs,
				   (PyObject*) cs) < 0)
			OUT_OF_MEMORY();
		Py_DECREF(cs);  /* two references left in codestats_dict */
	}
	RECLIMIT_SAFE_LEAVE();
	return cs;
}
Example #20
0
bool
SessionImpl::TryCreateFile (/*[in]*/ const char * lpszFileName,
                                     /*[in]*/ FileType	  fileType)
{
    CommandLineBuilder commandLine;
    PathName makeUtility;
    char szBasename[BufferSizes::MaxPath];
    PathName::Split (lpszFileName, 0, 0, szBasename, BufferSizes::MaxPath, 0, 0);
    switch (fileType.Get())
    {
    case FileType::BASE:
    case FileType::FMT:
        if (! FindFile(MIKTEX_INITEXMF_EXE, FileType::EXE, makeUtility))
        {
            FATAL_MIKTEX_ERROR ("SessionImpl::TryCreateFile",
                                T_("The MiKTeX configuration utility could not be found."),
                                0);
        }
        commandLine.AppendOption ("--dump-by-name=", szBasename);
        if (fileType == FileType::FMT)
        {
            commandLine.AppendOption ("--engine=", GetEngine());
        }
        break;
    case FileType::TFM:
        if (! FindFile(MIKTEX_MAKETFM_EXE, FileType::EXE, makeUtility))
        {
            FATAL_MIKTEX_ERROR ("SessionImpl::TryCreateFile",
                                T_("The MakeTFM utility could not be found."),
                                0);
        }
        commandLine.AppendOption ("-v");
        commandLine.AppendArgument (szBasename);
        break;
    default:
        return (false);
    }
    const size_t BUF_SIZE = 50000;
    char * szBuf = reinterpret_cast<char*>(malloc(BUF_SIZE));
    if (szBuf == 0)
    {
        OUT_OF_MEMORY ("malloc");
    }
    AutoMemoryPointer xxx (szBuf);
    size_t size = BUF_SIZE;
    int exitCode;
    if (! Process::Run(makeUtility,
                       commandLine.Get(),
                       szBuf,
                       &size,
                       &exitCode))
    {
        return (false);
    }
    if (exitCode != 0)
    {
        TraceError (T_("Make failed; output follows"));
        TraceError ("%.*s", static_cast<int>(size), szBuf);
        return (false);
    }
    return (true);
}
Example #21
0
/*----------------------------------------------------------------
 * Extract a random subgraph from a graph 'g' with a given
 * number of nodes ('nodes'). If 'connected' is true, the 
 * subgraph will be connected. Attributes of the subgraph are
 * shared with the original graph.
 * The subgraph will not inherit the node/edge destroy functions
 * nor the node/edge compatibility predicates.
 * 
 * IMPORTANT
 *   You have to init the random seed by calling srand() before
 *   invoking this function.
 ----------------------------------------------------------------*/
Graph* ExtractSubgraph(Graph *g, int nodes, bool connected)
  { assert(g!=NULL);
    assert(nodes>=0); 
    assert(nodes<=g->NodeCount());

    int i,j;
    int n=g->NodeCount();

    node_id *map=(node_id*)calloc(n, sizeof(node_id));
    if (n>0 && map==NULL)
      OUT_OF_MEMORY();
    for(i=0; i<n; i++)
      map[i]=NULL_NODE;


    ARGEdit ed;

    visit_param param;

    for(i=0; i<nodes; i++)
      { // Choose a node which has not yet been used
        node_id id=irand(0, n-1);
	node_id id0=id;
        
	bool found=false;
        
	do {
	  while (map[id]!=NULL_NODE) 
	    { if (++id == n)
	        id=0;
              if (id==id0)
	        { if (i==0 || !connected)
		    CANT_HAPPEN();
		  else
		    FAIL("Cannot extract a connected subgraph");
		}
       	    }

	  // check for the connectedness of the new node
          if (i>0 && connected)
	    { 
	      for(j=0; j<g->OutEdgeCount(id) && !found; j++)
	        { if (map[g->GetOutEdge(id, j)]!=NULL_NODE)
		    found=true;
		}
	      for(j=0; j<g->InEdgeCount(id) && !found; j++)
	        { if (map[g->GetInEdge(id, j)]!=NULL_NODE)
		    found=true;
		}
	      if (!found)
	        { if (++id == n)
	            id=0;
                  if (id==id0)
	            FAIL("Cannot extract a connected subgraph");
		}
	    }
	  else
	    { found=true;
	    }
	} while (!found); 


	// now add the node to the ARGEdit

	map[id]=i;

	ed.InsertNode(g->GetNodeAttr(id));
      }

    // Now add the edges to the new graph
    param.ed=&ed;
    param.map=map;
    for(i=0; i<n; i++)
      { if (map[i]!=NULL_NODE)
	  g->VisitOutEdges(i, edge_insert_visitor, &param);
      }


    // Construct the graph and return it

    Graph *sub=new Graph(&ed);

    return sub;
  }
/**
 * Find nearest vertex and/or edge and/or face, for each vertex (adapted from shrinkwrap.c).
 */
static void get_vert2geom_distance(int numVerts, float (*v_cos)[3],
                                   float *dist_v, float *dist_e, float *dist_f,
                                   DerivedMesh *target, const SpaceTransform *loc2trgt)
{
	int i;
	BVHTreeFromMesh treeData_v = NULL_BVHTreeFromMesh;
	BVHTreeFromMesh treeData_e = NULL_BVHTreeFromMesh;
	BVHTreeFromMesh treeData_f = NULL_BVHTreeFromMesh;
	BVHTreeNearest nearest_v   = NULL_BVHTreeNearest;
	BVHTreeNearest nearest_e   = NULL_BVHTreeNearest;
	BVHTreeNearest nearest_f   = NULL_BVHTreeNearest;

	if (dist_v) {
		/* Create a bvh-tree of the given target's verts. */
		bvhtree_from_mesh_verts(&treeData_v, target, 0.0, 2, 6);
		if (treeData_v.tree == NULL) {
			OUT_OF_MEMORY();
			return;
		}
	}
	if (dist_e) {
		/* Create a bvh-tree of the given target's edges. */
		bvhtree_from_mesh_edges(&treeData_e, target, 0.0, 2, 6);
		if (treeData_e.tree == NULL) {
			OUT_OF_MEMORY();
			return;
		}
	}
	if (dist_f) {
		/* Create a bvh-tree of the given target's faces. */
		bvhtree_from_mesh_faces(&treeData_f, target, 0.0, 2, 6);
		if (treeData_f.tree == NULL) {
			OUT_OF_MEMORY();
			return;
		}
	}

	/* Setup nearest. */
	nearest_v.index = nearest_e.index = nearest_f.index = -1;
	/*nearest_v.dist  = nearest_e.dist  = nearest_f.dist  = FLT_MAX;*/
	/* Find the nearest vert/edge/face. */
#ifndef __APPLE__
#pragma omp parallel for default(none) private(i) firstprivate(nearest_v,nearest_e,nearest_f) \
                         shared(treeData_v,treeData_e,treeData_f,numVerts,v_cos,dist_v,dist_e, \
                                dist_f,loc2trgt) \
                         schedule(static)
#endif
	for (i = 0; i < numVerts; i++) {
		float tmp_co[3];

		/* Convert the vertex to tree coordinates. */
		copy_v3_v3(tmp_co, v_cos[i]);
		space_transform_apply(loc2trgt, tmp_co);

		/* Use local proximity heuristics (to reduce the nearest search).
		 *
		 * If we already had an hit before, we assume this vertex is going to have a close hit to
		 * that other vertex, so we can initiate the "nearest.dist" with the expected value to that
		 * last hit.
		 * This will lead in prunning of the search tree.
		 */
		if (dist_v) {
			nearest_v.dist = nearest_v.index != -1 ? len_squared_v3v3(tmp_co, nearest_v.co) : FLT_MAX;
			/* Compute and store result. If invalid (-1 idx), keep FLT_MAX dist. */
			BLI_bvhtree_find_nearest(treeData_v.tree, tmp_co, &nearest_v, treeData_v.nearest_callback, &treeData_v);
			dist_v[i] = sqrtf(nearest_v.dist);
		}
		if (dist_e) {
			nearest_e.dist = nearest_e.index != -1 ? len_squared_v3v3(tmp_co, nearest_e.co) : FLT_MAX;
			/* Compute and store result. If invalid (-1 idx), keep FLT_MAX dist. */
			BLI_bvhtree_find_nearest(treeData_e.tree, tmp_co, &nearest_e, treeData_e.nearest_callback, &treeData_e);
			dist_e[i] = sqrtf(nearest_e.dist);
		}
		if (dist_f) {
			nearest_f.dist = nearest_f.index != -1 ? len_squared_v3v3(tmp_co, nearest_f.co) : FLT_MAX;
			/* Compute and store result. If invalid (-1 idx), keep FLT_MAX dist. */
			BLI_bvhtree_find_nearest(treeData_f.tree, tmp_co, &nearest_f, treeData_f.nearest_callback, &treeData_f);
			dist_f[i] = sqrtf(nearest_f.dist);
		}
	}

	if (dist_v)
		free_bvhtree_from_mesh(&treeData_v);
	if (dist_e)
		free_bvhtree_from_mesh(&treeData_e);
	if (dist_f)
		free_bvhtree_from_mesh(&treeData_f);
}
Example #23
0
/* Interface to run prompt completion */
Status pc_run_prompt_completer(const Session *sess, Prompt *prompt, int reverse)
{
    PromptType prompt_type = prompt->prompt_type;

    if (!pc_has_prompt_completer(prompt_type)) {
        return STATUS_SUCCESS;
    } 

    pr_clear_suggestions(prompt);

    char *prompt_content = pr_get_prompt_content(prompt);
    size_t prompt_content_len = strlen(prompt_content);

    if (prompt_content_len == 0) {
        free(prompt_content);
        return STATUS_SUCCESS;
    }

    const PromptCompleterConfig *pcc = &pc_prompt_completers[prompt_type];
    PromptCompleter completer = pcc->prompt_completer;
    Status status = completer(sess, prompt->suggestions, prompt_content,
                              prompt_content_len);

    if (!STATUS_IS_SUCCESS(status) || pr_suggestion_num(prompt) == 0) {
        free(prompt_content);
        return status;
    }

    list_sort(prompt->suggestions, pc_suggestion_comparator);
    
    /* Add the inital input from the user to the list of suggestions
     * so that it can be cycled back to when all the suggestions have
     * been displayed */
    PromptSuggestion *inital_input = pc_new_suggestion(prompt_content,
                                                       SR_NO_MATCH, NULL);
    free(prompt_content);

    if (inital_input == NULL ||
        !list_add(prompt->suggestions, inital_input)) {
        free(inital_input);
        return OUT_OF_MEMORY("Unable to allocated suggestions");
    }

    /* At this point there should be at least one suggestion plus
     * the inital input */
    assert(pr_suggestion_num(prompt) > 1);

    size_t start_index = 0;

    /* <S-Tab> can be used to reverse through the suggestions and
     * invoke prompt completion in reverse, so start from end of suggestion
     * list if necessary */
    if (reverse) {
        start_index = pr_suggestion_num(prompt) - 2;
    }

    /* Update prompt content with first suggestion */
    status = pr_show_suggestion(prompt, start_index);

    return status;
}
Example #24
0
static Status pc_complete_path(const Session *sess, List *suggestions,
                               const char *str, size_t str_len)
{
    (void)sess;

    /* When only ~ is provided expand it to users home directory */
    if (strcmp("~", str) == 0) {
        str = getenv("HOME"); 
        str_len = strlen(str); 
    }

    /* Create copies that we can modify */
    char *path1 = strdup(str); 
    char *path2 = strdup(str);

    if (path1 == NULL || path2 == NULL) {
        free(path1);
        free(path2);
        return OUT_OF_MEMORY("Unable to allocate memory for path");
    }

    Status status = STATUS_SUCCESS;

    /* Split into containing directory and file name */
    const char *dir_path;
    const char *file_name;
    size_t file_name_len;
    /* Need to take special care with root directory */
    int is_root_only = (strcmp("/", path1) == 0);

    if (!is_root_only &&
        path1[str_len - 1] == '/') {
        /* Path is a directory only so set file name
         * part to NULL to match all files in directory */
        path1[str_len - 1] = '\0';
        dir_path = path1;
        free(path2);
        path2 = NULL;
        file_name = NULL;
        file_name_len = 0;
    } else {
        dir_path = dirname(path1);
        
        if (is_root_only) {
            file_name = NULL;
            file_name_len = 0;
        } else {
            file_name = basename(path2);
            file_name_len = strlen(file_name);
        }
    }

    int home_dir_path = (dir_path[0] == '~');
    const char *canon_dir_path;
    DIR *dir = NULL;

    if (home_dir_path) {
        /* Expand ~ to users home directory so we can read the 
         * directory entries. Any suggestions provided to user 
         * will still start with ~ */
        const char *home_path = getenv("HOME"); 
        canon_dir_path = concat(home_path, dir_path + 1);

        if (canon_dir_path == NULL) {
            status = OUT_OF_MEMORY("Unable to allocated path");
            goto cleanup;
        }
    } else {
        canon_dir_path = dir_path;
    }

    dir = opendir(canon_dir_path);

    if (home_dir_path) {
        free((char *)canon_dir_path);
    }

    if (dir == NULL) {
        goto cleanup;
    }
    
    if (strcmp(dir_path, "/") == 0) {
        dir_path = "";
    }

    struct dirent *dir_ent;
    PromptSuggestion *suggestion;
    SuggestionRank rank;
    size_t dir_ent_num = 0;
    errno = 0;

    while (dir_ent_num++ < MAX_DIR_ENT_NUM &&
           (dir_ent = readdir(dir)) != NULL) {
        if (errno) {
            status = st_get_error(ERR_UNABLE_TO_READ_DIRECTORY,
                                  "Unable to read from directory - %s",
                                  strerror(errno));
            goto cleanup;
        }

        if (strcmp(".", dir_ent->d_name) == 0 ||
            strcmp("..", dir_ent->d_name) == 0) {
            continue;
        }

        rank = SR_NO_MATCH;

        if (file_name == NULL) {
            rank = SR_DEFAULT_MATCH;            
        } else if (strcmp(file_name, dir_ent->d_name) == 0) {
            rank = SR_EXACT_MATCH;
        } else if (strncmp(file_name, dir_ent->d_name, file_name_len) == 0) {
            rank = SR_STARTS_WITH; 
        } else if (strstr(file_name, dir_ent->d_name) != NULL) {
            rank = SR_CONTAINS;
        }

        if (rank != SR_NO_MATCH) {
            char *suggestion_path;

            if (dir_ent->d_type == DT_DIR) {
                suggestion_path = concat_all(4, dir_path, "/",
                                             dir_ent->d_name,"/");
            } else {
                suggestion_path = concat_all(3, dir_path, "/",
                                             dir_ent->d_name);
            }

            if (suggestion_path == NULL) {
                status = OUT_OF_MEMORY("Unable to allocated suggested path");
                goto cleanup;
            }

            suggestion = pc_new_suggestion(suggestion_path, rank, NULL);

            free(suggestion_path);
            
            if (suggestion == NULL || !list_add(suggestions, suggestion)) {
                free(suggestion);
                status = OUT_OF_MEMORY("Unable to allocated suggested buffer");
                goto cleanup;
            }
        }
    }

cleanup:
    if (dir != NULL) {
        closedir(dir);
    }

    free(path1);
    free(path2);

    return status;
}
Example #25
0
/*
 * Shrinkwrap moving vertexs to the nearest surface point on the target
 *
 * it builds a BVHTree from the target mesh and then performs a
 * NN matches for each vertex
 */
static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
{
	int i;

	BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
	BVHTreeNearest nearest  = NULL_BVHTreeNearest;

	/* Create a bvh-tree of the given target */
	bvhtree_from_mesh_faces(&treeData, calc->target, 0.0, 2, 6);
	if (treeData.tree == NULL) {
		OUT_OF_MEMORY();
		return;
	}

	/* Setup nearest */
	nearest.index = -1;
	nearest.dist_sq = FLT_MAX;


	/* Find the nearest vertex */
#ifndef __APPLE__
#pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(calc, treeData) schedule(static)
#endif
	for (i = 0; i < calc->numVerts; ++i) {
		float *co = calc->vertexCos[i];
		float tmp_co[3];
		float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
		if (weight == 0.0f) continue;

		/* Convert the vertex to tree coordinates */
		if (calc->vert) {
			copy_v3_v3(tmp_co, calc->vert[i].co);
		}
		else {
			copy_v3_v3(tmp_co, co);
		}
		space_transform_apply(&calc->local2target, tmp_co);

		/* Use local proximity heuristics (to reduce the nearest search)
		 *
		 * If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
		 * so we can initiate the "nearest.dist" with the expected value to that last hit.
		 * This will lead in pruning of the search tree. */
		if (nearest.index != -1)
			nearest.dist_sq = len_squared_v3v3(tmp_co, nearest.co);
		else
			nearest.dist_sq = FLT_MAX;

		BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);

		/* Found the nearest vertex */
		if (nearest.index != -1) {
			if (calc->smd->shrinkOpts & MOD_SHRINKWRAP_KEEP_ABOVE_SURFACE) {
				/* Make the vertex stay on the front side of the face */
				madd_v3_v3v3fl(tmp_co, nearest.co, nearest.no, calc->keepDist);
			}
			else {
				/* Adjusting the vertex weight,
				 * so that after interpolating it keeps a certain distance from the nearest position */
				const float dist = sasqrt(nearest.dist_sq);
				if (dist > FLT_EPSILON) {
					/* linear interpolation */
					interp_v3_v3v3(tmp_co, tmp_co, nearest.co, (dist - calc->keepDist) / dist);
				}
				else {
					copy_v3_v3(tmp_co, nearest.co);
				}
			}

			/* Convert the coordinates back to mesh coordinates */
			space_transform_invert(&calc->local2target, tmp_co);
			interp_v3_v3v3(co, co, tmp_co, weight);  /* linear interpolation */
		}
	}

	free_bvhtree_from_mesh(&treeData);
}
Example #26
0
/*
 * Shrinkwrap to the nearest vertex
 *
 * it builds a kdtree of vertexs we can attach to and then
 * for each vertex performs a nearest vertex search on the tree
 */
static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
{
	int i;

	BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
	BVHTreeNearest  nearest  = NULL_BVHTreeNearest;


	BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6));
	if (treeData.tree == NULL) {
		OUT_OF_MEMORY();
		return;
	}

	//Setup nearest
	nearest.index = -1;
	nearest.dist = FLT_MAX;
#ifndef __APPLE__
#pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(treeData,calc) schedule(static)
#endif
	for (i = 0; i<calc->numVerts; ++i) {
		float *co = calc->vertexCos[i];
		float tmp_co[3];
		float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
		if (weight == 0.0f) continue;


		//Convert the vertex to tree coordinates
		if (calc->vert) {
			copy_v3_v3(tmp_co, calc->vert[i].co);
		}
		else {
			copy_v3_v3(tmp_co, co);
		}
		space_transform_apply(&calc->local2target, tmp_co);

		//Use local proximity heuristics (to reduce the nearest search)
		//
		//If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
		//so we can initiate the "nearest.dist" with the expected value to that last hit.
		//This will lead in prunning of the search tree.
		if (nearest.index != -1)
			nearest.dist = len_squared_v3v3(tmp_co, nearest.co);
		else
			nearest.dist = FLT_MAX;

		BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);


		//Found the nearest vertex
		if (nearest.index != -1) {
			//Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
			float dist = sasqrt(nearest.dist);
			if (dist > FLT_EPSILON) weight *= (dist - calc->keepDist)/dist;

			//Convert the coordinates back to mesh coordinates
			copy_v3_v3(tmp_co, nearest.co);
			space_transform_invert(&calc->local2target, tmp_co);

			interp_v3_v3v3(co, co, tmp_co, weight);	//linear interpolation
		}
	}

	free_bvhtree_from_mesh(&treeData);
}