void ZB_resize(ZBuffer *zb, void *frame_buffer, int xsize, int ysize) { int size; // xsize must be a multiple of 4 xsize = xsize & ~3; zb->xsize = xsize; zb->ysize = ysize; zb->linesize = (xsize * zb->pixelbytes + 3) & ~3; size = zb->xsize * zb->ysize * sizeof(unsigned int); gl_free(zb->zbuf); zb->zbuf = (unsigned int *)gl_malloc(size); if (zb->frame_buffer_allocated) zb->pbuf.free(); if (!frame_buffer) { byte *pbuf = (byte *)gl_malloc(zb->ysize * zb->linesize); zb->pbuf.set(zb->cmode, pbuf); zb->frame_buffer_allocated = 1; } else { zb->pbuf = (byte *)frame_buffer; zb->frame_buffer_allocated = 0; } }
void ZB_resize(ZBuffer *zb, void *frame_buffer, int xsize, int ysize) { int size; // xsize must be a multiple of 4 xsize = xsize & ~3; zb->xsize = xsize; zb->ysize = ysize; zb->linesize = (xsize * PSZB + 3) & ~3; size = zb->xsize * zb->ysize * sizeof(unsigned short); gl_free(zb->zbuf); zb->zbuf = (unsigned short *)gl_malloc(size); size = zb->xsize * zb->ysize * sizeof(unsigned int); gl_free(zb->zbuf2); zb->zbuf2 = (unsigned int *)gl_malloc(size); if (zb->frame_buffer_allocated) gl_free(zb->pbuf); if (!frame_buffer) { zb->pbuf = (PIXEL *)gl_malloc(zb->ysize * zb->linesize); zb->frame_buffer_allocated = 1; } else { zb->pbuf = (PIXEL *)frame_buffer; zb->frame_buffer_allocated = 0; } }
FrameBuffer::FrameBuffer(int width, int height, const Graphics::PixelBuffer &frame_buffer) : _depthWrite(true) { int size; this->xsize = width; this->ysize = height; this->cmode = frame_buffer.getFormat(); PSZB = this->pixelbytes = this->cmode.bytesPerPixel; this->pixelbits = this->cmode.bytesPerPixel * 8; this->linesize = (xsize * this->pixelbytes + 3) & ~3; size = this->xsize * this->ysize * sizeof(unsigned int); this->zbuf = (unsigned int *)gl_malloc(size); if (!frame_buffer) { byte *pixelBuffer = (byte *)gl_malloc(this->ysize * this->linesize); this->pbuf.set(this->cmode, pixelBuffer); this->frame_buffer_allocated = 1; } else { this->frame_buffer_allocated = 0; this->pbuf = frame_buffer; } this->current_texture = NULL; this->shadow_mask_buf = NULL; this->buffer.pbuf = this->pbuf.getRawBuffer(); this->buffer.zbuf = this->zbuf; _blendingEnabled = false; _alphaTestEnabled = false; _depthFunc = TGL_LESS; }
void ZB_resize(ZBuffer * zb, void *frame_buffer, int xsize, int ysize) { int size; /* xsize must be a multiple of 4 */ xsize = xsize & ~3; zb->xsize = xsize; zb->ysize = ysize; zb->linesize = (xsize * PSZB + 3) & ~3; size = zb->xsize * zb->ysize * sizeof(unsigned short); gl_free(zb->zbuf); zb->zbuf = gl_malloc(size); if (zb->frame_buffer_allocated) gl_free(zb->pbuf); if (frame_buffer == NULL) { zb->pbuf = gl_malloc(zb->ysize * zb->linesize); zb->frame_buffer_allocated = 1; } else { zb->pbuf = frame_buffer; zb->frame_buffer_allocated = 0; } }
Buffer *ZB_genOffscreenBuffer(ZBuffer *zb) { Buffer *buf = (Buffer *)gl_malloc(sizeof(Buffer)); buf->pbuf = (byte *)gl_malloc(zb->ysize * zb->linesize); int size = zb->xsize * zb->ysize * sizeof(unsigned int); buf->zbuf = (unsigned int *)gl_malloc(size); return buf; }
Buffer *FrameBuffer::genOffscreenBuffer() { Buffer *buf = (Buffer *)gl_malloc(sizeof(Buffer)); buf->pbuf = (byte *)gl_malloc(this->ysize * this->linesize); int size = this->xsize * this->ysize * sizeof(unsigned int); buf->zbuf = (unsigned int *)gl_malloc(size); return buf; }
GLSpecBuf *specbuf_get_buffer(GLContext *c, const int shininess_i, const float shininess) { GLSpecBuf *found, *oldest; found = oldest = c->specbuf_first; while (found && found->shininess_i != shininess_i) { if (found->last_used < oldest->last_used) { oldest = found; } found = found->next; } if (found) { found->last_used = c->specbuf_used_counter++; return found; } if (!oldest || c->specbuf_num_buffers < MAX_SPECULAR_BUFFERS) { // create new buffer GLSpecBuf *buf = (GLSpecBuf *)gl_malloc(sizeof(GLSpecBuf)); if (!buf) error("could not allocate specular buffer"); c->specbuf_num_buffers++; buf->next = c->specbuf_first; c->specbuf_first = buf; buf->last_used = c->specbuf_used_counter++; buf->shininess_i = shininess_i; calc_buf(buf, shininess); return buf; } //overwrite the lru buffer oldest->shininess_i = shininess_i; oldest->last_used = c->specbuf_used_counter++; calc_buf(oldest, shininess); return oldest; }
GLSpecBuf * specbuf_get_buffer(GLContext *c, const int shininess_i, const float shininess) { GLSpecBuf *found, *oldest; found = oldest = c->specbuf_first; while (found && found->shininess_i != shininess_i) { if (found->last_used < oldest->last_used) { oldest = found; } found = found->next; } if (found) { /* hey, found one! */ found->last_used = c->specbuf_used_counter++; return found; } if (oldest == NULL || c->specbuf_num_buffers < MAX_SPECULAR_BUFFERS) { /* create new buffer */ GLSpecBuf *buf = gl_malloc(sizeof(GLSpecBuf)); if (!buf) gl_fatal_error("could not allocate specular buffer"); c->specbuf_num_buffers++; buf->next = c->specbuf_first; c->specbuf_first = buf; buf->last_used = c->specbuf_used_counter++; buf->shininess_i = shininess_i; calc_buf(buf, shininess); return buf; } /* overwrite the lru buffer */ /*tgl_trace("overwriting spec buffer :(\n");*/ oldest->shininess_i = shininess_i; oldest->last_used = c->specbuf_used_counter++; calc_buf(oldest, shininess); return oldest; }
void pe_init (void) { int i, max; struct trans *t; struct ls *n; /* initialize the pe priority queue */ pe.q.size = 0; pe.q.tab = 0; pe.q.skip = 0; /* compute the maximum preset + postset size in the input net */ max = 0; for (n = u.net.trans.next; n; n = n->next) { t = ls_i (struct trans, n, nod); if (max < t->pre.deg + t->cont.deg) max = t->pre.deg + t->cont.deg; } /* initialize the comb with proper sizes */ max += 2; pe.comb.tab = gl_malloc (sizeof (struct comb_entry) * max); for (i = 0; i < max; i++) { pe.comb.tab[i].size = 4096; pe.comb.tab[i].tab = gl_realloc (0, 4096 * sizeof (struct ec*)); } }
/* * ALESSANDRO: copy and paste of ReadCmdToken that sets sbuf to NULL instead of aborting * is something goes wrong. I know this is a terrible practice but I need this done the day * before yesterday =) */ void ReadToken (FILE *file){ register int len = 0; char *string = sbuf; if (!string) sbuf = string = gl_malloc (sballoc = 512); if (!isalnum((int)(*string++ = ReadCharComment(file)))){ sbuf=NULL; return; } len++; while (isalnum((int)(*string = getc(file))) || *string == '_') { string++; len++; if (len >= sballoc) { sbuf = gl_realloc (sbuf,sballoc += 512); string = sbuf + len; } } ungetc(*string, file); *string = '\0'; }
void glopTexImage2D(GLContext *c, GLParam *p) { int target = p[1].i; int level = p[2].i; int components = p[3].i; int width = p[4].i; int height = p[5].i; int border = p[6].i; int format = p[7].i; int type = p[8].i; void *pixels = p[9].p; GLImage *im; unsigned char *pixels1; int do_free; if (!(target == TGL_TEXTURE_2D && level == 0 && components == 3 && border == 0 && format == TGL_RGBA && type == TGL_UNSIGNED_BYTE)) { error("glTexImage2D: combination of parameters not handled"); } do_free = 0; if (width != 256 || height != 256) { pixels1 = (unsigned char *)gl_malloc(256 * 256 * 4); // no interpolation is done here to respect the original image aliasing ! //gl_resizeImageNoInterpolate(pixels1, 256, 256, (unsigned char *)pixels, width, height); // used interpolation anyway, it look much better :) --- aquadran gl_resizeImage(pixels1, 256, 256, (unsigned char *)pixels, width, height); do_free = 1; width = 256; height = 256; } else { pixels1 = (unsigned char *)pixels; } im = &c->current_texture->images[level]; im->xsize = width; im->ysize = height; if (im->pixmap) gl_free(im->pixmap); im->pixmap = gl_malloc(width * height * 3); if (im->pixmap) gl_convertRGB_to_5R6G5B8A((unsigned short *)im->pixmap, pixels1, width, height); if (do_free) gl_free(pixels1); }
/* Create context */ pl110_Context *pl110_CreateContext(){ pl110_Context *ctx; ctx = (pl110_Context*)gl_malloc( sizeof(pl110_Context) ); if( ctx == NULL ){ return NULL; } ctx->gl_context = NULL; return ctx; }
ostgl_context * ostgl_create_context(const int xsize, const int ysize, const int depth, void **framebuffers, const int numbuffers) { ostgl_context *context; int i; ZBuffer *zb; gl_assert(depth == 16); /* support for other depths must include bpp convertion */ gl_assert(numbuffers >= 1); context = gl_malloc(sizeof(ostgl_context)); gl_assert(context); context->zbs = gl_malloc(sizeof(void*)*numbuffers); context->framebuffers = gl_malloc(sizeof(void*)*numbuffers); gl_assert(context->zbs != NULL && context->framebuffers != NULL); for (i = 0; i < numbuffers; i++) { context->framebuffers[i] = framebuffers[i]; zb = ZB_open(xsize, ysize, ZB_MODE_5R6G5B, 0, NULL, NULL, framebuffers[i]); if (zb == NULL) { fprintf(stderr, "Error while initializing Z buffer\n"); exit(1); } context->zbs[i] = zb; } if (++buffercnt == 1) { glInit(context->zbs[0]); } context->xsize = xsize; context->ysize = ysize; context->numbuffers = numbuffers; return context; }
NGLXContext nglXCreateContext(NGLXContext shareList, int flags) { TinyNGLXContext *ctx; if (shareList != NULL) { gl_fatal_error("No sharing available in TinyGL"); } ctx=gl_malloc(sizeof(TinyNGLXContext)); if (!ctx) return NULL; ctx->gl_context=NULL; return (NGLXContext) ctx; }
void ZB_initDither(ZBuffer *zb,int nb_colors, unsigned char *color_indexes,int *color_table) { int c,r,g,b,i,index,r1,g1,b1; if (nb_colors < (_R * _G * _B)) { fprintf(stderr,"zdither: not enough colors\n"); exit(1); } for(i=0;i<nb_colors;i++) color_table[i]=0; zb->nb_colors=nb_colors; zb->ctable=gl_malloc(nb_colors * sizeof(int)); for (r = 0; r < _R; r++) { for (g = 0; g < _G; g++) { for (b = 0; b < _B; b++) { r1=(r*255) / (_R - 1); g1=(g*255) / (_G - 1); b1=(b*255) / (_B - 1); index=DITHER_INDEX(r,g,b); c=(r1 << 16) | (g1 << 8) | b1; zb->ctable[index]=c; color_table[index]=c; } } } zb->dctable=gl_malloc( DITHER_TABLE_SIZE ); for(i=0;i<DITHER_TABLE_SIZE;i++) { r=(i >> 12) & 0x7; g=(i >> 8) & 0xF; b=(i >> 3) & 0x7; index=DITHER_INDEX(r,g,b); zb->dctable[i]=color_indexes[index]; } }
void marking_init (void) { int i; /* initialize the hash table; h.size is the size of the array h.tab; * h.tab is a vector of lists; h.tab[i] is a singly-linked list storing * all the pairs (marking,history) with the same marking */ /* FIXME use prime numbers! */ hash.size = 1 + u.net.numpl * 800; hash.tab = gl_malloc (hash.size * sizeof (struct ls)); for (i = hash.size - 1; i >= 0; i--) ls_init (hash.tab + i); }
void glInit(void *zbuffer1, int textureSize) { FrameBuffer *zbuffer = (FrameBuffer *)zbuffer1; GLContext *c; GLViewport *v; if ((textureSize & (textureSize - 1))) error("glInit: texture size not power of two: %d", textureSize); if (textureSize <= 1 || textureSize > 4096) error("glInit: texture size not allowed: %d", textureSize); c = new GLContext(); gl_ctx = c; c->fb = zbuffer; c->fb->_textureSize = c->_textureSize = textureSize; c->fb->_textureSizeMask = (textureSize - 1) << ZB_POINT_ST_FRAC_BITS; // allocate GLVertex array c->vertex_max = POLYGON_MAX_VERTEX; c->vertex = (GLVertex *)gl_malloc(POLYGON_MAX_VERTEX * sizeof(GLVertex)); // viewport v = &c->viewport; v->xmin = 0; v->ymin = 0; v->xsize = zbuffer->xsize; v->ysize = zbuffer->ysize; v->updated = 1; // shared state initSharedState(c); // lists c->exec_flag = 1; c->compile_flag = 0; c->print_flag = 0; c->in_begin = 0; // lights for (int i = 0; i < T_MAX_LIGHTS; i++) { GLLight *l = &c->lights[i]; l->ambient = Vector4(0, 0, 0, 1); if (i == 0) { l->diffuse = Vector4(1, 1, 1, 1); l->specular = Vector4(1, 1, 1, 1); l->has_specular = true; } else { l->diffuse = Vector4(0, 0, 0, 1); l->specular = Vector4(0, 0, 0, 1); l->has_specular = false; } l->position = Vector4(0, 0, 1, 0); l->spot_direction = Vector3(0, 0, -1); l->spot_exponent = 0; l->spot_cutoff = 180; l->attenuation[0] = 1; l->attenuation[1] = 0; l->attenuation[2] = 0; l->cos_spot_cutoff = -1.0f; l->norm_spot_direction = Vector3(0, 0, -1); l->norm_position = Vector3(0, 0, 1); l->enabled = 0; l->next = NULL; l->prev = NULL; } c->first_light = NULL; c->ambient_light_model = Vector4(0.2f, 0.2f, 0.2f, 1); c->local_light_model = 0; c->lighting_enabled = 0; c->light_model_two_side = 0; // default materials */ for (int i = 0; i < 2; i++) { GLMaterial *m = &c->materials[i]; m->emission = Vector4(0, 0, 0, 1); m->ambient = Vector4(0.2f, 0.2f, 0.2f, 1); m->diffuse = Vector4(0.8f, 0.8f, 0.8f, 1); m->specular = Vector4(0, 0, 0, 1); m->has_specular = false; m->shininess = 0; } c->current_color_material_mode = TGL_FRONT_AND_BACK; c->current_color_material_type = TGL_AMBIENT_AND_DIFFUSE; c->color_material_enabled = 0; // textures glInitTextures(c); // default state c->current_color = Vector4(1.0f, 1.0f, 1.0f, 1.0f); c->longcurrent_color[0] = 65535; c->longcurrent_color[1] = 65535; c->longcurrent_color[2] = 65535; c->longcurrent_color[3] = 65535; c->current_normal = Vector4(1.0f, 0.0f, 0.0f, 0.0f); c->current_edge_flag = 1; c->current_tex_coord = Vector4(0.0f, 0.0f, 0.0f, 1.0f); c->polygon_mode_front = TGL_FILL; c->polygon_mode_back = TGL_FILL; c->current_front_face = 0; // 0 = GL_CCW 1 = GL_CW c->current_cull_face = TGL_BACK; c->current_shade_model = TGL_SMOOTH; c->cull_face_enabled = 0; // clear c->clear_color = Vector4(0.0f, 0.0f, 0.0f, 0.0f); c->clear_depth = 0; // selection c->render_mode = TGL_RENDER; c->select_buffer = NULL; c->name_stack_size = 0; // blending c->fb->enableBlending(false); // alpha test c->fb->enableAlphaTest(false); // matrix c->matrix_mode = 0; c->matrix_stack_depth_max[0] = MAX_MODELVIEW_STACK_DEPTH; c->matrix_stack_depth_max[1] = MAX_PROJECTION_STACK_DEPTH; c->matrix_stack_depth_max[2] = MAX_TEXTURE_STACK_DEPTH; for (int i = 0; i < 3; i++) { c->matrix_stack[i] = (Matrix4 *)gl_zalloc(c->matrix_stack_depth_max[i] * sizeof(Matrix4)); c->matrix_stack_ptr[i] = c->matrix_stack[i]; } tglMatrixMode(TGL_PROJECTION); tglLoadIdentity(); tglMatrixMode(TGL_TEXTURE); tglLoadIdentity(); tglMatrixMode(TGL_MODELVIEW); tglLoadIdentity(); tglBlendFunc(TGL_SRC_ALPHA, TGL_ONE_MINUS_SRC_ALPHA); tglAlphaFunc(TGL_ALWAYS, 0.f); tglDepthFunc(TGL_LESS); c->matrix_model_projection_updated = 1; // opengl 1.1 arrays c->client_states = 0; // opengl 1.1 polygon offset c->offset_states = 0; // shadow mode c->shadow_mode = 0; // clear the resize callback function pointer c->gl_resize_viewport = NULL; // specular buffer c->specbuf_first = NULL; c->specbuf_used_counter = 0; c->specbuf_num_buffers = 0; // depth test c->depth_test = 0; c->color_mask = (1 << 24) | (1 << 16) | (1 << 8) | (1 << 0); const int kDrawCallMemory = 5 * 1024 * 1024; c->_currentAllocatorIndex = 0; c->_drawCallAllocator[0].initialize(kDrawCallMemory); c->_drawCallAllocator[1].initialize(kDrawCallMemory); c->_enableDirtyRectangles = false; Graphics::Internal::tglBlitSetScissorRect(0, 0, c->fb->xsize, c->fb->ysize); }
void glInit(void *zbuffer1) { ZBuffer *zbuffer = (ZBuffer *)zbuffer1; GLContext *c; GLViewport *v; c = (GLContext *)gl_zalloc(sizeof(GLContext)); gl_ctx = c; c->zb = zbuffer; // allocate GLVertex array c->vertex_max = POLYGON_MAX_VERTEX; c->vertex = (GLVertex *)gl_malloc(POLYGON_MAX_VERTEX * sizeof(GLVertex)); // viewport v = &c->viewport; v->xmin = 0; v->ymin = 0; v->xsize = zbuffer->xsize; v->ysize = zbuffer->ysize; v->updated = 1; // shared state initSharedState(c); // lists c->exec_flag = 1; c->compile_flag = 0; c->print_flag = 0; c->in_begin = 0; // lights for (int i = 0; i < T_MAX_LIGHTS; i++) { GLLight *l = &c->lights[i]; l->ambient = gl_V4_New(0, 0, 0, 1); l->diffuse = gl_V4_New(1, 1, 1, 1); l->specular = gl_V4_New(1, 1, 1, 1); l->position = gl_V4_New(0, 0, 1, 0); l->norm_position = gl_V3_New(0, 0, 1); l->spot_direction = gl_V3_New(0, 0, -1); l->norm_spot_direction = gl_V3_New(0, 0, - 1); l->spot_exponent = 0; l->spot_cutoff = 180; l->attenuation[0] = 1; l->attenuation[1] = 0; l->attenuation[2] = 0; l->enabled = 0; } c->first_light = NULL; c->ambient_light_model = gl_V4_New(0.2f, 0.2f, 0.2f, 1); c->local_light_model = 0; c->lighting_enabled = 0; c->light_model_two_side = 0; // default materials */ for (int i = 0; i < 2; i++) { GLMaterial *m = &c->materials[i]; m->emission = gl_V4_New(0, 0, 0, 1); m->ambient = gl_V4_New(0.2f, 0.2f, 0.2f, 1); m->diffuse = (gl_V4_New(0.8f, 0.8f, 0.8f, 1)); m->specular = gl_V4_New(0, 0, 0, 1); m->shininess = 0; } c->current_color_material_mode = TGL_FRONT_AND_BACK; c->current_color_material_type = TGL_AMBIENT_AND_DIFFUSE; c->color_material_enabled = 0; // textures glInitTextures(c); // default state c->current_color.X = 1.0; c->current_color.Y = 1.0; c->current_color.Z = 1.0; c->current_color.W = 1.0; c->longcurrent_color[0] = 65535; c->longcurrent_color[1] = 65535; c->longcurrent_color[2] = 65535; c->current_normal.X = 1.0; c->current_normal.Y = 0.0; c->current_normal.Z = 0.0; c->current_normal.W = 0.0; c->current_edge_flag = 1; c->current_tex_coord.X = 0; c->current_tex_coord.Y = 0; c->current_tex_coord.Z = 0; c->current_tex_coord.W = 1; c->polygon_mode_front = TGL_FILL; c->polygon_mode_back = TGL_FILL; c->current_front_face = 0; // 0 = GL_CCW 1 = GL_CW c->current_cull_face = TGL_BACK; c->current_shade_model = TGL_SMOOTH; c->cull_face_enabled = 0; // clear c->clear_color.v[0] = 0; c->clear_color.v[1] = 0; c->clear_color.v[2] = 0; c->clear_color.v[3] = 0; c->clear_depth = 0; // selection c->render_mode = TGL_RENDER; c->select_buffer = NULL; c->name_stack_size = 0; // matrix c->matrix_mode = 0; c->matrix_stack_depth_max[0] = MAX_MODELVIEW_STACK_DEPTH; c->matrix_stack_depth_max[1] = MAX_PROJECTION_STACK_DEPTH; c->matrix_stack_depth_max[2] = MAX_TEXTURE_STACK_DEPTH; for (int i = 0; i < 3; i++) { c->matrix_stack[i] = (M4 *)gl_zalloc(c->matrix_stack_depth_max[i] * sizeof(M4)); c->matrix_stack_ptr[i] = c->matrix_stack[i]; } tglMatrixMode(TGL_PROJECTION); tglLoadIdentity(); tglMatrixMode(TGL_TEXTURE); tglLoadIdentity(); tglMatrixMode(TGL_MODELVIEW); tglLoadIdentity(); c->matrix_model_projection_updated = 1; // opengl 1.1 arrays c->client_states = 0; // opengl 1.1 polygon offset c->offset_states = 0; // shadow mode c->shadow_mode = 0; // clear the resize callback function pointer c->gl_resize_viewport = NULL; // specular buffer c->specbuf_first = NULL; c->specbuf_used_counter = 0; c->specbuf_num_buffers = 0; // depth test c->depth_test = 0; c->color_mask = (1 << 24) | (1 << 16) | (1 << 8) | (1 << 0); }
/* Object initialization is called once after all object have been created */ int metrics::init(OBJECT *parent) { OBJECT *hdr = OBJECTHDR(this); int index, indexa, indexb, returnval; char work_metrics[1025]; char *startVal, *endVal, *workVal; char workbuffer[1025]; char metricbuffer[257]; FILE *FPVal; FINDLIST *CandidateObjs; OBJECT *temp_obj; bool *temp_bool; FUNCTIONADDR funadd = NULL; //Ensure our "module metrics" object is populated if (module_metrics_obj == NULL) { GL_THROW("Please specify a module metrics object for metrics:%s",hdr->name); /* TROUBLESHOOT To operate properly, the metrics object must have the corresponding module's metrics calculator linked. If this object is missing, metrics has no idea what to calculate and will not proceed. */ } //It's not null, map up the init function and call it (this must exist, even if it does nothing) funadd = (FUNCTIONADDR)(gl_get_function(module_metrics_obj,"init_reliability")); //Make sure it was found if (funadd == NULL) { GL_THROW("Unable to map reliability init function on %s in %s",module_metrics_obj->name,hdr->name); /* TROUBLESHOOT While attempting to initialize the reliability module in the "module of interest" metrics device, a error was encountered. Ensure this object fully supports reliability and try again. If the bug persists, please submit your code and a bug report to the trac website. */ } Extra_Data = ((void *(*)(OBJECT *, OBJECT *))(*funadd))(module_metrics_obj,hdr); //Make sure it worked if (Extra_Data==NULL) { GL_THROW("Unable to map reliability init function on %s in %s",module_metrics_obj->name,hdr->name); //defined above } //Figure out how many indices we should be finding index = 0; while ((metrics_oi[index] != '\0') && (index < 1024)) { if (metrics_oi[index] == ',') { num_indices++; //Increment counter } index++; //Increment pointer } //Make sure we didn't blow the top off if (index == 1024) { GL_THROW("Maximum length exceeded on metrics_of_interest in metrics:%s",hdr->name); /* TROUBLESHOOT While parsing the metrics_of_interest list, the maximum length (1024 characters) was reached. This can cause undesired behavior. Ensure the metrics list is within this character count. If it is, please try again. If the error persists, please submit your code and a bug report via the trac website. */ } //See if at least one was found. If it was, that means there are 2 (it counts commas) if (num_indices >= 1) num_indices++; //See if we were a solitary one - if so, increment accordingly if ((num_indices == 0) && (index > 1)) num_indices = 1; //Make sure at least one was found if (num_indices == 0) { GL_THROW("No indices of interest specified for metrics:%s",hdr->name); /* TROUBLESHOOT No indices were found to read. Please specify the proper indices and try again. */ } //Malloc us up! CalcIndices = (INDEXARRAY*)gl_malloc(num_indices * sizeof(INDEXARRAY)); //Make sure it worked if (CalcIndices == NULL) { GL_THROW("Failure to allocate indices memory in metrics:%s",hdr->name); /* TROUBLESHOOT While allocating the storage matrix for the indices to calculate, an error occurred. Please try again. If the error persists, please submit you code and a bug report using the trac website. */ } //Initialize these, just in case for (index=0; index<num_indices; index++) { CalcIndices[index].MetricLoc = NULL; //No address by default for (indexa=0; indexa<257; indexa++) //+1 due to end \0 CalcIndices[index].MetricName[indexa]='\0'; } //Populate it up - copy it first so we don't destroy the original metrics_oi.copy_to(work_metrics); //Set initial pointers startVal = work_metrics; endVal = work_metrics; //Loop through and find them for (index=0; index<num_indices; index++) //Loop through { //Find the next comma or end point while ((*endVal != ',') && (*endVal != '\0')) { endVal++; } //Replace us (comma) with EOS (\0) *endVal='\0'; //Copy us into the structure workVal = startVal; indexa = 0; while ((workVal<=endVal) && (indexa < 256)) { //Copy the value in CalcIndices[index].MetricName[indexa] = *workVal; //Copy into secondary metricbuffer[indexa] = *workVal; //Increment pointers indexa++; workVal++; } //apply the "_int" portion for the interval search indexb = indexa-1; //Now update pointers appropriately and proceed endVal++; startVal = endVal; //Now try to find this variable CalcIndices[index].MetricLoc = get_metric(module_metrics_obj,CalcIndices[index].MetricName); //Make sure it worked if (CalcIndices[index].MetricLoc == NULL) { GL_THROW("Unable to find metric %s in object %s for metric:%s",CalcIndices[index].MetricName.get_string(),module_metrics_obj->name,hdr->name); /* TROUBLESHOOT While attempting to map out a reliability metric, the desired metric was not found. Please check the variable name and ensure the metric is being published in the module metrics object and try again. If the error persists, please submit your code and a bug report to the trac website. */ } //Get the interval metric - if it exists - and there is room if ((indexb+4) <= 256) { metricbuffer[indexb] = '_'; metricbuffer[(indexb+1)] = 'i'; metricbuffer[(indexb+2)] = 'n'; metricbuffer[(indexb+3)] = 't'; metricbuffer[(indexb+4)] = '\0'; //Try to map it CalcIndices[index].MetricLocInterval = get_metric(module_metrics_obj,metricbuffer); //No NULL check - if it wasn't found, we won't deal with it } }//end metric traversion //Map our reset functions for ease reset_interval_func = (FUNCTIONADDR)(gl_get_function(module_metrics_obj,"reset_interval_metrics")); //Make sure it worked if (reset_interval_func == NULL) { GL_THROW("Failed to map interval reset in metrics object %s for metrics:%s",module_metrics_obj->name,hdr->name); /* TROUBLESHOOT While attempting to map the interval statistics reset function, the metrics object encountered a problem. Please make sure the module metrics object supports a "reset_interval_metrics" function. If so, please try again. If the error persists, please submit your code and a bug report using the trac website. */ } reset_annual_func = (FUNCTIONADDR)(gl_get_function(module_metrics_obj,"reset_annual_metrics")); //Make sure it worked if (reset_annual_func == NULL) { GL_THROW("Failed to map annual reset in metrics object %s for metrics:%s",module_metrics_obj->name,hdr->name); /* TROUBLESHOOT While attempting to map the annual statistics reset function, the metrics object encountered a problem. Please make sure the module metrics object supports a "reset_interval_metrics" function. If so, please try again. If the error persists, please submit your code and a bug report using the trac website. */ } compute_metrics = (FUNCTIONADDR)(gl_get_function(module_metrics_obj,"calc_metrics")); //Make sure it worked if (compute_metrics == NULL) { GL_THROW("Failed to map metric computation function in metrics object %s for metrics:%s",module_metrics_obj->name,hdr->name); /* TROUBLESHOOT While attempting to map the function to compute the desired metrics, the metrics object encountered a problem. Please make sure the module metrics object supports a "calc_metrics" function. If so, please try again. If the error persists, please submit your code and a bug report using the trac website. */ } //Call the resets - interval returnval = ((int (*)(OBJECT *, OBJECT *))(*reset_interval_func))(hdr,module_metrics_obj); if (returnval != 1) //See if it failed { GL_THROW("Failed to reset interval metrics for %s by metrics:%s",module_metrics_obj->name,hdr->name); /* TROUBLESHOOT The metrics object encountered an error while attempting to reset the interval statistics variables. Please try again. If the error persists, submit your code and a bug report via the trac website. */ } //Call the resets - annual returnval = ((int (*)(OBJECT *, OBJECT *))(*reset_annual_func))(hdr,module_metrics_obj); if (returnval != 1) //See if it failed { GL_THROW("Failed to reset annual metrics for %s by metrics:%s",module_metrics_obj->name,hdr->name); /* TROUBLESHOOT The metrics object encountered an error while attempting to reset the annual statistics variables. Please try again. If the error persists, submit your code and a bug report via the trac website. */ } //Convert our calculation interval to a timestamp metric_interval = (TIMESTAMP)metric_interval_dbl; report_interval = (TIMESTAMP)report_interval_dbl; //See if it is a year - flag appropriately if (metric_interval == 31536000) metric_equal_annual = true; //Make sure we have a file name provided if (report_file[0] == '\0') //None specified { GL_THROW("Please specify a proper report file name if you would like an output file from metrics:%s",hdr->name); /* TROUBLESHOOT While attempting to write the report file, an invalid file name was provided. Please provide a valid file name and try again. */ } //Open the file to clear it FPVal = fopen(report_file,"wt"); //Make sure it worked if (FPVal == NULL) { GL_THROW("Unable to create the report file '%s' for metrics:%s",report_file,hdr->name); /* TROUBLESHOOT While attempting to write the metrics output file, an error occurred. Please make sure you have write permissions at that location and try again. If the error persists, please submit your code and a bug report using the trac website. */ } //It must exist - write the typical header nonsense fprintf(FPVal,"Reliability report for %s\n", gl_global_getvar("modelname",workbuffer,(1025*sizeof(char)))); //Find our lucky candidate objects CandidateObjs = gl_find_objects(FL_GROUP,customer_group.get_string()); if (CandidateObjs==NULL) { GL_THROW("Failure to find devices for %s specified as: %s",hdr->name,customer_group.get_string()); /* TROUBLESHOOT While attempting to populate the list of devices to check for reliability metrics, the metrics object failed to find any desired objects. Please make sure the objects exist and try again. If the bug persists, please submit your code using the trac website. */ } //Do a zero-find check as well if (CandidateObjs->hit_count == 0) { GL_THROW("Failure to find devices for %s specified as: %s",hdr->name,customer_group.get_string()); //Defined above } //Pull the count CustomerCount = CandidateObjs->hit_count; //Make us an array! Customers = (CUSTARRAY*)gl_malloc(CustomerCount*sizeof(CUSTARRAY)); //Make sure it worked if (Customers == NULL) { GL_THROW("Failure to allocate customer list memory in metrics:%s",hdr->name); /* TROUBLESHOOT While allocating the memory for the list of customers, GridLAB-D encountered a problem. Please try again. If the error persists, please submit your code and a bug report via the trac website. */ } //Let's populate the beast now! temp_obj = NULL; for (index=0; index<CustomerCount; index++) { //Find the object temp_obj = gl_find_next(CandidateObjs, temp_obj); if (temp_obj == NULL) { GL_THROW("Failed to populate customer list in metrics: %s",hdr->name); /* TROUBLESHOOT While populating the metrics customer list, an object failed to be located. Please try again. If the error persists, please submit your code and a bug report to the trac website. */ } Customers[index].CustomerObj = temp_obj; //Try to find our "outage" indicator and map its address temp_bool = get_outage_flag(temp_obj, "customer_interrupted"); //make sure it found it if (temp_bool == NULL) { GL_THROW("Unable to find interrupted flag for customer object %s in metrics:%s",temp_obj->name,hdr->name); /* TROUBLESHOOT While attempting to link to the 'customer interrupted' flag, an error occurred. Please ensure the object supports being polled by reliability as a customer (customer_interrupted exists as a published property) and try again. If the error persists, please submit your code and a bug report via the trac website. */ } //Write this value in Customers[index].CustInterrupted = temp_bool; if (index == 0) //First customer, handle slightly different { //Populate the secondary index - needs to exist, even if never used //Try to find our secondary "outage" indicator and map its address temp_bool = get_outage_flag(temp_obj, "customer_interrupted_secondary"); //make sure it found it if (temp_bool == NULL) //Not found, assume no one else wants one { gl_warning("Unable to find secondary interruption flag, no secondary interruptions recorded in metrics:%s",hdr->name); /* TROUBLESHOOT While attempting to link to the 'secondary customer interrupted' flag, it was not found. THe object may not support "secondary interruption counts" and this message is valid. If a secondary count was desired, ensure the object supports being polled by reliability as a customer (customer_interrupted_secondary exists as a published property) and try again. If the error persists, please submit your code and a bug report via the trac website. */ } else //One found, assume all want one now { secondary_interruptions_count = true; //Write this value in Customers[index].CustInterrupted_Secondary = temp_bool; } } else if (secondary_interruptions_count == true) //Decided we want it { //Populate the secondary index - needs to exist, even if never used //Try to find our secondary "outage" indicator and map its address temp_bool = get_outage_flag(temp_obj, "customer_interrupted_secondary"); //make sure it found it if (temp_bool == NULL) { GL_THROW("Unable to find secondary interruption flag for customer object %s in metrics:%s",temp_obj->name,hdr->name); /* TROUBLESHOOT While attempting to link to the 'secondary customer interrupted' flag, an error occurred. Please ensure the object supports being polled by reliability as a customer (customer_interrupted_secondary exists as a published property) and try again. If the error persists, please submit your code and a bug report via the trac website. */ } //Write this value in Customers[index].CustInterrupted_Secondary = temp_bool; } //Defaulted else - unwanted }//end population loop //Free up list gl_free(CandidateObjs); //Write the customer count and header information to the file we have going fprintf(FPVal,"Number of customers = %d\n\n",CustomerCount); //See if the particular metrics object has any "comments" to add to the file header (units, notes, etc.) funadd = NULL; //Reset function pointer - just in case //Map up the "extra print" function - if it isn't there, well nothing is done funadd = (FUNCTIONADDR)(gl_get_function(module_metrics_obj,"logfile_extra")); //See if it was found if (funadd != NULL) { //Do the extra printing returnval = ((int (*)(OBJECT *, char *))(*funadd))(module_metrics_obj,workbuffer); //Make sure it worked if (returnval==0) { GL_THROW("Failed to write extra header material for %s in %s",module_metrics_obj->name,hdr->name); /* TROUBLESHOOT While attempting to write the extra material into the file header, an error occurred. Please try again. If the error persists, please submit your code and a bug report via the trac website. */ } //Print it out fprintf(FPVal,"%s",workbuffer); } //Close the file handle fclose(FPVal); return 1; /* return 1 on success, 0 on failure - We're so awesome we always assume we work */ }
ZBuffer *ZB_open(int xsize, int ysize, int mode, int nb_colors, unsigned char *color_indexes, int *color_table, void *frame_buffer) { ZBuffer *zb; int size; zb = gl_malloc(sizeof(ZBuffer)); if (zb == NULL) return NULL; zb->xsize = xsize; zb->ysize = ysize; zb->mode = mode; zb->linesize = (xsize * PSZB + 3) & ~3; switch (mode) { #ifdef TGL_FEATURE_8_BITS case ZB_MODE_INDEX: ZB_initDither(zb, nb_colors, color_indexes, color_table); break; #endif #ifdef TGL_FEATURE_32_BITS case ZB_MODE_RGBA: #endif #ifdef TGL_FEATURE_24_BITS case ZB_MODE_RGB24: #endif case ZB_MODE_5R6G5B: zb->nb_colors = 0; break; default: goto error; } size = zb->xsize * zb->ysize * sizeof(unsigned short); zb->zbuf = gl_malloc(size); if (zb->zbuf == NULL) goto error; if (frame_buffer == NULL) { zb->pbuf = gl_malloc(zb->ysize * zb->linesize); if (zb->pbuf == NULL) { gl_free(zb->zbuf); goto error; } zb->frame_buffer_allocated = 1; } else { zb->frame_buffer_allocated = 0; zb->pbuf = frame_buffer; } zb->current_texture = NULL; return zb; error: gl_free(zb); return NULL; }
static struct event * _pe_comb_new_event (void) { struct trans *t; struct event *e; struct cond *c; int i; t = pe.comb.t; ASSERT (t); ASSERT (t->pre.deg + t->cont.deg == pe.comb.size + 1); /* allocate and initialize the event */ e = gl_malloc (sizeof (struct event)); ls_insert (&u.unf.events, &e->nod); al_init (&e->pre); al_init (&e->post); al_init (&e->cont); al_init (&e->ac); al_init (&e->hist); e->ft = t; ls_insert (&t->events, &e->tnod); e->m = 0; e->id = u.unf.numev++; /* we will update this if we find one history for this event which is * not a cutoff */ e->iscutoff = 1; /* add pe.comb.r->c to either the preset or context of e */ if (pe.comb.ispre) { al_add (&e->pre, pe.comb.r->c); al_add (&pe.comb.r->c->post, e); } else { al_add (&e->cont, pe.comb.r->c); al_add (&pe.comb.r->c->cont, e); } /* set up preset and context */ for (i = 0; i < pe.comb.size; i++) { c = pe.comb.tab[i].tab[pe.comb.tab[i].i]->c; if (pe.comb.tab[i].ispre) { al_add (&e->pre, c); al_add (&c->post, e); } else { al_add (&e->cont, c); al_add (&c->cont, e); } } ASSERT (e->pre.deg == t->pre.deg); ASSERT (e->cont.deg == t->cont.deg); #ifdef CONFIG_DEBUG DPRINT ("+ Event e%d:%s; pre {", e->id, e->ft->name); for (i = e->pre.deg - 1; i >= 0; i--) { c = (struct cond *) e->pre.adj[i]; DPRINT (" c%d:%s", c->id, c->fp->name); } DPRINT ("}; cont {"); for (i = e->cont.deg - 1; i >= 0; i--) { c = (struct cond *) e->cont.adj[i]; DPRINT (" c%d:%s", c->id, c->fp->name); } DPRINT ("}\n"); #endif /* therefore, at this the moment the event has no postset */ return e; }
SCHED_LIST *new_slist(){ SCHED_LIST *l = (SCHED_LIST *)gl_malloc(sizeof(SCHED_LIST)); memset(l, 0, sizeof(SCHED_LIST)); return l; }
void glopVertex(GLContext * c, GLParam * p) { GLVertex *v; int n, i, cnt; gl_assert(c->in_begin != 0); n = c->vertex_n; cnt = c->vertex_cnt; cnt++; c->vertex_cnt = cnt; /* quick fix to avoid crashes on large polygons */ if (n >= c->vertex_max) { GLVertex *newarray; c->vertex_max <<= 1; /* just double size */ newarray = gl_malloc(sizeof(GLVertex) * c->vertex_max); if (!newarray) { gl_fatal_error("unable to allocate GLVertex array.\n"); } memcpy(newarray, c->vertex, n * sizeof(GLVertex)); gl_free(c->vertex); c->vertex = newarray; } /* new vertex entry */ v = &c->vertex[n]; n++; v->coord.X = p[1].f; v->coord.Y = p[2].f; v->coord.Z = p[3].f; v->coord.W = p[4].f; gl_vertex_transform(c, v); /* color */ if (c->lighting_enabled) { gl_shade_vertex(c, v); } else { v->color = c->current_color; } /* tex coords */ if (c->texture_2d_enabled) { if (c->apply_texture_matrix) { gl_M4_MulV4(&v->tex_coord, c->matrix_stack_ptr[2], &c->current_tex_coord); } else { v->tex_coord = c->current_tex_coord; } } /* precompute the mapping to the viewport */ if (v->clip_code == 0) gl_transform_to_viewport(c, v); /* edge flag */ v->edge_flag = c->current_edge_flag; switch (c->begin_type) { case GL_POINTS: gl_draw_point(c, &c->vertex[0]); n = 0; break; case GL_LINES: if (n == 2) { gl_draw_line(c, &c->vertex[0], &c->vertex[1]); n = 0; } break; case GL_LINE_STRIP: case GL_LINE_LOOP: if (n == 1) { c->vertex[2] = c->vertex[0]; } else if (n == 2) { gl_draw_line(c, &c->vertex[0], &c->vertex[1]); c->vertex[0] = c->vertex[1]; n = 1; } break; case GL_TRIANGLES: if (n == 3) { gl_draw_triangle(c, &c->vertex[0], &c->vertex[1], &c->vertex[2]); n = 0; } break; case GL_TRIANGLE_STRIP: if (cnt >= 3) { if (n == 3) n = 0; /* needed to respect triangle orientation */ switch(cnt & 1) { case 0: gl_draw_triangle(c,&c->vertex[2],&c->vertex[1],&c->vertex[0]); break; default: case 1: gl_draw_triangle(c,&c->vertex[0],&c->vertex[1],&c->vertex[2]); break; } } break; case GL_TRIANGLE_FAN: if (n == 3) { gl_draw_triangle(c, &c->vertex[0], &c->vertex[1], &c->vertex[2]); c->vertex[1] = c->vertex[2]; n = 2; } break; case GL_QUADS: if (n == 4) { c->vertex[2].edge_flag = 0; gl_draw_triangle(c, &c->vertex[0], &c->vertex[1], &c->vertex[2]); c->vertex[2].edge_flag = 1; c->vertex[0].edge_flag = 0; gl_draw_triangle(c, &c->vertex[0], &c->vertex[2], &c->vertex[3]); n = 0; } break; case GL_QUAD_STRIP: if (n == 4) { gl_draw_triangle(c, &c->vertex[0], &c->vertex[1], &c->vertex[2]); gl_draw_triangle(c, &c->vertex[1], &c->vertex[3], &c->vertex[2]); for (i = 0; i < 2; i++) c->vertex[i] = c->vertex[i + 2]; n = 2; } break; case GL_POLYGON: break; default: gl_fatal_error("glBegin: type %x not handled\n", c->begin_type); } c->vertex_n = n; }
void marking_add (struct h *h) { struct hash_entry *he, *nhe; struct ls *buckl, *n; int ret; ASSERT (h); ASSERT (h->marking); ASSERT (h->corr != 0); /* histories always initialized as cutoffs */ /* h->corr = 0; return; */ /* add the marking h->marking to the hash table if there is no * other history h' such that h->marking = h'->marking; if such h' * exists, then h is a cutoff; the function returns 1 iff h is a cutoff */ /* determine if the marking h->marking is in the hash table */ ASSERT (marking_hash (h->marking) == h->hash); buckl = hash.tab + h->hash; for (n = buckl->next; n; n = n->next) { he = ls_i (struct hash_entry, n, nod); ret = nl_compare (he->h->marking, h->marking); if (ret == 0) break; } #ifdef CONFIG_MCMILLAN /* if it is the case, and the corresponding history is smaller, * according to the McMillan's order, then it is a cutoff */ if (n && h_cmp (he->h, h) < 0) { #else /* if present in the hash table, then we know h is a cutoff, as we are * sure that the corresponding history is smaller (the ERV order is * total) */ if (n) { // FIXME -- this deosn't work!!! ASSERT (h_cmp (he->h, h) < 0); ASSERT (h_cmp (he->h, h) <= 0); #endif /* deallocate the marking and set history h as a cutoff, whose * corresponding history is he->h */ ASSERT (he); nl_delete (h->marking); h->marking = 0; h->corr = he->h; u.unf.numcutoffs++; return; } /* otherwise, insert h into the table */ h->corr = 0; nhe = gl_malloc (sizeof (struct hash_entry)); nhe->h = h; ls_insert (buckl, &nhe->nod); return; } static void _marking_print (const struct nl *l) { if (! l) return; _marking_print (l->next); PRINT (" %s", ((const struct place*) (l->node))->name); } void marking_print (const struct h *h) { _marking_print (h->marking); }
/** * Object initialization is called once after all object have been created * * @param parent a pointer to this object's parent * @return 1 on success, 0 on error */ int histogram::init(OBJECT *parent) { PROPERTY *prop = NULL; OBJECT *obj = OBJECTHDR(this); char tprop[64], tpart[8]; int e = 0; TAPEFUNCS *tf = 0; tprop[0]=0; tpart[0] = 0; if(parent == NULL) /* better have a group... */ { OBJECT *group_obj = NULL; CLASS *oclass = NULL; if(group[0] == NULL){ gl_error("Histogram has no parent and no group"); return 0; } group_list = gl_find_objects(FL_GROUP,group.get_string()); if(group_list == NULL){ gl_error("Histogram group could not be parsed"); return 0; } if(group_list->hit_count < 1){ gl_error("Histogram group is an empty set"); return 0; } /* non-empty set */ /* parse complex part of property */ test_for_complex(tprop, tpart); while(group_obj = gl_find_next(group_list, group_obj)){ prop = gl_find_property(group_obj->oclass, property.get_string()); if(prop == NULL){ gl_error("Histogram group is unable to find prop '%s' in class '%s' for group '%s'", property.get_string(), group_obj->oclass->name, group.get_string()); return 0; } /* check to see if all the group objects are in the same class, allowing us to cache the target property */ if (oclass == NULL){ oclass = group_obj->oclass; prop_ptr = prop; } if(oclass != group_obj->oclass){ prop_ptr = NULL; } } } else { /* if we have a parent, we only focus on that one object */ test_for_complex(tprop, tpart); prop = gl_find_property(parent->oclass, property.get_string()); if(prop == NULL){ gl_error("Histogram parent '%s' of class '%s' does not contain property '%s'", parent->name ? parent->name : "(anon)", parent->oclass->name, property.get_string()); return 0; } else { prop_ptr = prop; /* saved for later */ } } // initialize first timesteps if(counting_interval > 0.0) next_count = gl_globalclock + counting_interval; if(sampling_interval > 0.0) next_sample = gl_globalclock + sampling_interval; /* * This will create a uniform partition over the specified range */ if((bin_count > 0) && (min < max)) { int i=0; double range = max - min; double step = range/bin_count; //throw("Histogram bin_count is temporarily disabled."); bin_list = (BIN *)gl_malloc(sizeof(BIN) * bin_count); if(bin_list == NULL){ gl_error("Histogram malloc error: unable to alloc %i * %i bytes for %s", bin_count, sizeof(BIN), obj->name ? obj->name : "(anon. histogram)"); return 0; } memset(bin_list, 0, sizeof(BIN) * bin_count); for(i = 0; i < bin_count; i++){ bin_list[i].low_val = min + i * step; bin_list[i].high_val = bin_list[i].low_val + step; bin_list[i].low_inc = 1; bin_list[i].high_inc = 0; } bin_list[i-1].high_inc = 1; /* tail value capture */ binctr = (int *)gl_malloc(sizeof(int) * bin_count); memset(binctr, 0, sizeof(int) * bin_count); } else if (bins[0] != 0) /* * This will parse the bin strings as specified. The valid basic form is "(a..b)". Brackets are optional, [ & ] are inclusive. A dash may replace the '..'. * If a or b is not present, the bin will fill in a positve/negative infinity. */ { char *cptr = bins; char bincpy[1025]; int i = 0; bin_count = 1; /* assume at least one */ /* would be better to count the number of times strtok succeeds, but this should work -mh */ //while(*cptr != 0){ for(cptr = bins; *cptr != 0; ++cptr){ if(*cptr == ',' && cptr[1] != 0){ ++bin_count; } // ++cptr; } bin_list = (BIN *)gl_malloc(sizeof(BIN) * bin_count); if(bin_list == NULL){ gl_error("Histogram malloc error: unable to alloc %i * %i bytes for %s", bin_count, sizeof(BIN), obj->name ? obj->name : "(anon. histogram)"); return 0; } memset(bin_list, 0, sizeof(BIN) * bin_count); memcpy(bincpy, bins, 1024); cptr = strtok(bincpy, ",\t\r\n\0"); if(prop->ptype == PT_complex || prop->ptype == PT_double || prop->ptype == PT_int16 || prop->ptype == PT_int32 || prop->ptype == PT_int64 || prop->ptype == PT_float || prop->ptype == PT_real){ for(i = 0; i < bin_count && cptr != NULL; ++i){ if(parse_bin_val(cptr, bin_list+i) == 0){ gl_error("Histogram unable to parse \'%s\' in %s", cptr, obj->name ? obj->name : "(unnamed histogram)"); return 0; } cptr = strtok(NULL, ",\t\r\n\0"); /* minor efficiency gain to use the incremented pointer from parse_bin */ } } else if (prop->ptype == PT_enumeration || prop->ptype == PT_set){ for(i = 0; i < bin_count && cptr != NULL; ++i){ if(parse_bin_enum(cptr, bin_list+i, prop) == 0){ gl_error("Histogram unable to parse \'%s\' in %s", cptr, obj->name ? obj->name : "(unnamed histogram)"); return 0; } cptr = strtok(NULL, ",\t\r\n\0"); /* minor efficiency gain to use the incremented pointer from parse_bin */ } } if(i < bin_count){ gl_error("Histrogram encountered a problem parsing bins for %s", obj->name ? obj->name : "(unnamed histogram)"); return 0; } binctr = (int *)malloc(sizeof(int) * bin_count); memset(binctr, 0, sizeof(int) * bin_count); } else { gl_error("Histogram has neither bins or a bin range to work with"); return 0; } /* open file ~ copied from recorder.c */ /* if prefix is omitted (no colons found) */ // if (sscanf(filename,"%32[^:]:%1024[^:]:%[^:]",ftype,fname,flags)==1) // { /* filename is file by default */ strcpy(fname,filename); // strcpy(ftype,"file"); // } /* if no filename given */ if (strcmp(fname,"")==0) /* use object name-id as default file name */ sprintf(fname,"%s-%d.%s",obj->parent->oclass->name,obj->parent->id, ftype.get_string()); /* if type is file or file is stdin */ tf = get_ftable(mode); if(tf == NULL) return 0; ops = tf->histogram; /* same mentality as a recorder, 'cept for the header properties */ if(ops == NULL) return 0; return ops->open(this, fname, flags); }
int passive_controller::init(OBJECT *parent){ OBJECT *hdr = OBJECTHDR(this); PROPERTY *enduseProperty; if(parent == NULL){ gl_error("passive_controller has no parent and will be operating in 'dummy' mode"); } else { if(output_state_propname[0] == 0 && output_setpoint_propname[0] == 0){ GL_THROW("passive_controller has no output properties"); } // expectation_addr if(expectation_object != 0){ expectation_property = gl_get_property(expectation_object, expectation_propname); if(expectation_property == 0){ GL_THROW("passive_controller cannot find its expectation property"); } expectation_addr = (void *)((unsigned int64)expectation_object + sizeof(OBJECT) + (unsigned int64)expectation_property->addr); } if(observation_object != 0){ // observation_addr observation_prop = gl_get_property(observation_object, observation_propname); if(observation_prop != 0){ observation_addr = (void *)((unsigned int64)observation_object + sizeof(OBJECT) + (unsigned int64)observation_prop->addr); } if (pool_pump_model == false) { // observation_mean_addr observation_mean_prop = gl_get_property(observation_object, observation_mean_propname); if(observation_mean_prop != 0){ observation_mean_addr = (void *)((unsigned int64)observation_object + sizeof(OBJECT) + (unsigned int64)observation_mean_prop->addr); } // observation_stdev_addr stdev_observation_property = gl_get_property(observation_object, observation_stdev_propname); if(stdev_observation_property != 0){ observation_stdev_addr = (void *)((unsigned int64)observation_object + sizeof(OBJECT) + (unsigned int64)stdev_observation_property->addr); } } } // output_state if(output_state_propname[0] != 0){ output_state_prop = gl_get_property(parent, output_state_propname); if(output_state_prop == NULL){ GL_THROW("passive_controller parent \"%s\" does not contain property \"%s\"", (parent->name ? parent->name : "anon"), output_state_propname.get_string()); } output_state_addr = (void *)((unsigned int64)parent + sizeof(OBJECT) + (unsigned int64)output_state_prop->addr); } // output_setpoint if (control_mode != this->CM_PROBOFF && control_mode != this->CM_ELASTICITY_MODEL) { if(output_setpoint_propname[0] == 0 && output_setpoint_propname[0] == 0){ GL_THROW("passive_controller has no output properties"); } if(output_setpoint_propname[0] != 0){ output_setpoint_property = gl_get_property(parent, output_setpoint_propname); if(output_setpoint_property == NULL){ GL_THROW("passive_controller parent \"%s\" does not contain property \"%s\"", (parent->name ? parent->name : "anon"), output_setpoint_propname.get_string()); } output_setpoint_addr = (void *)((unsigned int64)parent + sizeof(OBJECT) + (unsigned int64)output_setpoint_property->addr); } } } if (pool_pump_model == false && control_mode != CM_ELASTICITY_MODEL) gl_set_dependent(hdr, expectation_object); gl_set_dependent(hdr, observation_object); if(observation_object == NULL){ GL_THROW("passive_controller observation_object object is undefined, and can not function"); } // // make sure that the observation_object and expectable are ranked above the controller // if(base_setpoint != 0.0){ orig_setpoint = 1; } if (pool_pump_model == true) { if (control_mode != CM_DUTYCYCLE) GL_THROW("pool pump mode must be used with control mode set to DUTYCYCLE"); if (firstTierHours == 0 || secondTierHours == 0) GL_THROW("Please set first and second tier hours in pool pump duty cycle mode"); if (firstTierPrice == 0 || secondTierPrice == 0) GL_THROW("Please set first and second tier prices in pool pump duty cycle mode"); } if(dPeriod == 0.0){ dPeriod = 300.0; period = 300; // five minutes } else { period = (TIMESTAMP)floor(dPeriod + 0.5); } if (gl_object_isa(parent,"ZIPload","residential")) { zipLoadParent = true; } if(zipLoadParent == true && control_mode == CM_ELASTICITY_MODEL){ ThirdTierArraySize = 0; SecondTierArraySize = 0; FirstTierArraySize = 0; elasticityPeriod = 24; if(subElasticityFirstSecond > 0) gl_warning("The peak to offpeak Substitution Elasticity is positive. While this is allowed, it is typically the reverse of convention, as an increase in peak to offpeak price ratio generally produces a reduction in peak load to offpeak load. This is indicated by a negative peak to offpeak Substitution Elasticity value."); if(subElasticityFirstThird > 0) gl_warning("The critical peak to offpeak Substitution Elasticity is positive. While this is allowed, it is typically the reverse of convention, as an increase in critical peak to offpeak price ratio generally produces a reduction in peak load to offpeak load. This is indicated by a negative critical peak to offpeak Substitution Elasticity value."); if(dailyElasticity > 0) gl_warning("The Daily Elasticity is positive. While this is allowed, it is typically the reverse of convention, as an increase in daily price generally produces a reduction in daily load. This is indicated by a negative Daily Elasticity value."); if(critical_day >= 0.5){ if (firstTierPrice == 0) GL_THROW("Please set first tier price in the Elasticity Model"); if (oldFirstTierPrice == 0) GL_THROW("Please set old first tier price in the Elasticity Model"); if (thirdTierHours == 0) GL_THROW("Please set third tier hours in the Elasticity Model"); if (thirdTierPrice == 0) GL_THROW("Please set third tier price in the Elasticity Model"); if (oldThirdTierPrice == 0){ oldThirdTierPrice = oldFirstTierPrice; gl_warning("Old third tier price is missing. System will assume the old pricing scheme was a fixed pricing scheme and use the old first tier price"); } if(check_two_tier_cpp != true){ if (secondTierHours == 0) GL_THROW("Please set second tier hours in the Elasticity Model"); if (secondTierPrice == 0) GL_THROW("Please set second tier price in the Elasticity Model"); if (oldSecondTierPrice == 0){ oldSecondTierPrice = oldFirstTierPrice; gl_warning("Old second tier price is missing. System will assume the old pricing scheme was a fixed pricing scheme and use the old first tier price"); } if(firstTierHours == 0){ firstTierHours = elasticityPeriod - thirdTierHours - secondTierHours; } else{ if((thirdTierHours+secondTierHours+firstTierHours) != elasticityPeriod) GL_THROW("Please set the tier hours correctly in the Elasticity Model"); } SecondTierArraySize = (int)(((secondTierHours * 3600) / period)); //Calculation of the price ratios and change in price ratios. //This will not change for the course of the simulation oldPriceRatioSecondFirst = oldSecondTierPrice/oldFirstTierPrice; newPriceRatioSecondFirst = secondTierPrice/firstTierPrice; if(linearizeElasticity == true) { peakPriceMultiplier = pow(newPriceRatioSecondFirst/oldPriceRatioSecondFirst,subElasticityFirstSecond); } else{ peakPriceMultiplier = 1 + ((subElasticityFirstSecond)*(newPriceRatioSecondFirst-oldPriceRatioSecondFirst)/oldPriceRatioSecondFirst); priceDiffSecond = secondTierPrice - oldSecondTierPrice; } } else{ if(firstTierHours == 0){ firstTierHours = elasticityPeriod - thirdTierHours; } else{ if((thirdTierHours+firstTierHours) != elasticityPeriod) GL_THROW("Please set the tier hours correctly in the Elasticity Model"); } } ThirdTierArraySize = (int)(((thirdTierHours * 3600) / period)); //Calculation of the price ratios and change in price ratios. //This will not change for the course of the simulation oldPriceRatioThirdFirst = oldThirdTierPrice/oldFirstTierPrice; newPriceRatioThirdFirst = thirdTierPrice/firstTierPrice; if(linearizeElasticity == true) { criticalPriceMultiplier = pow(newPriceRatioThirdFirst/oldPriceRatioThirdFirst,subElasticityFirstThird); } else{ criticalPriceMultiplier = 1 + ((subElasticityFirstThird)*(newPriceRatioThirdFirst-oldPriceRatioThirdFirst)/oldPriceRatioThirdFirst); priceDiffThird = thirdTierPrice - oldThirdTierPrice; } } else{ if (firstTierPrice == 0) GL_THROW("Please set first tier price in the Elasticity Model"); if (oldFirstTierPrice == 0) GL_THROW("Please set old first tier price in the Elasticity Model"); if(firstTierHours == 0){ firstTierHours = elasticityPeriod - secondTierHours; } else{ if((secondTierHours+firstTierHours) != elasticityPeriod) GL_THROW("Please set the tier hours correctly in the Elasticity Model"); } if (secondTierHours == 0) GL_THROW("Please set second tier hours in the Elasticity Model"); if (secondTierPrice == 0) GL_THROW("Please set second tier price in the Elasticity Model"); if (oldSecondTierPrice == 0){ oldSecondTierPrice = oldFirstTierPrice; gl_warning("Old second tier price is missing. System will assume the old pricing scheme was a fixed pricing scheme and use the old first tier price"); } SecondTierArraySize = (int)(((secondTierHours * 3600) / period)); //Calculation of the price ratios and change in price ratios. //This will not change for the course of the simulation oldPriceRatioSecondFirst = oldSecondTierPrice/oldFirstTierPrice; newPriceRatioSecondFirst = secondTierPrice/firstTierPrice; if(linearizeElasticity == true) { peakPriceMultiplier = pow(newPriceRatioSecondFirst/oldPriceRatioSecondFirst,subElasticityFirstSecond); } else{ peakPriceMultiplier = 1 + ((subElasticityFirstSecond)*(newPriceRatioSecondFirst-oldPriceRatioSecondFirst)/oldPriceRatioSecondFirst); priceDiffSecond = secondTierPrice - oldSecondTierPrice; } } FirstTierArraySize = (int)(((firstTierHours * 3600) / period)); priceDiffFirst = firstTierPrice - oldFirstTierPrice; ArraySize = (int)(((elasticityPeriod * 3600) / period)); if(price_offset==0) price_offset = 10E-6 ; tier_prices = (double *)gl_malloc(ArraySize*sizeof(double)); if (tier_prices == NULL) GL_THROW("Failure to allocate tier_prices array"); cleared_load = (double *)gl_malloc(ArraySize*sizeof(double)); if (cleared_load == NULL) GL_THROW("Failure to allocate cleared_load array"); offPeakLoad = (double *)gl_malloc(FirstTierArraySize*sizeof(double)); if (offPeakLoad == NULL) GL_THROW("Failure to allocate offPeakLoad array"); peakLoad = (double *)gl_malloc(SecondTierArraySize*sizeof(double)); if (peakLoad == NULL) GL_THROW("Failure to allocate peakLoad array"); criticalPeakLoad = (double *)gl_malloc(ThirdTierArraySize*sizeof(double)); if (criticalPeakLoad == NULL) GL_THROW("Failure to allocate criticalPeakLoad array"); //Link up to parent object enduseProperty = gl_get_property(parent,"base_power"); if (enduseProperty == NULL) GL_THROW("Unable to map base power property"); current_load_enduse = (enduse*)GETADDR(parent,enduseProperty); //Initialize the array locations ArrayIndex = 0; ThirdTierArrayIndex = 0; SecondTierArrayIndex = 0; FirstTierArrayIndex = 0; for(int32 i=0; i < ArraySize; i++){ tier_prices[i] = 0; cleared_load[i] = 0; } for(int32 i=0; i < FirstTierArraySize; i++){ offPeakLoad[i] = 0; } for(int32 i=0; i < SecondTierArraySize; i++){ peakLoad[i] = 0; } for(int32 i=0; i < ThirdTierArraySize; i++){ criticalPeakLoad[i] = 0; } } return 1; }
// Initialize a distribution meter, return 1 on success int meter::init(OBJECT *parent) { char temp_buff[128]; if(power_market != 0){ price_prop = gl_get_property(power_market, "current_market.clearing_price"); if(price_prop == 0){ GL_THROW("meter::power_market object \'%s\' does not publish \'current_market.clearing_price\'", (power_market->name ? power_market->name : "(anon)")); } } // Count the number of phases...for use with meter_power_consumption if (meter_power_consumption != complex(0,0)) { no_phases = 0; if (has_phase(PHASE_A)) no_phases += 1; if (has_phase(PHASE_B)) no_phases += 1; if (has_phase(PHASE_C)) no_phases += 1; } check_prices(); last_t = dt = 0; //Update tracking flag //Get server mode variable gl_global_getvar("multirun_mode",temp_buff,sizeof(temp_buff)); //See if we're not in standalone if (strcmp(temp_buff,"STANDALONE")) //strcmp returns a 0 if they are the same { if ((solver_method == SM_NR) && (bustype == SWING)) { meter_NR_servered = true; //Set this flag for later use //Allocate the storage vector prev_voltage_value = (complex *)gl_malloc(3*sizeof(complex)); //Check it if (prev_voltage_value==NULL) { GL_THROW("Failure to allocate memory for voltage tracking array"); /* TROUBLESHOOT While attempting to allocate memory for the voltage tracking array used by the master/slave functionality, an error occurred. Please try again. If the error persists, please submit your code and a bug report via the trac website. */ } //Populate it with zeros for now, just cause - init sets voltages in node prev_voltage_value[0] = complex(0.0,0.0); prev_voltage_value[1] = complex(0.0,0.0); prev_voltage_value[2] = complex(0.0,0.0); } } return node::init(parent); }
void glopTexImage2D(GLContext *c,GLParam *p) { int target=p[1].i; int level=p[2].i; int components=p[3].i; int width=p[4].i; int height=p[5].i; int border=p[6].i; int format=p[7].i; int type=p[8].i; void *pixels=p[9].p; GLImage *im; int do_free; int isRGBA = (format == GL_RGBA); #if 0 if (target == GL_TEXTURE_2D && level == 0 && components == 4 && border == 0 && format == GL_RGBA && type == GL_UNSIGNED_BYTE) { im=&c->current_texture->images[level]; im->xsize=width; im->ysize=height; if (im->pixmap!=NULL) gl_free(im->pixmap); #if TGL_FEATURE_RENDER_BITS == 32 im->pixmap=gl_malloc(width*height*4); if(im->pixmap) { gl_convertRGBA_to_8A8R8G8B(im->pixmap,pixels,width,height); } #elif TGL_FEATURE_RENDER_BITS == 16 im->pixmap=gl_malloc(width*height*2); if(im->pixmap) { gl_convertRGBA_to_5R6G5B(im->pixmap,pixels,width,height); } #else #error 32 or 16 #endif return; } #endif unsigned char *pixels1; if (!(target == GL_TEXTURE_2D && level == 0 && (components == 3 || components == 4) && border == 0 && (format == GL_RGB || format == GL_RGBA ) && type == GL_UNSIGNED_BYTE)) { gl_fatal_error("glTexImage2D: combinaison of parameters not handled"); } do_free=0; if (width != NEWXS || height != NEWYS) { pixels1 = gl_malloc(NEWXS * NEWYS * 3); /* no interpolation is done here to respect the original image aliasing ! */ if(isRGBA) gl_resizeImageNoInterpolate_rgba2rgb(pixels1,NEWXS,NEWYS,pixels,width,height); else gl_resizeImageNoInterpolate(pixels1,NEWXS,NEWYS,pixels,width,height); do_free=1; width=NEWXS; height=NEWYS; } else { pixels1=pixels; } im=&c->current_texture->images[level]; im->xsize=width; im->ysize=height; if (im->pixmap!=NULL) gl_free(im->pixmap); #if TGL_FEATURE_RENDER_BITS == 24 im->pixmap=gl_malloc(width*height*3); if(im->pixmap) { memcpy(im->pixmap,pixels1,width*height*3); } #elif TGL_FEATURE_RENDER_BITS == 32 im->pixmap=gl_malloc(width*height*4); if(im->pixmap) { gl_convertRGB_to_8A8R8G8B(im->pixmap,pixels1,width,height); } #elif TGL_FEATURE_RENDER_BITS == 16 im->pixmap=gl_malloc(width*height*2); if(im->pixmap) { gl_convertRGB_to_5R6G5B(im->pixmap,pixels1,width,height); } #else #error TODO #endif if (do_free) gl_free(pixels1); }