示例#1
0
n_file * tranfer_out_json(void)
{
    n_file *output_file = 0L;
    noble_simulation *local_sim = sim_sim();
    
    n_object * simulation_object = obj_object(0L, "information", transfer_sim_obj());
    
    obj_object(simulation_object, "land", transfer_land_obj());
    
    if (local_sim->num > 0)
    {
        n_uint        count = 1;
        noble_being *local_beings = local_sim->beings;
        n_object    *being_object = transfer_being_obj(&(local_beings[0]));
        n_array     *beings = array_object(being_object);
        while (count < local_sim->num)
        {
            being_object = transfer_being_obj(&(local_beings[count++]));
            array_add(beings, array_object(being_object));
        }
        obj_array(simulation_object, "beings", beings);
    }
    
    output_file = obj_json(simulation_object);
    
    obj_free((n_array **) &simulation_object);
    
    return output_file;
}
示例#2
0
static void testErrorMessage(CuTest* tc, const char *expected, const char *tlv_file,
		int (*obj_new)(KSI_CTX *ctx, void **),
		void (*obj_free)(void*),
		const KSI_TlvTemplate *tmplete) {
	int res;
	void *obj = NULL;
	char buf[1024];
	size_t len;
	FILE *f = NULL;
	KSI_FTLV ftlv;

	KSI_ERR_clearErrors(ctx);

	f = fopen(getFullResourcePath(tlv_file), "rb");
	CuAssert(tc, "Failed to open file.", f != NULL);

	res = KSI_FTLV_fileRead(f, (unsigned char *)buf, sizeof(buf), &len, &ftlv);
	CuAssert(tc, "Failed read from file.", res == KSI_OK);

	res = obj_new(ctx, &obj);
	CuAssert(tc, "Unable create new obj.", res == KSI_OK);

	res = KSI_TlvTemplate_parse(ctx, (unsigned char *)buf, (unsigned)len, tmplete, obj);
	CuAssert(tc, "Parsing invalid obj must fail.", res != KSI_OK);

	res = KSI_ERR_getBaseErrorMessage(ctx, buf, sizeof(buf), NULL, NULL);
	CuAssert(tc, "Unable to get base error message.", res == KSI_OK);

	CuAssert(tc, "Wrong error message.", strcmp(buf, expected) == 0);

	if (f != NULL) fclose(f);
	obj_free(obj);
}
示例#3
0
void gc_sweep()
{
	unsigned long heap_n;
	RVALUE *ptr, *ptr_end;
	int n = 0;
	
	for( heap_n = 0; heap_n < rabbit_heaps_used; ++heap_n ) {
		ptr     = rabbit_heaps[ heap_n ];
		ptr_end = ptr + RABBIT_HEAP_SLOT_LEN;
		
		while( ptr < ptr_end ) {
			if( !(ptr->as.free.flags & FLAG_GC_MARK) ) {
				if( ptr->as.free.flags ) {
					obj_free( (VALUE)ptr );
					ptr->as.free.flags = 0;
					ptr->as.free.next  = free_list;
					free_list = ptr;
					++n;
				}
			} else {
				ptr->as.free.flags &= ~FLAG_GC_MARK;
			}
			ptr++;
		}
	}

	if( free_len() < RABBIT_HEAP_FREE_MIN ) {
		rabbit_heap_stretch();
	}
}
示例#4
0
static int __init init( void ) {
   int i;
   long tst = 0, sum = 0;
   if( mode != 0 && mode != 1 ) {
      printk( KERN_ERR "illegal mode value\n" );
      return -EINVAL;
   }
   if( !( line = kmalloc( sizeof(void*) * number, GFP_KERNEL ) ) ) {
      printk( KERN_ERR "kmalloc error\n" );
      goto mout;
   }
   for( i = 0; i < number; i++ ) line[ i ] = NULL; 
   if( !( pool = pool_create() ) ) {
      printk( KERN_ERR "pool create error\n" );
      goto pout;
   };
   printk( KERN_INFO "pool created\n" );
   printk( KERN_INFO "%d objects in pool before allocation\n", pool->curr_nr );
   for( i = 0; i < number; i++ ) {
      cycles_t t1, t2;
      schedule();   
      t1 = get_cycles();
      if( !( line[ i ] = obj_alloc() ) ) {
         printk( KERN_ERR "object allocation error\n" );
         goto oout;
      }
      t2 = get_cycles();
      sum += ( t2 - t1 ); 
   }
   sum /= number;
   for( i = 0; i < number; i++ ) tst += ( obj_test( line[ i ], i ) ? 1 : 0 );
   printk( KERN_INFO "%d objects in pool after allocation\n", pool->curr_nr );
   printk( KERN_INFO "allocate %ld objects (size %ld) in %ld cycles\n", number, size, sum );
   printk( KERN_INFO "tested OK objects: %ld\n", tst );
   for( i = 0; i < number; i++ ) obj_free( line[ i ] ); 
   pool_destroy();
   printk( KERN_INFO "pool destroyed\n" );
   kfree( line );
   return -1; //0;
oout:
   for( i = 0; i < number; i++ ) obj_free( line[ i ] ); 
pout:
   pool_destroy();
mout:
   kfree( line );
   return -ENOMEM;
}
示例#5
0
文件: obj.c 项目: mattjakob/s3d
void obj_list_free(Object *ol)
{
  Object *t, *o = ol;
  while (o != NULL) {
    t = o; o = o->next;
    obj_free(t);
  }
}
示例#6
0
文件: Entity.c 项目: Mulambev/Midterm
void entity_free(Entity *ent)
{
    if (!ent)
    {
        slog("passed a null entity");
        return;
    }
    ent[0].inuse = 0;
    obj_free(ent->objModel);
    FreeSprite(ent->texture);
}
示例#7
0
void obj_free(n_array ** array)
{
    if (*array)
    {
        n_array * next = (n_array *)((*array)->next);
        if (next)
        {
            obj_free(&next);
        }
        object_primitive_free(array);
    }
}
示例#8
0
文件: gc.c 项目: AndreOF/ArangoDB
static size_t
incremental_sweep_phase(mrb_state *mrb, size_t limit)
{
  struct heap_page *page = mrb->sweeps;
  size_t tried_sweep = 0;

  while (page && (tried_sweep < limit)) {
    RVALUE *p = page->objects;
    RVALUE *e = p + MRB_HEAP_PAGE_SIZE;
    size_t freed = 0;
    int dead_slot = 1;
    int full = (page->freelist == NULL);

    while (p<e) {
      if (is_dead(mrb, &p->as.basic)) {
        if (p->as.basic.tt != MRB_TT_FREE) {
          obj_free(mrb, &p->as.basic);
          p->as.free.next = page->freelist;
          page->freelist = (struct RBasic*)p;
          freed++;
        }
      }
      else {
        paint_partial_white(mrb, &p->as.basic); /* next gc target */
        dead_slot = 0;
      }
      p++;
    }

    /* free dead slot */
    if (dead_slot && freed < MRB_HEAP_PAGE_SIZE) {
      struct heap_page *next = page->next;

      unlink_heap_page(mrb, page);
      unlink_free_heap_page(mrb, page);
      mrb_free(mrb, page);
      page = next;
    }
    else {
      if (full && freed > 0) {
        link_free_heap_page(mrb, page);
      }
      page = page->next;
    }
    tried_sweep += MRB_HEAP_PAGE_SIZE;
    mrb->live -= freed;
    mrb->gc_live_after_mark -= freed;
  }
  mrb->sweeps = page;
  return tried_sweep;
}
示例#9
0
文件: obj.c 项目: beoran/eruta
/** Reduce the reference count of the object, possibly calling done and free 
on the object if it's reference count became 0. This will return NULL if 
the reference count became 0, otherwise it will return ptr. */
void * obj_unref(void * ptr) { 
  ObjHeader * header;
  header = obj_objheader(ptr);
  if(!header) return NULL;
  header->refcount--;
  /* only free at exactly 0, if unref is called too much, 
    it will go negative and the free will not be called too many times */
  if(header->refcount == 0) {
    // first call the destructor, then the free function.
    obj_done(ptr);
    obj_free(ptr); 
    return NULL;
  }
  return ptr;
}
示例#10
0
VectorPath::~VectorPath()
{
	if (fPath)
		obj_free(fPath);

#ifdef ICON_O_MATIC
	if (fListeners.CountItems() > 0) {
		PathListener* listener = (PathListener*)fListeners.ItemAt(0);
		char message[512];
		sprintf(message, "VectorPath::~VectorPath() - "
				 "there are still listeners attached! %p/%s",
				 listener, typeid(*listener).name());
		debugger(message);
	}
#endif
}
示例#11
0
static void object_primitive_free(n_array ** array)
{
    n_array * referenced_array = * array;
    switch(object_type(referenced_array))
    {
        case OBJECT_ARRAY:
        case OBJECT_OBJECT:
        {
            n_array * child = (n_array *)referenced_array->data;
            obj_free(&child);
        }
        default:
            memory_free((void **)array);
            break;
    }
}
示例#12
0
文件: gc.c 项目: Everysick/mruby
void
free_heap(mrb_state *mrb, mrb_gc *gc)
{
  mrb_heap_page *page = gc->heaps;
  mrb_heap_page *tmp;
  RVALUE *p, *e;

  while (page) {
    tmp = page;
    page = page->next;
    for (p = objects(tmp), e=p+MRB_HEAP_PAGE_SIZE; p<e; p++) {
      if (p->as.free.tt != MRB_TT_FREE)
        obj_free(mrb, &p->as.basic, TRUE);
    }
    mrb_free(mrb, tmp);
  }
}
示例#13
0
文件: gc.c 项目: anehing/mruby
void
mrb_free_heap(mrb_state *mrb)
{
  struct heap_page *page = mrb->heaps;
  struct heap_page *tmp;
  RVALUE *p, *e;

  while (page) {
    tmp = page;
    page = page->next;
    for (p = tmp->objects, e=p+MRB_HEAP_PAGE_SIZE; p<e; p++) {
      if (p->as.free.tt != MRB_TT_FREE)
        obj_free(mrb, &p->as.basic);
    }
    mrb_free(mrb, tmp);
  }
}
示例#14
0
文件: obj.c 项目: jxy859/nvml
/*
 * pmemobj_free -- frees an existing object
 */
void
pmemobj_free(PMEMoid *oidp)
{
	LOG(3, "oid.off 0x%016jx", oidp->off);

	/* log notice message if used inside a transaction */
	_POBJ_DEBUG_NOTICE_IN_TX();

	if (oidp->off == 0)
		return;

	PMEMobjpool *pop = cuckoo_get(pools, oidp->pool_uuid_lo);

	ASSERTne(pop, NULL);
	ASSERT(OBJ_OID_IS_VALID(pop, *oidp));

	obj_free(pop, oidp);
}
示例#15
0
文件: asm.c 项目: forestbelton/tenyr
static int obj_fini(FILE *stream, void **ud)
{
    int rc = 0;

    struct obj_fdata *u = *ud;
    struct obj *o = u->o;

    if (u->flags & ASM_ASSEMBLE) {
        o->records->size = u->insns;
        o->sym_count = u->syms;
        o->rlc_count = u->rlcs;

        obj_write(u->o, stream);
    }

    obj_free(u->o);

    free(*ud);
    *ud = NULL;

    return rc;
}
示例#16
0
n_object * object_file_to_tree(n_file * file)
{
    n_object * base_object = 0L;
    n_int      something_wrong = 0;
    
    tracking_array_open = 0;
    tracking_object_open = 0;
    tracking_string_quote = 0;
    io_whitespace_json(file);
    file->location = 0;

    base_object = object_file_base(file);
    
    if (tracking_array_open != 0)
    {
        (void)SHOW_ERROR("Array json does not match up");
        something_wrong = 1;
    }
    if (tracking_object_open != 0)
    {
        (void)SHOW_ERROR("Object json does not match up");
        something_wrong = 1;
    }
    if (tracking_string_quote != 0)
    {
        (void)SHOW_ERROR("String quote json does not match up");
        something_wrong = 1;
    }
    if (something_wrong)
    {
        obj_free((n_array **) &base_object);
        return 0L;
    }
    
    return base_object;
}
示例#17
0
int main(int argc, char* argv[])
{
    int cw = 750;
    int ch = 750;

    cg_init(cw, ch, NULL);

    glClearColor(0,0,1,1);
    // Actualizar la pantalla:
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glMatrixMode(GL_PROJECTION);
    glViewport(0,0,cw, ch);
    glFrustum(-1,1,-1,1,1,1000);

    glEnable(GL_LIGHTING);

    // glEnable(GL_NORMALIZE);
    float l0[] = {1.0f,1.0f,1.0f,1.0f};
    float la[] = {0.10f,0.10f,0.10f,1.0f};
    float l0p[]= {1.0f,1.0f,1.0f,1.0f};
    float ls[] = {1.0f,1.0f,1.0f,1.0f};
    glLightfv(GL_LIGHT0, GL_AMBIENT, la);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, l0);
    glLightfv(GL_LIGHT0, GL_POSITION, l0p);
    glLightfv(GL_LIGHT0, GL_SPECULAR, ls);
    glEnable(GL_LIGHT0);

    float cyan[] = {1.0f, 1.0f, 1.0f, 1.f};
    glMaterialfv(GL_FRONT, GL_DIFFUSE, cyan);
    glMaterialfv(GL_FRONT, GL_SPECULAR, ls);
    glMateriali(GL_FRONT, GL_SHININESS, 16);

    float ang = 0.0f;
    float pitch = 0.0f;
    float ang_vel = 1.0f;


    char done = 0;
    char wireframe = 0;
    char bfc = 0;
    glEnable(GL_DEPTH_TEST);
    char zbuff = 1;
    unsigned char key_pressed[1024];
    memset(key_pressed, 0, 1024);

    char use_shader = 0;
    char specular = 0;
    Shader gouraud = shader_new("shaders/gouraud_vp.glsl", "shaders/gouraud_fp.glsl");
    GLint uniform_especular = shader_get_unif_loc(gouraud, "especular");
    GLint uniform_tex = shader_get_unif_loc(gouraud, "tex");

    Obj* objPtr ;
    int example = atoi(argv[1]);

    if (example==1 || example==3)
        objPtr = obj_load("../Models/knight_texturas.obj");
    else if (example==2)
        objPtr = obj_load("../Models/box_texturas.obj");

    //Cargo la imagen de disco usando SDL_image
    SDL_Surface* surface; // = IMG_Load("../Models/knight.png");

    if (example==1 )
        surface = IMG_Load("../Models/knight.png");
    else if (example==2)
        surface = IMG_Load("../Models/box.jpg");
    else if (example==3)
        surface = IMG_Load("../Models/knight_good.png");


//    Obj* objPtr = obj_load("../Models/knight_texturas.obj");
//    Obj* objPtr = obj_load("../Models/box_texturas.obj");

    //Cargo la imagen de disco usando SDL_image
//    SDL_Surface* surface = IMG_Load("../Models/knight.png");
//    SDL_Surface* surface = IMG_Load("../Models/knight_good.png");
//    SDL_Surface* surface = IMG_Load("../Models/box.jpg");

    if (surface==NULL) { //Si falla la carga de la imagen, despliego el mensaje de error correspondiente y termino el programa.
        printf("Error: \"%s\"\n", SDL_GetError());
        return 1;
    }

    GLuint texture;
    //Creo un espacio para alojar una textura en memoria de video
    glGenTextures(1,&texture);
    //Activo la textura nro 0
    glActiveTexture(GL_TEXTURE0);
    //Habilito la carga para la textura recien creada
    glBindTexture(GL_TEXTURE_2D,texture);

    //Cargo los datos de la imagen en la textura.
    glTexImage2D(GL_TEXTURE_2D,
                 0,
                 GL_RGBA,
                 surface->w,
                 surface->h,
                 0,
                 GL_RGB,GL_UNSIGNED_BYTE,
                 surface->pixels);
    //Luego de copiada la imagen a memoria de video, puedo liberarla sin problemas
    SDL_FreeSurface(surface);

    //Seteo el filtro a usar cuando se mapea la textura a una superficie mas chica (GL_LINEAR = filtro bilineal)
    glTexParameteri(GL_TEXTURE_2D,
                    GL_TEXTURE_MIN_FILTER,
                    GL_LINEAR);
    //Seteo el filtro a usar cuando se mapea la textura a una superficie mas grande (GL_LINEAR = filtro bilineal)
    glTexParameteri(GL_TEXTURE_2D,
                    GL_TEXTURE_MAG_FILTER,
                    GL_LINEAR);

    //Seteo el comportamiento cuando encuentro coordenadas de textura fuera del rango [0,1]
    //GL_REPEAT es el comportamiento por defecto.
    glTexParameteri(GL_TEXTURE_2D,
                    GL_TEXTURE_WRAP_S,
                    GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D,
                    GL_TEXTURE_WRAP_T,
                    GL_REPEAT);

    while (!done)
    {

        SDL_Event event;
        while(SDL_PollEvent(&event))
        {
            switch (event.type)
            {
            case SDL_KEYDOWN:
                key_pressed[event.key.keysym.sym] = 1;
                if (event.key.keysym.sym == SDLK_p)
                {
                    use_shader = !use_shader;
                    break;
                }
                else if (event.key.keysym.sym == SDLK_s)
                {
                    specular = !specular;
                    break;
                }
                else if (event.key.keysym.sym == SDLK_z)
                {
                    zbuff = !zbuff;
                    if(zbuff)
                        glEnable(GL_DEPTH_TEST);
                    else
                        glDisable(GL_DEPTH_TEST);
                    break;
                }
                else if (event.key.keysym.sym == SDLK_m)
                {
                    wireframe = !wireframe;
                    if(wireframe)
                        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
                    else
                        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
                    break;
                }
                else if (event.key.keysym.sym == SDLK_b)
                {
                    bfc = !bfc;
                    if(bfc)
                    {
                        glEnable(GL_CULL_FACE);
                        glCullFace(GL_BACK);
                        glFrontFace(GL_CW);
                    }
                    else
                        glDisable(GL_CULL_FACE);
                    break;
                }
                else if (event.key.keysym.sym != SDLK_ESCAPE)
                    break;
            case SDL_QUIT :
                done = 1;
                break;
            case SDL_KEYUP:
                key_pressed[event.key.keysym.sym] = 0;

            }
        }

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        if (example==1 || example==3)
            glTranslatef(0.0f, 0.0f, -50.0f);
        else if (example==2)
            glTranslatef(0.0f, 0.0f, -2.0f);

//        glTranslatef(0.0f, 0.0f, -50.0f);
//        glTranslatef(0.0f, 0.0f, -2.0f);

        glRotatef(pitch, 1.0f, 0.0f, 0.0f);
        glRotatef(ang, 0.0f, 1.0f, 0.0f);

        glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);

        if(key_pressed[SDLK_RIGHT]) ang += ang_vel;
        if(key_pressed[SDLK_LEFT]) ang -= ang_vel;
        if(key_pressed[SDLK_UP]) pitch += ang_vel;
        if(key_pressed[SDLK_DOWN]) pitch -= ang_vel;

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

        //Informo a OpenGL que para todas las operaciones a continuaci�n utilice las texturas 2D cargadas
        glEnable(GL_TEXTURE_2D);

        if(use_shader)
        {
            shader_use(gouraud);
            glUniform1i(uniform_especular, specular);
            //Le digo al shader que el sampler2D de nombre "tex" se corresponde con GL_TEXTURE0
            //que es donde cargu� mi textura.
            glUniform1i(uniform_tex, 0);
            //Luego asocio la textura con el id "texture"
            glBindTexture(GL_TEXTURE_2D,texture);
            obj_render2(objPtr);
            shader_stop(gouraud);
        }
        else
        {
            glBindTexture(GL_TEXTURE_2D,texture);
            obj_render2(objPtr);
        }

        cg_repaint();
    } // while

    // Liberar recursos:
    obj_free(objPtr);
    shader_free(gouraud);
    glDeleteTextures(1,&texture);
    cg_close();

    return 0;
}
示例#18
0
文件: obj.c 项目: jxy859/nvml
/*
 * obj_realloc_common -- (internal) common routine for resizing
 *                          existing objects
 */
static int
obj_realloc_common(PMEMobjpool *pop, struct object_store *store,
	PMEMoid *oidp, size_t size, unsigned int type_num,
	void (*constr_alloc)(PMEMobjpool *pop, void *ptr, void *arg),
	void (*constr_realloc)(PMEMobjpool *pop, void *ptr, void *arg))
{

	/* if OID is NULL just allocate memory */
	if (OBJ_OID_IS_NULL(*oidp)) {
		struct carg_alloc carg;
		carg.size = size;

		/* if size is 0 - do nothing */
		if (size == 0)
			return 0;

		return obj_alloc_construct(pop, oidp, size, type_num,
						constr_alloc, &carg);
	}

	if (size > PMEMOBJ_MAX_ALLOC_SIZE) {
		ERR("requested size too large");
		errno = ENOMEM;
		return -1;
	}

	/* if size is 0 just free */
	if (size == 0) {
		obj_free(pop, oidp);
		return 0;
	}

	struct carg_realloc carg;
	carg.ptr = OBJ_OFF_TO_PTR(pop, oidp->off);
	carg.new_size = size;
	carg.old_size = pmemobj_alloc_usable_size(*oidp);
	carg.user_type = type_num;
	carg.constructor = NULL;
	carg.arg = NULL;

	struct oob_header *pobj = OOB_HEADER_FROM_OID(pop, *oidp);
	uint16_t user_type_old = pobj->data.user_type;

	ASSERT(user_type_old < PMEMOBJ_NUM_OID_TYPES);

	if (type_num >= PMEMOBJ_NUM_OID_TYPES) {
		errno = EINVAL;
		ERR("!obj_realloc_construct");
		LOG(2, "type_num has to be in range [0, %u]",
		    PMEMOBJ_NUM_OID_TYPES - 1);
		return -1;
	}

	struct list_head *lhead_old = &store->bytype[user_type_old].head;
	if (type_num == user_type_old) {
		int ret = list_realloc(pop, lhead_old, 0, NULL, size,
				constr_realloc, &carg, 0, 0, oidp);
		if (ret)
			LOG(2, "list_realloc failed");

		return ret;
	} else {
		struct list_head *lhead_new = &store->bytype[type_num].head;

		/*
		 * Redo log updates 8 byte entries, so we have to prepare
		 * full 8-byte value even if we want to update smaller field
		 * (here: user_type).
		 */
		struct oob_header_data d = pobj->data;
		d.user_type = type_num;

		uint64_t data_offset = OOB_OFFSET_OF(*oidp, data);

		int ret = list_realloc_move(pop, lhead_old, lhead_new, 0, NULL,
				size, constr_realloc, &carg, data_offset,
				*((uint64_t *)&d), oidp);
		if (ret)
			LOG(2, "list_realloc_move failed");

		return ret;
	}
}
示例#19
0
/**
 * Dibuje el modelo definido por el archivo knight.obj 1 disponible en webasignatura. El
 * formato del archivo OBJ se encuentra definido en el anexo I de este documento. Cada
 * triángulo del modelo debe ser dibujado usando un tono de gris randómico en sus vértices.
 * Nota: Para parsear el archivo obj, puede utilizar las funciones fgets (definida en stdio.h),
 * strcmp, strtok (definidas en string.h), atof y atoi (definidas en stdlib.h).
 */
int main(int argc, char* argv[])
{
// Crear una ventana de 500x500 pixels:
	int cw = 900;
	int ch = 900;

	cg_init(cw, ch, NULL);

#ifdef WIN32
    freopen( "CON", "w", stdout );
    freopen( "CON", "w", stderr );
#endif

	printf("GL Version: %s\n", glGetString(GL_VERSION));
	// Actualizar la pantalla:
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glMatrixMode(GL_PROJECTION);
	glViewport(0,0,cw, ch);
	glFrustum(-1,1,-1,1,1,1000);

	//Habilito la iluminación del pipeline estático de OpenGL.
	glEnable(GL_LIGHTING);

	//Creo un Vec4 para representar el color (RGBA) y la Intensidad de la luz.
	//P.e.: (1,1,1,1) = Luz Blanca intensa, (0.5,0.5,0.5,1) = Luz blanca tenue, (0.5,0,0,1) = Luz roja tenue.
	float l0[] = {1.0f,1.0f,1.0f,1.0f};
	//Creo un Vec4 para representar el color (RGBA) y la intensidad de la iluminación ambiente de la luz
	float la[] = {0.10f,0.10f,0.10f,1.0f};
	//Creo un Vec4 para representar la posición de la luz. El cuarto elemento representa el tipo de luz: 1=puntual, 0=direccional
	float l0p[]= {1.0f,1.0f,1.0f,1.0f};
	//Creo un Vec4 para representar el color (RGBA) y la intensidad especular de la luz
	float ls[] = {1.0f,1.0f,1.0f,1.0f};
	//Cargo la intesidad ambiente de la Luz Nro 0 del pipline estático.
	glLightfv(GL_LIGHT0, GL_AMBIENT, la);
	//Cargo la intesidad difusa de la Luz Nro 0 del pipline estático.
	glLightfv(GL_LIGHT0, GL_DIFFUSE, l0);
	//Cargo la posición de la Luz Nro 0 del pipline estático.
	glLightfv(GL_LIGHT0, GL_POSITION, l0p);
	//Cargo la intesidad especular de la Luz Nro 0 del pipline estático.
	glLightfv(GL_LIGHT0, GL_SPECULAR, ls);
	//Prendo la Luz nro 0 del pipline estático. Hay 8 luces, representadas por las constantes GL_LIGHT0 a GL_LIGHT7
	//Por defecto está todas apagadas al inicio.
	glEnable(GL_LIGHT0);

	//Creo un Vec4 para representar el color difuso(RGBA) del material del objeto a dibujar.
	float cyan[] = {1.0f, 0.0f, 1.0f, 1.f};
	//Cargo el color difuso del la cara de adelante del objeto a dibujar.
	glMaterialfv(GL_FRONT, GL_DIFFUSE, cyan);
	//Cargo el color especular del la cara de adelante del objeto a dibujar.
	glMaterialfv(GL_FRONT, GL_SPECULAR, ls);
	//Cargo el coeficiente especular de la cara de adelante del objeto a dibujar.
	glMateriali(GL_FRONT, GL_SHININESS, 32);

	float ang = 0.0f;
	float pitch = 0.0f;
	float ang_vel = 1.0f;

	Obj* obj = obj_load("Models/knight.obj");

	printf("num of faces %d\n", obj->numfaces);    // delete
	printf("num of vertices %d\n", obj->numverts);  // delete


	char done = 0;
	char wireframe = 0;
	char bfc = 0;
	glEnable(GL_DEPTH_TEST);
	char zbuff = 1;
	unsigned char key_pressed[1024];
	memset(key_pressed, 0, 1024);

	while (!done)
	{

		SDL_Event event;
		while(SDL_PollEvent(&event))
		{
			switch (event.type)
			{
				case SDL_KEYDOWN:
					key_pressed[event.key.keysym.sym] = 1;
					if (event.key.keysym.sym == SDLK_z)
					{
						zbuff = !zbuff;
						if(zbuff)
							glEnable(GL_DEPTH_TEST);
						else
							glDisable(GL_DEPTH_TEST);
						break;
					}
					else if (event.key.keysym.sym == SDLK_m)
					{
						wireframe = !wireframe;
						if(wireframe)
							glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
						else
							glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
						break;
					}
					else if (event.key.keysym.sym == SDLK_b)
					{
						bfc = !bfc;
						if(bfc)
						{
							glEnable(GL_CULL_FACE);
							glCullFace(GL_BACK);
							glFrontFace(GL_CW);
						}
						else
							glDisable(GL_CULL_FACE);
						break;
					}
					else if (event.key.keysym.sym != SDLK_ESCAPE)
						break;
				case SDL_QUIT : done = 1;break;
				case SDL_KEYUP: key_pressed[event.key.keysym.sym] = 0;

			}
		}

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glTranslatef(0.0f, 0.0f, -50.0f);
		glRotatef(pitch, 1.0f, 0.0f, 0.0f);
		glRotatef(ang, 0.0f, 1.0f, 0.0f);

		glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);

		if(key_pressed[SDLK_RIGHT]) ang += ang_vel;
		if(key_pressed[SDLK_LEFT]) ang -= ang_vel;
		if(key_pressed[SDLK_UP]) pitch += ang_vel;
		if(key_pressed[SDLK_DOWN]) pitch -= ang_vel;

		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

		obj_render(obj);

		cg_repaint();
	}
	obj_free(obj);
	// Liberar recursos:
	cg_close();

	// Ejemplo del modulo de Manejo de Memoria (MM):
	int* pint = (int *)cg_malloc(10*sizeof(int));
	printf("pint is a pointer: %p\n", pint);
	cg_free(pint); // olvidarse de liberar este objeto produce un mensaje


	return 0;
}
示例#20
0
/**
 * 2. Determinación de superficies ocultas por medio de Z-Buffer y optimización por Backface culling.
 */
int main(int argc, char* argv[])
{
	// Crear una ventana de 750x750 pixels.
	int cw = 750;
	int ch = 750;

	cg_init(cw, ch, NULL);

	// Actualizar la pantalla:
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glMatrixMode(GL_PROJECTION);
	glViewport(0,0,cw, ch);
	glFrustum(-1,1,-1,1,1,1000);

	Obj* obj = obj_load("../Models/knight.obj");

	float ang = 0.0f;
	float pitch = 0.0f;
	float ang_vel = 1.0f;

	char done = 0;
	char wireframe = 0;
	char bfc = 0;
	glEnable(GL_DEPTH_TEST);
	char zbuff = 1;
	unsigned char key_pressed[1024];
	memset(key_pressed, 0, 1024);

	while (!done)
	{
		SDL_Event event;
		while(SDL_PollEvent(&event))
		{
			switch (event.type)
			{
				case SDL_KEYDOWN:
					key_pressed[event.key.keysym.sym] = 1;

					if (event.key.keysym.sym == SDLK_z)
					{
						zbuff = !zbuff;
						if(zbuff)
							glEnable(GL_DEPTH_TEST);
						else
							glDisable(GL_DEPTH_TEST);
						break;
					}
					else if (event.key.keysym.sym == SDLK_b)
					{
						bfc = !bfc;
						if(bfc)
						{
							glEnable(GL_CULL_FACE);
							glCullFace(GL_BACK);
							glFrontFace(GL_CW);
						}
						else
							glDisable(GL_CULL_FACE);
						break;
					}
					else if (event.key.keysym.sym == SDLK_m)
					{
						wireframe = !wireframe;
						if(wireframe)
							glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
						else
							glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
						break;
					}
					else if (event.key.keysym.sym != SDLK_ESCAPE)
						break;
				case SDL_QUIT :
					done = 1;
					break;
				case SDL_KEYUP:
					key_pressed[event.key.keysym.sym] = 0;

			}
		}

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glTranslatef(0.0f, 0.0f, -50.0f);
		glRotatef(pitch, 1.0f, 0.0f, 0.0f);
		glRotatef(ang, 0.0f, 1.0f, 0.0f);
		glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);

		if(key_pressed[SDLK_RIGHT]) ang += ang_vel;
		if(key_pressed[SDLK_LEFT]) ang -= ang_vel;
		if(key_pressed[SDLK_UP]) pitch += ang_vel;
		if(key_pressed[SDLK_DOWN]) pitch -= ang_vel;

		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
		obj_render(obj);
		cg_repaint();
	}

	// Liberar recursos:
	obj_free(obj);
	cg_close();

	return 0;
}
示例#21
0
int main(int argc, char *argv[])
{
    int i;
    float r = 0;
	int f = -15;
	int g = 0;
	int l = 0;
	int y = 0;
	int u = 15;
	int q = 0;
	int gamestate=0;
	int PlayerHP=15, Bosshealth=30, enemy1health=5, enemy2health=5, Bigtimer=600, CD;
	int SpawnLemon1=0, SpawnLemon2=0, SpawnLemon3=0, SpawnBigLemon=0, enemybullet=0;
	float Lemonx1=0, Lemonx2=0, Lemonx3=0, LemonxBig=0, enemybulletx=0;
	int Lemony1=0, Lemony2=0, Lemony3=0, LemonyBig=0, enemybullety=0;
	int a=0, b=0, c=0, d=0, count, Goomba_attack1=0, Goomba_attack2=0, Goomba_move1, Goomba_move2;
    Space *space;
    Entity *cube1,*cube2, *Actor;
    char bGameLoopRunning = 1;
	Vec3D Bosspos = {u, y, 2};
	Vec3D enemy1pos = {5, 10, 2};
	Vec3D enemy2pos = {5, -10, 2};
    Vec3D cameraPosition = {0,0,70.3};
    Vec3D cameraRotation = {0,0,360};
    SDL_Event e;
    Obj *megaman,*boss, *mapp, *mape, *lemon, *BossHPBar, *PlayerHPBar, *Goomba;
    Sprite *megamantexture, *bosstexture, *maptexture1, *maptexture2, *lemontexture, *BosstextureHP, *PlayertextureHP, *Goombatexture;
    
    init_logger("gametest3d.log");
    if (graphics3d_init(1024,768,1,"gametest3d",33) != 0)
    {
        return -1;
    }
    model_init();
    obj_init();
    entity_init(255);
    
   //load objects, models here, replace cube with megaman
    megaman = obj_load("models/MPU.obj");
	//load his uv map "texture file"
    megamantexture = LoadSprite("models/MegaManBody1.png",1024,1024);

	PlayerHPBar = obj_load("models/cube.obj");
	PlayertextureHP = NULL;


	boss = obj_load("models/Fireman.obj");
	bosstexture = LoadSprite("models/FireManBody1.png",1024,1024);

	BossHPBar = obj_load("models/cube.obj");
	BosstextureHP = NULL;

	Goomba = obj_load("models/goomba.obj");
	Goombatexture = LoadSprite("models/goomba_tex.png",1024,1024);

    mapp = obj_load("models/MidtermMapSingle.obj");
	maptexture1 = LoadSprite("models/PlayerTile(Red).png",1024,1024);

	mape = obj_load("models/MidtermMapSingle.obj");
	maptexture2 = LoadSprite("models/BossTile(Blue).png",1024,1024);
    
    lemon = obj_load("models/cube.obj");
	lemontexture = NULL;//LoadSprite("models/cube_text.png",1024,1024);
    
	    
    while (bGameLoopRunning)
    {
        entity_think_all();

        while ( SDL_PollEvent(&e) ) 
        {
            if (e.type == SDL_QUIT)
            {
                bGameLoopRunning = 0;
            }
            else if (e.type == SDL_KEYDOWN)
            {
                if (e.key.keysym.sym == SDLK_ESCAPE)
                {
                    bGameLoopRunning = 0;
                }
                else if (e.key.keysym.sym == SDLK_x)
                {
                    cameraPosition.z++;
                }
                else if (e.key.keysym.sym == SDLK_z)
                {
                    cameraPosition.z--;
                }
                else if (e.key.keysym.sym == SDLK_h)
                {
                    vec3d_add(
                        cameraPosition,
                        cameraPosition,
                        vec3d(
                            -sin(cameraRotation.z * DEGTORAD),
                            cos(cameraRotation.z * DEGTORAD),
                            0
                        ));
                }
                else if (e.key.keysym.sym == SDLK_y)
                {
                    vec3d_add(
                        cameraPosition,
                        cameraPosition,
                        vec3d(
                            sin(cameraRotation.z * DEGTORAD),
                            -cos(cameraRotation.z * DEGTORAD),
                            0
                        ));
                }
                else if (e.key.keysym.sym == SDLK_j)
                {
                    vec3d_add(
                        cameraPosition,
                        cameraPosition,
                        vec3d(
                            cos(cameraRotation.z * DEGTORAD),
                            sin(cameraRotation.z * DEGTORAD),
                            0
                        ));
                }
                else if (e.key.keysym.sym == SDLK_g)
                {
                    vec3d_add(
                        cameraPosition,
                        cameraPosition,
                        vec3d(
                            -cos(cameraRotation.z * DEGTORAD),
                            -sin(cameraRotation.z * DEGTORAD),
                            0
                        ));
                }
				else if (e.key.keysym.sym == SDLK_d)
                {
                   
				   
				   if(f >= -5)
				   {
					   f = -5;
				   }
				   else
				   {
					   f += 10;
				   }
                }
				else if (e.key.keysym.sym == SDLK_a)
                {
                   
				   
				   if(f <= -20)
				   {
					   f = -25;
				   }
				   else
				   {
					   f -= 10;
				   }
				  			
                }
				else if (e.key.keysym.sym == SDLK_w)
                {
                   
				   if(g >= 5)
				   {
					   g = 10;
				   }
				   else
				   {
					   g += 10;
				   }
			
                }
				else if (e.key.keysym.sym == SDLK_s)
                {
                   
				   g -= 10;
				    if(g <= -5)
				   {
					   g = -10;
				   }
			
                }
                else if (e.key.keysym.sym == SDLK_LEFT)
                {
                    cameraRotation.z += 1;
                }
                else if (e.key.keysym.sym == SDLK_RIGHT)
                {
                    cameraRotation.z -= 1;
                }
                else if (e.key.keysym.sym == SDLK_UP)
                {
                    cameraRotation.x += 1;
                }
                else if (e.key.keysym.sym == SDLK_DOWN)
                {
                    cameraRotation.x -= 1;
                }
                else if (e.key.keysym.sym == SDLK_SPACE)
                {
                    
					CD = TIME + Bigtimer;					
					
                }
				else if (e.key.keysym.sym == SDLK_n)
                {
                   
				   if (enemy1health <= 0 && enemy2health <= 0)
				   {
					   gamestate=1;
				   }
			
                }
				else if (e.key.keysym.sym == SDLK_n)
                {
                   
				   if (enemy1health <= 0 && enemy2health <= 0)
				   {
					   gamestate=1;
				   }
			
                }
            }
			else if (e.type == SDL_KEYUP)
			{
				if (e.key.keysym.sym == SDLK_SPACE)
				{
					
					if (TIME >= CD && SpawnBigLemon !=1)
					{
						SpawnBigLemon = 1;
						LemonxBig = f;
						LemonyBig = g;
					}
					else if (SpawnLemon1 != 1)
					{
						SpawnLemon1 = 1;
						Lemonx1 = f;
						Lemony1 = g;
					}
					else if (SpawnLemon2 != 1)
					{
						SpawnLemon2 = 1;
						Lemonx2 = f;
						Lemony2 = g;
					}
					else if (SpawnLemon3 != 1)
					{
						SpawnLemon3 = 1;
						Lemonx3 = f;
						Lemony3 = g;
					}
					
				}
			}
				
        }

                
        graphics3d_frame_begin();
        
        glPushMatrix();
        set_camera(
            cameraPosition,
            cameraRotation);
        
        //entity_draw_all();
      
		if (PlayerHP > 0 )
		{
		//Megaman
        obj_draw(
            megaman,
            vec3d(f, g, 2),
            vec3d(90,90,0),
            vec3d(0.5,0.5,0.5),
            vec4d(1,1,1,1),
            megamantexture
        );

		//Megaman HP BAR
		obj_draw(
            PlayerHPBar,
            vec3d(-30+PlayerHP/(2),20,2),
            vec3d(90,-90,0),
            vec3d(.9,.9,PlayerHP/(2)),
            vec4d(0,1,0,1),
			PlayertextureHP
        );
		}

		//Megaman Projectiles
		//Lemon1
		if (SpawnLemon1 != 0)
		{
			obj_draw(
			lemon,
            vec3d(Lemonx1 + a*(.4), Lemony1, 4),
            vec3d(90,90,0),
            vec3d(1,1,2),
            vec4d(.95,.89,0,1),
		    lemontexture
		);
			a++;
				if (Lemonx1 + a*(.4) >=30)
				{
					SpawnLemon1 = 0;
					a=0;
				}
				else if (Lemonx1 + a*(.4) == enemy1pos.x && Lemony1 == enemy1pos.y)
				{
					SpawnLemon1 = 0;
					a=0;
					enemy1health -= 1;
					//slog("Enemy Health %d",enemy1health);
				}
				else if (Lemonx1 + a*(.4) == enemy2pos.x && Lemony1 == enemy2pos.y)
				{
					SpawnLemon1 = 0;
					a=0;
					enemy2health -= 1;
					//slog("Enemy Health %d",enemy2health);
				}
				else if (gamestate == 1 && Lemonx1 + a*(.4) == Bosspos.x && Lemony1 == Bosspos.y)
				{
				SpawnLemon1 = 0;
				a=0;
				Bosshealth -= 1;
				//slog("Boss Health %d",Bosshealth);
				}
		}
		//Lemon2
		if (SpawnLemon2 != 0)
		{
			obj_draw(
			lemon,
            vec3d(Lemonx2 + b*(.4), Lemony2, 4),
            vec3d(90,90,0),
            vec3d(1,1,2),
            vec4d(.95,.89,0,1),
		    lemontexture
		);
			b++;
				if (Lemonx2 + b*(.4) >=30)
				{
					SpawnLemon2 = 0;
					b=0;
				}
				else if (Lemonx2 + b*(.4) == enemy1pos.x && Lemony2 == enemy1pos.y)
				{
					SpawnLemon2 = 0;
					b=0;
					enemy1health -= 1;
					//slog("Enemy Health %d",enemy1health);
				}
				else if (Lemonx2 + b*(.4) == enemy2pos.x && Lemony2 == enemy2pos.y)
				{
					SpawnLemon2 = 0;
					b=0;
					enemy2health -= 1;
					//slog("Enemy Health %d",enemy2health);
				}
				else if (gamestate == 1 && Lemonx2 + b*(.4) == Bosspos.x && Lemony2 == Bosspos.y)
				{
					SpawnLemon2 = 0;
					b=0;
					Bosshealth -= 1;
					//slog("Boss Health %d",Bosshealth);
				}
		}
		if (SpawnLemon3 != 0)
		{
			obj_draw(
			lemon,
            vec3d(Lemonx3 + c*(.4), Lemony3, 4),
            vec3d(90,90,0),
            vec3d(1,1,2),
            vec4d(.95,.89,0,1),
		    lemontexture
		);
			c++;
				//lemons fly off staege
				if (Lemonx3 + c*(.4) >=30)
				{
					SpawnLemon3 = 0;
					c=0;
				}
				//lemons collide with enemies
				else if (Lemonx3 + c*(.4) == enemy1pos.x && Lemony3 == enemy1pos.y)
				{
					SpawnLemon3 = 0;
					c=0;
					enemy1health -= 1;
					slog("Enemy Health %d",enemy1health);
				}
				else if (Lemonx3 + c*(.4) == enemy2pos.x && Lemony3 == enemy2pos.y)
				{
					SpawnLemon3 = 0;
					c=0;
					enemy2health -= 1;
					slog("Enemy Health %d",enemy2health);
				}
				else if (gamestate == 1 && Lemonx3 + c*(.4) == Bosspos.x && Lemony3 == Bosspos.y)
				{
					SpawnLemon3 = 0;
					c=0;
					Bosshealth -= 1;
					//slog("Boss Health %d",Bosshealth);
				}
		}
		if (SpawnBigLemon != 0)
		{
			obj_draw(
			lemon,
            vec3d(LemonxBig + d*(.4), LemonyBig, 4),
            vec3d(90,90,0),
            vec3d(2,2,4),
            vec4d(.9,.3,.1,1),
		    lemontexture
		);
			d++;
				if (LemonxBig + d*(.4) >=30)
				{
					SpawnBigLemon = 0;
					d=0;
				}
				else if (LemonxBig + d*(.4) == enemy1pos.x && LemonyBig == enemy1pos.y)
				{
					SpawnBigLemon = 0;
					d=0;
					enemy1health -= 5;
					//slog("Enemy Health %d",enemy1health);
				}
				else if (LemonxBig + d*(.4) == enemy2pos.x && LemonyBig == enemy2pos.y)
				{
					SpawnBigLemon = 0;
					d=0;
					enemy2health -= 5;
					//slog("Enemy Health %d",enemy2health);
				}
				else if (gamestate == 1 && LemonxBig + d*(.4) == Bosspos.x && LemonyBig == Bosspos.y)
				{
					SpawnBigLemon = 0;
					d=0;
					Bosshealth -= 5;
					slog("Boss Health %d",Bosshealth);
				}
		}

		
		//MAP
		obj_draw(
            mapp,
            vec3d(-15,0,2),
            vec3d(90,90,0),
            vec3d(5,5,5),
            vec4d(1,1,1,1),
		    maptexture1
		);
		obj_draw(
            mape,
            vec3d(15,0,2),
            vec3d(90,90,0),
            vec3d(5,5,5),
            vec4d(1,1,1,1),
		    maptexture2
		);
		

		//Enemies
		if (gamestate == 0)
		{

			if (enemy1health > 0)
			{
			//enemy_move(enemypos.x,enemypos.y, &enemypos);
			//enemy_attack1(Goomba_attack1, &enemy1pos);

			obj_draw(
            Goomba,
            vec3d(enemy1pos.x,enemy1pos.y,2),
            vec3d(90,-90,0),
            vec3d(0.1,0.1,0.1),
            vec4d(1,1,1,1),
            Goombatexture
			);
						
			if (Goomba_attack1 == 0)
			{
				Goomba_attack1 = rand_ranged( 1, 5); //start to (end - 1)
				if (Goomba_attack1 == 2)
				{
					Goomba_attack1 = 1;
				}
		
			};

			if (Goomba_attack1 == 1)
			{
				enemy1pos.x -=.1;
				if (enemy1pos.x <= -30)
				{
					Goomba_attack1 = 0;
					enemy1pos.x = 5;
				}
			}

			}
			else
			{
				enemy1pos.x = 50;
				enemy1pos.y = 50;
			}

			if (enemy2health > 0)
			{
			//enemy_move(enemypos.x,enemypos.y, &enemypos);
			//enemy_attack2(Goomba_attack2, &enemy2pos);
			obj_draw(
            Goomba,
            vec3d(enemy2pos.x,enemy2pos.y,2),
            vec3d(90,-90,0),
            vec3d(0.1,0.1,0.1),
            vec4d(1,1,1,1),
            Goombatexture
			);

			//bottom Goomba won't attack

			if (Goomba_attack2 == 0)
			{
				Goomba_attack2 = rand_ranged( 1, 5); //start to (end - 1)
				if (Goomba_attack2 == 2)
				{
					Goomba_attack2 = 1;
				}
		
			};

			if (Goomba_attack2 == 1)
			{
				enemy2pos.x -=.1;
				if (enemy2pos.x <= -30)
				{
					Goomba_attack2 = 0;
					enemy2pos.x = 5;
				}
			}

			
			}
			else
			{
				enemy2pos.x = 50;
				enemy2pos.y = 50;
			}
			
		}
		if (gamestate != 0)
		{
		if (Bosshealth > 0)
		{
			Boss_move(Bosspos.x,Bosspos.y, &Bosspos);      	    
			//Fire man
			obj_draw(
				boss,
				vec3d(Bosspos.x,Bosspos.y,2),
				vec3d(90,-90,0),
				vec3d(0.5,0.5,0.5),
				vec4d(1,1,1,1),
				bosstexture
				);

				obj_draw(
				BossHPBar,
				vec3d(30-Bosshealth/(2.5),20,2),
				vec3d(90,-90,0),
				vec3d(.9,.9,Bosshealth/(2.5)),
				vec4d(1,0,0,1),
				BosstextureHP
			);

		}
		else
		{
			obj_free(boss);

			Bosspos.x = 50;
			Bosspos.y = 50;
			slog("You WIN!");
		}
		

		}
        
        if (r > 360)r -= 360;
        glPopMatrix();
        /* drawing code above here! */
        graphics3d_next_frame();
	} 
	return 0;
	}
示例#22
0
/*
 * obj_realloc_common -- (internal) common routine for resizing
 *                          existing objects
 */
static int
obj_realloc_common(PMEMobjpool *pop, struct object_store *store,
	PMEMoid *oidp, size_t size, type_num_t type_num, int zero_init)
{

	/* if OID is NULL just allocate memory */
	if (OBJ_OID_IS_NULL(*oidp)) {
		/* if size is 0 - do nothing */
		if (size == 0)
			return 0;

		return obj_alloc_construct(pop, oidp, size, type_num,
				zero_init, NULL, NULL);
	}

	if (size > PMEMOBJ_MAX_ALLOC_SIZE) {
		ERR("requested size too large");
		errno = ENOMEM;
		return -1;
	}

	/* if size is 0 just free */
	if (size == 0) {
		obj_free(pop, oidp);
		return 0;
	}

	struct carg_realloc carg;
	carg.ptr = OBJ_OFF_TO_PTR(pop, oidp->off);
	carg.new_size = size;
	carg.old_size = pmemobj_alloc_usable_size(*oidp);
	carg.user_type = type_num;
	carg.constructor = NULL;
	carg.arg = NULL;
	carg.zero_init = zero_init;

	struct oob_header *pobj = OOB_HEADER_FROM_OID(pop, *oidp);
	type_num_t user_type_old = pobj->data.user_type;

	/* callers should have checked this */
	ASSERT(type_num < PMEMOBJ_NUM_OID_TYPES);
	ASSERT(user_type_old < PMEMOBJ_NUM_OID_TYPES);

	struct list_head *lhead_old = &store->bytype[user_type_old].head;
	if (type_num == user_type_old) {
		int ret = list_realloc(pop, lhead_old, 0, NULL, size,
				constructor_realloc, &carg, 0, 0, oidp);
		if (ret)
			LOG(2, "list_realloc failed");

		/* oidp could be different, so we need to get the ptr again */
		VALGRIND_DO_MAKE_MEM_NOACCESS(pop,
			&OOB_HEADER_FROM_OID(pop, *oidp)->data.padding,
			sizeof (OOB_HEADER_FROM_OID(pop, *oidp)->data.padding));

		return ret;
	} else {
		struct list_head *lhead_new = &store->bytype[type_num].head;

		/*
		 * Header padding doubles as a red zone to check for header
		 * overwrites. Disable it temporarily so we can modify the type
		 * number.
		 */
		VALGRIND_DO_MAKE_MEM_DEFINED(pop,
			&OOB_HEADER_FROM_OID(pop, *oidp)->data.padding,
			sizeof (OOB_HEADER_FROM_OID(pop, *oidp)->data.padding));

		/*
		 * Redo log updates 8 byte entries, so we have to prepare
		 * full 8-byte value even if we want to update smaller field
		 * (here: user_type).
		 */
		struct oob_header_data d = pobj->data;
		d.user_type = type_num;

		uint64_t data_offset = OOB_OFFSET_OF(*oidp, data);

		int ret = list_realloc_move(pop, lhead_old, lhead_new, 0, NULL,
				size, constructor_realloc, &carg, data_offset,
				*((uint64_t *)&d), oidp);
		if (ret)
			LOG(2, "list_realloc_move failed");

		/* oidp could be different, so we need to get the ptr again */
		VALGRIND_DO_MAKE_MEM_NOACCESS(pop,
			&OOB_HEADER_FROM_OID(pop, *oidp)->data.padding,
			sizeof (OOB_HEADER_FROM_OID(pop, *oidp)->data.padding));

		return ret;
	}
}
示例#23
0
/*
 * Map a shared object into memory.  The "fd" argument is a file descriptor,
 * which must be open on the object and positioned at its beginning.
 * The "path" argument is a pathname that is used only for error messages.
 *
 * The return value is a pointer to a newly-allocated Obj_Entry structure
 * for the shared object.  Returns NULL on failure.
 */
Obj_Entry *
map_object(const char *path, char *buf, ssize_t size)
{
    Obj_Entry *obj;
    Elf_Ehdr *hdr;
    int i;
    Elf_Phdr *phdr;
    Elf_Phdr *phlimit;
    Elf_Phdr **segs;
    int nsegs;
    Elf_Phdr *phdyn;
    Elf_Phdr *phinterp;
    Elf_Phdr *phtls;
    caddr_t mapbase;
    size_t mapsize;
    Elf_Off base_offset;
    Elf_Addr base_vaddr;
    Elf_Addr base_vlimit;
    caddr_t base_addr;
    Elf_Off data_offset;
    Elf_Addr data_vaddr;
    Elf_Addr data_vlimit;
    caddr_t data_addr;
    int data_prot;
    int data_flags;
    Elf_Addr clear_vaddr;
    caddr_t clear_addr;
    caddr_t clear_page;
    Elf_Addr phdr_vaddr;
    size_t nclear, phsize;
    Elf_Addr bss_vaddr;
    Elf_Addr bss_vlimit;
    caddr_t bss_addr;

    
    hdr = get_elf_header(path, buf, size);
    if (hdr == NULL)
	return (NULL);

    /*
     * Scan the program header entries, and save key information.
     *
     * We expect that the loadable segments are ordered by load address.
     */
    phdr = (Elf_Phdr *) ((char *)hdr + hdr->e_phoff);
    phsize  = hdr->e_phnum * sizeof (phdr[0]);
    phlimit = phdr + hdr->e_phnum;
    nsegs = -1;
    phdyn = phinterp = phtls = NULL;
    phdr_vaddr = 0;
    segs = alloca(sizeof(segs[0]) * hdr->e_phnum);
    while (phdr < phlimit) {
	switch (phdr->p_type) {

	case PT_INTERP:
	    phinterp = phdr;
	    break;

	case PT_LOAD:
	    segs[++nsegs] = phdr;
    	    if ((segs[nsegs]->p_align & (PAGE_SIZE - 1)) != 0) {
		_rtld_error("%s: PT_LOAD segment %d not page-aligned",
		    path, nsegs);
		return NULL;
	    }
	    break;

	case PT_PHDR:
	    phdr_vaddr = phdr->p_vaddr;
	    phsize = phdr->p_memsz;
	    break;

	case PT_DYNAMIC:
	    phdyn = phdr;
	    break;

	case PT_TLS:
	    phtls = phdr;
	    break;
	}

	++phdr;
    }
    if (phdyn == NULL) {
	_rtld_error("%s: object is not dynamically-linked", path);
	return NULL;
    }

    if (nsegs < 0) {
	_rtld_error("%s: too few PT_LOAD segments", path);
	return NULL;
    }

    /*
     * Map the entire address space of the object, to stake out our
     * contiguous region, and to establish the base address for relocation.
     */
    base_offset = trunc_page(segs[0]->p_offset);
    base_vaddr = trunc_page(segs[0]->p_vaddr);
    base_vlimit = round_page(segs[nsegs]->p_vaddr + segs[nsegs]->p_memsz);
    mapsize = base_vlimit - base_vaddr;
    base_addr = hdr->e_type == ET_EXEC ? (caddr_t) base_vaddr : NULL;

    mapbase = mmap(base_addr, mapsize, PROT_NONE, MAP_ANON | MAP_PRIVATE |
      MAP_NOCORE, -1, 0);
    if (mapbase == (caddr_t) -1) {
	_rtld_error("%s: mmap of entire address space failed: %s",
	  path, strerror(errno));
	return NULL;
    }
    if (base_addr != NULL && mapbase != base_addr) {
	_rtld_error("%s: mmap returned wrong address: wanted %p, got %p",
	  path, base_addr, mapbase);
	munmap(mapbase, mapsize);
	return NULL;
    }

    for (i = 0; i <= nsegs; i++) {
	size_t data_vsize;

	/* Overlay the segment onto the proper region. */
	data_offset = trunc_page(segs[i]->p_offset);
	data_vaddr = trunc_page(segs[i]->p_vaddr);
	data_vlimit = round_page(segs[i]->p_vaddr + segs[i]->p_filesz);
	data_addr = mapbase + (data_vaddr - base_vaddr);
	data_prot = convert_prot(segs[i]->p_flags) | PROT_WRITE;
	data_vsize = data_vlimit - data_vaddr;
	data_flags = convert_flags(segs[i]->p_flags) |	\
	    MAP_FIXED | MAP_ANON | MAP_PRIVATE;
	if (mmap(data_addr, data_vsize, data_prot, data_flags,
		-1, data_offset) == (caddr_t) -1) {
	    _rtld_error("%s: mmap of data failed: %s", path, strerror(errno));
	    return NULL;
	}
	bcopy(buf + data_offset, data_addr, MIN(data_vsize, (size - data_offset)));

	/* Do BSS setup */
	if (segs[i]->p_filesz != segs[i]->p_memsz) {

	    /* Clear any BSS in the last page of the segment. */
	    clear_vaddr = segs[i]->p_vaddr + segs[i]->p_filesz;
	    clear_addr = mapbase + (clear_vaddr - base_vaddr);
	    clear_page = mapbase + (trunc_page(clear_vaddr) - base_vaddr);

	    if ((nclear = data_vlimit - clear_vaddr) > 0) {
		/* Make sure the end of the segment is writable */
		if ((data_prot & PROT_WRITE) == 0 && -1 ==
		     mprotect(clear_page, PAGE_SIZE, data_prot|PROT_WRITE)) {
			_rtld_error("%s: mprotect failed: %s", path,
			    strerror(errno));
			return NULL;
		}

		memset(clear_addr, 0, nclear);

		/* Reset the data protection back */
		if ((data_prot & PROT_WRITE) == 0)
		    mprotect(clear_page, PAGE_SIZE, data_prot);
	    }

	    /* Overlay the BSS segment onto the proper region. */
	    bss_vaddr = data_vlimit;
	    bss_vlimit = round_page(segs[i]->p_vaddr + segs[i]->p_memsz);
	    bss_addr = mapbase +  (bss_vaddr - base_vaddr);
	    if (bss_vlimit > bss_vaddr) {	/* There is something to do */
		if (mprotect(bss_addr, bss_vlimit - bss_vaddr, data_prot) == -1) {
		    _rtld_error("%s: mprotect of bss failed: %s", path,
			strerror(errno));
		    return NULL;
		}
	    }
	}

	if (phdr_vaddr == 0 && data_offset <= hdr->e_phoff &&
	  (data_vlimit - data_vaddr + data_offset) >=
	  (hdr->e_phoff + hdr->e_phnum * sizeof (Elf_Phdr))) {
	    phdr_vaddr = data_vaddr + hdr->e_phoff - data_offset;
	}
    }

    obj = obj_new();
    obj->mapbase = mapbase;
    obj->mapsize = mapsize;
    obj->textsize = round_page(segs[0]->p_vaddr + segs[0]->p_memsz) -
      base_vaddr;
    obj->vaddrbase = base_vaddr;
    obj->relocbase = mapbase - base_vaddr;
    obj->dynamic = (const Elf_Dyn *) (obj->relocbase + phdyn->p_vaddr);
    if (hdr->e_entry != 0)
	obj->entry = (caddr_t) (obj->relocbase + hdr->e_entry);
    if (phdr_vaddr != 0) {
	obj->phdr = (const Elf_Phdr *) (obj->relocbase + phdr_vaddr);
    } else {
	obj->phdr = malloc(phsize);
	if (obj->phdr == NULL) {
	    obj_free(obj);
	    _rtld_error("%s: cannot allocate program header", path);
	     return NULL;
	}
	memcpy((char *)obj->phdr, (char *)hdr + hdr->e_phoff, phsize);
	obj->phdr_alloc = true;
    }
    obj->phsize = phsize;
    if (phinterp != NULL)
	obj->interp = (const char *) (obj->relocbase + phinterp->p_vaddr);
    if (phtls != NULL) {
	tls_dtv_generation++;
	obj->tlsindex = ++tls_max_index;
	obj->tlssize = phtls->p_memsz;
	obj->tlsalign = phtls->p_align;
	obj->tlsinitsize = phtls->p_filesz;
	obj->tlsinit = mapbase + phtls->p_vaddr;
    }
    return obj;
}
示例#24
0
文件: itty.c 项目: seanlynch/itty
void decref(obj_t *o) {
    assert(o->refcnt > 0);
    if (--o->refcnt == 0) obj_free(o);
}
示例#25
0
/*
 * Map a shared object into memory.  The "fd" argument is a file descriptor,
 * which must be open on the object and positioned at its beginning.
 * The "path" argument is a pathname that is used only for error messages.
 *
 * The return value is a pointer to a newly-allocated Obj_Entry structure
 * for the shared object.  Returns NULL on failure.
 */
Obj_Entry *
map_object(int fd, const char *path, const struct stat *sb)
{
    Obj_Entry *obj;
    Elf_Ehdr *hdr;
    int i;
    Elf_Phdr *phdr;
    Elf_Phdr *phlimit;
    Elf_Phdr **segs;
    int nsegs;
    Elf_Phdr *phdyn;
    Elf_Phdr *phinterp;
    Elf_Phdr *phtls;
    caddr_t mapbase;
    caddr_t shlib_base;
    size_t mapsize;
    Elf_Addr base_vaddr;
    Elf_Addr base_vlimit;
    caddr_t base_addr;
    Elf_Off data_offset;
    Elf_Addr data_vaddr;
    Elf_Addr data_vlimit;
    caddr_t data_addr;
    int data_prot;
    int data_flags;
    Elf_Addr clear_vaddr;
    caddr_t clear_addr;
    caddr_t clear_page;
    Elf_Addr phdr_vaddr;
    size_t nclear, phsize;
    Elf_Addr bss_vaddr;
    Elf_Addr bss_vlimit;
    caddr_t bss_addr;
    Elf_Word stack_flags;
    Elf_Addr relro_page;
    size_t relro_size;
    Elf_Addr note_start;
    Elf_Addr note_end;

    hdr = get_elf_header(fd, path);
    if (hdr == NULL)
	return (NULL);

    if (__ld_sharedlib_base) {
	shlib_base = (void *)(intptr_t)strtoul(__ld_sharedlib_base, NULL, 0);
    } else {
	shlib_base = NULL;
    }

    /*
     * Scan the program header entries, and save key information.
     *
     * We expect that the loadable segments are ordered by load address.
     */
    phdr = (Elf_Phdr *) ((char *)hdr + hdr->e_phoff);
    phsize  = hdr->e_phnum * sizeof (phdr[0]);
    phlimit = phdr + hdr->e_phnum;
    nsegs = -1;
    phdyn = phinterp = phtls = NULL;
    phdr_vaddr = 0;
    relro_page = 0;
    relro_size = 0;
    note_start = 0;
    note_end = 0;
    segs = alloca(sizeof(segs[0]) * hdr->e_phnum);
    stack_flags = RTLD_DEFAULT_STACK_PF_EXEC | PF_R | PF_W;
    while (phdr < phlimit) {
	switch (phdr->p_type) {

	case PT_INTERP:
	    phinterp = phdr;
	    break;

	case PT_LOAD:
	    segs[++nsegs] = phdr;
	    if ((segs[nsegs]->p_align & (PAGE_SIZE - 1)) != 0) {
		_rtld_error("%s: PT_LOAD segment %d not page-aligned",
		    path, nsegs);
		goto error;
	    }
	    break;

	case PT_PHDR:
	    phdr_vaddr = phdr->p_vaddr;
	    phsize = phdr->p_memsz;
	    break;

	case PT_DYNAMIC:
	    phdyn = phdr;
	    break;

	case PT_TLS:
	    phtls = phdr;
	    break;

	case PT_GNU_STACK:
	    stack_flags = phdr->p_flags;
	    break;

	case PT_GNU_RELRO:
	    relro_page = phdr->p_vaddr;
	    relro_size = phdr->p_memsz;
	    break;

	case PT_NOTE:
	    if (phdr->p_offset > PAGE_SIZE ||
	      phdr->p_offset + phdr->p_filesz > PAGE_SIZE)
		break;
	    note_start = (Elf_Addr)(char *)hdr + phdr->p_offset;
	    note_end = note_start + phdr->p_filesz;
	    break;
	}

	++phdr;
    }
    if (phdyn == NULL) {
	_rtld_error("%s: object is not dynamically-linked", path);
	goto error;
    }

    if (nsegs < 0) {
	_rtld_error("%s: too few PT_LOAD segments", path);
	goto error;
    }

    /*
     * Map the entire address space of the object, to stake out our
     * contiguous region, and to establish the base address for relocation.
     */
    base_vaddr = trunc_page(segs[0]->p_vaddr);
    base_vlimit = round_page(segs[nsegs]->p_vaddr + segs[nsegs]->p_memsz);
    mapsize = base_vlimit - base_vaddr;
    base_addr = (caddr_t) base_vaddr;

    if (base_addr == NULL && shlib_base) {
	size_t limit = 1024 * 256 * 1024;
	size_t offset;

	for (offset = 0; offset < limit; offset += 256 * 1024) {
		mapbase = mmap(shlib_base + offset, mapsize,
			       PROT_NONE,
			       MAP_ANON | MAP_PRIVATE | MAP_NOCORE |
			       MAP_TRYFIXED,
			       -1, 0);
		if (mapbase != MAP_FAILED)
			break;
	}
    } else {
	mapbase = mmap(base_addr, mapsize,
		       PROT_NONE,
		       MAP_ANON | MAP_PRIVATE | MAP_NOCORE,
		       -1, 0);
    }
    if (mapbase == (caddr_t) -1) {
	_rtld_error("%s: mmap of entire address space failed: %s",
	  path, rtld_strerror(errno));
	goto error;
    }
    if (base_addr != NULL && mapbase != base_addr) {
	_rtld_error("%s: mmap returned wrong address: wanted %p, got %p",
	  path, base_addr, mapbase);
	goto error1;
    }

    for (i = 0; i <= nsegs; i++) {
	/* Overlay the segment onto the proper region. */
	data_offset = trunc_page(segs[i]->p_offset);
	data_vaddr = trunc_page(segs[i]->p_vaddr);
	data_vlimit = round_page(segs[i]->p_vaddr + segs[i]->p_filesz);
	data_addr = mapbase + (data_vaddr - base_vaddr);
	data_prot = convert_prot(segs[i]->p_flags);
	data_flags = convert_flags(segs[i]->p_flags) | MAP_FIXED;
	if (mmap(data_addr, data_vlimit - data_vaddr, data_prot,
	  data_flags, fd, data_offset) == (caddr_t) -1) {
	    _rtld_error("%s: mmap of data failed: %s", path,
		rtld_strerror(errno));
	    goto error1;
	}

	/* Do BSS setup */
	if (segs[i]->p_filesz != segs[i]->p_memsz) {

	    /* Clear any BSS in the last page of the segment. */
	    clear_vaddr = segs[i]->p_vaddr + segs[i]->p_filesz;
	    clear_addr = mapbase + (clear_vaddr - base_vaddr);
	    clear_page = mapbase + (trunc_page(clear_vaddr) - base_vaddr);

	    if ((nclear = data_vlimit - clear_vaddr) > 0) {
		/* Make sure the end of the segment is writable */
		if ((data_prot & PROT_WRITE) == 0 && -1 ==
		     mprotect(clear_page, PAGE_SIZE, data_prot|PROT_WRITE)) {
			_rtld_error("%s: mprotect failed: %s", path,
			    rtld_strerror(errno));
			goto error1;
		}

		memset(clear_addr, 0, nclear);

		/*
		 * reset the data protection back, enable the segment to be
		 * coredumped since we modified it.
		 */
		if ((data_prot & PROT_WRITE) == 0) {
		    madvise(clear_page, PAGE_SIZE, MADV_CORE);
		    mprotect(clear_page, PAGE_SIZE, data_prot);
		}
	    }

	    /* Overlay the BSS segment onto the proper region. */
	    bss_vaddr = data_vlimit;
	    bss_vlimit = round_page(segs[i]->p_vaddr + segs[i]->p_memsz);
	    bss_addr = mapbase +  (bss_vaddr - base_vaddr);
	    if (bss_vlimit > bss_vaddr) {	/* There is something to do */
		if (mmap(bss_addr, bss_vlimit - bss_vaddr, data_prot,
		    data_flags | MAP_ANON, -1, 0) == (caddr_t)-1) {
		    _rtld_error("%s: mmap of bss failed: %s", path,
			rtld_strerror(errno));
		    goto error1;
		}
	    }
	}

	if (phdr_vaddr == 0 && data_offset <= hdr->e_phoff &&
	  (data_vlimit - data_vaddr + data_offset) >=
	  (hdr->e_phoff + hdr->e_phnum * sizeof (Elf_Phdr))) {
	    phdr_vaddr = data_vaddr + hdr->e_phoff - data_offset;
	}
    }

    obj = obj_new();
    if (sb != NULL) {
	obj->dev = sb->st_dev;
	obj->ino = sb->st_ino;
    }
    obj->mapbase = mapbase;
    obj->mapsize = mapsize;
    obj->textsize = round_page(segs[0]->p_vaddr + segs[0]->p_memsz) -
      base_vaddr;
    obj->vaddrbase = base_vaddr;
    obj->relocbase = mapbase - base_vaddr;
    obj->dynamic = (const Elf_Dyn *) (obj->relocbase + phdyn->p_vaddr);
    if (hdr->e_entry != 0)
	obj->entry = (caddr_t) (obj->relocbase + hdr->e_entry);
    if (phdr_vaddr != 0) {
	obj->phdr = (const Elf_Phdr *) (obj->relocbase + phdr_vaddr);
    } else {
	obj->phdr = malloc(phsize);
	if (obj->phdr == NULL) {
	    obj_free(obj);
	    _rtld_error("%s: cannot allocate program header", path);
	    goto error1;
	}
	memcpy((char *)obj->phdr, (char *)hdr + hdr->e_phoff, phsize);
	obj->phdr_alloc = true;
    }
    obj->phsize = phsize;
    if (phinterp != NULL)
	obj->interp = (const char *) (obj->relocbase + phinterp->p_vaddr);
    if (phtls != NULL) {
	tls_dtv_generation++;
	obj->tlsindex = ++tls_max_index;
	obj->tlssize = phtls->p_memsz;
	obj->tlsalign = phtls->p_align;
	obj->tlsinitsize = phtls->p_filesz;
	obj->tlsinit = mapbase + phtls->p_vaddr;
    }
    obj->stack_flags = stack_flags;
    if (relro_size) {
        obj->relro_page = obj->relocbase + trunc_page(relro_page);
        obj->relro_size = round_page(relro_size);
    }
    if (note_start < note_end)
       digest_notes(obj, note_start, note_end);
    munmap(hdr, PAGE_SIZE);
    return (obj);

error1:
    munmap(mapbase, mapsize);
error:
    munmap(hdr, PAGE_SIZE);
    return (NULL);
}
示例#26
0
文件: obj.c 项目: BlackBoxe/minuit
void _op_obj_import(void)
{
	t_context *C=ctx_get();
	char *filename=C->event->standby_string;

	if(filename)
	{
		// init list
		OBJECTS=lst_new("lst");

		// parse file
		t_file *file = file_new(filename);

		free(C->event->standby_string);
		//C->event->standby_function=NULL;
		C->event->callback=NULL;

		file_read(file);
		file_read_lines(file);

		//parse words
		t_link *link;
		t_link *l;
		t_word *word;

		for(link=file->lines->first;link;link=link->next)
		{
			t_line *line = link->data;
			line_read_words(line);
		}

		// parse tokens
		int object_start;
		int line_object;
		int is_face;
		//int tot_object;
		int tot_vert;
		int tot_face;
		int tot_tri;
		int tot_quad;
		int tot_indice;

		char *object_name;

		//tot_object=0;
		tot_face=0;
		tot_quad=0;
		tot_tri=0;
		object_start=0;
		
		for(link=file->lines->first;link;link=link->next)
		{
			// LINE
			t_line *line = link->data;

			// RESET
			is_face=0;

			for(l=line->words->first;l;l=l->next)
			{
				// WORD

				word=l->data;

				if(word_equal(word,"o"))
				{
					if(object_start)
					{
						obj_add(object_name,tot_vert,tot_face,tot_quad,tot_tri);

						tot_vert=0;
						tot_face=0;
						tot_quad=0;
						tot_tri=0;
					
						free(object_name);
					}
					else
					{
						object_start=1;
					}

					tot_vert=0;
					line_object=1;
				}
				else if(line_object)
				{
					object_name=(char *)malloc(sizeof(char)*(strlen(word->data)+1));
					strcpy(object_name,word->data);
					line_object=0;
				}
				else if(word_equal(word,"v"))
				{
					tot_vert++;
				}
				else if(word_equal(word,"f"))
				{
					tot_face++;
					is_face=1;
					tot_indice=0;
				}
				else if(is_face)
				{
					tot_indice++;
				}
				else if(word_equal(word,"usemtl"))
				{
				}
				else if(word_equal(word,"s"))
				{
				}
			}

			if(is_face)
			{
				if(tot_indice==4)
				{
					tot_quad++;
				}
				else
				{
					tot_tri++;
				}
			}
		}

		// add last object
		obj_add(object_name,tot_vert,tot_face,tot_quad,tot_tri);

		// vars
		int is_data=0;
		int indice_vertex=0;
		int indice_face=0;
		int cursor_tri=0;
		int cursor_quad=0;
		int global_cursor=0;
		int tmp_global_cursor=0;
		int face[4];

		object_start=0;

		t_token_type token;
		t_link *link_object;
		t_obj *obj;

		for(link=file->lines->first;link;link=link->next)
		{
			// LINE

			t_line *line = link->data;
			
			// reset
			is_data=0;
			indice_face=0;

			for(l=line->words->first;l;l=l->next)
			{
				// WORD

				word=l->data;

				if(word_equal(word,"o"))
				{
					token=token_object;

					if(object_start)
					{
						if(link_object->next) link_object=link_object->next;
						obj=link_object->data;
						// global cursor
						global_cursor+=tmp_global_cursor;
						tmp_global_cursor=obj->tot_vert;
					}
					//first
					else
					{
						link_object=OBJECTS->first;
						obj=link_object->data;
						object_start=1;
						tmp_global_cursor=obj->tot_vert;
					}

					indice_vertex=0;
					indice_face=0;
					cursor_tri=0;
					cursor_quad=0;
				}
				else if(word_equal(word,"v"))
				{
					token=token_vertex;
				}
				else if(word_equal(word,"f"))
				{
					token=token_face;
				}
				else if(word_equal(word,"usemtl"))
				{
					token=token_material;
				}
				else if(word_equal(word,"s"))
				{
					token=token_unknown;
				}
				else
				{
					is_data=1;
				}

				if(is_data)
				{
					if(token==token_vertex)
					{
						obj->verts[indice_vertex]=atof(word->data);
						indice_vertex++;
					}
					else if(token==token_face)
					{
						face[indice_face]=atoi(word->data);
						indice_face++;
					}
				}
			}

			// store face indice
			if(token==token_face)
			{
				int i;
				if(indice_face==3)
				{
					for(i=0;i<3;i++)
					{
						obj->tris[cursor_tri]=face[i]-global_cursor-1;
						cursor_tri++;
					}
				}
				else
				{
					for(i=0;i<4;i++)
					{
						obj->quads[cursor_quad]=face[i]-global_cursor-1;
						cursor_quad++;
					}
				}
			}
		}

		
		// add objects to scene

		C->scene->store=1;

		for(link=OBJECTS->first;link;link=link->next)
		{
			t_obj *obj = link->data;

			// new mesh
			t_node *node_mesh=mesh_make(
						obj->name,
						//"me_obj",
						obj->tot_vert,
						obj->tot_face,
						obj->tot_quad,
						obj->tot_tri,
						obj->verts,
						obj->quads,
						obj->tris);


			// new object
			t_node *node_object=object_add("mesh",obj->name);

			// link
			t_object *object=node_object->data;
			object->cls->link(object,node_mesh);
		}

		C->scene->store=0;

		// free obj

		for(link=OBJECTS->first;link;link=link->next)
		{
			t_obj *obj = link->data;
			obj_free(obj);
		}
	}
}
示例#27
0
void _cdecl operator delete(void* ptr){
	obj_free(ptr);
}
示例#28
0
static n_array * object_file_array(n_file * file)
{
    n_array * base_array = 0L;
    
    n_object_stream_type stream_type;
    n_object_stream_type stream_type_in_this_array = OBJ_TYPE_EMPTY;
    if (file->data[file->location] != '[') // TODO: Replace with smart char handling
    {
        (void)SHOW_ERROR("json not array as expected");
        return base_array;
    }
    
    tracking_array_open ++;
    
    file->location ++;
    do{
        CHECK_FILE_SIZE("end of json file reach unexpectedly");
        stream_type = object_stream_char(file->data[file->location]);
        
        if (stream_type_in_this_array == OBJ_TYPE_EMPTY)
        {
            stream_type_in_this_array = stream_type;
        }
        else if (stream_type_in_this_array != stream_type)
        {
            obj_free(&base_array);
            (void)SHOW_ERROR("array contains mutliple types");
            return 0L;
        }
        
        if (stream_type == OBJ_TYPE_ARRAY_OPEN)
        {
            n_array * array_value = object_file_array(file);
            if (array_value)
            {
                stream_type = object_stream_char(file->data[file->location]);
                
                if ((stream_type == OBJ_TYPE_ARRAY_CLOSE) || (stream_type == OBJ_TYPE_COMMA))
                {
                    if (base_array == 0L)
                    {
                        base_array = array_array(array_value);
                    }
                    else
                    {
                        array_add(base_array, array_array(array_value));
                    }
                }
            }
            stream_type = object_stream_char(file->data[file->location]);
        }
        if (stream_type == OBJ_TYPE_OBJECT_OPEN)
        {
            n_object * object_value = object_file_base(file);
            OBJ_DBG(object_value, "object value is nil?");
            if (object_value)
            {
                file->location++;
                CHECK_FILE_SIZE("end of json file reach unexpectedly");
                stream_type = object_stream_char(file->data[file->location]);
                
                if ((stream_type == OBJ_TYPE_ARRAY_CLOSE) || (stream_type == OBJ_TYPE_COMMA))
                {
                    if (base_array == 0L)
                    {
                        base_array = array_object(object_value);
                    }
                    else
                    {
                        array_add(base_array, array_object(object_value));
                    }
                }
            }
            
            OBJ_DBG(base_array, "base array still nil?");

            CHECK_FILE_SIZE("end of json file reach unexpectedly");
            stream_type = object_stream_char(file->data[file->location]);
        }
        if (stream_type == OBJ_TYPE_STRING_NOTATION)
        {
            n_string string_value = object_file_read_string(file);
            if (string_value)
            {
                stream_type = object_stream_char(file->data[file->location]);
                
                if ((stream_type == OBJ_TYPE_ARRAY_CLOSE) || (stream_type == OBJ_TYPE_COMMA))
                {
                    if (base_array == 0L)
                    {
                        base_array = array_string(string_value);
                    }
                    else
                    {
                        array_add(base_array, array_string(string_value));
                    }
                }
            }
            stream_type = object_stream_char(file->data[file->location]);
        }
        if (stream_type == OBJ_TYPE_NUMBER)
        {
            n_int with_error;
            n_int number_value = object_file_read_number(file, &with_error);
            
            if (with_error == 0)
            {
                stream_type = object_stream_char(file->data[file->location]);
                
                if ((stream_type == OBJ_TYPE_ARRAY_CLOSE) || (stream_type == OBJ_TYPE_COMMA))
                {
                    if (base_array == 0L)
                    {
                        base_array = array_number(number_value);
                    }
                    else
                    {
                        array_add(base_array, array_number(number_value));
                    }
                }
            }
            stream_type = object_stream_char(file->data[file->location]);
        }
        if (stream_type == OBJ_TYPE_ARRAY_CLOSE)
        {
            tracking_array_open --;
        }
        file->location ++;
        
        OBJ_DBG(base_array, "base array nil check?");
    }while (stream_type == OBJ_TYPE_COMMA);
    
    OBJ_DBG(base_array, "base array really nil?");
    
    return base_array;
}
示例#29
0
文件: gc.c 项目: anehing/mruby
static size_t
incremental_sweep_phase(mrb_state *mrb, size_t limit)
{
  struct heap_page *page = mrb->sweeps;
  size_t tried_sweep = 0;

  while (page && (tried_sweep < limit)) {
    RVALUE *p = page->objects;
    RVALUE *e = p + MRB_HEAP_PAGE_SIZE;
    size_t freed = 0;
    mrb_bool dead_slot = TRUE;
    int full = (page->freelist == NULL);

    if (is_minor_gc(mrb) && page->old) {
      /* skip a slot which doesn't contain any young object */
      p = e;
      dead_slot = FALSE;
    }
    while (p<e) {
      if (is_dead(mrb, &p->as.basic)) {
        if (p->as.basic.tt != MRB_TT_FREE) {
          obj_free(mrb, &p->as.basic);
          p->as.free.next = page->freelist;
          page->freelist = (struct RBasic*)p;
          freed++;
        }
      }
      else {
        if (!is_generational(mrb))
          paint_partial_white(mrb, &p->as.basic); /* next gc target */
        dead_slot = 0;
      }
      p++;
    }

    /* free dead slot */
    if (dead_slot && freed < MRB_HEAP_PAGE_SIZE) {
      struct heap_page *next = page->next;

      unlink_heap_page(mrb, page);
      unlink_free_heap_page(mrb, page);
      mrb_free(mrb, page);
      page = next;
    }
    else {
      if (full && freed > 0) {
        link_free_heap_page(mrb, page);
      }
      if (page->freelist == NULL && is_minor_gc(mrb))
        page->old = TRUE;
      else
        page->old = FALSE;
      page = page->next;
    }
    tried_sweep += MRB_HEAP_PAGE_SIZE;
    mrb->live -= freed;
    mrb->gc_live_after_mark -= freed;
  }
  mrb->sweeps = page;
  return tried_sweep;
}
示例#30
0
/*
 *	Read the symbols in an object and register them in the symbol table.
 *	Return -1 if there is an error.
 */
static int loadobj(const char *objname, int ignore_suffix)
{
	static char *currdir;
	static int currdir_len;
	int fp;
	MODULE *mod;
	SYMBOL *undefs[5000];
	SYMBOL *defsym[5000];
	struct obj_file *f;
	struct obj_section *sect;
	struct obj_symbol *objsym;
	int i;
	int is_2_2;
	int ksymtab;
	int len;
	int n_undefs = 0;
	int n_defsym = 0;
	char *p;
	void *image;
	unsigned long m_size;

	p = strrchr(objname, '/');
	len = 1 + (int)(p - objname);

	if ((fp = open(objname, O_RDONLY)) < 0)
		return 1;

	if (!(f = obj_load(fp, ET_REL, objname))) {
		close(fp);
		return -1;
	}
	close(fp);

	/*
	 * Allow arch code to define _GLOBAL_OFFSET_TABLE_
	 */
	arch_create_got(f);

	/*
	 * If we have changed base directory
	 * then use the defined symbols from modules
	 * in the _same_ directory to resolve whatever
	 * undefined symbols there are.
	 *
	 * This strategy ensures that we will have
	 * as correct dependencies as possible,
	 * even if the same symbol is defined by
	 * other modules in other directories.
	 */
	if (currdir_len != len || currdir == NULL ||
	    strncmp(currdir, objname, len) != 0) {
		if (currdir)
			resolve();
		currdir = bb_xstrdup(objname);
		currdir_len = len;
	}

	mod = modules + n_modules++;
	mod->name = bb_xstrdup(objname);

	if ((sect = obj_find_section(f, "__ksymtab")) != NULL)
		ksymtab = sect->idx; /* Only in 2.2 (or at least not 2.0) */
	else
		ksymtab = -1;

	if (sect ||
	    obj_find_section(f, ".modinfo") ||
	    obj_find_symbol(f, "__this_module"))
		is_2_2 = 1;
	else
		is_2_2 = 0;

	for (i = 0; i < HASH_BUCKETS; ++i) {
		for (objsym = f->symtab[i]; objsym; objsym = objsym->next) {
			if (objsym->secidx == SHN_UNDEF) {
				if (ELFW(ST_BIND)(objsym->info) != STB_WEAK &&
				    objsym->r_type /* assumes that R_arch_NONE is always 0 on all arch */) {
					undefs[n_undefs++] = addsym(objsym->name,
								    mod,
								    SYM_UNDEF,
								    ignore_suffix);
				}
				continue;
			}
			/* else */

			if (is_2_2 && ksymtab != -1) {
				/* A 2.2 module using EXPORT_SYMBOL */
				if (objsym->secidx == ksymtab &&
				    ELFW(ST_BIND)(objsym->info) == STB_GLOBAL) {
					/* Ignore leading "__ksymtab_" */
					defsym[n_defsym++] = addsym(objsym->name + 10,
								    mod,
								    SYM_DEFINED,
								    ignore_suffix);
				}
				continue;
			}
			/* else */

			if (is_2_2) {
				/*
				 * A 2.2 module _not_ using EXPORT_SYMBOL
				 * It might still want to export symbols,
				 * although strictly speaking it shouldn't...
				 * (Seen in pcmcia)
				 */
				if (ELFW(ST_BIND)(objsym->info) == STB_GLOBAL) {
					defsym[n_defsym++] = addsym(objsym->name,
								    mod,
								    SYM_DEFINED,
								    ignore_suffix);
				}
				continue;
			}
			/* else */

			/* Not undefined or 2.2 ksymtab entry */
			if (objsym->secidx < SHN_LORESERVE
			/*
			 * The test below is removed for 2.0 compatibility
			 * since some 2.0-modules (correctly) hide the
			 * symbols it exports via register_symtab()
			 */
			/* && ELFW(ST_BIND)(objsym->info) == STB_GLOBAL */
			     ) {
				defsym[n_defsym++] = addsym(objsym->name,
							    mod,
							    SYM_DEFINED,
							    ignore_suffix);
			}
		}
	}

	/*
	 *	Finalize the information about a module.
	 */
	mod->defsym.n_syms = n_defsym;
	if (n_defsym > 0) {
		int size = n_defsym * sizeof(SYMBOL *);

		mod->defsym.symtab = (SYMBOL **)xmalloc(size);
		memcpy(mod->defsym.symtab, defsym, size);
	} else
		mod->defsym.symtab = NULL;

	mod->undefs.n_syms = n_undefs;
	if (n_undefs > 0) {
		int size = n_undefs * sizeof(SYMBOL *);

		mod->undefs.symtab = (SYMBOL **) xmalloc(size);
		memcpy(mod->undefs.symtab, undefs, size);
		mod->resolved = 0;
	} else {
		mod->undefs.symtab = NULL;
		mod->resolved = 1;
	}

	/* Do a pseudo relocation to base address 0x1000 (arbitrary).
	 * All undefined symbols are treated as absolute 0.  This builds
	 * enough of a module to allow extraction of internal data such
	 * as device tables.
	 */
	obj_clear_undefineds(f);
	obj_allocate_commons(f);
	m_size = obj_load_size(f);
	if (!obj_relocate(f, 0x1000)) {
		bb_error_msg("depmod obj_relocate failed\n");
		return(-1);
	}
	extract_generic_string(f, mod);
	image = xmalloc(m_size);
	obj_create_image(f, image);
	free(image);

	obj_free(f);
	return 0;
}