// ---------------------------------------------------------------------------- size_t vertex_buffer_insert( vertex_buffer_t * self, const size_t index, const void * vertices, const size_t vcount, const GLushort * indices, const size_t icount ) { size_t vstart, istart, i; ivec4 item; assert( self ); assert( vertices ); assert( indices ); self->state = FROZEN; // Push back vertices vstart = vector_size( self->vertices ); vertex_buffer_push_back_vertices( self, vertices, vcount ); // Push back indices istart = vector_size( self->indices ); vertex_buffer_push_back_indices( self, indices, icount ); // Update indices within the vertex buffer for( i=0; i<icount; ++i ) { *(GLushort *)(vector_get( self->indices, istart+i )) += vstart; } // Insert item item.x = vstart; item.y = vcount; item.z = istart; item.w = icount; vector_insert( self->items, index, &item ); self->state = DIRTY; return index; }
int main() { // declare and initialize a new vector Vector vector; vector_init(&vector); // fill it up with 150 arbitrary values // this should expand capacity up to 200 int i; for (i = 200; i > -50; i--) { vector_append(&vector, i); } // set a value at an arbitrary index // this will expand and zero-fill the vector to fit vector_set(&vector, 4452, 21312984); // print out an arbitrary value in the vector printf("Heres the value at 27: %d\n", vector_get(&vector, 27)); // we're all done playing with our vector, // so free its underlying data array vector_free(&vector); // so free its underlying data array }
void *hello_packet_thread_ip6(void *ptr){ struct eigrp_proccess *proc; interface *iff; proc = (struct eigrp_proccess *)ptr; //Prepare the hello packet once so we don't have to make it over and over int i; struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_addr.s_addr = inet_addr("224.0.0.10"); packetv4_param *packet = create_empty_packet(OPCODE_HELLO, 0, sin); create_hello_packet(packet,proc); while(proc->running){ for(i=0;i<proc->ifs.size;i++){ iff = vector_get(&proc->ifs,i); //Record packets sent proc->stats.packets_sent[OPCODE_HELLO]++; if(iff->ip4_init && iff->running) send_ip4_packet(packet, iff->socket4); } sleep(proc->hello_interval); } free(packet); return NULL; }
// ---------------------------------------------------------------------------- void vertex_buffer_render_item ( vertex_buffer_t *self, size_t index ) { ivec4 * item = (ivec4 *) vector_get( self->items, index ); assert( self ); assert( index < vector_size( self->items ) ); if( self->indices->size ) { size_t start = item->istart; size_t count = item->icount; glDrawElements( self->mode, count, GL_UNSIGNED_SHORT, (void *)(start*sizeof(GLushort)) ); } else if( self->vertices->size ) { size_t start = item->vstart; size_t count = item->vcount; glDrawArrays( self->mode, start*self->vertices->item_size, count); } }
// ---------------------------------------------------- texture_font_delete --- void texture_font_delete( texture_font_t *self ) { assert( self ); if( self->filename ) { //free( self->filename ); g_free( self->filename ); } size_t i; texture_glyph_t *glyph; for( i=0; i<vector_size( self->glyphs ); ++i) { glyph = *(texture_glyph_t **) vector_get( self->glyphs, i ); texture_glyph_delete( glyph); } vector_delete( self->glyphs ); //free( self ); g_free( self ); }
void cesk_diff_buffer_free(cesk_diff_buffer_t* mem) { if(NULL == mem) return; int i, sz; sz = vector_size(mem->buffer); for(i = mem->converted; i < sz; i ++) { _cesk_diff_node_t* node; node = (_cesk_diff_node_t*)vector_get(mem->buffer, i); if(NULL == node || NULL == node->value) continue; switch(node->type) { case CESK_DIFF_ALLOC: case CESK_DIFF_STORE: cesk_value_decref((cesk_value_t*)node->value); break; case CESK_DIFF_REG: cesk_set_free((cesk_set_t*)node->value); break; } } vector_free(mem->buffer); free(mem); }
END_TEST START_TEST(test_edge) { graph_addEdge(g, n1, n2, 42); mu_assert(vector_get(g->nodes, n1).p != NULL, "Arête 1->2 absente"); mu_assert(((Edge*)vector_get(g->nodes, n1).p)->dest == n2, "Mauvaise destination de l'arête 1->2"); mu_assert(((Edge*)vector_get(g->nodes, n1).p)->weight == 42, "Mauvais poids de l'arête 1->2"); mu_assert(vector_get(g->nodes, n2).p != NULL, "Arête 2->1 absente; le graphe n'est pas orienté, \ il faut des arêtes dans les deux sens"); mu_assert(((Edge*)vector_get(g->nodes, n2).p)->dest == n1, "Mauvaise destination de l'arête 2->1"); mu_assert(((Edge*)vector_get(g->nodes, n2).p)->weight == 42, "Mauvais poids de l'arête 2->1"); }
/* ------------------------------------------------------------------------- */ void texture_font_generate_kerning( TextureFont *self ) { size_t i, j, k, count; FT_Library library; FT_Face face; FT_UInt glyph_index, prev_index; TextureGlyph *glyph, *prev_glyph; FT_Vector kerning; /* Load font */ if( !texture_font_load_face( &library, self->filename, self->size, &face ) ) { return; } /* For each glyph couple combination, check if kerning is necessary */ for( i=0; i<self->glyphs->size; ++i ) { glyph = (TextureGlyph *) vector_get( self->glyphs, i ); /* Remove any old kerning information */ if( glyph->kerning ) { free( glyph->kerning ); glyph->kerning = 0; glyph->kerning_count = 0; } /* Count how many kerning pairs we need */ count = 0; glyph_index = FT_Get_Char_Index( face, glyph->charcode ); for( j=0; j<self->glyphs->size; ++j ) { prev_glyph = (TextureGlyph *) vector_get( self->glyphs, j ); prev_index = FT_Get_Char_Index( face, prev_glyph->charcode ); FT_Get_Kerning( face, prev_index, glyph_index, FT_KERNING_UNFITTED, &kerning ); if( kerning.x != 0.0 ) { count++; } } /* No kerning at all */ if( !count ) { continue; } /* Store kerning pairs */ glyph->kerning = (KerningPair *) malloc( count * sizeof(KerningPair) ); glyph->kerning_count = count; k = 0; for( j=0; j<self->glyphs->size; ++j ) { prev_glyph = (TextureGlyph *) vector_get( self->glyphs, j ); prev_index = FT_Get_Char_Index( face, prev_glyph->charcode ); FT_Get_Kerning( face, prev_index, glyph_index, FT_KERNING_UNFITTED, &kerning ); if( kerning.x != 0.0 ) { glyph->kerning[k].charcode = prev_glyph->charcode; // 64 * 64 because of 26.6 encoding AND the transform matrix used // in texture_font_load_face (hres = 64) glyph->kerning[k].kerning = kerning.x/ (float)(64.0f*64.0f); ++k; } } } FT_Done_Face( face ); FT_Done_FreeType( library ); }
component* menu_selected(menu *menu) { component **res = vector_get(&menu->objs, menu->selected); return *res; }
vector *hash_table_get_bucket(hash_table *t, const char *key) { return vector_get(&t->buckets, hash(key) % vector_size(&t->buckets)); }
int execute_time_travel(command_stream_t stream) { command_t cmd; struct vector *gnodes = make_vector(DEFAULT_STACK_CAPAC); struct vector *running_nodes = make_vector(DEFAULT_STACK_CAPAC); /* Create all nodes and build input/output list */ while ((cmd = read_command_stream(stream)) != NULL) { struct graph_node *node = make_graph_node(cmd); build_input_output_list(node, cmd); vector_push(gnodes, node); } /* Calculate dependencies */ calc_dependencies(gnodes); /* Run initial nodes, then continue to run gnodes with zero dependencies until there are none left */ for (int i = 0; i < gnodes->size; ++i) { struct graph_node *node = vector_get(gnodes, i); if (node->deps == 0) { dispatch_graph_node(node); vector_push(running_nodes, node); } } int last_status = 0; while (running_nodes->size > 0) /* Poll for finished commands in running_nodes */ { for (int i = 0; i < running_nodes->size; ++i) { struct graph_node *node = vector_get(running_nodes, i); int pid = node->pid; int wait_result; /* Don't block for waitpid(); check the next running process immediately */ wait_result = waitpid(pid, &last_status, WNOHANG); if (wait_result > 0) { struct vector *depped_by = node->node_deps; for (int j = 0; j < depped_by->size; ++j) { struct graph_node *dep_node = vector_get(depped_by, j); dep_node->deps--; if (dep_node->deps == 0) { dispatch_graph_node(dep_node); vector_push(running_nodes, dep_node); } } vector_remove(running_nodes, i); --i; last_status = WEXITSTATUS(last_status); } else if (wait_result < 0) ERR("Failed to waitpid() for child\n"); } } /* Cleanup */ for (int i = 0; i < gnodes->size; ++i) free_graph_node(vector_get(gnodes, i)); free_vector(gnodes); free_vector(running_nodes); return last_status; }
extern "C" sgx_status_t sgx_ra_proc_msg2_trusted( sgx_ra_context_t context, const sgx_ra_msg2_t *p_msg2, //(g_b||spid||quote_type|| KDF_ID ||sign_gb_ga||cmac||sig_rl_size||sig_rl) const sgx_target_info_t *p_qe_target, sgx_report_t *p_report, sgx_quote_nonce_t* p_nonce) { sgx_status_t se_ret = SGX_ERROR_UNEXPECTED; //p_msg2[in] p_qe_target[in] p_report[out] p_nonce[out] in EDL file if(vector_size(&g_ra_db) <= context || !p_msg2 || !p_qe_target || !p_report || !p_nonce) return SGX_ERROR_INVALID_PARAMETER; ra_db_item_t* item = NULL; if(0 != vector_get(&g_ra_db, context, reinterpret_cast<void**>(&item)) || item == NULL ) return SGX_ERROR_INVALID_PARAMETER; sgx_ec256_private_t a; memset(&a, 0, sizeof(a)); // Create gb_ga sgx_ec256_public_t gb_ga[2]; sgx_ec256_public_t sp_pubkey; sgx_ec_key_128bit_t smkey = {0}; sgx_ec_key_128bit_t skey = {0}; sgx_ec_key_128bit_t mkey = {0}; sgx_ec_key_128bit_t vkey = {0}; sgx_ra_derive_secret_keys_t ra_key_cb = NULL; memset(&gb_ga[0], 0, sizeof(gb_ga)); sgx_spin_lock(&item->item_lock); //sgx_ra_get_ga must have been called if (item->state != ra_get_gaed) { sgx_spin_unlock(&item->item_lock); return SGX_ERROR_INVALID_STATE; } memcpy(&a, &item->a, sizeof(a)); memcpy(&gb_ga[1], &item->g_a, sizeof(gb_ga[1])); memcpy(&sp_pubkey, &item->sp_pubkey, sizeof(sp_pubkey)); ra_key_cb = DEC_KDF_POINTER(item->derive_key_cb); sgx_spin_unlock(&item->item_lock); memcpy(&gb_ga[0], &p_msg2->g_b, sizeof(gb_ga[0])); sgx_ecc_state_handle_t ecc_state = NULL; // ecc_state need to be freed when exit. se_ret = sgx_ecc256_open_context(&ecc_state); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; return se_ret; } sgx_ec256_dh_shared_t dh_key; memset(&dh_key, 0, sizeof(dh_key)); sgx_ec256_public_t* p_msg2_g_b = const_cast<sgx_ec256_public_t*>(&p_msg2->g_b); se_ret = sgx_ecc256_compute_shared_dhkey(&a, (sgx_ec256_public_t*)p_msg2_g_b, &dh_key, ecc_state); if(SGX_SUCCESS != se_ret) { if (SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; sgx_ecc256_close_context(ecc_state); return se_ret; } // Verify signature of gb_ga uint8_t result; sgx_ec256_signature_t* p_msg2_sign_gb_ga = const_cast<sgx_ec256_signature_t*>(&p_msg2->sign_gb_ga); se_ret = sgx_ecdsa_verify((uint8_t *)&gb_ga, sizeof(gb_ga), &sp_pubkey, p_msg2_sign_gb_ga, &result, ecc_state); if(SGX_SUCCESS != se_ret) { if (SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; sgx_ecc256_close_context(ecc_state); return se_ret; } if(SGX_EC_VALID != result) { sgx_ecc256_close_context(ecc_state); return SGX_ERROR_INVALID_SIGNATURE; } do { if(NULL != ra_key_cb) { se_ret = ra_key_cb(&dh_key, p_msg2->kdf_id, &smkey, &skey, &mkey, &vkey); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret && SGX_ERROR_INVALID_PARAMETER != se_ret && SGX_ERROR_KDF_MISMATCH != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } } else if (p_msg2->kdf_id == 0x0001) { se_ret = derive_key(&dh_key, "SMK", (uint32_t)(sizeof("SMK") -1), &smkey); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } se_ret = derive_key(&dh_key, "SK", (uint32_t)(sizeof("SK") -1), &skey); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } se_ret = derive_key(&dh_key, "MK", (uint32_t)(sizeof("MK") -1), &mkey); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } se_ret = derive_key(&dh_key, "VK", (uint32_t)(sizeof("VK") -1), &vkey); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } } else { se_ret = SGX_ERROR_KDF_MISMATCH; break; } sgx_cmac_128bit_tag_t mac; uint32_t maced_size = offsetof(sgx_ra_msg2_t, mac); se_ret = sgx_rijndael128_cmac_msg(&smkey, (const uint8_t *)p_msg2, maced_size, &mac); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } //Check mac if(0 == consttime_memequal(mac, p_msg2->mac, sizeof(mac))) { se_ret = SGX_ERROR_MAC_MISMATCH; break; } //create a nonce se_ret =sgx_read_rand((uint8_t*)p_nonce, sizeof(sgx_quote_nonce_t)); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } sgx_spin_lock(&item->item_lock); //sgx_ra_get_ga must have been called if (item->state != ra_get_gaed) { se_ret = SGX_ERROR_INVALID_STATE; sgx_spin_unlock(&item->item_lock); break; } memcpy(&item->g_b, &p_msg2->g_b, sizeof(item->g_b)); memcpy(&item->smk_key, smkey, sizeof(item->smk_key)); memcpy(&item->sk_key, skey, sizeof(item->sk_key)); memcpy(&item->mk_key, mkey, sizeof(item->mk_key)); memcpy(&item->vk_key, vkey, sizeof(item->vk_key)); memcpy(&item->qe_target, p_qe_target, sizeof(sgx_target_info_t)); memcpy(&item->quote_nonce, p_nonce, sizeof(sgx_quote_nonce_t)); sgx_report_data_t report_data = {{0}}; se_static_assert(sizeof(sgx_report_data_t)>=sizeof(sgx_sha256_hash_t)); // H = SHA256(ga || gb || VK_CMAC) uint32_t sha256ed_size = offsetof(ra_db_item_t, sp_pubkey); //report_data is 512bits, H is 256bits. The H is in the lower 256 bits of report data while the higher 256 bits are all zeros. se_ret = sgx_sha256_msg((uint8_t *)&item->g_a, sha256ed_size, (sgx_sha256_hash_t *)&report_data); if(SGX_SUCCESS != se_ret) { if (SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; sgx_spin_unlock(&item->item_lock); break; } //REPORTDATA = H se_ret = sgx_create_report(p_qe_target, &report_data, p_report); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; sgx_spin_unlock(&item->item_lock); break; } item->state = ra_proc_msg2ed; sgx_spin_unlock(&item->item_lock); }while(0); memset_s(&dh_key, sizeof(dh_key), 0, sizeof(dh_key)); sgx_ecc256_close_context(ecc_state); memset_s(&a, sizeof(sgx_ec256_private_t),0, sizeof(sgx_ec256_private_t)); memset_s(smkey, sizeof(sgx_ec_key_128bit_t),0, sizeof(sgx_ec_key_128bit_t)); memset_s(skey, sizeof(sgx_ec_key_128bit_t),0, sizeof(sgx_ec_key_128bit_t)); memset_s(mkey, sizeof(sgx_ec_key_128bit_t),0, sizeof(sgx_ec_key_128bit_t)); memset_s(vkey, sizeof(sgx_ec_key_128bit_t),0, sizeof(sgx_ec_key_128bit_t)); return se_ret; }
// TKE interface for isv enclaves sgx_status_t sgx_ra_init_ex( const sgx_ec256_public_t *p_pub_key, int b_pse, sgx_ra_derive_secret_keys_t derive_key_cb, sgx_ra_context_t *p_context) { int valid = 0; sgx_status_t ret = SGX_SUCCESS; sgx_ecc_state_handle_t ecc_state = NULL; // initialize g_kdf_cookie for the first time sgx_ra_init_ex is called. if (unlikely(g_kdf_cookie == 0)) { uintptr_t rand = 0; do { if (SGX_SUCCESS != sgx_read_rand((unsigned char *)&rand, sizeof(rand))) { return SGX_ERROR_UNEXPECTED; } } while (rand == 0); sgx_spin_lock(&g_ra_db_lock); if (g_kdf_cookie == 0) { g_kdf_cookie = rand; memset_s(&rand, sizeof(rand), 0, sizeof(rand)); } sgx_spin_unlock(&g_ra_db_lock); } if(!p_pub_key || !p_context) return SGX_ERROR_INVALID_PARAMETER; if(!sgx_is_within_enclave(p_pub_key, sizeof(sgx_ec256_public_t))) return SGX_ERROR_INVALID_PARAMETER; //derive_key_cb can be NULL if (NULL != derive_key_cb && !sgx_is_within_enclave((const void*)derive_key_cb, 0)) { return SGX_ERROR_INVALID_PARAMETER; } ret = sgx_ecc256_open_context(&ecc_state); if(SGX_SUCCESS != ret) { if(SGX_ERROR_OUT_OF_MEMORY != ret) ret = SGX_ERROR_UNEXPECTED; return ret; } ret = sgx_ecc256_check_point((const sgx_ec256_public_t *)p_pub_key, ecc_state, &valid); if(SGX_SUCCESS != ret) { if(SGX_ERROR_OUT_OF_MEMORY != ret) ret = SGX_ERROR_UNEXPECTED; sgx_ecc256_close_context(ecc_state); return ret; } if(!valid) { sgx_ecc256_close_context(ecc_state); return SGX_ERROR_INVALID_PARAMETER; } sgx_ecc256_close_context(ecc_state); //add new item to g_ra_db ra_db_item_t* new_item = (ra_db_item_t*)malloc(sizeof(ra_db_item_t)); if (!new_item) { return SGX_ERROR_OUT_OF_MEMORY; } memset(new_item,0, sizeof(ra_db_item_t)); memcpy(&new_item->sp_pubkey, p_pub_key, sizeof(new_item->sp_pubkey)); if(b_pse) { //sgx_create_pse_session() must have been called ret = sgx_get_ps_sec_prop(&new_item->ps_sec_prop); if (ret!=SGX_SUCCESS) { SAFE_FREE(new_item); return ret; } } new_item->derive_key_cb = ENC_KDF_POINTER(derive_key_cb); new_item->state = ra_inited; //find first empty slot in g_ra_db int first_empty = -1; ra_db_item_t* item = NULL; sgx_spin_lock(&g_ra_db_lock); uint32_t size = vector_size(&g_ra_db); for (uint32_t i = 0; i < size; i++) { if(0 != vector_get(&g_ra_db, i, reinterpret_cast<void**>(&item))) { sgx_spin_unlock(&g_ra_db_lock); SAFE_FREE(new_item); return SGX_ERROR_UNEXPECTED; } if(item == NULL) { first_empty = i; break; } } //if there is a empty slot, use it if (first_empty >= 0) { errno_t vret = vector_set(&g_ra_db, first_empty, new_item); UNUSED(vret); assert(vret == 0); *p_context = first_empty; } //if there are no empty slots, add a new item to g_ra_db else { if(size >= INT32_MAX) { //overflow sgx_spin_unlock(&g_ra_db_lock); SAFE_FREE(new_item); return SGX_ERROR_OUT_OF_MEMORY; } if(0 != vector_push_back(&g_ra_db, new_item)) { sgx_spin_unlock(&g_ra_db_lock); SAFE_FREE(new_item); return SGX_ERROR_OUT_OF_MEMORY; } *p_context = size; } sgx_spin_unlock(&g_ra_db_lock); return SGX_SUCCESS; }
void minHeapDecreaseKey(int current_index, Heap *heap){ while(current_index > 0 && compare(vector_get(heap_parent(current_index), heap->vector), vector_get(current_index, heap->vector), heap) > 0){ vector_swap(current_index, heap_parent(current_index), heap->vector); current_index = heap_parent(current_index); } }
// ----------------------------------------------- texture_atlas_get_region --- ivec4 texture_atlas_get_region( texture_atlas_t * self, const size_t width, const size_t height ) { int y, best_index; size_t best_height, best_width; ivec3 *node, *prev; ivec4 region = {{0,0,width,height}}; size_t i; assert( self ); best_height = UINT_MAX; best_index = -1; best_width = UINT_MAX; for( i=0; i<self->nodes->size; ++i ) { y = texture_atlas_fit( self, i, width, height ); if( y >= 0 ) { node = (ivec3 *) vector_get( self->nodes, i ); if( ( (y + height) < best_height ) || ( ((y + height) == best_height) && (node->z > 0 && (size_t)node->z < best_width)) ) { best_height = y + height; best_index = i; best_width = node->z; region.x = node->x; region.y = y; } } } if( best_index == -1 ) { region.x = -1; region.y = -1; region.width = 0; region.height = 0; return region; } node = (ivec3 *) malloc( sizeof(ivec3) ); if( node == NULL) { fprintf( stderr, "line %d: No more memory for allocating data\n", __LINE__ ); exit( EXIT_FAILURE ); } node->x = region.x; node->y = region.y + height; node->z = width; vector_insert( self->nodes, best_index, node ); free( node ); for(i = best_index+1; i < self->nodes->size; ++i) { node = (ivec3 *) vector_get( self->nodes, i ); prev = (ivec3 *) vector_get( self->nodes, i-1 ); if (node->x < (prev->x + prev->z) ) { int shrink = prev->x + prev->z - node->x; node->x += shrink; node->z -= shrink; if (node->z <= 0) { vector_erase( self->nodes, i ); --i; } else { break; } } else { break; } } texture_atlas_merge( self ); self->used += width * height; return region; }
/*----------------------[cstr_vector]----------------------------*/ void cstr_vector_delete(vector *v, int index) { cstring *s = vector_get(v, index); cstr_free(s); vector_delete(v, index); }
// alanwu: x, y and radius specifies the search region (square) void OnePass(Vector * blobList, char *image, int x, int y, int radius) { xil_printf("start OnePass\n"); // label for each pixel // unsigned short label [DISPLAY_WIDTH * DISPLAY_HEIGHT]; unsigned short *label = ddr_label; // keep at max 1024 labels int MAX_LABEL = 1024; int equal_label_lookup [MAX_LABEL]; int cur_label = 1; // threshold to mark a white int threshold = 13*16; int n = 0, i = 0, j = 0; int i_start, i_end, j_start, j_end; //for (n = 0; n < DISPLAY_WIDTH * DISPLAY_HEIGHT; n++) for (n = 0; n < DISPLAY_COLUMNS * DISPLAY_ROWS; n++) { label[n] = 0; } for (n = 0; n < MAX_LABEL; n++) { equal_label_lookup[n] = 0; } i_start = clip_width(x - radius); i_end = clip_width(x + radius); j_start = clip_height(y - radius); j_end = clip_height(y + radius); // scan the whole frame for (j = j_start; j < j_end; j++) { for (i = i_start; i < i_end; i++) { // label white pixels if (isWhitePixel(i, j, image, threshold)) { //xil_printf("pixel: %d, %d, %d\n",image[_B(i, j)] >> 2, image[_G(i, j)] >> 2, image[_R(i, j)] >> 2); // ignore corners int smallest_lable = cur_label; if ((i > 0) && (j > 0) && (i < DISPLAY_COLUMNS) && (j < DISPLAY_ROWS)) { // only look at west and north pixels, since these labels are known int west_label = label[label_index(i - 1, j)]; int north_label = label[label_index(i, j - 1)]; // case 1: both west and north labels are present // use west label, and mark west and north label to be equivalent if ((west_label != 0) && (north_label != 0)) { label[label_index(i, j)] = west_label; struct Blob getBlob = vector_get(blobList, west_label - 1); getBlob.count += 1; getBlob.total_x += i; getBlob.total_y += j; vector_set(blobList, west_label - 1, getBlob); if ((equal_label_lookup[west_label] == 0) && (west_label > north_label)) { equal_label_lookup[west_label] = north_label; } } // case 2: only west or north label is present // set current pixel label to that label else if ((west_label == 0) && (north_label != 0)) { label[label_index(i, j)] = north_label; struct Blob getBlob = vector_get(blobList, north_label - 1); getBlob.count += 1; getBlob.total_x += i; getBlob.total_y += j; vector_set(blobList, north_label - 1, getBlob); } else if ((west_label != 0) && (north_label == 0)) { label[label_index(i, j)] = west_label; struct Blob getBlob = vector_get(blobList, west_label - 1); getBlob.count += 1; getBlob.total_x += i; getBlob.total_y += j; vector_set(blobList, west_label - 1, getBlob); } // case 3: add a new label // also create a new blob corresponding to the new label else { label[label_index(i, j)] = cur_label; struct Blob newBlob; newBlob.count = 1; newBlob.total_x = i; newBlob.total_y = j; vector_append(blobList, newBlob); cur_label++; } } } } } xil_printf("for loop 2\n"); // reduce equal labels // scan the equal label lookup table once and reduce the blobs for (i = 0; i < MAX_LABEL; i++ ) { int thisLabel = i; int nextLabel = equal_label_lookup[i]; if (nextLabel != 0) { while (true) { thisLabel = nextLabel; nextLabel = equal_label_lookup[thisLabel]; if (nextLabel == 0) { // find the root equal_label_lookup[i] = thisLabel; // add to the root blob struct Blob rootBlob; struct Blob currentBlob; rootBlob = vector_get(blobList, thisLabel - 1); currentBlob = vector_get(blobList, i - 1); rootBlob.count += currentBlob.count; rootBlob.total_x += currentBlob.total_x; rootBlob.total_y += currentBlob.total_y; vector_set(blobList, thisLabel - 1, rootBlob); // clear the chil blob count currentBlob.count = 0; vector_set(blobList, i - 1, currentBlob); break; } } } } xil_printf("end one pass\n"); /* // only take the blobs that has valid counts List<Blob> final_blob_list = new List<Blob>(); foreach (Blob blob in blob_list) { if (blob.count > 1) { final_blob_list.Add(blob); } }*/ }
int main() { /************************************ * INITIALIZATIONS ************************************/ // Set up Camera VDMA VDMAInit(FrameBuffer); // Set up Compositor unsigned int threshold = 0x0CCC0FFF; CompositorInit(FrameBuffer, DrawBuffer, DisplayBuffer, threshold); // Initialize Buffers FillBuffer(FrameBuffer,0x00ff0000); //black FillBuffer(DrawBuffer,0x0); //black FillBuffer(DisplayBuffer,0x0); //black // Turn on Display Display(DisplayBuffer); /************************************ * MAIN LOOP ************************************/ while(1){ // Capture a Frame // -We are guaranteed a single frame because Microblaze is faster than // 30Hz, so as long as we don't sleep to early, we are guaranteed // VDMA will write a single frame and stop, decreasing the sleep // value more will not make a difference, may cause no frame to be written // -If there is a compositor/VMDA race condition, use VDMAStopAndWait() VDMAStart(); sleep(500000); VDMAStop(); // Run Compositor // -Super slow, need to accelerate CompositorRun(); // LED Detection & Draw on Drawing Buffer // -Currently this appears to give very large unchanging values //unsigned int x = CompositorGetXPos(); //unsigned int y = CompositorGetYPos(); // find the white blobs Vector blobList; vector_init(&blobList); // search region: 80 pix box at the center OnePass(&blobList, (char*) FrameBuffer, 640/2, 480/2, 240); // draw the found blobs int i, avg_x, avg_y, radius; struct Blob blob; for (i = 0; i < blobList.size; i ++){ blob = vector_get(&blobList, i); avg_x = blob.total_x/blob.count; avg_y = blob.total_y/blob.count; radius = sqrt(blob.count)/2; //DrawSqure(avg_x, avg_y, radius, 2, (char*) DrawBuffer, 15, 15, 15); FillColor(avg_x-radius, avg_y-radius, avg_x+radius, avg_y+radius, (char*) DrawBuffer, 0, 0, 15); } } }
// ----------------------------------------------------------- build_buffer --- void build_buffer( void ) { vec2 pen; texture_font_t *font; vec4 black = {{0.0, 0.0, 0.0, 1.0}}; vec4 white = {{1.0, 1.0, 1.0, 1.0}}; vec4 none = {{1.0, 1.0, 1.0, 0.0}}; vec4 color = white; if( p_invert ) { color = black; } markup_t markup = { .family = "Source Sans Pro", .size = 10.0, .bold = 0, .italic = 0, .spacing = p_interval, .gamma = p_gamma, .foreground_color = color, .background_color = none, .underline = 0, .underline_color = color, .overline = 0, .overline_color = color, .strikethrough = 0, .strikethrough_color = color, .font = 0, }; text_buffer_clear( text_buffer ); texture_atlas_t * atlas = font_manager->atlas; texture_atlas_clear( atlas ); if( p_family == VERA) { font = texture_font_new_from_file( atlas, p_size, "fonts/Vera.ttf" ); } else if( p_family == VERA_MONO) { font = texture_font_new_from_file( atlas, p_size, "fonts/VeraMono.ttf" ); } else if( p_family == LUCKIEST_GUY) { font = texture_font_new_from_file( atlas, p_size, "fonts/LuckiestGuy.ttf" ); } else if( p_family == SOURCE_SANS ) { font = texture_font_new_from_file( atlas, p_size, "fonts/SourceSansPro-Regular.ttf" ); } else if( p_family == SOURCE_CODE ) { font = texture_font_new_from_file( atlas, p_size, "fonts/SourceCodePro-Regular.ttf" ); } else if( p_family == OLD_STANDARD ) { font = texture_font_new_from_file( atlas, p_size, "fonts/OldStandard-Regular.ttf" ); } else if( p_family == LOBSTER ) { font = texture_font_new_from_file( atlas, p_size, "fonts/Lobster-Regular.ttf" ); } else { fprintf( stderr, "Error : Unknown family type\n" ); return; } if (!font) return; markup.font = font; font->hinting = p_hinting; font->kerning = p_kerning; font->filtering = 1; float norm = 1.0/(p_primary + 2*p_secondary + 2*p_tertiary); font->lcd_weights[0] = (unsigned char)(p_tertiary*norm*255); font->lcd_weights[1] = (unsigned char)(p_secondary*norm*255); font->lcd_weights[2] = (unsigned char)(p_primary*norm*255); font->lcd_weights[3] = (unsigned char)(p_secondary*norm*255); font->lcd_weights[4] = (unsigned char)(p_tertiary*norm*255); pen.x = 10; pen.y = 600 - font->height - 10; text_buffer_printf( text_buffer, &pen, &markup, text, NULL ); // Post-processing for width and orientation vertex_buffer_t * vbuffer = text_buffer->buffer; size_t i; for( i=0; i < vector_size( vbuffer->items ); ++i ) { ivec4 *item = (ivec4 *) vector_get( vbuffer->items, i); glyph_vertex_t * v0 = /* x0,y0 */ (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+0 ); //glyph_vertex_t * v1 = /* x0,y1 */ // (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+1 ); glyph_vertex_t * v2 = /* x1,y1 */ (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+2 ); glyph_vertex_t * v3 = /* x1,y0 */ (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+3 ); float x0 = v0->x, y0 = v0->y; float x1 = v2->x, y1 = v2->y; v2->x = v3->x = x0 + (x1-x0)*p_width; float dy = fabs(y1-y0); float dx = tan(p_faux_italic/180.0 * M_PI) * dy; v0->x += dx; v0->shift = fmod(v0->shift + dx-(int)(dx),1.0); v3->x += dx; v3->shift = fmod(v3->shift + dx-(int)(dx),1.0); } glBindTexture( GL_TEXTURE_2D, font_manager->atlas->id ); GLenum gl_format = (font_manager->atlas->depth == LCD_FILTERING_OFF) ? GL_RED : GL_RGB; glTexImage2D( GL_TEXTURE_2D, 0, gl_format, font_manager->atlas->width, font_manager->atlas->height, 0, gl_format, GL_UNSIGNED_BYTE, font_manager->atlas->data ); texture_font_delete( font ); } // ------------------------------------------------------------------- quit --- void reset( void ) { p_family = VERA; p_size = 12.0; p_invert = 0; p_kerning = 1; p_hinting = 1; p_lcd_filtering = 1; p_gamma = 1.75; p_interval = 0.0; p_weight = 0.33; p_width = 1.0; p_faux_weight = 0.0; p_faux_italic = 0.0; // FT_LCD_FILTER_LIGHT p_primary = 1.0/3.0; p_secondary = 1.0/3.0; p_tertiary = 0.0/3.0; // FT_LCD_FILTER_DEFAULT // p_primary = 3.0/9.0; // p_secondary = 2.0/9.0; // p_tertiary = 1.0/9.0; build_buffer(); }
// -------------------------------------------------------- console_render --- void console_render( console_t *self ) { int viewport[4]; glGetIntegerv( GL_VIEWPORT, viewport ); size_t i, index; self->pen.x = 0; self->pen.y = viewport[3]; vertex_buffer_clear( console->buffer ); int cursor_x = self->pen.x; int cursor_y = self->pen.y; markup_t markup; // console_t buffer markup = self->markup[MARKUP_FAINT]; self->pen.y -= markup.font->height; for( i=0; i<self->lines->size; ++i ) { wchar_t *text = * (wchar_t **) vector_get( self->lines, i ) ; if( wcslen(text) > 0 ) { console_add_glyph( console, text[0], L'\0', &markup ); for( index=1; index < wcslen(text)-1; ++index ) { console_add_glyph( console, text[index], text[index-1], &markup ); } } self->pen.y -= markup.font->height - markup.font->linegap; self->pen.x = 0; cursor_x = self->pen.x; cursor_y = self->pen.y; } // Prompt markup = self->markup[MARKUP_BOLD]; if( wcslen( self->prompt ) > 0 ) { console_add_glyph( console, self->prompt[0], L'\0', &markup ); for( index=1; index < wcslen(self->prompt); ++index ) { console_add_glyph( console, self->prompt[index], self->prompt[index-1], &markup ); } } cursor_x = (int) self->pen.x; // Input markup = self->markup[MARKUP_NORMAL]; if( wcslen(self->input) > 0 ) { console_add_glyph( console, self->input[0], L'\0', &markup ); if( self->cursor > 0) { cursor_x = (int) self->pen.x; } for( index=1; index < wcslen(self->input); ++index ) { console_add_glyph( console, self->input[index], self->input[index-1], &markup ); if( index < self->cursor ) { cursor_x = (int) self->pen.x; } } } // Cursor (we use the black character (-1) as texture ) texture_glyph_t *glyph = texture_font_get_glyph( markup.font, -1 ); float r = markup.foreground_color.r; float g = markup.foreground_color.g; float b = markup.foreground_color.b; float a = markup.foreground_color.a; int x0 = cursor_x+1; int y0 = cursor_y + markup.font->descender; int x1 = cursor_x+2; int y1 = y0 + markup.font->height - markup.font->linegap; float s0 = glyph->s0; float t0 = glyph->t0; float s1 = glyph->s1; float t1 = glyph->t1; GLuint indices[] = {0,1,2, 0,2,3}; vertex_t vertices[] = { { x0,y0,0, s0,t0, r,g,b,a }, { x0,y1,0, s0,t1, r,g,b,a }, { x1,y1,0, s1,t1, r,g,b,a }, { x1,y0,0, s1,t0, r,g,b,a } }; vertex_buffer_push_back( self->buffer, vertices, 4, indices, 6 ); glEnable( GL_TEXTURE_2D ); glUseProgram( shader ); { glUniform1i( glGetUniformLocation( shader, "texture" ), 0 ); glUniformMatrix4fv( glGetUniformLocation( shader, "model" ), 1, 0, model.data); glUniformMatrix4fv( glGetUniformLocation( shader, "view" ), 1, 0, view.data); glUniformMatrix4fv( glGetUniformLocation( shader, "projection" ), 1, 0, projection.data); vertex_buffer_render( console->buffer, GL_TRIANGLES ); } }
VALUE_TYPE getMinHeapMinimum(Heap *heap){ HeapNode* node = vector_get(0, heap->vector); return node->value; }
int main(int argc, char *argv[]) { vector_t *vector = vector_alloc(data_free_func); if (vector == NULL) { log_error("Failed to alloc vector"); return RET_FAILED; } for (int i = 0; i < TEST_NUM; i ++) { data_t *data = my_malloc(sizeof(data_t)); data->num = i; vector_unshift(vector, data); for (int j = 0; j <= i; j ++) { data_t *unshift = vector_get(vector, j); test(vector_get, i - j, unshift->num); } } for (int i = 0; i < TEST_NUM; i ++) { data_t *data = vector_pop(vector); test(vector_pop, i, data->num); data_free_func(data); } vector_empty(vector); for (int i = 0; i < TEST_NUM; i ++) { data_t *data = my_malloc(sizeof(data_t)); data->num = i; if (i & 0x1) { vector_unshift(vector, data); } else { vector_push_back(vector, data); } } for (int i = 0; i < TEST_NUM / 2; i ++) { data_t *data = vector_shift(vector); test(vector_shift, TEST_NUM - 2 * i - 1, data->num); data_free_func(data); } for (int i = 0; i < TEST_NUM / 2; i ++) { data_t *data = vector_shift(vector); test(vector_shift, 2 * i, data->num); data_free_func(data); } vector_empty(vector); for (int i = 0; i < TEST_NUM; i ++) { data_t *data = my_malloc(sizeof(data_t)); data->num = i; vector_push_back(vector, data); } for (int i = 0; i < vector_size(vector); i ++) { data_t *data = vector_get(vector, i); test(vector_get, i, data->num); } vector_destroy(vector); }
static HeapNode* heap_get(int current_index, Heap* heap){ HeapNode* node = vector_get(current_index, heap->vector); return node; }
int main(int argc, char **argv) { vector_t *v; printf("Calling vector_new()\n"); v = vector_new(); printf("Calling vector_delete()\n"); vector_delete(v); printf("vector_new() again\n"); v = vector_new(); printf("These should all return 0 (vector_get()): "); printf("%d ", vector_get(v, 0)); printf("%d ", vector_get(v, 1)); printf("%d\n", vector_get(v, 2)); printf("Doing a bunch of vector_set()s\n"); vector_set(v, 0, 98); vector_set(v, 11, 15); vector_set(v, 15, -23); vector_set(v, 24, 65); vector_set(v, 500, 3); vector_set(v, 12, -123); vector_set(v, 15, 21); vector_set(v, 25, 43); printf("These should be equal:\n"); printf("98 = %d\n", vector_get(v, 0)); printf("15 = %d\n", vector_get(v, 11)); printf("65 = %d\n", vector_get(v, 24)); printf("-123 = %d\n", vector_get(v, 12)); printf("21 = %d\n", vector_get(v, 15)); printf("43 = %d\n", vector_get(v, 25)); printf("0 = %d\n", vector_get(v, 23)); printf("0 = %d\n", vector_get(v, 1)); printf("0 = %d\n", vector_get(v, 501)); printf("3 = %d\n", vector_get(v, 500)); vector_delete(v); printf("Test complete.\n"); return 0; }
/* the caller is supposed to fill the quote field in emp_msg3 before calling * this function.*/ extern "C" sgx_status_t sgx_ra_get_msg3_trusted( sgx_ra_context_t context, uint32_t quote_size, sgx_report_t* qe_report, sgx_ra_msg3_t *emp_msg3, //(mac||g_a||ps_sec_prop||quote) uint32_t msg3_size) { if(vector_size(&g_ra_db) <= context ||!quote_size || !qe_report || !emp_msg3) return SGX_ERROR_INVALID_PARAMETER; ra_db_item_t* item = NULL; if(0 != vector_get(&g_ra_db, context, reinterpret_cast<void**>(&item)) || item == NULL ) return SGX_ERROR_INVALID_PARAMETER; //check integer overflow of msg3_size and quote_size if (UINTPTR_MAX - reinterpret_cast<uintptr_t>(emp_msg3) < msg3_size || UINT32_MAX - quote_size < sizeof(sgx_ra_msg3_t) || sizeof(sgx_ra_msg3_t) + quote_size != msg3_size) return SGX_ERROR_INVALID_PARAMETER; if (!sgx_is_outside_enclave(emp_msg3, msg3_size)) return SGX_ERROR_INVALID_PARAMETER; // // fence after boundary check // this also stops speculation in case of // branch associated // with sizeof(sgx_ra_msg3_t) + quote_size != msg3_size // mispredicting // sgx_lfence(); sgx_status_t se_ret = SGX_ERROR_UNEXPECTED; //verify qe report se_ret = sgx_verify_report(qe_report); if(se_ret != SGX_SUCCESS) { if (SGX_ERROR_MAC_MISMATCH != se_ret && SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; return se_ret; } sgx_spin_lock(&item->item_lock); //sgx_ra_proc_msg2_trusted must have been called if (item->state != ra_proc_msg2ed) { sgx_spin_unlock(&item->item_lock); return SGX_ERROR_INVALID_STATE; } //verify qe_report attributes and mr_enclave same as quoting enclave if( memcmp( &qe_report->body.attributes, &item->qe_target.attributes, sizeof(sgx_attributes_t)) || memcmp( &qe_report->body.mr_enclave, &item->qe_target.mr_enclave, sizeof(sgx_measurement_t)) ) { sgx_spin_unlock(&item->item_lock); return SGX_ERROR_INVALID_PARAMETER; } sgx_ra_msg3_t msg3_except_quote_in; sgx_cmac_128bit_key_t smk_key; memcpy(&msg3_except_quote_in.g_a, &item->g_a, sizeof(msg3_except_quote_in.g_a)); memcpy(&msg3_except_quote_in.ps_sec_prop, &item->ps_sec_prop, sizeof(msg3_except_quote_in.ps_sec_prop)); memcpy(&smk_key, &item->smk_key, sizeof(smk_key)); sgx_spin_unlock(&item->item_lock); sgx_sha_state_handle_t sha_handle = NULL; sgx_cmac_state_handle_t cmac_handle = NULL; //SHA256(NONCE || emp_quote) sgx_sha256_hash_t hash = {0}; se_ret = sgx_sha256_init(&sha_handle); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; return se_ret; } if (NULL == sha_handle) { return SGX_ERROR_UNEXPECTED; } do { se_ret = sgx_sha256_update((uint8_t *)&item->quote_nonce, sizeof(item->quote_nonce), sha_handle); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } //cmac M := ga || PS_SEC_PROP_DESC(all zero if unused) ||emp_quote sgx_cmac_128bit_tag_t mac; se_ret = sgx_cmac128_init(&smk_key, &cmac_handle); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } if (NULL == cmac_handle) { se_ret = SGX_ERROR_UNEXPECTED; break; } se_ret = sgx_cmac128_update((uint8_t*)&msg3_except_quote_in.g_a, sizeof(msg3_except_quote_in.g_a), cmac_handle); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } se_ret = sgx_cmac128_update((uint8_t*)&msg3_except_quote_in.ps_sec_prop, sizeof(msg3_except_quote_in.ps_sec_prop), cmac_handle); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } // sha256 and cmac quote uint8_t quote_piece[32]; const uint8_t* emp_quote_piecemeal = emp_msg3->quote; uint32_t quote_piece_size = static_cast<uint32_t>(sizeof(quote_piece)); while (emp_quote_piecemeal < emp_msg3->quote + quote_size) { //calculate size of one piece, the size of them are sizeof(quote_piece) except for the last one. if (static_cast<uint32_t>(emp_msg3->quote + quote_size - emp_quote_piecemeal) < quote_piece_size) quote_piece_size = static_cast<uint32_t>(emp_msg3->quote - emp_quote_piecemeal) + quote_size ; memcpy(quote_piece, emp_quote_piecemeal, quote_piece_size); se_ret = sgx_sha256_update(quote_piece, quote_piece_size, sha_handle); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } se_ret = sgx_cmac128_update(quote_piece, quote_piece_size, cmac_handle); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } emp_quote_piecemeal += sizeof(quote_piece); } ERROR_BREAK(se_ret); //get sha256 hash value se_ret = sgx_sha256_get_hash(sha_handle, &hash); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } //get cmac value se_ret = sgx_cmac128_final(cmac_handle, &mac); if (SGX_SUCCESS != se_ret) { if(SGX_ERROR_OUT_OF_MEMORY != se_ret) se_ret = SGX_ERROR_UNEXPECTED; break; } //verify qe_report->body.report_data == SHA256(NONCE || emp_quote) if(0 != memcmp(&qe_report->body.report_data, &hash, sizeof(hash))) { se_ret = SGX_ERROR_MAC_MISMATCH; break; } memcpy(&msg3_except_quote_in.mac, mac, sizeof(mac)); memcpy(emp_msg3, &msg3_except_quote_in, offsetof(sgx_ra_msg3_t, quote)); se_ret = SGX_SUCCESS; }while(0); memset_s(&smk_key, sizeof(smk_key), 0, sizeof(smk_key)); (void)sgx_sha256_close(sha_handle); if(cmac_handle != NULL) sgx_cmac128_close(cmac_handle); return se_ret; }
void refine_bases (void *info, membership_t membership, membership_t comembership, vector *bases, int mode) { uscalar_t i, length; length = vector_length (bases); #ifdef DEBUG fprintf (stderr, "refine bases, num of DNF = %d",length); #endif for (i = 0; i < length; i++) { basis *B; bitvector *a_i; vector *T_i; uscalar_t l, T_i_len, j; bool b; B = (basis *) vector_get (bases, i); /* * extends each unsatisfying assignment by FALSE */ a_i = B->a; l = bitvector_length (a_i); bitvector_resize (a_i, l + 1); bitvector_set (a_i, l, false); if(mode==CDNF_PlusPlus) b = (*comembership) (info, a_i) == true ? false : true; else b=false; bitvector_set (a_i, l, b); #ifdef DEBUG fprintf (stderr, "extends basis: "); bitvector_print (a_i); #endif #ifdef DEBUG fprintf (stderr, "extends support: "); #endif T_i = B->T; T_i_len = vector_length (T_i); /* except the last basis, all bases have at least one support */ assert (i == length - 1 || T_i_len > 0); for (j = 0; j < T_i_len; j++) { bitvector *v; bool c; /* * extends v to v+b if MEM (v+b) = YES * to v+!b if MEM (v+b) = NO */ v = (bitvector *)vector_get (T_i, j); assert (bitvector_length (v) == l); bitvector_resize (v, l + 1); bitvector_set (v, l, b); c = (*membership) (info, v) == true ? b : !b; if (c != b) bitvector_set (v, l, c); #ifdef DEBUG bitvector_print (v); #endif } /* clean up disjunction for the current basis */ cdnfformula_disjunction_free (B->H); B->H = NULL; /* remove the last basis if it has no support */ if (T_i_len == 0) { assert (i == length - 1); bitvector_free (a_i); vector_free (T_i); free (vector_get (bases, length - 1)); vector_resize (bases, length - 1); } } /* * reconstruct disjunctions for the bases */ rebuild_disjunctions (bases); }
// ------------------------------------------------------------------- main --- int main( int argc, char **argv ) { FILE* test; size_t i, j; int arg; char * font_cache = " !\"#$%&'()*+,-./0123456789:;<=>?" "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_" "`abcdefghijklmnopqrstuvwxyz{|}~"; float font_size = 0.0; const char * font_filename = NULL; const char * header_filename = NULL; const char * variable_name = "font"; int show_help = 0; size_t texture_width = 128; for ( arg = 1; arg < argc; ++arg ) { if ( 0 == strcmp( "--font", argv[arg] ) || 0 == strcmp( "-f", argv[arg] ) ) { ++arg; if ( font_filename ) { fprintf( stderr, "Multiple --font parameters.\n" ); print_help(); exit( 1 ); } if ( arg >= argc ) { fprintf( stderr, "No font file given.\n" ); print_help(); exit( 1 ); } font_filename = argv[arg]; continue; } if ( 0 == strcmp( "--header", argv[arg] ) || 0 == strcmp( "-o", argv[arg] ) ) { ++arg; if ( header_filename ) { fprintf( stderr, "Multiple --header parameters.\n" ); print_help(); exit( 1 ); } if ( arg >= argc ) { fprintf( stderr, "No header file given.\n" ); print_help(); exit( 1 ); } header_filename = argv[arg]; continue; } if ( 0 == strcmp( "--help", argv[arg] ) || 0 == strcmp( "-h", argv[arg] ) ) { show_help = 1; break; } if ( 0 == strcmp( "--size", argv[arg] ) || 0 == strcmp( "-s", argv[arg] ) ) { ++arg; if ( 0.0 != font_size ) { fprintf( stderr, "Multiple --size parameters.\n" ); print_help(); exit( 1 ); } if ( arg >= argc ) { fprintf( stderr, "No font size given.\n" ); print_help(); exit( 1 ); } errno = 0; font_size = atof( argv[arg] ); if ( errno ) { fprintf( stderr, "No valid font size given.\n" ); print_help(); exit( 1 ); } continue; } if ( 0 == strcmp( "--variable", argv[arg] ) || 0 == strcmp( "-arg", argv[arg] ) ) { ++arg; if ( 0 != strcmp( "font", variable_name ) ) { fprintf( stderr, "Multiple --variable parameters.\n" ); print_help(); exit( 1 ); } if ( arg >= argc ) { fprintf( stderr, "No variable name given.\n" ); print_help(); exit( 1 ); } variable_name = argv[arg]; continue; } if ( 0 == strcmp( "--texture", argv[arg] ) || 0 == strcmp( "-t", argv[arg] ) ) { ++arg; if ( 128.0 != texture_width ) { fprintf( stderr, "Multiple --texture parameters.\n" ); print_help(); exit( 1 ); } if ( arg >= argc ) { fprintf( stderr, "No texture size given.\n" ); print_help(); exit( 1 ); } errno = 0; texture_width = atof( argv[arg] ); if ( errno ) { fprintf( stderr, "No valid texture size given.\n" ); print_help(); exit( 1 ); } continue; } fprintf( stderr, "Unknown parameter %s\n", argv[arg] ); print_help(); exit( 1 ); } if ( show_help ) { print_help(); exit( 1 ); } if ( !font_filename ) { fprintf( stderr, "No font file given.\n" ); print_help(); exit( 1 ); } if ( !( test = fopen( font_filename, "r" ) ) ) { fprintf( stderr, "Font file \"%s\" does not exist.\n", font_filename ); } fclose( test ); if ( 4.0 > font_size ) { fprintf( stderr, "Font size too small, expected at least 4 pt.\n" ); print_help(); exit( 1 ); } if ( !header_filename ) { fprintf( stderr, "No header file given.\n" ); print_help(); exit( 1 ); } texture_atlas_t * atlas = texture_atlas_new( texture_width, texture_width, 1 ); texture_font_t * font = texture_font_new_from_file( atlas, font_size, font_filename ); size_t missed = texture_font_load_glyphs( font, font_cache ); printf( "Font filename : %s\n" "Font size : %.1f\n" "Number of glyphs : %ld\n" "Number of missed glyphs : %ld\n" "Texture size : %ldx%ldx%ld\n" "Texture occupancy : %.2f%%\n" "\n" "Header filename : %s\n" "Variable name : %s\n", font_filename, font_size, strlen(font_cache), missed, atlas->width, atlas->height, atlas->depth, 100.0 * atlas->used / (float)(atlas->width * atlas->height), header_filename, variable_name ); size_t texture_size = atlas->width * atlas->height *atlas->depth; size_t glyph_count = font->glyphs->size; size_t max_kerning_count = 1; for( i=0; i < glyph_count; ++i ) { texture_glyph_t *glyph = *(texture_glyph_t **) vector_get( font->glyphs, i ); if( vector_size(glyph->kerning) > max_kerning_count ) { max_kerning_count = vector_size(glyph->kerning); } } FILE *file = fopen( header_filename, "w" ); // ------------- // Header // ------------- fprintf( file, "/* ============================================================================\n" " * Freetype GL - A C OpenGL Freetype engine\n" " * Platform: Any\n" " * WWW: https://github.com/rougier/freetype-gl\n" " * ----------------------------------------------------------------------------\n" " * Copyright 2011,2012 Nicolas P. Rougier. All rights reserved.\n" " *\n" " * Redistribution and use in source and binary forms, with or without\n" " * modification, are permitted provided that the following conditions are met:\n" " *\n" " * 1. Redistributions of source code must retain the above copyright notice,\n" " * this list of conditions and the following disclaimer.\n" " *\n" " * 2. Redistributions in binary form must reproduce the above copyright\n" " * notice, this list of conditions and the following disclaimer in the\n" " * documentation and/or other materials provided with the distribution.\n" " *\n" " * THIS SOFTWARE IS PROVIDED BY NICOLAS P. ROUGIER ''AS IS'' AND ANY EXPRESS OR\n" " * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n" " * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n" " * EVENT SHALL NICOLAS P. ROUGIER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n" " * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n" " * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n" " * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n" " * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" " * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n" " * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" " *\n" " * The views and conclusions contained in the software and documentation are\n" " * those of the authors and should not be interpreted as representing official\n" " * policies, either expressed or implied, of Nicolas P. Rougier.\n" " * ============================================================================\n" " */\n"); // ---------------------- // Structure declarations // ---------------------- fprintf( file, "#include <stddef.h>\n" "#include <stdint.h>\n" "#ifdef __cplusplus\n" "extern \"C\" {\n" "#endif\n" "\n" "typedef struct\n" "{\n" " uint32_t codepoint;\n" " float kerning;\n" "} kerning_t;\n\n" ); fprintf( file, "typedef struct\n" "{\n" " uint32_t codepoint;\n" " int width, height;\n" " int offset_x, offset_y;\n" " float advance_x, advance_y;\n" " float s0, t0, s1, t1;\n" " size_t kerning_count;\n" " kerning_t kerning[%zu];\n" "} texture_glyph_t;\n\n", max_kerning_count ); fprintf( file, "typedef struct\n" "{\n" " size_t tex_width;\n" " size_t tex_height;\n" " size_t tex_depth;\n" " char tex_data[%zu];\n" " float size;\n" " float height;\n" " float linegap;\n" " float ascender;\n" " float descender;\n" " size_t glyphs_count;\n" " texture_glyph_t glyphs[%zu];\n" "} texture_font_t;\n\n", texture_size, glyph_count ); fprintf( file, "texture_font_t %s = {\n", variable_name ); // ------------ // Texture data // ------------ fprintf( file, " %zu, %zu, %zu, \n", atlas->width, atlas->height, atlas->depth ); fprintf( file, " {" ); for( i=0; i < texture_size; i+= 32 ) { for( j=0; j < 32 && (j+i) < texture_size ; ++ j) { if( (j+i) < (texture_size-1) ) { fprintf( file, "%d,", atlas->data[i+j] ); } else { fprintf( file, "%d", atlas->data[i+j] ); } } if( (j+i) < texture_size ) { fprintf( file, "\n " ); } } fprintf( file, "}, \n" ); // ------------------- // Texture information // ------------------- fprintf( file, " %ff, %ff, %ff, %ff, %ff, %zu, \n", font->size, font->height, font->linegap,font->ascender, font->descender, glyph_count ); // -------------- // Texture glyphs // -------------- fprintf( file, " {\n" ); for( i=0; i < glyph_count; ++i ) { texture_glyph_t * glyph = *(texture_glyph_t **) vector_get( font->glyphs, i ); /* // Debugging information printf( "glyph : '%lc'\n", glyph->codepoint ); printf( " size : %dx%d\n", glyph->width, glyph->height ); printf( " offset : %+d%+d\n", glyph->offset_x, glyph->offset_y ); printf( " advance : %ff, %ff\n", glyph->advance_x, glyph->advance_y ); printf( " tex coords.: %ff, %ff, %ff, %ff\n", glyph->u0, glyph->v0, glyph->u1, glyph->v1 ); printf( " kerning : " ); if( glyph->kerning_count ) { for( j=0; j < glyph->kerning_count; ++j ) { printf( "('%lc', %ff)", glyph->kerning[j].codepoint, glyph->kerning[j].kerning ); if( j < (glyph->kerning_count-1) ) { printf( ", " ); } } } else { printf( "None" ); } printf( "\n\n" ); */ // TextureFont fprintf( file, " {%u, ", glyph->codepoint ); fprintf( file, "%zu, %zu, ", glyph->width, glyph->height ); fprintf( file, "%d, %d, ", glyph->offset_x, glyph->offset_y ); fprintf( file, "%ff, %ff, ", glyph->advance_x, glyph->advance_y ); fprintf( file, "%ff, %ff, %ff, %ff, ", glyph->s0, glyph->t0, glyph->s1, glyph->t1 ); fprintf( file, "%zu, ", vector_size(glyph->kerning) ); if (vector_size(glyph->kerning) == 0) { fprintf( file, "0" ); } else { fprintf( file, "{ " ); for( j=0; j < vector_size(glyph->kerning); ++j ) { kerning_t *kerning = (kerning_t *) vector_get( glyph->kerning, j); fprintf( file, "{%u, %ff}", kerning->codepoint, kerning->kerning ); if( j < (vector_size(glyph->kerning)-1)) { fprintf( file, ", " ); } } fprintf( file, "}" ); } fprintf( file, " },\n" ); } fprintf( file, " }\n};\n" ); fprintf( file, "#ifdef __cplusplus\n" "}\n" "#endif\n" ); return 0; }
boolformula_t *learn_core (void *info, uscalar_t num_vars, membership_t membership, membership_t comembership, equivalence_t equivalence, int mode) { equivalence_result_t *eq_result; conjunction *conjecture; vector *bases; bases = vector_new (0); conjecture = get_conjecture (bases); boolformula_t* b_conjecture = cdnfformula_to_boolformula (conjecture); vector_free (conjecture); eq_result = (*equivalence) (info, num_vars, boolformula_copy (b_conjecture)); if (eq_result->is_equal) { //fprintf(stderr,"Number of Variables Used : %d\n", (unsigned int)num_vars); free(eq_result); return b_conjecture; } else { boolformula_free(b_conjecture); } #ifdef DEBUG fprintf (stderr, "add first basis with "); bitvector_print (eq_result->counterexample); #endif assert (bitvector_length (eq_result->counterexample) == num_vars + 1); add_basis (bases, eq_result->counterexample); bitvector_free (eq_result->counterexample); free(eq_result); while (true) { vector *I; bitvector *v; uscalar_t j, length; conjecture = get_conjecture (bases); #ifdef DEBUG fprintf (stderr, "new conjecture = "); boolformula_print (conjecture); #endif boolformula_t* b_conjecture = cdnfformula_to_boolformula (conjecture); vector_free (conjecture); eq_result = (*equivalence) (info, num_vars, boolformula_copy (b_conjecture)); if (eq_result->is_equal) { //fprintf(stderr,"Number of Variables Used : %d\n", (unsigned int)num_vars); cleanup (bases); free (eq_result); return b_conjecture; } else { boolformula_free(b_conjecture); } /* H_i's are still in bases, only free the conjunction */ assert (bitvector_length (eq_result->counterexample) == num_vars + 1); v = eq_result->counterexample; I = get_indices_to_modify (bases, v); if (vector_length (I) == 0) { if(mode==CDNF_Plus3 && (*membership)(info,v)==true) { #ifdef DEBUG fprintf (stderr, "conflict detected on: "); bitvector_print (v); fprintf (stderr, "num of variables: %d \n",num_vars); #endif refine_bases(info, membership,comembership,bases,mode); num_vars++; } else { #ifdef DEBUG fprintf (stderr, "add basis: "); bitvector_print (v); #endif add_basis (bases, v); } bitvector_free (v); free(eq_result); vector_free (I); continue; } free(eq_result); #ifdef DEBUG fprintf (stderr, "fix m_dnf with "); bitvector_print (v); #endif length = vector_length (I); for (j = 0; j < length; j++) { uscalar_t i; basis *B; bitvector *a_i, *v_i, *xor; vector *T_i; disjunction *H_i; monomial *m; i = (uscalar_t) vector_get (I, j); B = (basis *) vector_get (bases, i); a_i = B->a; T_i = B->T; H_i = B->H; v_i = bitvector_copy (v); walk (info, membership, v_i, a_i); xor = bitvector_xor (v_i, a_i); /* when xor == 0, a conflict has occurred. */ /* assert (!bitvector_is_zeros (xor)); */ if (bitvector_is_zeros (xor)) { #ifdef DEBUG fprintf (stderr, "conflict with the basis "); bitvector_print (a_i); #endif bitvector_free (xor); bitvector_free (v_i); if(mode==CDNF_PlusPlus||mode==CDNF_Plus3) { /* increase the number of variables */ #ifdef DEBUG fprintf (stderr, "num of variables: %d \n",num_vars); #endif refine_bases (info, membership, comembership, bases,mode); num_vars++; } else { bitvector_free (v); vector_free (I); return NULL; } break; } #ifdef DEBUG fprintf (stderr, "add support "); bitvector_print (v_i); #endif /* store v_i in T_i */ /* note that the original CDNF algorithm stores xor in S_i */ vector_add (T_i, v_i); /* compute M_DNF (v_i + a_i) */ m = cdnfformula_monomial_M_DNF (xor); /* compute m (x ^ a_i) */ m = compute_m_of_x_xor_a (m, a_i); vector_add (H_i, m); bitvector_free (xor); } bitvector_free (v); vector_free (I); } }
// ------------------------------------------------- texture_font_get_glyph --- texture_glyph_t * texture_font_get_glyph( texture_font_t * self, wchar_t charcode ) { assert( self ); size_t i; static wchar_t *buffer = 0; texture_glyph_t *glyph; assert( self ); assert( self->filename ); assert( self->atlas ); /* Check if charcode has been already loaded */ for( i=0; i<self->glyphs->size; ++i ) { glyph = *(texture_glyph_t **) vector_get( self->glyphs, i ); if( (glyph->charcode == charcode) && (glyph->outline_type == self->outline_type) && (glyph->outline_thickness == self->outline_thickness) ) { return glyph; } } /* charcode -1 is special : it is used for line drawing (overline, * underline, strikethrough) and background. */ if( charcode == (wchar_t)(-1) ) { size_t width = self->atlas->width; size_t height = self->atlas->height; ivec4 region = texture_atlas_get_region( self->atlas, 5, 5 ); texture_glyph_t * glyph = texture_glyph_new( ); static unsigned char data[4*4*3] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; if ( region.x < 0 ) { // fprintf( stderr, "Texture atlas is full (line %d)\n", __LINE__ ); return NULL; } #ifndef RENDERSTRING texture_atlas_set_region( self->atlas, region.x, region.y, 4, 4, data, 0 ); #else data[0]=0; #endif glyph->charcode = (wchar_t)(-1); glyph->s0 = (region.x+2)/(float)width; glyph->t0 = (region.y+2)/(float)height; glyph->s1 = (region.x+3)/(float)width; glyph->t1 = (region.y+3)/(float)height; vector_push_back( self->glyphs, &glyph ); return glyph; //*(texture_glyph_t **) vector_back( self->glyphs ); } /* Glyph has not been already loaded */ if( !buffer) { buffer = (wchar_t *) calloc( 2, sizeof(wchar_t) ); } buffer[0] = charcode; if( texture_font_load_glyphs( self, buffer ) == 0 ) { return *(texture_glyph_t **) vector_back( self->glyphs ); } return NULL; }
// ----------------------------------------------------------- build_buffer --- void build_buffer( void ) { vec2 pen; texture_font_t *font; vec4 black = {{0.0, 0.0, 0.0, 1.0}}; vec4 white = {{1.0, 1.0, 1.0, 1.0}}; vec4 none = {{1.0, 1.0, 1.0, 0.0}}; vec4 color = white; if( p_invert ) { color = black; } markup_t markup = { .family = "Source Sans Pro", .size = 10.0, .bold = 0, .italic = 0, .rise = 0.0, .spacing = p_interval, .gamma = p_gamma, .foreground_color = color, .background_color = none, .underline = 0, .underline_color = color, .overline = 0, .overline_color = color, .strikethrough = 0, .strikethrough_color = color, .font = 0, }; text_buffer_clear( buffer ); texture_atlas_t * atlas = buffer->manager->atlas; texture_atlas_clear( atlas ); if( p_family == VERA) { font = texture_font_new_from_file( atlas, p_size, "fonts/Vera.ttf" ); } else if( p_family == VERA_MONO) { font = texture_font_new_from_file( atlas, p_size, "fonts/VeraMono.ttf" ); } else if( p_family == LUCKIEST_GUY) { font = texture_font_new_from_file( atlas, p_size, "fonts/LuckiestGuy.ttf" ); } else if( p_family == SOURCE_SANS ) { font = texture_font_new_from_file( atlas, p_size, "fonts/SourceSansPro-Regular.ttf" ); } else if( p_family == SOURCE_CODE ) { font = texture_font_new_from_file( atlas, p_size, "fonts/SourceCodePro-Regular.ttf" ); } else if( p_family == OLD_STANDARD ) { font = texture_font_new_from_file( atlas, p_size, "fonts/OldStandard-Regular.ttf" ); } else if( p_family == LOBSTER ) { font = texture_font_new_from_file( atlas, p_size, "fonts/Lobster-Regular.ttf" ); } else { fprintf( stderr, "Error : Unknown family type\n" ); return; } if (!font) return; markup.font = font; font->hinting = p_hinting; font->kerning = p_kerning; font->filtering = 1; float norm = 1.0/(p_primary + 2*p_secondary + 2*p_tertiary); font->lcd_weights[0] = (unsigned char)(p_tertiary*norm*256); font->lcd_weights[1] = (unsigned char)(p_secondary*norm*256); font->lcd_weights[2] = (unsigned char)(p_primary*norm*256); font->lcd_weights[3] = (unsigned char)(p_secondary*norm*256); font->lcd_weights[4] = (unsigned char)(p_tertiary*norm*256); pen.x = 10; pen.y = 600 - font->height - 10; text_buffer_printf( buffer, &pen, &markup, text, NULL ); // Post-processing for width and orientation vertex_buffer_t * vbuffer = buffer->buffer; size_t i; for( i=0; i < vector_size( vbuffer->items ); ++i ) { ivec4 *item = (ivec4 *) vector_get( vbuffer->items, i); glyph_vertex_t * v0 = /* x0,y0 */ (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+0 ); //glyph_vertex_t * v1 = /* x0,y1 */ // (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+1 ); glyph_vertex_t * v2 = /* x1,y1 */ (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+2 ); glyph_vertex_t * v3 = /* x1,y0 */ (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+3 ); float x0 = v0->x, y0 = v0->y; float x1 = v2->x, y1 = v2->y; v2->x = v3->x = x0 + (x1-x0)*p_width; float dy = abs(y1-y0); float dx = tan(p_faux_italic/180.0 * M_PI) * dy; v0->x += dx; v0->shift = fmod(v0->shift + dx-(int)(dx),1.0); v3->x += dx; v3->shift = fmod(v3->shift + dx-(int)(dx),1.0); } texture_font_delete( font ); } // ---------------------------------------------------------------- display --- void display( GLFWwindow* window ) { vec4 black = {{0.0, 0.0, 0.0, 1.0}}; vec4 white = {{1.0, 1.0, 1.0, 1.0}}; if( !p_invert ) { glClearColor( 0, 0, 0, 1 ); buffer->base_color = white; } else { glClearColor( 1, 1, 1, 1 ); buffer->base_color = black; } glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glUseProgram( buffer->shader ); { glUniformMatrix4fv( glGetUniformLocation( buffer->shader, "model" ), 1, 0, model.data); glUniformMatrix4fv( glGetUniformLocation( buffer->shader, "view" ), 1, 0, view.data); glUniformMatrix4fv( glGetUniformLocation( buffer->shader, "projection" ), 1, 0, projection.data); text_buffer_render( buffer ); } TwDraw( ); glfwSwapBuffers( window ); }