Ejemplo n.º 1
0
void TradeManager::UpdateAdviceText()
{
	ctp2_HyperTextBox *advice = (ctp2_HyperTextBox *)aui_Ldl::GetObject(s_tradeAdviceBlock, "Advice");
	Assert(advice);
	if(advice) {
		Assert(m_createList);
		
		SlicContext sc;
		
		Player *p = g_player[g_selected_item->GetVisiblePlayer()];

		if(m_createList) {
			ctp2_ListItem *selItem = (ctp2_ListItem *)m_createList->GetSelectedItem();
			if(selItem && !m_createList->IsHidden()) {
				CreateListData *data = (CreateListData *)selItem->GetUserData();
				sc.AddCity(data->m_source);
				sc.AddCity(data->m_destination);
				sc.AddGood(data->m_resource);
				sc.AddGold(data->m_price);
				sc.AddInt(data->m_caravans);
				
				MBCHAR interp[k_MAX_NAME_LEN];
				interp[0] = 0;
				
				stringutils_Interpret(g_theStringDB->GetNameStr("SELECTED_TRADE_ADVICE"),
									  sc, interp);

				if(p) {
					if(data->m_caravans > (p->m_tradeTransportPoints - p->m_usedTradeTransportPoints)) {
						SlicContext sc2;
						sc2.AddInt(data->m_caravans - (p->m_tradeTransportPoints - p->m_usedTradeTransportPoints));

						strcat(interp + strlen(interp), "  ");

						stringutils_Interpret(g_theStringDB->GetNameStr("NEED_MORE_CARAVANS"),
											  sc2, interp + strlen(interp));
					}
				}

				advice->SetHyperText(interp);
			} else {
				
				if(p) {
					PointerList<CreateListData>::Walker walk(&m_createData);
					CreateListData *maxData = NULL;
					while(walk.IsValid()) {
						CreateListData *data = walk.GetObj();
						if(data->m_curDestination.m_id != 0) {
							
							walk.Next();
							continue;
						}
						if(data->m_caravans <= (p->m_tradeTransportPoints - p->m_usedTradeTransportPoints)) {
							if(!maxData || data->m_price > maxData->m_price) {
								maxData = data;
							}
						}
						walk.Next();
					}

					MBCHAR interp[k_MAX_NAME_LEN];
					interp[0] = 0;
						
					if(maxData) {
						SlicContext sc;
						sc.AddCity(maxData->m_source);
						sc.AddCity(maxData->m_destination);
						sc.AddGood(maxData->m_resource);
						
						stringutils_Interpret(g_theStringDB->GetNameStr("CREATE_ROUTE_ADVICE"),
											  sc, interp);
					} else if(m_createData.GetCount() > 0) {
						strcpy(interp, g_theStringDB->GetNameStr("BUILD_MORE_CARAVANS"));
					} else {
						strcpy(interp, g_theStringDB->GetNameStr("MAXIMUM_TRADE_EFFICIENCY"));
					}
					
					advice->SetHyperText(interp);
				}
			}
		}
	}
}
Ejemplo n.º 2
0
/* eval -- evaluate a list, producing a list */
extern List *eval(List *list0, Binding *binding0, int flags) {
	Closure *volatile cp;
	List *fn;

	if (++evaldepth >= maxevaldepth)
		fail("es:eval", "max-eval-depth exceeded");

	Ref(List *, list, list0);
	Ref(Binding *, binding, binding0);
	Ref(char *, funcname, NULL);

restart:
	if (list == NULL) {
		RefPop3(funcname, binding, list);
		--evaldepth;
		return true;
	}
	assert(list->term != NULL);

	if ((cp = getclosure(list->term)) != NULL) {
		switch (cp->tree->kind) {
		    case nPrim:
			assert(cp->binding == NULL);
			list = prim(cp->tree->u[0].s, list->next, binding, flags);
			break;
		    case nThunk:
			list = walk(cp->tree->u[0].p, cp->binding, flags);
			break;
		    case nLambda:
			ExceptionHandler

				Push p;
				Ref(Tree *, tree, cp->tree);
				Ref(Binding *, context,
					       bindargs(tree->u[0].p,
							list->next,
							cp->binding));
				if (funcname != NULL)
					varpush(&p, "0",
						    mklist(mkterm(funcname,
								  NULL),
							   NULL));
				list = walk(tree->u[1].p, context, flags);
				if (funcname != NULL)
					varpop(&p);
				RefEnd2(context, tree);
	
			CatchException (e)

				if (termeq(e->term, "return")) {
					list = e->next;
					goto done;
				}
				throw(e);

			EndExceptionHandler
			break;
		    case nList: {
			list = glom(cp->tree, cp->binding, TRUE);
			list = append(list, list->next);
			goto restart;
		    }
		    default:
			panic("eval: bad closure node kind %d",
			      cp->tree->kind);
		    }
		goto done;
	}

	/* the logic here is duplicated in $&whatis */

	Ref(char *, name, getstr(list->term));
	fn = varlookup2("fn-", name, binding);
	if (fn != NULL) {
		funcname = name;
		list = append(fn, list->next);
		RefPop(name);
		goto restart;
	}
	if (isabsolute(name)) {
		char *error = checkexecutable(name);
		if (error != NULL)
			fail("$&whatis", "%s: %s", name, error);
		list = forkexec(name, list, flags & eval_inchild);
		RefPop(name);
		goto done;
	}
	RefEnd(name);

	fn = pathsearch(list->term);
	if (fn != NULL && fn->next == NULL
	    && (cp = getclosure(fn->term)) == NULL) {
		char *name = getstr(fn->term);
		list = forkexec(name, list, flags & eval_inchild);
		goto done;
	}

	list = append(fn, list->next);
	goto restart;

done:
	--evaldepth;
	if ((flags & eval_exitonfalse) && !istrue(list))
		exit(exitstatus(list));
	RefEnd2(funcname, binding);
	RefReturn(list);
}
Ejemplo n.º 3
0
//----------------------------------------------------------------------------
//
// Name       : UnseenCell::Serialize
//
// Description: Serialization method
//
// Parameters : archive			: The source/target archive
//
// Globals    : -
//
// Returns    : -
//
// Remark(s)  : -
//
//----------------------------------------------------------------------------
void UnseenCell::Serialize(CivArchive &archive)
{
	sint32 l;
	if(archive.IsStoring()) {
		m_point.Serialize(archive);
		archive.StoreChunk((uint8 *)&m_env, ((uint8 *)&m_slaveBits)+sizeof(m_slaveBits));

		{
			// A dirty workaround in order not to change the save game format.
			// UnseenInstallationInfo is now abused to store m_visibleCityOwner
			// as visibility member. As both are of type uint32 it is not a
			// problem. Its type is marked as -1. At least this doesn't interfere
			// with anything else, as the installation data is just stored in
			// this class but it isn't aceessed. Maybe a mistake or a left
			// over from CTP1.
			m_installations->AddTail(new UnseenInstallationInfo(-1, m_visibleCityOwner));
			archive << m_installations->GetCount();
			PointerList<UnseenInstallationInfo>::Walker walk(m_installations);
			while(walk.IsValid()) {
				archive.Store((uint8*)walk.GetObj(), sizeof(UnseenInstallationInfo));
				walk.Next();
			}
		}

		{
			archive << m_improvements->GetCount();
			PointerList<UnseenImprovementInfo>::Walker walk(m_improvements);
			while(walk.IsValid()) {
				archive.Store((uint8*)walk.GetObj(), sizeof(UnseenImprovementInfo));
				walk.Next();
			}
		}


		if (m_cityName)
		{
			l = strlen(m_cityName) + 1;
			archive << l;
			archive.Store((uint8*)m_cityName, (strlen(m_cityName) + 1) * sizeof(MBCHAR));
		}
		else
		{
			l = 0;
			archive << l;
		}

		archive << (sint32)(m_actor != NULL);
		if (m_actor) {
			m_actor->Serialize(archive);
		}
		m_tileInfo->Serialize(archive);
	}
	else
	{
		m_point.Serialize(archive);
		archive.LoadChunk((uint8 *)&m_env, ((uint8 *)&m_slaveBits)+sizeof(m_slaveBits));

		if (m_installations)
		{
			m_installations->DeleteAll();
		}
		else
		{
			m_installations = new PointerList<UnseenInstallationInfo>;
		}

		archive >> l;

		UnseenInstallationInfo* tmpUII;
		bool    vCityOwnerNotSet = true;
		sint32  i;
		for(i = 0; i < l; i++) {
			tmpUII = new UnseenInstallationInfo(archive);

			// Only store the additional UnseenInstallationInfo in the
			// save file but not in the UnseenCell object itsself.
			if(tmpUII->m_type >= 0){
				m_installations->AddTail(tmpUII);
			}
			else{
				m_visibleCityOwner = tmpUII->m_visibility;
				vCityOwnerNotSet = false;
				delete tmpUII;
			}
		}
		// Backwards compartibility: If this UnseenCell didn't have an m_visibleCityOwner
		if(vCityOwnerNotSet) m_visibleCityOwner = g_theWorld->GetCell(m_point)->GetCityOwner().m_id;

		if (m_improvements)
		{
			m_improvements->DeleteAll();
		}
		else
		{
			m_improvements = new PointerList<UnseenImprovementInfo>;
		}

		archive >> l;
		for(i = 0; i < l; i++) {
			m_improvements->AddTail(new UnseenImprovementInfo(archive));
		}

		delete [] m_cityName;
		archive >> l;
		if (l > 0)
		{
			m_cityName = new MBCHAR[l];
			archive.Load((uint8*)m_cityName, l * sizeof(MBCHAR));
		}
		else
		{
			m_cityName = NULL;
		}

		sint32 hasActor;
		archive >> hasActor;

		ReleaseActor(m_actor);
		if (hasActor)
		{
			m_actor = new UnitActor(archive);
		}

		delete m_tileInfo;
		m_tileInfo = new TileInfo(g_theWorld->GetTileInfo(m_point));
		Assert(m_tileInfo);
		m_tileInfo->Serialize(archive);
	}
}
        void VectorizerVisitorExpression::visit(const Nodecl::FunctionCall& n)
        {
            Nodecl::NodeclBase called = n.get_called();
            ERROR_CONDITION(!called.is<Nodecl::Symbol>(),
                    "Vectorizer: %s found. This kind of function call is not supported yet",
                    ast_print_node_type(called.get_kind()));

            Nodecl::Symbol called_sym = called.as<Nodecl::Symbol>();

            // Vectorizing arguments
            walk(n.get_arguments());

            // Special functions
            if (called_sym.get_symbol().get_name() == "fabsf")
            {
                const Nodecl::VectorFabs vector_fabs_call =
                    Nodecl::VectorFabs::make(
                            n.get_arguments().as<Nodecl::List>().front().shallow_copy(),
                            get_qualified_vector_to(n.get_type(), _vector_length),
                            n.get_locus());

                n.replace(vector_fabs_call);
            }
            else //Common functions
            {
                // Get the best vector version of the function available
                Nodecl::NodeclBase best_version =
                    TL::Vectorization::Vectorizer::_function_versioning.get_best_version(
                            called_sym.get_symbol().get_name(), _device, _vector_length, _target_type);

                ERROR_CONDITION(best_version.is_null(), "Vectorizer: the best vector function for '%s' is null",
                        called_sym.get_symbol().get_name().c_str());

                // Create new called symbol
                Nodecl::Symbol new_called;
                if (best_version.is<Nodecl::FunctionCode>())
                {
                    new_called = best_version.as<Nodecl::FunctionCode>().get_symbol().
                        make_nodecl(n.get_locus());
                }
                else if (best_version.is<Nodecl::Symbol>())
                {
                    new_called = best_version.as<Nodecl::Symbol>().get_symbol().
                        make_nodecl(n.get_locus());
                }
                else
                {
                    running_error("Vectorizer: %s found as vector function version in function versioning.",
                            ast_print_node_type(best_version.get_kind()));
                }

                const Nodecl::VectorFunctionCall vector_function_call =
                    Nodecl::VectorFunctionCall::make(
                            new_called,
                            n.get_arguments().shallow_copy(),
                            n.get_alternate_name().shallow_copy(),
                            n.get_function_form().shallow_copy(),
                            get_qualified_vector_to(n.get_type(), _vector_length),
                            n.get_locus());

                n.replace(vector_function_call);
            }
        }
Ejemplo n.º 5
0
int main(int argc, char **argv)
{
	int i, j;
	Graph::VertexWeightedGraph *G;
	TDTree *T=NULL;
	DP_info info;
	list<int> optimal_solution;
    int rank, size;
    double stime, etime;

    int storage_nodes = 1;
    
    MPI_Group orig_group, new_group;

    double leaf_time;
    double nonleaf_time;
    long smem_hwm;
    long rmem_hwm;

    

    MPI_Init (&argc, &argv);
    MPI_Comm_rank (MPI_COMM_WORLD, &rank);
    MPI_Comm_size (MPI_COMM_WORLD, &size);

    // There is a seperate log file for each processor, strictly for
    // debugging and development purposes only.

    char lfname[100];
    char efname[100];
    sprintf (lfname, "parallel_wis-%d.log", rank);
    sprintf (efname, "parallel_wis-error.log", rank);
    //0: debug, 5: critical
    LOG_INIT(lfname, efname, 0);


     if (!(size > storage_nodes + 2))
     {
         FERROR ("No enough processors, please allocate more\n");
         FERROR ("Processor distribution: head_node: %d storage_nodes: %d compute_nodes: %d\n", 1, storage_nodes, size - (storage_nodes + 1));
         MPI_Finalize ();
         exit (0);
     }


	// Process command line options
	int help = info.process_DP_info(argc, argv);
	if(help == -1){
	  if(rank == 0)
	    {
	      usage(argv[0]);
	    } 
	  MPI_Finalize ();
	  exit (1);
	}
	
	// Create the graph for WIS
	create_WIS_graph(&info, G);
	// See if the MIP is to be written/solved
	if(info.write_mod)
	{
		write_ind_set_model(info.DIMACS_file, info.model_file, G);
		if(info.solve_mip)
		{
			// Use GLPSOL to run the MIP solver
			char command_string[100];
			sprintf(command_string,"%s -m %s",GLPSOL,info.model_file);
			fprintf(stderr,"Will use %s to solve MIP. Solution will be written to %s.MIP.WIS.sol",
                    GLPSOL,info.DIMACS_file);
			system(command_string);
		}
		return 1;		
	}
		
	
	// Create the tree decomposition using the options
	create_tree_decomposition(&info, G, &T);
	// Check to see if the DP is to be done
	if(info.decompose_only)
	{
		printf("%s: Treewidth %d\n", info.DIMACS_file, T->width);
		//delete G;
		//delete T;
		return 1;
	}


    T->head_node = 0;
    T->allnodes = new vector<int>(size, -1);
    //T->storage_nodes = new vector<int>(size, -1);
    //T->compute_nodes = new vector<int>(size, -1);

    (*T->allnodes)[0] = HEAD_NODE;
    for (i = 1; i < size; i++)
    {
        if ((storage_nodes > 0) && (i % 4 == 1))
        {
            T->storage_nodes.push_back(i);
            (*T->allnodes)[i] = STORAGE_NODE;
            storage_nodes --;
        }
        else
        {
            T->compute_nodes.push_back(i);
            (*T->allnodes)[i] = COMPUTE_NODE;
        }
    }

    if (MPI_SUCCESS != 
        MPI_Comm_group(MPI_COMM_WORLD, &orig_group))
    {
        FERROR ("MPI Test any failed at processor : %d %s:%d\n", T->rank, __FILE__, __LINE__);
        MPI_Finalize();
    }

    if (MPI_SUCCESS != 
        MPI_Group_incl (orig_group, T->compute_nodes.size(), &T->compute_nodes.front(), &new_group))
    {
        FERROR ("MPI Test any failed at processor : %d %s:%d\n", T->rank, __FILE__, __LINE__);
        MPI_Finalize();
    }

    MPI_Comm compute_nodes_comm;
    if (MPI_SUCCESS != 
        MPI_Comm_create (MPI_COMM_WORLD, new_group, &compute_nodes_comm))
    {
        FERROR ("MPI Test any failed at processor : %d %s:%d\n", T->rank, __FILE__, __LINE__);
        MPI_Finalize();
    }

    T->compute_nodes_comm = &compute_nodes_comm;
    T->storage_nodes_size = T->storage_nodes.size();
    T->compute_nodes_size = T->compute_nodes.size();

    if ((*T->allnodes)[rank] == HEAD_NODE)
    {
        parallel_wis_head_init (T, size, rank);
        parallel_wis_head_start (T);
    }
    else if ((*T->allnodes)[rank] == COMPUTE_NODE)
    {
        parallel_wis_compute_init (T, size, rank);
    }
    else if ((*T->allnodes)[rank] == STORAGE_NODE)
    {
        parallel_wis_storage_init (T, size, rank);
        parallel_wis_storage_start (T);
    }


    if ((*T->allnodes)[T->rank] == COMPUTE_NODE)
    {
        DEBUG("post order walk\n");
        // Create the post_order walk
        vector<int> walk(T->num_tree_nodes,GD_UNDEFINED);
        T->post_order_walk(&walk);

        stime = MPI_Wtime();
        int j;
        DEBUG("starting loop\n");
        for(i = 0; i < T->num_tree_nodes; i++)
        {
            CRIT("processing node : ############# %d\n", walk[i]);
            DEBUG(" %d  more nodes left\n", (T->num_tree_nodes - i));
            T->compute_table(compute_weighted_ind_sets_parallel, walk[i]);
            MPI_Barrier (compute_nodes_comm);

            if(T->info->free_children)
            {
                for(j = 0; (j < T->storage_nodes_size) && (T->rank == T->compute_nodes[0]); j++)
                {
                    if (MPI_SUCCESS !=
                        MPI_Send ((void *)&walk[i], 1, MPI_INT, T->storage_nodes[j], MPI_CHILD_FREE_TAG, MPI_COMM_WORLD))
                    {
                        FERROR ("MPI Irecv failed at processor : %d %s:%d\n", T->rank, __FILE__, __LINE__);
                        MPI_Finalize();
                    }
                }
            }
        }

        // Send termination signal to head node to nofity that
        // computation is over for the given tree
        if (MPI_SUCCESS != 
            MPI_Send (&T->rank, 1, MPI_INT, 0, MPI_COMP_TERM_TAG, MPI_COMM_WORLD))
        {
            FERROR ("MPI Send failed at processor : %d %s:%d\n", T->rank, __FILE__, __LINE__);
            MPI_Finalize();
        }
        
        // Set flag_recv_done when all tree nodes have been finished then
        // receiving threads can exit.
        T->flag_recv_done = 1;
        
        etime = MPI_Wtime ();
        

        // Store and reset info's table stats 
        info.orig_total_pc_table_entries=info.total_pc_table_entries;
        info.orig_total_table_entries=info.total_table_entries;
        
        info.total_pc_table_entries=info.total_table_entries=0;
        
        
        // Compute some stats here in parent-child intersection to analyze 
        // why memory savings varies across different graphs
        // This is less than ideal, but you have to do it this way for something like make_nice
        // since there are "holes" in the tree_nodes[] array.  The above compute_table() loop
        // gets around this by using the post order walk that is filled with only valid tree node
        // indices!
        
        vector<int> intersection_sizes(T->tree_nodes.size(),-1);
        T->compute_parent_child_intersections(&intersection_sizes);
        info.avg_pc_proportion=0;
        int num_in_avg=0;
        for(i=0;i<(int)T->tree_nodes.size();i++)
        {
            if(T->tree_nodes[i])
            {
                num_in_avg++;
                info.avg_pc_proportion += ((double)intersection_sizes[i]/(double)T->tree_nodes[i]->bag.size());
            }
        }
        info.avg_pc_proportion = info.avg_pc_proportion/(double)num_in_avg;
    }

    smem_hwm = getHWmem();
    if ((*T->allnodes)[rank] == COMPUTE_NODE)
    {
    
        if (MPI_SUCCESS != 
            MPI_Reduce ((void *)&T->info->leaf_time, (void *)&leaf_time, 1, MPI_DOUBLE, MPI_MAX, 0, *T->compute_nodes_comm))
        {
            FERROR ("MPI Reduce failed at processor : %d %s:%d\n", T->rank, __FILE__, __LINE__);
            MPI_Finalize();
        }
        T->info->leaf_time = leaf_time;
    
        if (MPI_SUCCESS != 
            MPI_Reduce ((void *)&T->info->nonleaf_time, (void *)&nonleaf_time, 1, MPI_DOUBLE, MPI_MAX, 0, *T->compute_nodes_comm))
        {
            FERROR ("MPI Reduce failed at processor : %d %s:%d\n", T->rank, __FILE__, __LINE__);
            MPI_Finalize();
        }
        T->info->nonleaf_time = nonleaf_time;
    
        if (MPI_SUCCESS != 
            MPI_Reduce ((void *)&smem_hwm, (void *)&rmem_hwm, 1, MPI_LONG, MPI_MAX, 0, *T->compute_nodes_comm))
        {
            FERROR ("MPI Reduce failed at processor : %d %s:%d\n", T->rank, __FILE__, __LINE__);
            MPI_Finalize();
        }
    
        if (T->rank == T->compute_nodes[0])
            fprintf (stderr, "Memory HWM for all compute nodes: %d\n", rmem_hwm);
    }
    
    if (MPI_SUCCESS != 
        MPI_Reduce ((void *)&smem_hwm, (void *)&rmem_hwm, 1, MPI_LONG, MPI_MAX, 0, MPI_COMM_WORLD))
    {
        FERROR ("MPI Reduce failed at processor : %d %s:%d\n", T->rank, __FILE__, __LINE__);
        MPI_Finalize();
    }

    if (T->rank == 0)
        fprintf (stderr, "Memory HWM for all  nodes: %d\n", rmem_hwm);


    
    if ((*T->allnodes)[rank] == HEAD_NODE)
    {
        parallel_wis_head_cleanup (T);
    }
    else if ((*T->allnodes)[rank] == COMPUTE_NODE)
    {
        parallel_wis_compute_cleanup (T);
    }
    else if ((*T->allnodes)[rank] == STORAGE_NODE)
    {
        parallel_wis_storage_cleanup (T);
    }

    LOG_CLOSE();
    MPI_Finalize();

    if (T->rank == T->compute_nodes[0] )
        print_WIS_results(stdout, T, &info);

  	//delete T;
    //delete &G;
 	return 1;
}
Ejemplo n.º 6
0
static void
move (struct state *st)
{
    if (!st->move_length)
    {
	register int    tries = 0;
	st->move_dir = 0;
	if ((random() & 1) && think(st))
	{
	    talk(st, 0);		/* sets timeout to itself */
	    return;
	}
	if (!(random() % 3) && (st->interval = look(st)))
	{
	    st->next_fn = move;
	    return;
	}
	st->interval = 20 + random() % 100;
	do
	{
	    if (!tries)
		st->move_length = st->Width / 100 + random() % 90, tries = 8;
	    else
		tries--;
	    /* There maybe the case that we won't be able to exit from
	       this routine (especially when the geometry is too small)!!

	       Ensure that we can exit from this routine.
	     */
#if 1
	    if (!tries && (st->move_length <= 1)) {
	      st->move_length = 1;
	      break;
	    }
#endif
	    switch (random() % 8)
	    {
	    case 0:
		if (st->x - X_INCR * st->move_length >= 5)
		    st->move_dir = LEFT;
		break;
	    case 1:
		if (st->x + X_INCR * st->move_length <= st->Width - 70)
		    st->move_dir = RIGHT;
		break;
	    case 2:
		if (st->y - (Y_INCR * st->move_length) >= 5)
		    st->move_dir = UP, st->interval = 40;
		break;
	    case 3:
		if (st->y + Y_INCR * st->move_length <= st->Height - 70)
		    st->move_dir = DOWN, st->interval = 20;
		break;
	    case 4:
		if (st->x - X_INCR * st->move_length >= 5 && st->y - (Y_INCR * st->move_length) >= 5)
		    st->move_dir = (LEFT | UP);
		break;
	    case 5:
		if (st->x + X_INCR * st->move_length <= st->Width - 70 &&
		    st->y - Y_INCR * st->move_length >= 5)
		    st->move_dir = (RIGHT | UP);
		break;
	    case 6:
		if (st->x - X_INCR * st->move_length >= 5 &&
		    st->y + Y_INCR * st->move_length <= st->Height - 70)
		    st->move_dir = (LEFT | DOWN);
		break;
	    case 7:
		if (st->x + X_INCR * st->move_length <= st->Width - 70 &&
		    st->y + Y_INCR * st->move_length <= st->Height - 70)
		    st->move_dir = (RIGHT | DOWN);
		break;
	    default:
		/* No Defaults */
		break;
	    }
	} while (!st->move_dir);
    }
    if (st->move_dir)
      walk(st, st->move_dir);
    --st->move_length;
    st->next_fn = move;
}
Ejemplo n.º 7
0
void WalkAble::update(float delta)
{
	guidesMakeTrend();
	walk();
}
Ejemplo n.º 8
0
void MemberClass::ExportParser(FILE *outfile, char *recordName)
{
	char nicename[k_MAX_STRING];
	sint32 numTokens = 0;

	// TODO add aka and default names.

	fprintf(outfile, "static char *s_%s_%s_Tokens[] = {\n", recordName, m_name);
	PointerList<Datum>::Walker walk(&m_datumList);
	while(walk.IsValid()) {
		fprintf(outfile, "    \"%s\",\n", walk.GetObj()->m_name);
		walk.Next();
	}

	for (walk.SetList(&m_datumList); walk.IsValid(); walk.Next())
	{
		if(walk.GetObj()->m_akaName){
			fprintf(outfile, "    \"%s\",\n", walk.GetObj()->m_akaName);
		}
	}
	fprintf(outfile, "};\n");

	for (walk.SetList(&m_datumList); walk.IsValid(); walk.Next())
	{
		sprintf(nicename, "k_Token_%s_%s_%s", recordName, m_name, walk.GetObj()->m_name);
		fprintf(outfile, "#define %-40s ((k_Token_Custom_Base) + %d)\n", nicename, numTokens);
		numTokens++;
	}
	for (walk.SetList(&m_datumList); walk.IsValid(); walk.Next())
	{
		Datum *dat = walk.GetObj();
		if(dat->m_akaName){
			sprintf(nicename, "k_Token_%s_%s_%s", recordName, m_name, dat->m_akaName);
			fprintf(outfile, "#define %-40s ((k_Token_Custom_Base) + %d)\n", nicename, numTokens);
			numTokens++;
		}
	}
	fprintf(outfile, "#define k_Token_%s_%s_Max ((k_Token_Custom_Base) + %d)\n",
			recordName, m_name, numTokens);

	walk.SetList(&m_datumList);
	bool canParseSequentially = true;
	for
	(
		walk.SetList(&m_datumList);
		walk.IsValid() && canParseSequentially;
		walk.Next()
	)
	{
		switch(walk.GetObj()->m_type) {
			case DATUM_INT:
			case DATUM_FLOAT:
			case DATUM_STRING:
			case DATUM_FILE:
			case DATUM_RECORD:
				break;
			default:
				canParseSequentially = false;
				break;
		}
	}

	if (canParseSequentially) {
		fprintf(outfile, "sint32 %sRecord::%s::ParseSequential(DBLexer *lex)\n", recordName, m_name);
		fprintf(outfile, "{\n");

		for (walk.SetList(&m_datumList); walk.IsValid(); walk.Next())
		{
			Datum *dat = walk.GetObj();
			switch(dat->m_type) {
				case DATUM_INT:
					fprintf(outfile, "    if(!lex->GetIntAssignment(m_%s)) {\n", dat->m_name);
					fprintf(outfile, "        DBERROR((\"Expected integer\"));\n");
					fprintf(outfile, "        return 0;\n");
					fprintf(outfile, "    }\n");
					break;
				case DATUM_FLOAT:
					fprintf(outfile, "    if(!lex->GetFloatAssignment(m_%s)) {\n", dat->m_name);
					fprintf(outfile, "        DBERROR((\"Expected number\"));\n");
					fprintf(outfile, "        return 0;\n");
					fprintf(outfile, "    }\n");
					break;
				case DATUM_STRING:
				case DATUM_FILE:
					fprintf(outfile, "    if(!lex->GetFileAssignment(m_%s)) {\n", dat->m_name);
					fprintf(outfile, "        DBERROR((\"Expected string\"));\n");
					fprintf(outfile, "        return 0;\n");
					fprintf(outfile, "    }\n");
					break;
				case DATUM_RECORD:
					fprintf(outfile, "    if(!g_the%sDB->GetRecordFromLexer(lex, m_%s)) {\n", dat->m_subType, dat->m_name);
					fprintf(outfile, "        DBERROR((\"Expected record from %s DB\"));\n", dat->m_subType);
					fprintf(outfile, "        return 0;\n");
					fprintf(outfile, "    }\n");
					break;
				default:
					Assert(0);
					break;
			}
		}
		fprintf(outfile, "    return 1;\n");
		fprintf(outfile, "}\n\n");

		fprintf(outfile, "sint32 %sRecord::%s::ParseFullySequential(DBLexer *lex)\n", recordName, m_name);
		fprintf(outfile, "{\n");
		for (walk.SetList(&m_datumList); walk.IsValid(); )
		{
			Datum *dat = walk.GetObj();
			switch(dat->m_type) {
				case DATUM_INT:
					fprintf(outfile, "    if(!lex->GetInt(m_%s)) {\n", dat->m_name);
					fprintf(outfile, "        DBERROR((\"Expected integer\"));\n");
					fprintf(outfile, "        return 0;\n");
					fprintf(outfile, "    }\n");
					break;
				case DATUM_FLOAT:
					fprintf(outfile, "    if(!lex->GetFloat(m_%s)) {\n", dat->m_name);
					fprintf(outfile, "        DBERROR((\"Expected number\"));\n");
					fprintf(outfile, "        return 0;\n");
					fprintf(outfile, "    }\n");
					break;
				case DATUM_STRING:
				case DATUM_FILE:
					fprintf(outfile, "    if(!lex->GetFile(m_%s)) {\n", dat->m_name);
					fprintf(outfile, "        DBERROR((\"Expected string\"));\n");
					fprintf(outfile, "        return 0;\n");
					fprintf(outfile, "    }\n");
					break;
				case DATUM_RECORD:
					fprintf(outfile, "    if(!g_the%sDB->GetCurrentRecordFromLexer(lex, m_%s)) {\n", dat->m_subType, dat->m_name);
					fprintf(outfile, "        DBERROR((\"Expected record from %s DB\"));\n", dat->m_subType);
					fprintf(outfile, "        return 0;\n");
					fprintf(outfile, "    }\n");
					break;
				default:
					Assert(0);
					break;
			}
			walk.Next();
			if(walk.IsValid()){
				fprintf(outfile, "    lex->GetToken();\n");
			}
		}
		fprintf(outfile, "    return 1;\n");
		fprintf(outfile, "}\n\n");

	}

	fprintf(outfile, "sint32 %sRecord::%s::Parse(DBLexer *lex)\n", recordName, m_name);
	fprintf(outfile, "{\n");
	fprintf(outfile, "    bool done = false;\n");
	fprintf(outfile, "    sint32 tok;\n");
	fprintf(outfile, "    sint32 result = 0;\n");
	fprintf(outfile, "    tok = lex->PeekAhead();\n");
	fprintf(outfile, "    if(tok != k_Token_OpenBrace) {\n");
	fprintf(outfile, "        if(lex->GetCurrentToken() != k_Token_OpenBrace) {\n");
	if(canParseSequentially) {
		fprintf(outfile, "            if(ParseSequential(lex)) {\n");
		fprintf(outfile, "                return 1;\n");
		fprintf(outfile, "            }\n");
	}
	if(m_parseNum > 0){
		fprintf(outfile, "            if(ParseNum(lex)) {\n");
		fprintf(outfile, "                return 1;\n");
		fprintf(outfile, "            }\n");
	}
	fprintf(outfile, "            DBERROR((\"Expected open brace for %s\"));\n", m_name);
	fprintf(outfile, "            return 0;\n");
	fprintf(outfile, "        }\n");
	fprintf(outfile, "    }\n");
	fprintf(outfile, "    else {\n");
	fprintf(outfile, "        tok = lex->GetToken();\n");
	fprintf(outfile, "    }\n");
	fprintf(outfile, "    lex->SetTokens(s_%s_%s_Tokens, k_Token_%s_%s_Max);\n", recordName, m_name, recordName, m_name);
	fprintf(outfile, "    while(!done) {\n");
	fprintf(outfile, "        tok = lex->GetToken();\n");
	fprintf(outfile, "        switch(tok) {\n");

	ExportTokenCases(outfile, recordName);

	fprintf(outfile, "            case k_Token_CloseBrace:\n");
	fprintf(outfile, "                done = true;\n");
	fprintf(outfile, "                result = 1;\n");
	fprintf(outfile, "                break;\n");
	fprintf(outfile, "            default:\n");

	ExportDefaultToken(outfile, recordName);

	fprintf(outfile, "        }\n");
	fprintf(outfile, "    }\n");
	fprintf(outfile, "    lex->RestoreTokens();\n");
	fprintf(outfile, "    return result;\n");
	fprintf(outfile, "}\n\n");

	fprintf(outfile, "sint32 %sRecord::%s::ParseInArray(DBLexer *lex, %s **array, sint32 *numElements)\n",
			recordName, m_name, m_name);
	fprintf(outfile, "{\n");
	fprintf(outfile, "    if(*numElements > 0) {\n");
	fprintf(outfile, "        %s *oldArray = *array;\n", m_name);
	fprintf(outfile, "        *array = new %s[(*numElements) + 1];\n", m_name);
	fprintf(outfile, "        for (int i=0; i < (*numElements); i++)\n");
	fprintf(outfile, "             (*array)[i] = oldArray[i];\n");
	fprintf(outfile, "        delete [] oldArray;\n");
	fprintf(outfile, "    } else {\n");
	fprintf(outfile, "        *array = new %s[1];\n", m_name);
	fprintf(outfile, "    }\n");
	fprintf(outfile, "    (*array)[*numElements].Parse(lex);\n");
	fprintf(outfile, "    *numElements += 1;\n");
	fprintf(outfile, "    return 1;\n");
	fprintf(outfile, "}\n\n");

	fprintf(outfile, "sint32 %sRecord::%s::ParseInArray(DBLexer *lex, %s *array, sint32 *numElements, sint32 maxSize)\n",
			recordName, m_name, m_name);
	fprintf(outfile, "{\n");
	fprintf(outfile, "    if(*numElements >= maxSize) {\n");
	fprintf(outfile, "        return 0;\n");
	fprintf(outfile, "    }\n");
	fprintf(outfile, "    array[*numElements].Parse(lex);\n");
	fprintf(outfile, "    *numElements += 1;\n");
	fprintf(outfile, "    return 1;\n");
	fprintf(outfile, "}\n\n");

	if(canParseSequentially) {
		fprintf(outfile, "sint32 %sRecord::%s::ParseInArraySequential(DBLexer *lex, %s **array, sint32 *numElements)\n",
				recordName, m_name, m_name);
		fprintf(outfile, "{\n");
		fprintf(outfile, "    if(*numElements > 0) {\n");
		fprintf(outfile, "        %s *oldArray = *array;\n", m_name);
		fprintf(outfile, "        *array = new %s[(*numElements) + 1];\n", m_name);
		fprintf(outfile, "        for (int i=0; i < (*numElements); i++)\n");
		fprintf(outfile, "             (*array)[i] = oldArray[i];\n");
		fprintf(outfile, "        delete [] oldArray;\n");
		fprintf(outfile, "    } else {\n");
		fprintf(outfile, "        *array = new %s[1];\n", m_name);
		fprintf(outfile, "    }\n");
		fprintf(outfile, "    (*array)[*numElements].ParseFullySequential(lex);\n");
		fprintf(outfile, "    *numElements += 1;\n");
		fprintf(outfile, "    return 1;\n");
		fprintf(outfile, "}\n\n");

		fprintf(outfile, "sint32 %sRecord::%s::ParseInArraySequential(DBLexer *lex, %s *array, sint32 *numElements, sint32 maxSize)\n",
				recordName, m_name, m_name);
		fprintf(outfile, "{\n");
		fprintf(outfile, "    if(*numElements >= maxSize) {\n");
		fprintf(outfile, "        return 0;\n");
		fprintf(outfile, "    }\n");
		fprintf(outfile, "    array[*numElements].ParseFullySequential(lex);\n");
		fprintf(outfile, "    *numElements += 1;\n");
		fprintf(outfile, "    return 1;\n");
		fprintf(outfile, "}\n\n");
	}

	if(m_parseNum > 0){
		fprintf(outfile, "sint32 %sRecord::%s::ParseNum(DBLexer *lex)\n", recordName, m_name);
		fprintf(outfile, "{\n");
		fprintf(outfile, "    bool done = false;\n");
		fprintf(outfile, "    sint32 tok;\n");

		fprintf(outfile, "    lex->SetTokens(s_%s_%s_Tokens, k_Token_%s_%s_Max);\n", recordName, m_name, recordName, m_name);
		fprintf(outfile, "    for(sint32 i = 0; i < %i; ++i) {\n", m_parseNum);
		fprintf(outfile, "        tok = lex->GetToken();\n");
		fprintf(outfile, "        switch(tok) {\n");

		ExportTokenCases(outfile, recordName);

		fprintf(outfile, "            default:\n");

		ExportDefaultToken(outfile, recordName);

		fprintf(outfile, "        }\n");
		fprintf(outfile, "    }\n");
		fprintf(outfile, "    lex->RestoreTokens();\n");
		fprintf(outfile, "\n");
		fprintf(outfile, "    if(done)\n");
		fprintf(outfile, "        return 0;\n");
		fprintf(outfile, "\n");
		fprintf(outfile, "    return 1;\n");
		fprintf(outfile, "}\n\n");
	}

	ExportResolver(outfile, recordName);
}
Ejemplo n.º 9
0
void MemberClass::ExportTokenCases(FILE *outfile, char *recordName)
{
	for
	(
		PointerList<Datum>::Walker walk(&m_datumList);
		walk.IsValid();
		walk.Next()
	)
	{
		Datum *dat = walk.GetObj();
		fprintf(outfile,         "            case k_Token_%s_%s_%s:\n", recordName, m_name, dat->m_name);
		if(dat->m_akaName){
			fprintf(outfile,         "            case k_Token_%s_%s_%s:\n", recordName, m_name, dat->m_akaName);
		}
		if(dat->m_maxSize == k_MAX_SIZE_VARIABLE) {

			switch(dat->m_type) {
				case DATUM_INT:
					fprintf(outfile, "                if(!CTPRecord::ParseIntInArray(lex, &m_%s, &m_num%s)) {\n", dat->m_name, dat->m_name);
					break;
				case DATUM_STRINGID:
					fprintf(outfile, "                if(!CTPRecord::ParseStringIdInArray(lex, m_%s, &m_num%s)) {\n", dat->m_name, dat->m_name);
					break;
				case DATUM_FLOAT:
					fprintf(outfile, "                if(!CTPRecord::ParseFloatInArray(lex, &m_%s, &m_num%s)) {\n", dat->m_name, dat->m_name);
					break;
				case DATUM_STRING:
				case DATUM_FILE:
					fprintf(outfile, "                if(!CTPRecord::ParseFileInArray(lex, &m_%s, &m_num%s)) {\n", dat->m_name, dat->m_name);
					break;
				case DATUM_RECORD:
					fprintf(outfile, "                if(!g_the%sDB->ParseRecordInArray(lex, &m_%s, &m_num%s)) {\n", dat->m_subType, dat->m_name, dat->m_name);
					break;
				case DATUM_STRUCT:
					fprintf(outfile, "                if(!%sRecord::%s::ParseInArray(lex, &m_%s, &m_num%s)) {\n", recordName, dat->m_subType, dat->m_name, dat->m_name);
					break;
				default:
					Assert(0);
					break;
			}
			fprintf(outfile, "                    done = true; break;\n");
			fprintf(outfile, "                }\n");
		} else if(dat->m_maxSize > 0) {

			switch(dat->m_type) {
				case DATUM_INT:
					fprintf(outfile, "                if(!CTPRecord::GetIntInArray(lex, &m_%s, &m_num%s, k_MAX_%s)) {\n",
							dat->m_name, dat->m_name, dat->m_name);
					break;
				case DATUM_STRINGID:
					fprintf(outfile, "                if(!CTPRecord::GetStringIdInArray(lex, &m_%s, &m_num%s, k_MAX_%s)) {\n",
							dat->m_name, dat->m_name, dat->m_name);
					break;
				case DATUM_FLOAT:
					fprintf(outfile, "                if(!CTPRecord::ParseFloatInArray(lex, &m_%s, &m_num%s, k_MAX_%s)) {\n",
							dat->m_name, dat->m_name, dat->m_name);
					break;
				case DATUM_STRING:
				case DATUM_FILE:
					fprintf(outfile, "                if(!CTPRecord::ParseFileInArray(lex, &m_%s, &m_num%s, k_MAX_%s)) {\n",
							dat->m_name, dat->m_name, dat->m_name);
					break;
				case DATUM_RECORD:
					fprintf(outfile, "                if (!g_the%sDB->ParseRecordInArray(lex, &m_%s, &m_num%s, k_MAX_%s)) {\n",
							dat->m_subType, dat->m_name, dat->m_name, dat->m_name);
					break;
				case DATUM_STRUCT:
					fprintf(outfile, "                if(!%sRecord::%s::ParseInArray(lex, &m_%s, &m_num%s, k_MAX_%s)) {\n",
							recordName, dat->m_subType, dat->m_name, dat->m_name, dat->m_name);
					break;
				default:
					Assert(0);
					break;
			}
		} else if(dat->m_maxSize < 0) {
			switch(dat->m_type) {
				case DATUM_INT:
					fprintf(outfile, "                if(!lex->GetIntAssignment(m_%s)) {\n", dat->m_name);
					fprintf(outfile, "                    done = true; break;\n");
					fprintf(outfile, "                }\n");
					break;
				case DATUM_STRINGID:
					fprintf(outfile, "                if(!lex->GetStringIdAssignment(m_%s)) {\n", dat->m_name);
					fprintf(outfile, "                    done = true; break;\n");
					fprintf(outfile, "                }\n");
					break;
				case DATUM_BIT:
					fprintf(outfile, "                m_flags%d |= k_%s_%s_Bit;\n", dat->m_bitNum / 32,
							m_name, dat->m_name);
					break;
				case DATUM_BIT_PAIR:
					fprintf(outfile, "                m_flags%d |= k_%s_%s_Bit;\n", dat->m_bitNum / 32,
							m_name, dat->m_name);
					dat->ExportBitPairDirectParse(outfile, m_name);
					break;
				case DATUM_FLOAT:
					fprintf(outfile, "                if(!lex->GetFloatAssignment(m_%s)) {\n", dat->m_name);
					fprintf(outfile, "                    done = true; break;\n");
					fprintf(outfile, "                }\n");
					break;
				case DATUM_STRING:
				case DATUM_FILE:
					fprintf(outfile, "                if(!lex->GetFileAssignment(m_%s)) {\n", dat->m_name);
					fprintf(outfile, "                    done = true; break;\n");
					fprintf(outfile, "                }\n");
					break;
				case DATUM_RECORD:
					fprintf(outfile, "                if (!g_the%sDB->GetRecordFromLexer(lex, m_%s)) {\n", dat->m_subType, dat->m_name);
					fprintf(outfile, "                    done = true; break;\n");
					fprintf(outfile, "                }\n");
					break;
				case DATUM_STRUCT:
					fprintf(outfile, "                if(!m_%s.Parse(lex)) {\n", dat->m_name);
					fprintf(outfile, "                    done = true; break;\n");
					fprintf(outfile, "                }\n");
					break;
				case DATUM_BIT_GROUP:
					fprintf(outfile, "                if(!Parse%sBit(lex)) {\n", dat->m_name);
					fprintf(outfile, "                    done = true; break;\n");
					fprintf(outfile, "                }\n");
					break;
				default:
					Assert(0);
					break;
			}
		}
		fprintf(outfile,         "                break;\n");
	}
}
Ejemplo n.º 10
0
void MemberClass::ExportMethods(FILE *outfile)
{
	PointerList<Datum>::Walker walk(&m_datumList);
	bool const  l_HasItems  = walk.IsValid();

	// Constructors
	fprintf(outfile,     "        %s();\n", m_name);
	fprintf(outfile,     "        %s(CivArchive & archive){ Serialize(archive); };\n", m_name);
	/// @todo Check copy constructor
	// Destructor
	fprintf(outfile,     "        ~%s();\n", m_name);
	// Assignment
	if (l_HasItems)
	{
		fprintf(outfile, "        %s const & operator = (%s const & rval);\n", m_name, m_name);
	}
	else
	{
		// No action: use compiler provided default
	}

	// Equality
	fprintf(outfile,     "        bool operator == (%s const & rval) {\n", m_name);
	bool record_element_found = false;
	for (walk.SetList(&m_datumList); walk.IsValid(); walk.Next())
	{
		if (walk.GetObj()->m_type == DATUM_RECORD)
		{
			fprintf(outfile, "          if (m_%s != rval.m_%s)\n",
					walk.GetObj()->m_name, walk.GetObj()->m_name);
			fprintf(outfile, "             return false;\n");
			record_element_found = true;
		}
	}
	fprintf(outfile,     "          return %s;\n", record_element_found ? "true" : "false");
	fprintf(outfile,     "        }\n\n");

	walk.SetList(&m_datumList);
	bool canParseSequentially = true;
	for
	(
		walk.SetList(&m_datumList);
		walk.IsValid() && canParseSequentially;
		walk.Next()
	)
	{
		switch(walk.GetObj()->m_type) {
			case DATUM_INT:
			case DATUM_FLOAT:
			case DATUM_STRING:
			case DATUM_FILE:
			case DATUM_RECORD:
				break;
			default:
				canParseSequentially = false;
				break;
		}
	}

	// Specials
	fprintf(outfile,     "        void Serialize(CivArchive &archive);\n");
	fprintf(outfile,     "        sint32 Parse(DBLexer *lex);\n");
	if(canParseSequentially) {
		fprintf(outfile, "        sint32 ParseSequential(DBLexer *lex);\n");
		fprintf(outfile, "        sint32 ParseFullySequential(DBLexer *lex);\n");
	}
	if(m_parseNum > 0){
		fprintf(outfile, "        sint32 ParseNum(DBLexer *lex);\n");
	}
	fprintf(outfile,     "        static sint32 ParseInArray(DBLexer *lex, %s **array, sint32 *numElements);\n", m_name);
	fprintf(outfile,     "        static sint32 ParseInArray(DBLexer *lex, %s *array, sint32 *numElements, sint32 maxSize);\n", m_name);
	if(canParseSequentially) {
		fprintf(outfile, "        static sint32 ParseInArraySequential(DBLexer *lex, %s **array, sint32 *numElements);\n", m_name);
		fprintf(outfile, "        static sint32 ParseInArraySequential(DBLexer *lex, %s *array, sint32 *numElements, sint32 maxSize);\n", m_name);
	}
	fprintf(outfile,     "        void ResolveDBReferences();\n\n");

	for (walk.SetList(&m_datumList); walk.IsValid(); walk.Next())
	{
		walk.GetObj()->ExportAccessor(outfile, 1, m_name);
	}
}
Ejemplo n.º 11
0
void MemberClass::ExportInitialization(FILE *outfile, char *recordName)
{
	PointerList<Datum>::Walker walk(&m_datumList);
    bool const l_HasItems   = walk.IsValid();

	fprintf(outfile, "%sRecord::%s::%s()\n", recordName, m_name, m_name);
	fprintf(outfile, "{\n");

	sint32 i;
	for(i = 0; i  < FlagCount(); i++)
    {
		fprintf(outfile, "    m_flags%d = 0;\n", i);
	}

	for (walk.SetList(&m_datumList); walk.IsValid(); walk.Next())
    {
		walk.GetObj()->ExportInitialization(outfile);
	}
	fprintf(outfile, "}\n\n");

	fprintf(outfile, "%sRecord::%s::~%s()\n", recordName, m_name, m_name);
	fprintf(outfile, "{\n");
	for (walk.SetList(&m_datumList); walk.IsValid(); walk.Next())
    {
		walk.GetObj()->ExportDestructor(outfile);
	}
	fprintf(outfile, "}\n\n");

	if (l_HasItems)
    {
	    fprintf(outfile, "%sRecord::%s const & %sRecord::%s::operator = (%s const & rval)\n",
                recordName, m_name, recordName, m_name, m_name
               );
	    fprintf(outfile, "{\n");
        fprintf(outfile, "    if (this != &rval)\n");
        fprintf(outfile, "    {\n");
        for (i = 0; i < FlagCount(); ++i)
        {
		    fprintf(outfile, "        m_flags%d = rval.m_flags%d;\n", i, i);
        }
        fprintf(outfile, "\n");
	    for (walk.SetList(&m_datumList); walk.IsValid(); walk.Next())
        {
		    walk.GetObj()->ExportOperatorAssignment(outfile);
	    }
        fprintf(outfile, "    }\n\n");
        fprintf(outfile, "    return *this;\n");
	    fprintf(outfile, "}\n\n");
    }
    else
    {
        // No action: use compiler provided default
    }

	fprintf(outfile, "void %sRecord::%s::Serialize(CivArchive &archive)\n", recordName, m_name, m_name);
	fprintf(outfile, "{\n");

	fprintf(outfile, "    if(archive.IsStoring()) {\n");

	for(i = 0; i < FlagCount(); ++i)
    {
		fprintf(outfile, "        archive << m_flags%d;\n", i);
	}

	for (walk.SetList(&m_datumList); walk.IsValid(); walk.Next())
    {
		walk.GetObj()->ExportSerializationStoring(outfile);
	}

	fprintf(outfile, "    } else {\n");

	for(i = 0; i  < FlagCount(); i++) {
		fprintf(outfile, "        archive >> m_flags%d;\n", i);
	}

	for (walk.SetList(&m_datumList); walk.IsValid(); walk.Next())
	{
		walk.GetObj()->ExportSerializationLoading(outfile);
	}

	fprintf(outfile, "    }\n");

	fprintf(outfile, "}\n\n");
}
Ejemplo n.º 12
0
static void foreachObjectLink(ModifierData *md, Object *ob,
                              void (*walk)(void *userData, Object *ob, Object **obpoin), void *userData)
{
	SimpleDeformModifierData *smd  = (SimpleDeformModifierData *)md;
	walk(userData, ob, &smd->origin);
}
Ejemplo n.º 13
0
TEST(HitTests, ParseFields)
{
  ValCase cases[] = {
      // types
      {"int", "foo=42", "foo", "42", hit::Field::Kind::Int},
      {"float1", "foo=4.2", "foo", "4.2", hit::Field::Kind::Float},
      {"float2", "foo=.42", "foo", ".42", hit::Field::Kind::Float},
      {"float3", "foo=1e10", "foo", "1e10", hit::Field::Kind::Float},
      {"float4", "foo=e-23", "foo", "e-23", hit::Field::Kind::Float},
      {"float5", "foo=12.345e+67", "foo", "12.345e+67", hit::Field::Kind::Float},
      {"bool-true1", "foo=true", "foo", "true", hit::Field::Kind::Bool},
      {"bool-true2", "foo=yes", "foo", "yes", hit::Field::Kind::Bool},
      {"bool-true3", "foo=on", "foo", "on", hit::Field::Kind::Bool},
      {"bool-case1", "foo=TRUE", "foo", "TRUE", hit::Field::Kind::Bool},
      {"bool-case2", "foo=ON", "foo", "ON", hit::Field::Kind::Bool},
      {"bool-case3", "foo=YeS", "foo", "YeS", hit::Field::Kind::Bool},
      {"bool-false1", "foo=false", "foo", "false", hit::Field::Kind::Bool},
      {"bool-false2", "foo=no", "foo", "no", hit::Field::Kind::Bool},
      {"bool-false3", "foo=off", "foo", "off", hit::Field::Kind::Bool},
      {"string", "foo=bar", "foo", "bar", hit::Field::Kind::String},
      {"string-almost-float1", "foo=1e23.3", "foo", "1e23.3", hit::Field::Kind::String},
      {"string-almost-float2", "foo=1a23.3", "foo", "1a23.3", hit::Field::Kind::String},
      {"string-almost-float3", "foo=1.2.3", "foo", "1.2.3", hit::Field::Kind::String},
      {"string-almost-float4", "foo=1e2e3", "foo", "1e2e3", hit::Field::Kind::String},

      // quotes and escaping
      {"quotes", "foo='bar'", "foo", "bar", hit::Field::Kind::String},
      {"doublequotes", "foo=\"bar\"", "foo", "bar", hit::Field::Kind::String},
      {"quotes_quotes", "foo='\\'bar\\''", "foo", "'bar'", hit::Field::Kind::String},
      {"quotes_doublequotes", "foo='\"bar\"'", "foo", "\"bar\"", hit::Field::Kind::String},
      {"doublequotes_doublequotes",
       "foo=\"\\\"bar\\\"\"",
       "foo",
       "\"bar\"",
       hit::Field::Kind::String},

      // misc
      {"valid special field chars",
       "hello_./:<>-+world=foo",
       "hello_./:<>-+world",
       "foo",
       hit::Field::Kind::String},
      {"left-bracket-after-number", "[hello]foo=42[]", "hello/foo", "42", hit::Field::Kind::Int},
      {"ignore leading spaces 1", "foo=    bar", "foo", "bar", hit::Field::Kind::String},
      {"ignore leading spaces 2", "foo=     \t42", "foo", "42", hit::Field::Kind::Int},
      {"ignore trailing spaces", "foo=bar\t   ", "foo", "bar", hit::Field::Kind::String},
      {"ignore unknown escapes",
       "foo='hello \\my nam\\e is joe'",
       "foo",
       "hello \\my nam\\e is joe",
       hit::Field::Kind::String},
      {"no escaped newline",
       "foo='hello\\nworld'",
       "foo",
       "hello\\nworld",
       hit::Field::Kind::String},
      {"cosecutive string literal 1", "foo='bar''baz'", "foo", "barbaz", hit::Field::Kind::String},
      {"cosecutive string literal 2",
       "foo='bar'\n\n'baz'",
       "foo",
       "barbaz",
       hit::Field::Kind::String},
  };

  for (size_t i = 0; i < sizeof(cases) / sizeof(ValCase); i++)
  {
    auto test = cases[i];
    auto root = hit::parse("TEST", test.input);
    ExpandWalker exw("TEST");
    root->walk(&exw);
    auto n = root->find(test.key);
    if (!n)
    {
      FAIL() << "case " << i + 1 << " (" << test.name << ") failed to find key '" << test.key
             << "'\n";
      continue;
    }
    if (n->strVal() != test.val)
    {
      FAIL() << "case " << i + 1 << " (" << test.name << ") wrong value (key=" << test.key
             << "): got '" << n->strVal() << "', want '" << test.val << "'\n";
      continue;
    }

    auto f = dynamic_cast<hit::Field *>(n);
    if (!f)
      FAIL() << "case " << i + 1 << " node type is not NodeType::Field";
    else if (f->kind() != test.kind)
      FAIL() << "case " << i + 1 << " wrong kind (key=" << test.key << "): got '"
             << strkind(f->kind()) << "', want '" << strkind(test.kind) << "'\n";
  }
}
Ejemplo n.º 14
0
void
arrangement::compute_ACScellBeginEnd()
{
    int ncr_begin = -1;
    int ncr_end = -1;

    Walk_pl walk_pl(nonCriticalRegions);

    // get NCR start
    Rational xt(target_centre.x());
    Rational yt(target_centre.y());
    Conic_point_2 pt(xt,yt);
    Arrangement_2::Vertex_handle v = insert_point(nonCriticalRegions, pt, walk_pl);
    try
    {
        ncr_begin = v->face()->data();
        nonCriticalRegions.remove_isolated_vertex(v);
    }
    catch (const std::exception exn)
    {
        target_centre = QPoint(target_centre.x()+1, target_centre.y()+1);
        compute_ACScellBeginEnd();
        return;
    }

    // get NCR end
    Rational xe(target_centre_end.x());
    Rational ye(target_centre_end.y());
    Conic_point_2 pe(xe,ye);
    Arrangement_2::Vertex_handle w = insert_point(nonCriticalRegions, pe, walk_pl);
    try
    {
        ncr_end = w->face()->data();
        nonCriticalRegions.remove_isolated_vertex(w);
    }
    catch (const std::exception exn)
    {
        target_centre_end = QPoint(target_centre_end.x()+1, target_centre_end.y()+1);
        compute_ACScellBeginEnd();
        return;
    }

    // retrieve ACScell
    for (int i = 0; i < (int) ACScells.size(); i++)
    if (ACScells[i].NCR == ncr_begin)
    {
        Rational x(manipulator_centre.x());
        Rational y(manipulator_centre.y());
        Conic_point_2 p(x,y);
        Walk_pl walk(ACScells[i].arr);
        Arrangement_2::Vertex_handle u = insert_point(ACScells[i].arr, p, walk);
        try
        {
            if (!u->face()->is_unbounded())
            {
                ACScells[i].arr.remove_isolated_vertex(u);
                AcscellBegin = i;
                break;
            }
        }
        catch (const std::exception exn)
        {
            manipulator_centre = QPoint(manipulator_centre.x()+1, manipulator_centre.y()+1);
            compute_ACScellBeginEnd();
            return;
        }
    }

    for (int i = 0; i < (int) ACScells.size(); i++)
    if (ACScells[i].NCR == ncr_end)
    {
        Rational x(manipulator_centre_end.x());
        Rational y(manipulator_centre_end.y());
        Conic_point_2 p(x,y);
        Walk_pl walk(ACScells[i].arr);
        Arrangement_2::Vertex_handle u = insert_point(ACScells[i].arr, p, walk);
        try
        {
            if (!u->face()->is_unbounded())
            {
                ACScells[i].arr.remove_isolated_vertex(u);
                AcscellEnd = i;
                break;
            }
        }
        catch (const std::exception exn)
        {
            manipulator_centre_end = QPoint(manipulator_centre_end.x()+1, manipulator_centre_end.y()+1);
            compute_ACScellBeginEnd();
            return;
        }
    }
}
Ejemplo n.º 15
0
 void visit(const Nodecl::ClassMemberAccess& node)
 {
     walk(node.get_lhs());
     // Do not walk the rhs
 }
Ejemplo n.º 16
0
void MemberClass::ExportDefaultToken(FILE *outfile, char *recordName)
{
	PointerList<Datum>::Walker walk(&m_datumList);
	Datum *dat = walk.GetObj();
	if(dat->m_maxSize == k_MAX_SIZE_VARIABLE) {

		switch(dat->m_type) {
			case DATUM_INT:
				fprintf(outfile, "                Assert(false)\n");
				fprintf(outfile, "                if(!CTPRecord::ParseIntInArray(lex, &m_%s, &m_num%s)) {\n", dat->m_name, dat->m_name);
				break;
			case DATUM_STRINGID:
				fprintf(outfile, "                Assert(false)\n");
				fprintf(outfile, "                if(!CTPRecord::ParseStringIdInArray(lex, m_%s, &m_num%s)) {\n", dat->m_name, dat->m_name);
				break;
			case DATUM_FLOAT:
				fprintf(outfile, "                Assert(false)\n");
				fprintf(outfile, "                if(!CTPRecord::ParseFloatInArray(lex, &m_%s, &m_num%s)) {\n", dat->m_name, dat->m_name);
				break;
			case DATUM_STRING:
			case DATUM_FILE:
				fprintf(outfile, "                Assert(false)\n");
				fprintf(outfile, "                if(!CTPRecord::ParseFileInArray(lex, &m_%s, &m_num%s)) {\n", dat->m_name, dat->m_name);
				break;
			case DATUM_RECORD:
				fprintf(outfile, "                Assert(false)\n");
				fprintf(outfile, "                if(!g_the%sDB->ParseRecordInArray(lex, &m_%s, &m_num%s)) {\n", dat->m_subType, dat->m_name, dat->m_name);
				break;
			case DATUM_STRUCT:
				fprintf(outfile, "                if(!%sRecord::%s::ParseInArraySequential(lex, &m_%s, &m_num%s)) {\n", recordName, dat->m_subType, dat->m_name, dat->m_name);
				break;
			default:
				Assert(0);
				break;
		}
		fprintf(outfile,         "                    DBERROR((\"Unknown token\"));\n");
		fprintf(outfile,         "                    done = true; break;\n");
		fprintf(outfile,         "                }\n");
	} else if(dat->m_maxSize > 0) {

		switch(dat->m_type) {
			case DATUM_INT:
				fprintf(outfile, "                Assert(false)\n");
				fprintf(outfile, "                if(!CTPRecord::GetIntInArray(lex, &m_%s, &m_num%s, k_MAX_%s)) {\n",
						dat->m_name, dat->m_name, dat->m_name);
				break;
			case DATUM_STRINGID:
				fprintf(outfile, "                Assert(false)\n");
				fprintf(outfile, "                if(!CTPRecord::GetStringIdInArray(lex, &m_%s, &m_num%s, k_MAX_%s)) {\n",
						dat->m_name, dat->m_name, dat->m_name);
				break;
			case DATUM_FLOAT:
				fprintf(outfile, "                Assert(false)\n");
				fprintf(outfile, "                if(!CTPRecord::ParseFloatInArray(lex, &m_%s, &m_num%s, k_MAX_%s)) {\n",
						dat->m_name, dat->m_name, dat->m_name);
				break;
			case DATUM_STRING:
			case DATUM_FILE:
				fprintf(outfile, "                Assert(false)\n");
				fprintf(outfile, "                if(!CTPRecord::ParseFileInArray(lex, &m_%s, &m_num%s, k_MAX_%s)) {\n",
						dat->m_name, dat->m_name, dat->m_name);
				break;
			case DATUM_RECORD:
				fprintf(outfile, "                Assert(false)\n");
				fprintf(outfile, "                if(!g_the%sDB->ParseRecordInArray(lex, &m_%s, &m_num%s, k_MAX_%s)) {\n",
						dat->m_subType, dat->m_name, dat->m_name, dat->m_name);
				break;
			case DATUM_STRUCT:
				fprintf(outfile, "                if(!%sRecord::%s::ParseInArraySequential(lex, &m_%s, &m_num%s, k_MAX_%s)) {\n",
						recordName, dat->m_subType, dat->m_name, dat->m_name, dat->m_name);
				break;
			default:
				Assert(0);
				break;
		}
	} else if(dat->m_maxSize < 0) {
		switch(dat->m_type) {
			case DATUM_INT:
				fprintf(outfile, "                if(!lex->GetInt(m_%s)) {\n", dat->m_name);
				fprintf(outfile, "                    DBERROR((\"Unknown token\"));\n");
				fprintf(outfile, "                    done = true; break;\n");
				fprintf(outfile, "                }\n");
				break;
			case DATUM_STRINGID:
				fprintf(outfile, "                if(!lex->GetStringId(m_%s)) {\n", dat->m_name);
				fprintf(outfile, "                    DBERROR((\"Unknown token\"));\n");
				fprintf(outfile, "                    done = true; break;\n");
				fprintf(outfile, "                }\n");
				break;
			case DATUM_BIT:
				fprintf(outfile, "                m_flags%d |= k_%s_%s_Bit;\n", dat->m_bitNum / 32,
						m_name, dat->m_name);
				break;
			case DATUM_BIT_PAIR:
				fprintf(outfile, "                m_flags%d |= k_%s_%s_Bit;\n", dat->m_bitNum / 32,
						m_name, dat->m_name);
				dat->ExportBitPairDirectParse(outfile, m_name);
				break;
			case DATUM_FLOAT:
				fprintf(outfile, "                if(!lex->GetFloat(m_%s)) {\n", dat->m_name);
				fprintf(outfile, "                    DBERROR((\"Unknown token\"));\n");
				fprintf(outfile, "                    done = true; break;\n");
				fprintf(outfile, "                }\n");
				break;
			case DATUM_STRING:
			case DATUM_FILE:
				fprintf(outfile, "                if(!lex->GetFile(m_%s)) {\n", dat->m_name);
				fprintf(outfile, "                    DBERROR((\"Unknown token\"));\n");
				fprintf(outfile, "                    done = true; break;\n");
				fprintf(outfile, "                }\n");
				break;
			case DATUM_RECORD:
				fprintf(outfile, "                if(!g_the%sDB->GetCurrentRecordFromLexer(lex, m_%s)) {\n", dat->m_subType, dat->m_name);
				fprintf(outfile, "                    DBERROR((\"Unknown token\"));\n");
				fprintf(outfile, "                    done = true; break;\n");
				fprintf(outfile, "                }\n");
				break;
			case DATUM_STRUCT:
				fprintf(outfile, "                if(!m_%s.ParseFullySequential(lex)) {\n", dat->m_name);
				fprintf(outfile, "                    DBERROR((\"Unknown token\"));\n");
				fprintf(outfile, "                    done = true; break;\n");
				fprintf(outfile, "                }\n");
				break;
			case DATUM_BIT_GROUP:
				fprintf(outfile, "                if(!Parse%sBit(lex)) {\n", dat->m_name);
				fprintf(outfile, "                    DBERROR((\"Unknown token\"));\n");
				fprintf(outfile, "                    done = true; break;\n");
				fprintf(outfile, "                }\n");
				break;
			default:
				Assert(0);
				break;
		}
	}
	fprintf(outfile,             "                break;\n");
}
Ejemplo n.º 17
0
extern bool walk(Node *n, bool parent) {
top:	sigchk();
	if (n == NULL) {
		if (!parent)
			exit(0);
		set(TRUE);
		return TRUE;
	}
	switch (n->type) {
	case nArgs: case nBackq: case nConcat: case nCount:
	case nFlat: case nLappend: case nRedir: case nVar:
	case nVarsub: case nWord:
		exec(glob(glom(n)), parent);	/* simple command */
		break;
	case nBody:
		walk(n->u[0].p, TRUE);
		WALK(n->u[1].p, parent);
		/* WALK doesn't fall through */
	case nNowait: {
		int pid;
		if ((pid = rc_fork()) == 0) {
#if defined(RC_JOB) && defined(SIGTTOU) && defined(SIGTTIN) && defined(SIGTSTP)
			setsigdefaults(FALSE);
			rc_signal(SIGTTOU, SIG_IGN);	/* Berkeleyized version: put it in a new pgroup. */
			rc_signal(SIGTTIN, SIG_IGN);
			rc_signal(SIGTSTP, SIG_IGN);
			setpgid(0, getpid());
#else
			setsigdefaults(TRUE);		/* ignore SIGINT, SIGQUIT, SIGTERM */
#endif
			mvfd(rc_open("/dev/null", rFrom), 0);
			walk(n->u[0].p, FALSE);
			exit(getstatus());
		}
		if (interactive)
			fprint(2, "%d\n", pid);
		varassign("apid", word(nprint("%d", pid), NULL), FALSE);
		redirq = NULL; /* kill pre-redir queue */
		break;
	}
	case nAndalso: {
		bool oldcond = cond;
		cond = TRUE;
		if (walk(n->u[0].p, TRUE)) {
			cond = oldcond;
			WALK(n->u[1].p, parent);
		} else
			cond = oldcond;
		break;
	}
	case nOrelse: {
		bool oldcond = cond;
		cond = TRUE;
		if (!walk(n->u[0].p, TRUE)) {
			cond = oldcond;
			WALK(n->u[1].p, parent);
		} else
			cond = oldcond;
		break;
	}
	case nBang:
		set(!walk(n->u[0].p, TRUE));
		break;
	case nIf: {
		bool oldcond = cond;
		Node *true_cmd = n->u[1].p, *false_cmd = NULL;
		if (true_cmd != NULL && true_cmd->type == nElse) {
			false_cmd = true_cmd->u[1].p;
			true_cmd = true_cmd->u[0].p;
		}
		cond = TRUE;
		if (!walk(n->u[0].p, TRUE))
			true_cmd = false_cmd; /* run the else clause */
		cond = oldcond;
		WALK(true_cmd, parent);
	}
	case nWhile: {
		Jbwrap j;
		Edata jbreak;
		Estack e1, e2;
		bool testtrue, oldcond = cond;
		cond = TRUE;
		if (!walk(n->u[0].p, TRUE)) { /* prevent spurious breaks inside test */
			cond = oldcond;
			break;
		}
		if (sigsetjmp(j.j, 1))
			break;
		jbreak.jb = &j;
		except(eBreak, jbreak, &e1);
		do {
			Edata block;
			block.b = newblock();
			cond = oldcond;
			except(eArena, block, &e2);
			walk(n->u[1].p, TRUE);
			testtrue = walk(n->u[0].p, TRUE);
			unexcept(); /* eArena */
			cond = TRUE;
		} while (testtrue);
		cond = oldcond;
		unexcept(); /* eBreak */
		break;
	}
	case nForin: {
		List *l, *var = glom(n->u[0].p);
		Jbwrap j;
		Estack e1, e2;
		Edata jbreak;
		if (sigsetjmp(j.j, 1))
			break;
		jbreak.jb = &j;
		except(eBreak, jbreak, &e1);
		for (l = listcpy(glob(glom(n->u[1].p)), nalloc); l != NULL; l = l->n) {
			Edata block;
			assign(var, word(l->w, NULL), FALSE);
			block.b = newblock();
			except(eArena, block, &e2);
			walk(n->u[2].p, TRUE);
			unexcept(); /* eArena */
		}
		unexcept(); /* eBreak */
		break;
	}
	case nSubshell:
		if (dofork(TRUE)) {
			setsigdefaults(FALSE);
			walk(n->u[0].p, FALSE);
			rc_exit(getstatus());
		}
		break;
	case nAssign:
		if (n->u[0].p == NULL)
			rc_error("null variable name");
		assign(glom(n->u[0].p), glob(glom(n->u[1].p)), FALSE);
		set(TRUE);
		break;
	case nPipe:
		dopipe(n);
		break;
	case nNewfn: {
		List *l = glom(n->u[0].p);
		if (l == NULL)
			rc_error("null function name");
		while (l != NULL) {
			if (dashex)
				prettyprint_fn(2, l->w, n->u[1].p);
			fnassign(l->w, n->u[1].p);
			l = l->n;
		}
		set(TRUE);
		break;
	}
	case nRmfn: {
		List *l = glom(n->u[0].p);
		while (l != NULL) {
			if (dashex)
				fprint(2, "fn %S\n", l->w);
			fnrm(l->w);
			l = l->n;
		}
		set(TRUE);
		break;
	}
	case nDup:
		redirq = NULL;
		break; /* Null command */
	case nMatch: {
		List *a = glob(glom(n->u[0].p)), *b = glom(n->u[1].p);
		if (dashex)
			fprint(2, (a != NULL && a->n != NULL) ? "~ (%L) %L\n" : "~ %L %L\n", a, " ", b, " ");
		set(lmatch(a, b));
		break;
	}
	case nSwitch: {
		List *v = glom(n->u[0].p);
		while (1) {
			do {
				n = n->u[1].p;
				if (n == NULL)
					return istrue();
			} while (n->u[0].p == NULL || n->u[0].p->type != nCase);
			if (lmatch(v, glom(n->u[0].p->u[0].p))) {
				for (n = n->u[1].p; n != NULL && (n->u[0].p == NULL || n->u[0].p->type != nCase); n = n->u[1].p)
					walk(n->u[0].p, TRUE);
				break;
			}
		}
		break;
	}
	case nPre: {
		List *v;
		if (n->u[0].p->type == nRedir || n->u[0].p->type == nDup) {
			if (redirq == NULL && !dofork(parent)) /* subshell on first preredir */
				break;
			setsigdefaults(FALSE);
			qredir(n->u[0].p);
			if (!haspreredir(n->u[1].p))
				doredirs(); /* no more preredirs, empty queue */
			walk(n->u[1].p, FALSE);
			rc_exit(getstatus());
			/* NOTREACHED */
		} else if (n->u[0].p->type == nAssign) {
			if (isallpre(n->u[1].p)) {
				walk(n->u[0].p, TRUE);
				WALK(n->u[1].p, parent);
			} else {
				Estack e;
				Edata var;
				v = glom(n->u[0].p->u[0].p);
				assign(v, glob(glom(n->u[0].p->u[1].p)), TRUE);
				var.name = v->w;
				except(eVarstack, var, &e);
				walk(n->u[1].p, parent);
				varrm(v->w, TRUE);
				unexcept(); /* eVarstack */
			}
		} else
			panic("unexpected node in preredir section of walk");
		break;
	}
	case nBrace:
		if (n->u[1].p == NULL) {
			WALK(n->u[0].p, parent);
		} else if (dofork(parent)) {
			setsigdefaults(FALSE);
			walk(n->u[1].p, TRUE); /* Do redirections */
			redirq = NULL;   /* Reset redirection queue */
			walk(n->u[0].p, FALSE); /* Do commands */
			rc_exit(getstatus());
			/* NOTREACHED */
		}
		break;
	case nEpilog:
		qredir(n->u[0].p);
		if (n->u[1].p != NULL) {
			WALK(n->u[1].p, parent); /* Do more redirections. */
		} else {
			doredirs();	/* Okay, we hit the bottom. */
		}
		break;
	case nNmpipe:
		rc_error("named pipes cannot be executed as commands");
		/* NOTREACHED */
	default:
		panic("unknown node in walk");
		/* NOTREACHED */
	}
	return istrue();
}
Ejemplo n.º 18
0
		void foreach(In *c,void (In::*action)(ObjectType*)) // Applies a method to every layer element
		{
			walk([c,action](ObjectType *o){(c->*action)(o);});
		}
Ejemplo n.º 19
0
static void
talk (struct state *st, int force_erase)
{
    int             width = 0,
                    height,
                    Z,
                    total = 0;
    register char  *p,
                   *p2;
    char            args[MAXLINES][LINELEN];

    /* clear what we've written */
    if (st->talking || force_erase)
    {
	if (!st->talking)
	    return;
	XFillRectangle(st->dpy, st->window, st->bg_gc, st->s_rect.x - 5, st->s_rect.y - 5,
		       st->s_rect.width + 10, st->s_rect.height + 10);
	st->talking = 0;
	if (!force_erase)
	  st->next_fn = move;
	st->interval = 0;
	{
	  /* might as well check the st->window for size changes now... */
	  XWindowAttributes xgwa;
	  XGetWindowAttributes (st->dpy, st->window, &xgwa);
	  st->Width = xgwa.width + 2;
	  st->Height = xgwa.height + 2;
	}
	return;
    }
    p = st->words;
    /* If there is actually no words, just return */
    if (!*p)
    {
      st->talking = 0;
      return;
    }
    st->talking = 1;
    walk(st, FRONT);

    for (p2 = p; *p2; p2++)
      if (*p2 == '\t') *p2 = ' ';

    if (!(p2 = strchr(p, '\n')) || !p2[1])
      {
        XGlyphInfo extents;

	total = strlen (st->words);
	strncpy (args[0], st->words, LINELEN);
	args[0][LINELEN - 1] = 0;
        XftTextExtentsUtf8 (st->dpy, st->xftfont, 
                            (FcChar8 *) st->words, total,
                            &extents);
        width = extents.xOff;
	height = 0;
      }
    else
      /* p2 now points to the first '\n' */
      for (height = 0; p; height++)
	{
	  int             w;
          XGlyphInfo extents;
	  *p2 = 0;

          XftTextExtentsUtf8 (st->dpy, st->xftfont, 
                              (FcChar8 *) p, p2 - p,
                              &extents);
          w = extents.xOff;
	  if (w > width)
            width = w;

	  total += p2 - p;	/* total chars; count to determine reading
				 * time */
	  (void) strncpy(args[height], p, LINELEN);
	  args[height][LINELEN - 1] = 0;
	  if (height == MAXLINES - 1)
	    {
	      /* puts("Message too long!"); */
	      break;
	    }
	  p = p2 + 1;
	  if (!(p2 = strchr(p, '\n')))
	    break;
	}
    height++;

    /*
     * Figure out the height and width in pixels (height, width) extend the
     * new box by 15 pixels on the sides (30 total) top and bottom.
     */
    st->s_rect.width = width + 30;
    st->s_rect.height = height * font_height(st->xftfont) + 30;
    if (st->x - st->s_rect.width - 10 < 5)
	st->s_rect.x = 5;
    else if ((st->s_rect.x = st->x + 32 - (st->s_rect.width + 15) / 2)
	     + st->s_rect.width + 15 > st->Width - 5)
	st->s_rect.x = st->Width - 15 - st->s_rect.width;
    if (st->y - st->s_rect.height - 10 < 5)
	st->s_rect.y = st->y + 64 + 5;
    else
	st->s_rect.y = st->y - 5 - st->s_rect.height;

    XFillRectangle(st->dpy, st->window, st->text_bg_gc,
	 st->s_rect.x, st->s_rect.y, st->s_rect.width, st->s_rect.height);

    /* make a box that's 5 pixels thick. Then add a thin box inside it */
    XSetLineAttributes(st->dpy, st->text_fg_gc, 5, 0, 0, 0);
    XDrawRectangle(st->dpy, st->window, st->text_fg_gc,
		   st->s_rect.x, st->s_rect.y, st->s_rect.width - 1, st->s_rect.height - 1);
    XSetLineAttributes(st->dpy, st->text_fg_gc, 0, 0, 0, 0);
    XDrawRectangle(st->dpy, st->window, st->text_fg_gc,
	 st->s_rect.x + 7, st->s_rect.y + 7, st->s_rect.width - 15, st->s_rect.height - 15);

    st->X = 15;
    st->Y = 15 + font_height(st->xftfont);

    /* now print each string in reverse order (start at bottom of box) */
    for (Z = 0; Z < height; Z++)
    {
        int L = strlen(args[Z]);
        /* If there are continuous new lines, L can be 0 */
        if (L && (args[Z][L-1] == '\r' || args[Z][L-1] == '\n'))
          args[Z][--L] = 0;
        XftDrawStringUtf8 (st->xftdraw, &st->xftcolor, st->xftfont,
                           st->s_rect.x + st->X, st->s_rect.y + st->Y,
                           (FcChar8 *) args[Z], L);

	st->Y += font_height(st->xftfont);
    }
    st->interval = (total / 15) * 1000;
    if (st->interval < 2000) st->interval = 2000;
    st->next_fn = talk_1;
    *st->words = 0;
    st->lines = 0;
}
Ejemplo n.º 20
0
		void apply(void (ObjectType::*action)(OtherArg),OtherArg *a) // Uses a method from each element
		{
			walk([action,a](ObjectType *o){(o->*action)(a);});
		}
        void VectorizerVisitorExpression::visit(const Nodecl::Assignment& n)
        {
            Nodecl::NodeclBase lhs = n.get_lhs();
            walk(n.get_rhs());

            // Computing new vector type
            TL::Type vector_type = n.get_type();
            /*
            if (vector_type.is_lvalue_reference())
            {
                vector_type = vector_type.references_to();
            }
            */
            vector_type = get_qualified_vector_to(vector_type, _vector_length);

            if(lhs.is<Nodecl::ArraySubscript>())
            {
                // Vector Store
                if(Vectorizer::_analysis_info->is_adjacent_access(
                            Vectorizer::_analysis_scopes->back(),
                            lhs))
                {
                    TL::Type basic_type = lhs.get_type();
                    if (basic_type.is_lvalue_reference())
                    {
                        basic_type = basic_type.references_to();
                    }

                    const Nodecl::VectorStore vector_store =
                        Nodecl::VectorStore::make(
                                Nodecl::Reference::make(
                                    Nodecl::ParenthesizedExpression::make(
                                        lhs.shallow_copy(),
                                        basic_type,
                                        n.get_locus()),
                                    basic_type.get_pointer_to(),
                                    n.get_locus()),
                                n.get_rhs().shallow_copy(),
                                vector_type,
                                n.get_locus());

                    n.replace(vector_store);
                }
                else // Vector Scatter
                {
                    const Nodecl::ArraySubscript lhs_array = lhs.as<Nodecl::ArraySubscript>();

                    const Nodecl::NodeclBase base = lhs_array.get_subscripted();
                    const Nodecl::List subscripts = lhs_array.get_subscripts().as<Nodecl::List>();

                    std::cerr << "Scatter: " << lhs_array.prettyprint() << "\n";

                    ERROR_CONDITION(subscripts.size() > 1,
                            "Vectorizer: Scatter on multidimensional array is not supported yet!", 0);

                    Nodecl::NodeclBase strides = *subscripts.begin();
                    walk(strides);

                    const Nodecl::VectorScatter vector_scatter =
                        Nodecl::VectorScatter::make(
                                base.shallow_copy(),
                                strides,
                                n.get_rhs().shallow_copy(),
                                vector_type,
                                n.get_locus());

                    n.replace(vector_scatter);
                }
            }
            else // Register
            {
                walk(lhs);

                const Nodecl::VectorAssignment vector_assignment =
                    Nodecl::VectorAssignment::make(
                            lhs.shallow_copy(),
                            n.get_rhs().shallow_copy(),
                            vector_type,
                            n.get_locus());

                n.replace(vector_assignment);
            }
        }
Ejemplo n.º 22
0
		void apply(void (ObjectType::*action)()) // Uses a method from each object, without argument
		{
			walk([action](ObjectType *o){(o->*action)();});
		}
Ejemplo n.º 23
0
	void action(){
        if(walking){
            walk();
        }
	}
Ejemplo n.º 24
0
		void delete_all() // Delete all objects in the layer
		{
			walk([](ObjectType *o){delete o;});
		}
Ejemplo n.º 25
0
/* forloop -- evaluate a for loop */
static List *forloop(Tree *defn0, Tree *body0,
		     Binding *binding, int evalflags) {
	static List MULTIPLE = { NULL, NULL };

	Ref(List *, result, true);
	Ref(Binding *, outer, binding);
	Ref(Binding *, looping, NULL);
	Ref(Tree *, body, body0);

	Ref(Tree *, defn, defn0);
	for (; defn != NULL; defn = defn->u[1].p) {
		assert(defn->kind == nList);
		if (defn->u[0].p == NULL)
			continue;
		Ref(Tree *, assign, defn->u[0].p);
		assert(assign->kind == nAssign);
		Ref(List *, vars, glom(assign->u[0].p, outer, FALSE));
		Ref(List *, list, glom(assign->u[1].p, outer, TRUE));
		if (vars == NULL)
			fail("es:for", "null variable name");
		for (; vars != NULL; vars = vars->next) {
			char *var = getstr(vars->term);
			looping = mkbinding(var, list, looping);
			list = &MULTIPLE;
		}
		RefEnd3(list, vars, assign);
		SIGCHK();
	}
	looping = reversebindings(looping);
	RefEnd(defn);

	ExceptionHandler

		for (;;) {
			Boolean allnull = TRUE;
			Ref(Binding *, bp, outer);
			Ref(Binding *, lp, looping);
			Ref(Binding *, sequence, NULL);
			for (; lp != NULL; lp = lp->next) {
				Ref(List *, value, NULL);
				if (lp->defn != &MULTIPLE)
					sequence = lp;
				assert(sequence != NULL);
				if (sequence->defn != NULL) {
					value = mklist(sequence->defn->term,
						       NULL);
					sequence->defn = sequence->defn->next;
					allnull = FALSE;
				}
				bp = mkbinding(lp->name, value, bp);
				RefEnd(value);
			}
			RefEnd2(sequence, lp);
			if (allnull) {
				RefPop(bp);
				break;
			}
			result = walk(body, bp, evalflags & eval_exitonfalse);
			RefEnd(bp);
			SIGCHK();
		}

	CatchException (e)

		if (!termeq(e->term, "break"))
			throw(e);
		result = e->next;

	EndExceptionHandler

	RefEnd3(body, looping, outer);
	RefReturn(result);
}
Ejemplo n.º 26
0
void Character::update(float frameTime) {
	if(invertColorCount > 0)
	{
		if(invertColorCount == 1)
		{
			this->body->color = D3DCOLOR_ARGB(510,255,255,255) - this->body->color;
		}
		invertColorCount--;

	}

//Show the Character angle
	#ifdef SHOW_ANGLE
	sin.str("");
    sin << aimAngle;
	#endif

//Movement based on collision detection
	if (standingOn == 0 || !standingOn->getActive()) {
		D3DXVECTOR2 v (
			body->getVelocity().x, 
			body->getVelocity().y + frameTime * characterNS::GRAVITY_Y
		);

		setVelocity(v);
	} else {
		int xpos = body->getX();

		if (body->getCenterX() + 12 < standingOn->corners[0].x || body->getCenterX() - 12 > standingOn->corners[3].x) {
			standingOn = 0;
		}
	}

//Move left or right
	if (input->isKeyDown(characterNS::WALK_LEFT) ^ input->isKeyDown(characterNS::WALK_RIGHT)) {
		faceDir = input->isKeyDown(characterNS::WALK_RIGHT) ? 1 : -1;
		body->walking = true;
	} else {
		faceDir = 0;
		body->walking = false;
	}

//Crouch, disabled, sad face :(
	//body->crouch = input->isKeyDown(characterNS::CROUCH);
	//head->crouch = input->isKeyDown(characterNS::CROUCH);

	if (standingOn != 0) {
		walk(frameTime);

		if (input->isKeyDown(characterNS::JUMP) || input->isKeyDown('W')) {
			jump();
			body->jumping = true;
		} else {
			body->jumping = false;
		}
	} else {
		walk(frameTime/3);
		body->jumping = true;
	}

//Ready? Aim... <insert "fire" statement here, when ready>
	
	//aimAngle = atan2(
	//	body->getY() - static_cast<float>(input->getMouseY()),
	//	body->getX() - static_cast<float>(input->getMouseX())
	//);

//Determine orientation of the player, based on the mouse direction
	if (aimAngle > PI2) { // Quadrant 1
		faceDir = 1;
	}

	if (aimAngle < PI2 && aimAngle > 0.0) { // Quadrant 2
		faceDir = -1;
	}

	if (aimAngle > -PI2 && aimAngle <= 0.0) { // Quadrant 3
		faceDir = -1;
	}

	if (aimAngle < -PI2 && aimAngle <= 0.0) { // Quadrant 4
		faceDir = 1;
	}

//Set the direction of the player
	body->faceDir = faceDir;
//	head->faceDir = faceDir;

	body->update(frameTime);
	//cursor->update(frameTime);
//	head->update(frameTime);

	updateCorners();

	if(currentWeapon != 0)
	{
		currentWeapon->setAngle(aimAngle);
		currentWeapon->setX(getCenterX() + weaponPos.x * std::cos(aimAngle) + weaponPos.y * std::sin(aimAngle) - currentWeapon->getWidth()/2);
		currentWeapon->setY(getCenterY() + weaponPos.y * std::cos(aimAngle) + weaponPos.x * std::sin(aimAngle) -currentWeapon->getHeight()/2);
		currentWeapon->update(frameTime);
		//Reload if r is pressed or the ammoCount is 0
		if(reloadStep == 0 && (input->isKeyDown('R') || reinterpret_cast<Gun*>(currentWeapon)->mag->ammoCount == 0))
		{
			reloadStep = 1;
			reloadTimer = frameTime;
		}
		if(reloadStep != 0)
		{
			reloadTimer += frameTime;
			if(reloadTimer > static_cast<Gun*>(currentWeapon)->reloadTime)
			{
				if(static_cast<Gun*>(currentWeapon)->isMagInGun)
				{
					currentMag->loadAmmo();
				}
				static_cast<Gun*>(currentWeapon)->loadMag();
				reloadStep = 0;
			}
			else if(reloadTimer > static_cast<Gun*>(currentWeapon)->reloadTime/100)
			{
				static_cast<Gun*>(currentWeapon)->removeMag();
				currentMag->loadAmmo();
			}
		}
		currentWeapon->act(frameTime, input->getMouseLButton(), false, false, false, false);
		if(input->getMouseLButton())
		{
			cursor->setDegrees(frameTime*360 + cursor->getDegrees());
		}
	}
}
Ejemplo n.º 27
0
std::vector<Vec3d> ClosedPolygon::getEqualDistancePoints(int numSides, const Vec3d& center)
{
	std::vector<Vec3d> result;

	int N = closedPoints.size();

	if(N < 1)	return result; // empty polygon

	for(int i = 0; i < N; i++)
		lines.push_back(Line(closedPoints[i], closedPoints[(i+1) % N], i));

	this->computeLengths();

	// Distance to walk on polygon
	double segmentLength = this->closedLength / numSides;

	// Locate start point using vecUp
	Vec3d startPoint;
	int startIndex = 0;

	Plane halfPlane(vecUp, center);
	//testPlanes1.push_back(halfPlane);

	double minDist = DBL_MAX;

	// Test intersection with all lines and remember minimum one
	for(int i = 0; i < N; i++)
	{
		Vec3d pointIntersect;

		int res = halfPlane.LineIntersect(lines[i], pointIntersect);

		if(res == INTERSECT || res == ENDPOINT_INTERSECT)
		{
			Vec3d toIntsect = pointIntersect - center;

			if(toIntsect.norm() < minDist && dot(toIntsect, vecB) > 0)
			{
				minDist = toIntsect.norm();

				startPoint = pointIntersect;
				startIndex = i;
			}
		}
	}

	double t = lines[startIndex].timeAt(startPoint);
	int index = startIndex;

	// Compute equal-dist points on polygon
	for(int s = 0; s < numSides; s++)
	{
		// Add new point
		result.push_back(lines[index].pointAt(t));

		walk(segmentLength, t, index, &t, &index);
	}

	// if polygon is opposite direction then reverse 
	if( signedArea(result, plane.n, center) < 0 )
	{
		std::reverse(result.begin(), result.end());
		std::rotate(result.begin(), result.begin()+result.size()-1 , result.end());
	}

	return closedPoints = result;
}
Ejemplo n.º 28
0
void Character::update(float frameTime, bool rightButton, bool leftButton, bool jumpButton, bool shootButton, bool reloadButton)
{
	
//Show the Character angle

//Movement based on collision detection
	if (standingOn == 0 || !standingOn->getActive()) {
		D3DXVECTOR2 v (
			body->getVelocity().x, 
			body->getVelocity().y + frameTime * characterNS::GRAVITY_Y
		);

		setVelocity(v);
	} else {
		int xpos = body->getX();

		if (body->getCenterX() + 12 < standingOn->corners[0].x || body->getCenterX() - 12 > standingOn->corners[3].x) {
			standingOn = 0;
		}
	}

//Move left or right
	if (leftButton ^ rightButton) {
		faceDir = rightButton ? 1 : -1;
		body->walking = true;
	} else {
		faceDir = 0;
		body->walking = false;
	}


	if (standingOn != 0) {
		walk(frameTime);

		if (jumpButton) {
			jump();
			body->jumping = true;
		} else {
			body->jumping = false;
		}
	} else {
		walk(frameTime/3);
		body->jumping = true;
	}

//Determine orientation of the player, based on the mouse direction
	if (aimAngle > PI2) { // Quadrant 1
		faceDir = 1;
	}

	if (aimAngle < PI2 && aimAngle > 0.0) { // Quadrant 2
		faceDir = -1;
	}

	if (aimAngle > -PI2 && aimAngle <= 0.0) { // Quadrant 3
		faceDir = -1;
	}

	if (aimAngle < -PI2 && aimAngle <= 0.0) { // Quadrant 4
		faceDir = 1;
	}

//Set the direction of the player
	body->faceDir = faceDir;
//	head->faceDir = faceDir;

	body->update(frameTime);
	//cursor->update(frameTime);
//	head->update(frameTime);

	updateCorners();

	if(currentWeapon != 0)
	{
		currentWeapon->setAngle(aimAngle);
		currentWeapon->setX(getCenterX() + weaponPos.x * std::cos(aimAngle) + weaponPos.y * std::sin(aimAngle) - currentWeapon->getWidth()/2);
		currentWeapon->setY(getCenterY() + weaponPos.y * std::cos(aimAngle) + weaponPos.x * std::sin(aimAngle) -currentWeapon->getHeight()/2);
		currentWeapon->update(frameTime);
		//Reload if r is pressed or the ammoCount is 0
		if(reloadStep == 0 && (reloadButton || reinterpret_cast<Gun*>(currentWeapon)->mag->ammoCount == 0))
		{
			reloadStep = 1;
			reloadTimer = frameTime;
		}
		if(reloadStep != 0)
		{
			reloadTimer += frameTime;
			if(reloadTimer > static_cast<Gun*>(currentWeapon)->reloadTime)
			{
				if(static_cast<Gun*>(currentWeapon)->isMagInGun)
				{
					currentMag->loadAmmo();
				}
				static_cast<Gun*>(currentWeapon)->loadMag();
				reloadStep = 0;
			}
			else if(reloadTimer > static_cast<Gun*>(currentWeapon)->reloadTime/100)
			{
				static_cast<Gun*>(currentWeapon)->removeMag();
				currentMag->loadAmmo();
			}
		}
		currentWeapon->act(frameTime, shootButton, false, false, false, false);
	}
}
Ejemplo n.º 29
0
Archivo: persist.cpp Proyecto: aosm/tcl
void c4_SaveContext::SaveIt(c4_HandlerSeq &root_, c4_Allocator **spacePtr_,
  c4_Bytes &rootWalk_) {
  d4_assert(_space != 0);

  const t4_i32 size = _strategy.FileSize();
  if (_strategy._failure != 0)
    return ;

  const t4_i32 end = _fullScan ? 0 : size - _strategy._baseOffset;

  if (_differ == 0) {
    if (_mode != 1)
      _space->Initialize();

    // don't allocate anything inside the file in extend mode
    if (_mode == 2 && end > 0) {
      _space->Occupy(1, end - 1);
      _nextSpace->Occupy(1, end - 1);
    }

    // the header is always reserved
    _space->Occupy(1, 7);
    _nextSpace->Occupy(1, 7);

    if (end > 0) {
      d4_assert(end >= 16);
      _space->Occupy(end - 16, 16);
      _nextSpace->Occupy(end - 16, 16);
      _space->Occupy(end, 8);
      _nextSpace->Occupy(end, 8);
    }
  }

  //AllocDump("a1", false);
  //AllocDump("a2", true);

  // first pass allocates columns and constructs shallow walks
  c4_Column walk(root_.Persist());
  SetWalkBuffer(&walk);
  CommitSequence(root_, true);
  SetWalkBuffer(0);
  CommitColumn(walk);

  c4_Bytes tempWalk;
  walk.FetchBytes(0, walk.ColSize(), tempWalk, true);

  t4_i32 limit = _nextSpace->AllocationLimit();
  d4_assert(limit >= 8 || _differ != 0);

  if (limit < 0) {
    // 2006-01-12 #2: catch file size exceeding 2 Gb
    _strategy._failure =  - 1; // unusual non-zero value flags this case
    return ;
  }

  bool changed = _fullScan || tempWalk != rootWalk_;

  rootWalk_ = c4_Bytes(tempWalk.Contents(), tempWalk.Size(), true);

  _preflight = false;

  // special-case to avoid saving data if file is logically empty
  // in that case, the data is 0x80 0x81 0x80 (plus the header)
  if (!_fullScan && limit <= 11 && _differ == 0) {
    _space->Initialize();
    _nextSpace->Initialize();
    changed = false;
  }

  if (!changed)
    return ;

  //AllocDump("b1", false);
  //AllocDump("b2", true);

  if (_differ != 0) {
    int n = _differ->NewDiffID();
    _differ->CreateDiff(n, walk);
    return ;
  }

  d4_assert(_mode != 0 || _fullScan);

  // this is the place where writing may start

  // figure out where the new file ends and write a skip tail there
  t4_i32 end0 = end;

  // true if the file need not be extended due to internal free space
  bool inPlace = end0 == limit - 8;
  if (inPlace) {
    d4_assert(!_fullScan);
    _space->Release(end0, 8);
    _nextSpace->Release(end0, 8);
    end0 -= 16; // overwrite existing tail markers
  } else {
    /* 18-11-2005 write new end marker and flush it before *anything* else! */
    if (!_fullScan && end0 < limit) {
      c4_FileMark mark1(limit, 0);
      _strategy.DataWrite(limit, &mark1, sizeof mark1);
      _strategy.DataCommit(0);
      if (_strategy._failure != 0)
        return ;
    }

    c4_FileMark head(limit + 16-end, _strategy._bytesFlipped, end > 0);
    _strategy.DataWrite(end, &head, sizeof head);

    if (end0 < limit)
      end0 = limit;
    // create a gap
  }

  t4_i32 end1 = end0 + 8;
  t4_i32 end2 = end1 + 8;

  if (!_fullScan && !inPlace) {
    c4_FileMark mark1(end0, 0);
    _strategy.DataWrite(end0, &mark1, sizeof mark1);
#if q4_WIN32
    /* March 8, 2002
     * On at least NT4 with NTFS, extending a file can cause it to be
     * rounded up further than expected.  To prevent creating a bad
     * file (since the file does then not end with a marker), the
     * workaround it so simply accept the new end instead and rewrite.
     * Note that between these two writes, the file is in a bad state.
     */
    t4_i32 realend = _strategy.FileSize() - _strategy._baseOffset;
    if (realend > end1) {
      end0 = limit = realend - 8;
      end1 = realend;
      end2 = realend + 8;
      c4_FileMark mark1a(end0, 0);
      _strategy.DataWrite(end0, &mark1a, sizeof mark1a);
    }
#endif 
    d4_assert(_strategy.FileSize() == _strategy._baseOffset + end1);
  }

  _space->Occupy(end0, 16);
  _nextSpace->Occupy(end0, 16);

  // strategy.DataCommit(0); // may be needed, need more info on how FS's work
  // but this would need more work, since we can't adjust file-mapping here

  // second pass saves the columns and structure to disk
  CommitSequence(root_, true); // writes changed columns
  CommitColumn(walk);

  //! d4_assert(_curr == 0);
  d4_assert(_nextPosIndex == _newPositions.GetSize());

  if (_fullScan) {
    c4_FileMark mark1(limit, 0);
    _strategy.DataWrite(_strategy.FileSize() - _strategy._baseOffset,  &mark1,
      sizeof mark1);

    c4_FileMark mark2(limit - walk.ColSize(), walk.ColSize());
    _strategy.DataWrite(_strategy.FileSize() - _strategy._baseOffset,  &mark2,
      sizeof mark2);

    return ;
  }

  if (inPlace)
    d4_assert(_strategy.FileSize() == _strategy._baseOffset + end2);
  else {
    // make sure the allocated size hasn't changed
    d4_assert(_nextSpace->AllocationLimit() == limit + 16);
    d4_assert(end0 >= limit);
    d4_assert(_strategy.FileSize() - _strategy._baseOffset == end1);
  }

  if (walk.Position() == 0 || _strategy._failure != 0)
    return ;

  _strategy.DataCommit(0);

  c4_FileMark mark2(walk.Position(), walk.ColSize());
  _strategy.DataWrite(end1, &mark2, sizeof mark2);
  d4_assert(_strategy.FileSize() - _strategy._baseOffset == end2);

  // do not alter the file header in extend mode, unless it is new
  if (!_fullScan && (_mode == 1 || end == 0)) {
    _strategy.DataCommit(0);

    c4_FileMark head(end2, _strategy._bytesFlipped, false);
    d4_assert(head.IsHeader());
    _strategy.DataWrite(0, &head, sizeof head);

    // if the file became smaller, we could shrink it
    if (limit + 16 < end0) {
      /*
      Not yet, this depends on the strategy class being able to truncate, but
      there is no way to find out whether it does (the solution is to write tail
      markers in such a way that the file won't grow unnecessarily if it doesn't).

      The logic will probably be:

       * write new skip + commit "tails" at limit (no visible effect on file)
       * overwrite commit tail at end  with a skip to this new one (equivalent)
       * replace header with one pointing to that internal new one (equivalent)
       * flush (now the file is valid both truncated and not-yet-truncated

      end = limit;
       */
    }
  }

  // if using memory mapped files, make sure the map is no longer in use
  if (_strategy._mapStart != 0)
    root_.UnmappedAll();

  // commit and tell strategy object what the new file size is, this
  // may be smaller now, if old data at the end is no longer referenced
  _strategy.DataCommit(end2);

  d4_assert(_strategy.FileSize() - _strategy._baseOffset == end2);

  if (spacePtr_ != 0 && _space != _nextSpace) {
    d4_assert(*spacePtr_ == _space);
    delete  *spacePtr_;
    *spacePtr_ = _nextSpace;
    _nextSpace = 0;
  }
}
Ejemplo n.º 30
0
// on "init" you need to initialize your instance
bool City_layer::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    selected=nullptr;
    horizontalPlane=Plane(Vec3(0,1,0),Vec3(0,0,0));
    _rotation=0.f;
    //_firstrotation=0.f;
    
    Size size=Director::getInstance()->getWinSize();
    pCamera=Camera::createPerspective(60.0,size.width/size.height,0.1f,2000);
    pCamera->setCameraFlag(CameraFlag::USER1);
    pCamera->setPosition3D(Vec3(0,250,500));
    pCamera->lookAt(Vec3(0,0,0));
    addChild(pCamera);
    //sdsdsdsd
    
        node1=DrawNode3D::create();
        node1->clear();
        node1->setCameraMask(2);
        addChild(node1);
    
   // 天空盒
//    Skybox*sky=Skybox::create("Default/desert_left.jpg", "Default/desert_right.jpg", "Default/desert_top.jpg", "Default/desert_top.jpg", "Default/desert_front.jpg", "Default/desert_back.jpg");
//    sky->setCameraMask(2);
//    addChild(sky);

    
    
//    Terrain::DetailMap r("TerrainTest/dirt.jpg"),g("TerrainTest/Grass2.jpg"),b("TerrainTest/road.jpg"),a("TerrainTest/GreenSkin.jpg");
//    
//    Terrain::TerrainData data("TerrainTest/heightmap16.jpg","TerrainTest/alphamap.png",r,g,b,a);
//    
//    _terrain = Terrain::create(data,Terrain::CrackFixedType::SKIRT);
//    _terrain->setLODDistance(3.2f,6.4f,9.6f);
//    _terrain->setMaxDetailMapAmount(4);
//    addChild(_terrain);
//    _terrain->setCameraMask(2);
//    _terrain->setDrawWire(false);
    
    
    Terrain::DetailMap r("TerrainTest/dirt.jpg"),g("TerrainTest/Grass2.jpg"),b("TerrainTest/road.jpg"),a("TerrainTest/GreenSkin.jpg");
    
    //Terrain::TerrainData data("TerrainTest/heightmap0.jpg","TerrainTest/alphamapyellow.png",r,g,b,a);
   
    Terrain::TerrainData data("TerrainTest/heightmap16.jpg","TerrainTest/alphamap.png",r,g,b,a);
   
    _terrain = Terrain::create(data,Terrain::CrackFixedType::SKIRT);
    //_terrain->setLightMap("TerrainTest/Lightmap.png");
  
    _terrain->setLODDistance(3.2f,6.4f,9.6f);
    _terrain->setMaxDetailMapAmount(4);
    addChild(_terrain);
   
    _terrain->setScale(20.f, 1.f);
    _terrain->setScaleZ(20.f);
    _terrain->setCameraMask(2);
    _terrain->setDrawWire(false);

    // create_house("garbageTruck", Vec3(-50,0,100), Vec3(0,0,0),0.3);
    create_house("fanceWooden", Vec3(100,0,-100), Vec3(0,0,0),0.3);
    
    create_human1(Vec3(-50,0,100),1);
    create_human2(Vec3(50,0,100),1);
    
    create_house("houseBig", Vec3(-100,0,-100), Vec3(0,0,0),0.3);
    
//    auto floor=Sprite3D::create("plane.c3t","plane.png");
//    floor->setPosition3D(Vec3(480,0,0));
//    floor->setScaleX(100);
//    floor->setScaleY(100);
//    floor->setRotation3D(Vec3(90,0,0));
//    floor->setCameraMask(2);
//    addChild(floor);
//    
//    
//    Charecter1*player=Charecter1::create();
//    player->setPosition3D(Vec3(480,10,0));
//    player->setRotation3D(Vec3(0,0,0));
//    player->stand();
//    player->setCameraMask(2);
//    addChild(player,0,9);
//    
//    create_monster(Vec3(300,10,200));
//    create_monster(Vec3(500,10,-100));
//    create_monster(Vec3(-100,10,-400));
//    create_monster(Vec3(-100,10,300));
//    create_monster(Vec3(-900,10,1300));
//    create_monster(Vec3(-900,10,-1300));
//     create_monster(Vec3(1500,10,1300));
//     create_monster(Vec3(1500,10,-1300));
    auto touchEvt=EventListenerTouchOneByOne::create();
    touchEvt->onTouchBegan=[=](Touch*ptouch,Event*pevent){
        
        
            auto location = ptouch->getLocationInView();
            auto obbSize = vecObj.size();
            if(obbSize)
            {
                CCLOG("size:%lu",obbSize);
                Ray ray;
                calculateRayByLocationInView(&ray,location);
                bool touchOne=false;
                for(decltype(obbSize) i = 0; i < obbSize; i++)
                {
//                    Vec3 des = ray.intersects(horizontalPlane);
//                    CCLOG("X:%f,Y:%f,Z:%f",des.x,des.y,des.z);
//                    CCLOG("i:%lu",i);
                    if(ray.intersects(vecObj.at(i)->getAABB()))
                    {
                        touchOne=true;
                        if(dynamic_cast<CharecterBase*>(selected)){
                            auto pp = static_cast<CharecterBase*>(selected);
                            pp->mainLogic();
                            pp->scheduleUpdate();
                            
                        }
                        selected=vecObj.at(i);
//                        Vec3 corners[8]={};
//                        AABB aabbsp1=_aabb[i];
//                        aabbsp1.getCorners(corners);
//                        node1->drawCube(corners, Color4F(1,0,0,1));

                    }
                }
            
                if(!touchOne){
                        if(selected){
                            auto location = ptouch->getLocationInView();
                            Ray ray;
                            calculateRayByLocationInView(&ray,location);
                            Vec3 des = ray.intersects(horizontalPlane);
                    
                            if(dynamic_cast<CharecterBase*>(selected)){
                                //旋转
                                selected->unscheduleAllCallbacks();
                    
                                Vec3 delta=des-selected->getPosition3D();
                    
                                float angle =  Vec2(0,1).getAngle(Vec2(delta.x,delta.z));
                                if(delta.x!=0||delta.z!=0){
                                    Quaternion tt(Vec3(0,-1,0),angle);
                                    selected->setRotationQuat(tt);
                                }
                                //移动
                                auto pp = static_cast<CharecterBase*>(selected);
                                pp->speedDirection=Vec3(0,0,0);//自由移动失效
                                pp->walk();
                                
                                auto time =delta.length()/pp->walk_speed/30;
                                
                                CCLOG("%f->length,%f->time",delta.length(),time);
                                pp->runAction(Sequence::create(MoveTo::create(time, des),CallFuncN::create([=](Ref*pSender){
                                    pp->stand();
                                }),NULL));
                                
                            }else{
                                selected=nullptr;
                            }
                }
                }
            }
        

        
        return true;
    };
    touchEvt->onTouchMoved=[=](Touch*ptouch,Event*pevent){
           // 圆面相机 第3人称相机的移动
//            auto location=ptouch->getLocation();
//            Vec2 newPos=ptouch->getPreviousLocation()-location;
//            _rotation+=newPos.x/1000; //算出角度
//       
//            float deltax=100*sin(_rotation);//x增量
//            float deltaz=100*cos(_rotation);//z增量
//            pCamera->setPosition3D(Vec3(deltax,50,deltaz));
//            pCamera->lookAt(Vec3(0,0,0));
        auto location = ptouch->getLocation();
        auto delta=ptouch->getDelta();
        pCamera->setPosition3D(pCamera->getPosition3D()+Vec3(-delta.x,0,delta.y));
       // pCamera->lookAt(Vec3(0,0,0));
   
           };
  //    touchEvt->onTouchEnded=[=](Touch*ptouch,Event*pevent){
//    if(selected){
//        auto location = ptouch->getLocationInView();
//        Ray ray;
//        calculateRayByLocationInView(&ray,location);
//        Vec3 des = ray.intersects(horizontalPlane);
//        
//        if(dynamic_cast<CharecterBase*>(selected)){
//            //旋转
//            selected->unscheduleAllCallbacks();
//            
//            Vec3 delta=des-selected->getPosition3D();
//            
//            float angle =  Vec2(0,1).getAngle(Vec2(delta.x,delta.z));
//            if(delta.x!=0||delta.z!=0){
//                Quaternion tt(Vec3(0,-1,0),angle);
//                selected->setRotationQuat(tt);
//            }
//            //移动
//            auto pp = static_cast<CharecterBase*>(selected);
//            pp->speedDirection=Vec3(0,0,0);//自由移动失效
//            pp->walk();
//            
//            auto time =delta.length()/pp->walk_speed/30;
//            
//            CCLOG("%f->length,%f->time",delta.length(),time);
//            pp->runAction(Sequence::create(MoveTo::create(time, des),CallFuncN::create([=](Ref*pSender){
//                pp->stand();
//            }),NULL));
//            
//        }else{
//            selected=nullptr;
//        }
//        
//    }
     // };

    
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchEvt,this);
//
    scheduleUpdate();
    
    
    
    
    //地图缩放
    auto listener=EventListenerTouchAllAtOnce::create();
    listener->onTouchesBegan=[&](const std::vector<Touch*>&touches,Event *pevent)
    {
        Director*director=Director::getInstance();
        if (touches.size()>=2) {
            auto point1=director->convertToGL(touches.at(0)->getLocation());
            auto point2=director->convertToGL(touches.at(1)->getLocation());
            _distance=point1.getDistance(point2);
        }
    };
    listener->onTouchesMoved=[&](const std::vector<Touch*>&touches,Event *pevent)
    {
        
        Director*director=Director::getInstance();
        if (touches.size()>=2) {
            auto point1=director->convertToGL(touches.at(0)->getLocation());
            auto point2=director->convertToGL(touches.at(1)->getLocation());
            
            float new_distance=point1.getDistance(point2);
            float delta=new_distance-_distance;
            pCamera->setPosition3D(pCamera->getPosition3D()+Vec3(0,delta,delta));
            _distance=new_distance;
            
                   }
    };
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
    
    
    
    return true;
}