Exemple #1
0
Fichier : p.c Projet : 0branch/kona
Z void A(I n){DO(n,O(" "));}
Nef_polyhedron_3 clone_nef(Nef_polyhedron_3 N){
	Nef_polyhedron_3 O(N);
	return O;
}
Exemple #3
0
#include <lib9.h>
#include <kernel.h>
#include "draw.h"
#include "tk.h"
#include "label.h"

#define	O(t, e)		((long)(&((t*)0)->e))

TkOption tklabelopts[] =
{
	"text",		OPTtext,	O(TkLabel, text),	nil,
	"label",	OPTtext,	O(TkLabel, text),	nil,
	"underline",	OPTdist,	O(TkLabel, ul),		nil,
	"justify",	OPTflag,	O(TkLabel, justify),	tkjustify,
	"anchor",	OPTflag,	O(TkLabel, anchor),	tkanchor,
	"bitmap",	OPTbmap,	O(TkLabel, bitmap),	nil,
	"image",	OPTimag,	O(TkLabel, img),	nil,
	nil
};

char*
tklabel(TkTop *t, char *arg, char **ret)
{
	Tk *tk;
	char *e;
	TkLabel *tkl;
	TkName *names;
	TkOptab tko[3];

	tk = tknewobj(t, TKlabel, sizeof(Tk)+sizeof(TkLabel));
	if(tk == nil)
void w() {
    O(11);
}
//-------------------------------------------------------------------
int fdct_wrapping(int N1, int N2, int nbscales, int nbangles_coarse, int allcurvelets, CpxNumMat& x, vector< vector<CpxNumMat> >& c)
{
  //---------------------------------------------
  assert(N1==x.m() && N2==x.n());
  
  int F1 = N1/2;  int F2 = N2/2;
  // ifft original data
  CpxNumMat T(x);
  fftwnd_plan p = fftw2d_create_plan(N2, N1, FFTW_FORWARD, FFTW_ESTIMATE | FFTW_IN_PLACE);
  fftwnd_one(p, (fftw_complex*)T.data(), NULL);
  fftwnd_destroy_plan(p);
  double sqrtprod = sqrt(double(N1*N2));
  for(int j=0; j<N2; j++)	 for(int i=0; i<N1; i++)		T(i,j) /= sqrtprod;
  CpxOffMat O(N1, N2);
  fdct_wrapping_fftshift(T, O);
  
  //-----------------------------------------------------------------------------
  vector<CpxOffMat> Xhghs;
  Xhghs.resize(nbscales);
  CpxOffMat X;
  //unfold or not
  if(allcurvelets==1) {
	 //--------------------------
	 double XL1 = 4.0*N1/3.0;  double XL2 = 4.0*N2/3.0; //range
	 int XS1, XS2;  int XF1, XF2;  double XR1, XR2;  fdct_wrapping_rangecompute(XL1, XL2, XS1, XS2, XF1, XF2, XR1, XR2);
	 IntOffVec t1(XS1);
	 for(int i=-XF1; i<-XF1+XS1; i++)		if(     i<-N1/2) t1(i) = i+int(N1);		else if(i>(N1-1)/2) t1(i) = i-int(N1);		else t1(i) = i;
	 IntOffVec t2(XS2);
	 for(int i=-XF2; i<-XF2+XS2; i++)		if(     i<-N2/2) t2(i) = i+int(N2);		else if(i>(N2-1)/2) t2(i) = i-int(N2);		else t2(i) = i;
	 X.resize(XS1, XS2);
	 for(int j=-XF2; j<-XF2+XS2; j++)
		for(int i=-XF1; i<-XF1+XS1; i++)
		  X(i,j) = O(t1(i), t2(j));
	 DblOffMat lowpass(XS1,XS2);
	 fdct_wrapping_lowpasscompute(XL1, XL2, lowpass); //compute the low pass filter
	 for(int j=-XF2; j<-XF2+XS2; j++)
		for(int i=-XF1; i<-XF1+XS1; i++)
		  X(i,j) *= lowpass(i,j);
  } else {
	 //--------------------------
	 X = O;
  }
  //separate
  double XL1 = 4.0*N1/3.0;  double XL2 = 4.0*N2/3.0; //range
  for(int sc=nbscales-1; sc>0; sc--) {
	 double XL1n = XL1/2;	 double XL2n = XL2/2;
	 int XS1n, XS2n;  int XF1n, XF2n;  double XR1n, XR2n;
	 fdct_wrapping_rangecompute(XL1n, XL2n, XS1n, XS2n, XF1n, XF2n, XR1n, XR2n);
	 //computer filter
	 DblOffMat lowpass(XS1n, XS2n);
	 fdct_wrapping_lowpasscompute(XL1n, XL2n, lowpass);
	 DblOffMat hghpass(XS1n, XS2n);
	 for(int j=-XF2n; j<-XF2n+XS2n; j++)
		for(int i=-XF1n; i<-XF1n+XS1n; i++)
		  hghpass(i,j) = sqrt(1-lowpass(i,j)*lowpass(i,j));
	 //separate
	 CpxOffMat Xhgh(X);
	 for(int j=-XF2n; j<-XF2n+XS2n; j++)
		for(int i=-XF1n; i<-XF1n+XS1n; i++)
		  Xhgh(i,j) *= hghpass(i,j);
	 CpxOffMat Xlow(XS1n, XS2n);
	 for(int j=-XF2n; j<-XF2n+XS2n; j++)
		for(int i=-XF1n; i<-XF1n+XS1n; i++)
		  Xlow(i,j) = X(i,j) * lowpass(i,j);
	 //store and prepare for next level
	 Xhghs[sc] = Xhgh;
	 X = Xlow;
	 XL1 = XL1/2;	 XL2 = XL2/2;
  }
  Xhghs[0] = X;
  
  //-----------------------------------------------------------------------------
  vector<int> nbangles(nbscales);
  if(allcurvelets==1) {
	 //nbangles
	 nbangles[0] = 1;
	 for(int sc=1; sc<nbscales; sc++)		nbangles[sc] = nbangles_coarse * pow2( int(ceil(double(sc-1)/2)) );
	 //c
	 c.resize(nbscales);
	 for(int sc=0; sc<nbscales; sc++)		c[sc].resize( nbangles[sc] );
	 
	 double XL1 = 4.0*N1/3.0;  double XL2 = 4.0*N2/3.0; //range
	 for(int sc=nbscales-1; sc>0; sc--) {
		fdct_wrapping_sepangle(XL1, XL2, nbangles[sc], Xhghs[sc], c[sc]);
		XL1 /= 2;		XL2 /= 2;
	 }
	 fdct_wrapping_wavelet(Xhghs[0], c[0]);
  } else {
	 //nbangles
	 nbangles[0] = 1;
	 for(int sc=1; sc<nbscales-1; sc++)		nbangles[sc] = nbangles_coarse * pow2( int(ceil(double(sc-1)/2)) );
	 nbangles[nbscales-1] = 1;
	 //c
	 c.resize(nbscales);
	 for(int sc=0; sc<nbscales; sc++)		c[sc].resize( nbangles[sc] );
	 
	 fdct_wrapping_wavelet(Xhghs[nbscales-1], c[nbscales-1]);
	 double XL1 = 2.0*N1/3.0;  double XL2 = 2.0*N2/3.0; //range
	 for(int sc=nbscales-2; sc>0; sc--) {
		fdct_wrapping_sepangle(XL1, XL2, nbangles[sc], Xhghs[sc], c[sc]);
		XL1 /= 2;		XL2 /= 2;
	 }
	 fdct_wrapping_wavelet(Xhghs[0], c[0]);
  }
  
  return 0;
}
Exemple #6
0
inline O rot90(const O & o)
{
    return O(-o.y, o.x);
}
Exemple #7
0
#endif
)
{
    sl_index(i);

#ifdef DRAW
    gfx_fb_set(sl_getp(drawbase) + i, 0xff0000);
#endif

    cell * restrict cold = sl_getp(old) + i;
    cell * restrict cnew = sl_getp(new) + i;

#define P(p, i) (*(p+i))
#define O(i,o) (P(cold, i) << o)

    size_t offset = O(-1,2) | O(0,1) | O(1,0);

    cell newval = (sl_getp(rule) >> offset) & 1;
    P(cnew, 0) = newval;
#undef P
#undef O
#ifdef DRAW
    gfx_fb_set(sl_getp(drawbase) + i, newval ? -1 : 0);
#endif
}
sl_enddef

sl_def(cycle1D,,
       sl_glparm(size_t, w),
       sl_glparm(cell *, old),
       sl_glparm(cell *, new),
static AS3_Val prediction(void* self, AS3_Val args) {
	AS3_Val	in_arr = AS3_Undefined(), out_arr = AS3_Array(0);
	float *tmp, d, e;
	int i,j,k,l, n,x,y, newx,newy, il, dx,dy;
	LAYER *pL;

	AS3_ArrayValue( args, "AS3ValType", &in_arr );

	for(i=0; i < 1024; ++i)
    	data[i] = AS3_IntValue(AS3_Get(in_arr, AS3_Int(4*i+1))) /255.0;
    	
    n = 1;
    x = 32;
    y = 32;
    
    #define DATA(l,j,i) data[((l)*y + (j))*x + (i)]
    #define O(k,dy,dx) o[((k)*newy + (dy))*newx + (dx)]
    #define W(k,l,j,i) pL->w[(((k)*n + (l))*pL->y + (j))*pL->x + (i)]
    
    for (il=0; il < nl; ++il) {
        flyield();
        pL = L+il;
        newx = x+1-pL->x;
        newy = y+1-pL->y;

        for (dx=0; dx < newx; ++dx)
        for (dy=0; dy < newy; ++dy)
        for (k=0; k < pL->n; ++k) {
            d = pL->b[k];
            for (l=0; l < n; ++l)
            for(j=0; j < pL->y; ++j)
            for(i=0; i < pL->x; ++i)
                d += DATA(l,j+dy,i+dx)*W(k,l,j,i);
            O(k,dy,dx) = d;
        }

        if(pL->maxpool) {
            for (k=0; k < pL->n; ++k)
            for (dx=0; dx < newx; dx+=2)
            for (dy=0; dy < newy; dy+=2) {
                d=O(k,dy,dx);
                e=O(k,dy,dx+1); if(e>d) d=e;
                e=O(k,dy+1,dx); if(e>d) d=e;
                e=O(k,dy+1,dx+1); if(e>d) d=e;
                O(k,dy/2,dx/2)=d;
            }
            newx /= 2;
            newy /= 2;
        }

        for (dx=0; dx < newx; ++dx)
        for (dy=0; dy < newy; ++dy) {
            e = 0;
            for (k=0; k < pL->n; ++k) {
                d = O(k,dy,dx);
                if(pL->nonlin==1) d=1.0/(1.0 + exp(-d));
                else if(pL->nonlin==2) d=tanh(d);
                else if(pL->nonlin==3) { d=exp(d); e += d; }
                O(k,dy,dx) = d;
            }
            if(pL->nonlin==3 && e)
            for (k=0; k < pL->n; ++k)
                O(k,dy,dx) /= e;
        }
        
        tmp = data;
        data = o;
        o = tmp;
        
        x = newx;
        y = newy;
        n = pL->n;
    }

	for(i=0; i < n*x*y; ++i)
        AS3_Set(out_arr, AS3_Int(i), AS3_Number(data[i]));

	return out_arr;
}
Exemple #9
0
			unique_ptr_type extendEmpty() const
			{
				unique_ptr_type O(new this_type(slog+1));
				return UNIQUE_PTR_MOVE(O);
			}
int main()
{

    sf::RenderWindow window(sf::VideoMode(900, 900), "Tic Tac Toe");     // Create the main window - window.isOpen is now set to True
    sf::Texture gameboard;      //loads the gameboard image
    sf::Texture pieces;
    sf::Font font;              //font
    sf::Music music;            // Load a music to play

    //loads all files
    if (!gameboard.loadFromFile("tictactoe.png"))
        return EXIT_FAILURE;
    if (!pieces.loadFromFile("pieces.png"))
        return EXIT_FAILURE;
    if (!font.loadFromFile("arial.ttf"))
        return EXIT_FAILURE;
    if (!music.openFromFile("swapj.ogg"))
        return EXIT_FAILURE;

    //renders the use of the files
    sf::Sprite background(gameboard);       //puts background in window
    sf::Sprite O(pieces, sf::IntRect(0,0,280,280));
    sf::Sprite X(pieces, sf::IntRect(290,0,270,250));
    //music.play();
    Game match;
    // Start the game loop
    while (window.isOpen())
    {
        // Process events
        sf::Event event;

        window.draw(background); // Draw the sprite aka background
        window.display();  // Update the window

        while (window.pollEvent(event) && match.referee())
        {
            // Close window : exit
            window.display();
            if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
                window .close();

            switch(event.key.code){
                case '1':
                    if(match.checkData(0,0) == 0){
                        if(match.switchXO() == 0){
                            X.setPosition(0,0);
                            window.draw(X);
                        }
                        else{
                            O.setPosition(0,0);
                            window.draw(O);
                        }
                    }
                    break;
                case '2':
                     if(match.checkData(0,1) == 0){
                        if(match.switchXO() == 0){
                            X.setPosition(300,0);
                            window.draw(X);
                        }
                        else{
                            O.setPosition(300,0);
                            window.draw(O);
                        }
                    }
                    break;
                case '3':
                    if(match.checkData(0,2) == 0){
                        if(match.switchXO() == 0){
                            X.setPosition(600,0);
                            window.draw(X);
                        }
                        else{
                            O.setPosition(600,0);
                            window.draw(O);
                        }
                    }
                    break;
                case '4':
                    if(match.checkData(1,0) == 0){
                        if(match.switchXO() == 0){
                            X.setPosition(0,300);
                            window.draw(X);
                        }
                        else{
                            O.setPosition(0,300);
                            window.draw(O);
                        }
                    }
                    break;
                case '5':
                    if(match.checkData(1,1) == 0){
                        if(match.switchXO() == 0){
                            X.setPosition(300,300);
                            window.draw(X);
                        }
                        else{
                            O.setPosition(300,300);
                            window.draw(O);
                        }
                    }
                    break;
                case '6':
                    if(match.checkData(1,2) == 0){
                        if(match.switchXO() == 0){
                            X.setPosition(600,300);
                            window.draw(X);
                        }
                        else{
                            O.setPosition(600,300);
                            window.draw(O);
                        }
                    }
                    break;
                case '7':
                    if(match.checkData(2,0) == 0){
                        if(match.switchXO() == 0){
                            X.setPosition(0,600);
                            window.draw(X);
                        }
                        else{
                            O.setPosition(0,600);
                            window.draw(O);
                        }
                    }
                    break;
                case '8':
                    if(match.checkData(2,1) == 0){
                        if(match.switchXO() == 0){
                            X.setPosition(300,600);
                            window.draw(X);
                        }
                        else{
                            O.setPosition(300,600);
                            window.draw(O);
                        }
                    }
                    break;
                case '9':
                    if(match.checkData(2,2) == 0){
                        if(match.switchXO() == 0){
                            X.setPosition(600,600);
                            window.draw(X);
                        }
                        else{
                            O.setPosition(600,600);
                            window.draw(O);
                        }
                    }
                    break;
                default:
                    break;
            }

        }
    }

    return 0;
}
/**
 * Infere the order of a term according to its components
 * @param sig the signal to analyze
 * @return the order of sig 
 */
static int infereSigOrder(Tree sig)
{
	int 		i;
	double 		r;
    Tree		sel, s1, s2, s3, s4, ff, id, ls, l, x, y, var, body, type, name, file;

	xtended* xt = (xtended*) getUserData(sig);
	// primitive elements
	if (xt) 								
	{
		//return 3;
		vector<int> args;
		for (int i=0; i<sig->arity(); i++) { args.push_back( O(sig->branch(i)) ); }
		return xt->infereSigOrder(args);
	}

	
	else if (isSigInt(sig, &i))					return 0;
		
	else if (isSigReal(sig, &r)) 				return 0;
		
	else if (isSigInput(sig, &i))				return 3;
		
	else if (isSigOutput(sig, &i, s1)) 			return 3;
		
	else if (isSigDelay1(sig, s1)) 				return 3;
	
	else if (isSigPrefix(sig, s1, s2)) 			return 3;
	
	else if (isSigFixDelay(sig, s1, s2)) 		return 3;
	
	else if (isSigBinOp(sig, &i, s1, s2)) 		return max(O(s1),O(s2));
	
	else if (isSigIntCast(sig, s1))				return O(s1);
        
    else if (isSigFloatCast(sig, s1))           return O(s1);

    else if (isSigFFun(sig,ff,ls) && isNil(ls)) return 1;

    else if (isSigFFun(sig, ff, ls))            return max(1,O(ls));

    else if (isSigFConst(sig,type,name,file))   return 1;

    else if (isSigFVar(sig,type,name,file))     return 2;
		
	else if (isSigButton(sig)) 					return 2;
	
	else if (isSigCheckbox(sig))				return 2;
	
	else if (isSigVSlider(sig))					return 2;
	 
	else if (isSigHSlider(sig))					return 2;
	
	else if (isSigNumEntry(sig))				return 2;
		
	else if (isSigHBargraph(sig, l, x, y, s1)) 	return O(s1);
		
	else if (isSigVBargraph(sig, l, x, y, s1)) 	return O(s1);
		
	else if (isSigAttach(sig, s1, s2)) 			return O(s1);
				
	else if (isRec(sig, var, body))				exit(1); //return 3;  // not supposed to happen.
				
	else if (isRef(sig, var))					exit(1); //return 3;  // not supposed to happen. 

	else if (isProj(sig, &i, s1))				return 3;
	                                                	
	else if (isSigTable(sig, id, s1, s2)) 		return 3;
		
	else if (isSigWRTbl(sig, id, s1, s2, s3)) 	return 3; 
			
    else if (isSigRDTbl(sig, s1, s2)) 			return 3;

    else if (isSigDocConstantTbl(sig, s1, s2)) 	return 3;

    else if (isSigDocWriteTbl(sig,s1,s2,s3,s4)) return 3;

    else if (isSigDocAccessTbl(sig,s1,s2))      return 3;

    else if (isSigGen(sig, s1)) 				return 3;
		
	else if (isSigSelect2(sig,sel,s1,s2)) 		return 3;
		
	else if (isSigSelect3(sig,sel,s1,s2,s3)) 	return 3;	
	
	else if (isList(sig)) 
	{
		int r = 0;
		while (isList(sig)) { int x = O(hd(sig)); if (x > r) r = x; sig = tl(sig); }
		return r;
	}
	
	// unrecognized signal here
	fprintf(stderr, "ERROR infering signal order : unrecognized signal  : "); print(sig, stderr); fprintf(stderr, "\n");
	exit(1);
	return 0;
}
Exemple #12
0
    STRPTR * ml_StringPtr;
    struct Level1 * ml_Level1Ptr;
};

IPTR ByteDesc[]   = { sizeof(UBYTE),  SDM_UBYTE(0),  SDM_END };
IPTR WordDesc[]   = { sizeof(UWORD),  SDM_UWORD(0),  SDM_END };
IPTR LongDesc[]   = { sizeof(ULONG),  SDM_ULONG(0),  SDM_END };
IPTR FloatDesc[]  = { sizeof(FLOAT),  SDM_FLOAT(0),  SDM_END };
IPTR DoubleDesc[] = { sizeof(DOUBLE), SDM_DOUBLE(0), SDM_END };
IPTR StringDesc[] = { sizeof(STRPTR), SDM_STRING(0), SDM_END };

#define O(x)        offsetof(struct Level1,x)
IPTR Level1Desc[] =
{
    sizeof (struct Level1),
    SDM_UBYTE(O(l1_Byte)),
    SDM_ULONG(O(l1_Long)),
    SDM_END
};

#undef O
#define O(x)        offsetof(struct MainLevel,x)
IPTR MainDesc[] =
{
    sizeof (struct MainLevel),
    SDM_UBYTE(O(ml_Byte)),
    SDM_UBYTE(O(ml_UByte)),
    SDM_UWORD(O(ml_Word)),
    SDM_UWORD(O(ml_UWord)),
    SDM_ULONG(O(ml_Long)),
    SDM_ULONG(O(ml_ULong)),
// TODO:
1. Linked list
2. Circular Linked List (Deck of cards)
3. AVL Tree
4. BST Tree
5. Red Black Tree
6. Queue
7. Hash Table // With a bunch of different hash functions and different ways to handle collision
8. Stack
9. Heaps (Priority Queue)
10. Dynamically Allocated Array
11. Interval Tree
12. Segment Tree (Similar to Interval Tree)
12. Graph (both adjacency list and adjacency matrix with the algorithms)
13. Disjoint Set
14. Fibonacci Heap
15. BSP Tree = For determining order of print in graphic systems
16. Suffix Tree
17. Fenwick Tree = Binary Indexed Tree (For finding cumulative sums of array in O(logN))
Multithreaded Data Structures for UNIX

As well as, generate graph to compare speed (ECE344 Lab 4 and Lab 5)

// Use Structures instead of classes so works in both C and C++
//-----------------------------------------------------------------------------------------------------------





int main(int argc, char** argv){
  int fd,i;
  long count = 0;
  long fsize;
  long spacing;
  int scrambles;
  void* packet1,* packet2;
  struct stat st;
  if(argc < 4){
    O("Usage: %s <filename> <byte spacing> <number of scrambles>\n", argv[0]);
    exit(-1);
  }
  
  if(stat(argv[1], &st) != 0){
    O("error in stat\n");
    exit(-1);
  }


  spacing = atol(argv[2]);
  scrambles = atoi(argv[3]);

  fd = open(argv[1], O_RDWR);
  if(fd == -1){
    O("Error opening file %s\n", argv[1]);
    exit(-1);
  }

  fsize = st.st_size;
  long scr1,scr2;
  count = fsize/spacing;
  O("count: %ld\n", count);
  packet1 = malloc(spacing);
  packet2 = malloc(spacing);

  /* Interchange two random seqnums scramble times	*/
  for(i=0;i < scrambles;i++){
    scr1 = random() % count;
    scr2 = random() % count;
    while(scr1 == scr2)
      scr2 = random() % count;


    lseek(fd, scr1*spacing, SEEK_SET);
    if(read(fd, packet1,spacing) < 0){
      O("Read error\n");
      perror("read");
      exit(-1);
    }
    lseek(fd, scr2*spacing, SEEK_SET);
    if(read(fd, packet2,spacing) < 0){
      O("Read error\n");
      perror("read");
      exit(-1);
    }
    lseek(fd, scr2*spacing, SEEK_SET);
    if(write(fd, packet1,spacing) < 0){
      O("Write error\n");
      perror("write");
      exit(-1);
    }
    lseek(fd, scr1*spacing, SEEK_SET);
    if(write(fd, packet2,spacing) < 0){
      O("Write error\n");
      perror("write");
      exit(-1);
    }
    if( i%4 == 0)
      fprintf(stdout, ".");
  }
  fprintf(stdout, "Done!\n");

  free(packet1);
  free(packet2);
  if(close(fd) != 0){
    O("Error on close\n");
    exit(-1);
  }

  exit(0);
}
double FluidMixture::operator()(const ScalarFieldArray& indep, ScalarFieldArray& Phi_indep, Outputs outputs) const
{	static StopWatch watch("FluidMixture::operator()"); watch.start();

	//logPrintf("indep.size: %d nIndep: %d\n",indep.size(),nIndep);
	myassert(indep.size()==get_nIndep());

	//---------- Compute site densities from the independent variables ---------
	ScalarFieldTildeArray Ntilde(nDensities); //site densities (in reciprocal space)
	std::vector< vector3<> > P0(component.size()); //polarization densities G=0
	for(unsigned ic=0; ic<component.size(); ic++)
	{	const FluidComponent& c = *component[ic];
		ScalarFieldArray N(c.molecule.sites.size());
		c.idealGas->getDensities(&indep[c.offsetIndep], &N[0], P0[ic]);
		for(unsigned i=0; i<c.molecule.sites.size(); i++)
		{	//Replace negative densities with 0:
			double Nmin, Nmax;
			callPref(eblas_capMinMax)(gInfo.nr, N[i]->dataPref(), Nmin, Nmax, 0.);
			//store site densities in fourier space
			Ntilde[c.offsetDensity+i] = J(N[i]);
			N[i] = 0; //Really skimp on memory!
		}
	}

	//----------- Handle density constraints ------------
	std::vector<double> Nscale(component.size(), 1.0); //density scale factor that satisfies the constraint
	std::vector<double> Ntot_c; //vector of total number of molecules for each component
	std::vector<double> Nscale_Qfixed(component.size(), 0.); //derivative of Nscale w.r.t the fixed charge
	std::vector<std::vector<double> > Nscale_N0(component.size(), std::vector<double>(component.size(),0.0)); //jacobian of Nscale w.r.t the uncorrected molecule counts
	std::vector<string> names; //list of molecule names
	
	//Find fixed N and charged species:
	double Qfixed = 0.0;
	if(rhoExternal) Qfixed += integral(rhoExternal);
	std::vector<std::pair<double,double> > N0Q;
	for(unsigned ic=0; ic<component.size(); ic++)
	{	const FluidComponent& c = *component[ic];
		double Qmolecule = c.molecule.getCharge();
		if(c.Nnorm>0 || Qmolecule)
		{	double N0 = integral(Ntilde[c.offsetDensity])/c.molecule.sites[0]->positions.size();
			if(c.Nnorm>0)
			{	Nscale[ic] = c.Nnorm/N0;
				Nscale_N0[ic][ic] = -c.Nnorm/pow(N0,2);
				Qfixed += Qmolecule*c.Nnorm;
			}
			else
			{	N0Q.push_back(std::make_pair(N0, Qmolecule));
				names.push_back(c.molecule.name);
			}
		}
	}
	//Find the betaV (see Qtot()) that makes the unit cell neutral
	if(N0Q.size()==0)
	{	if(fabs(Qfixed)>fabs(Qtol))
			die("Unit cell has a fixed net charge %le,"
				"and there are no free charged species to neutralize it.\n", Qfixed);
	}
	else
	{	double Qprime, Qcell, betaV=0.0;
		if(Qfixed+Qtot(-HUGE_VAL,Qprime,N0Q)<0)
			die("Unit cell will always have a net negative charge (no free positive charges).\n")
		if(Qfixed+Qtot(+HUGE_VAL,Qprime,N0Q)>0)
			die("Unit cell will always have a net positive charge (no free negative charges).\n")

		for(int iter=0; iter<10; iter++) //while(1)
		{	Qcell = Qfixed+Qtot(betaV,Qprime,N0Q,&names,&gInfo,verboseLog);
			if(verboseLog) logPrintf("betaV = %le, Qcell = %le, Qprime = %le\n", betaV, Qcell, Qprime);
			if(fabs(Qcell)<fabs(Qtol)) break;	
			if(std::isnan(Qcell)) 
			  { betaV=0.0; break;}
			betaV -= Qcell/Qprime; //Newton-Raphson update
			
		}
		for(unsigned ic=0; ic<component.size(); ic++)
		{	const FluidComponent& ci = *component[ic];
			double Qi = ci.molecule.getCharge();
			if(Qi && ci.Nnorm<=0)
			{	Nscale[ic] = exp(-Qi*betaV);
				Nscale_Qfixed[ic] = exp(-Qi*betaV) * Qi / Qprime;
				for(unsigned jc=0; jc<component.size(); jc++)
				{	const FluidComponent& cj = *component[jc];
					double Qj = cj.molecule.getCharge();
					if(Qj && cj.Nnorm<=0)
						Nscale_N0[ic][jc] += Qi*Qj*exp(-(Qi+Qj)*betaV)/Qprime;
				}
			}
		}
	}
	std::vector<double> Phi_Nscale(component.size(), 0.0); //accumulate explicit derivatives w.r.t Nscale here

	//Apply the scale factors to the site densities
	for(unsigned ic=0; ic<component.size(); ic++)
	{	const FluidComponent& c = *component[ic];
		for(unsigned i=0; i<c.molecule.sites.size(); i++)
			Ntilde[c.offsetDensity+i] *= Nscale[ic];
		P0[ic] *= Nscale[ic];
		Ntot_c.push_back(integral(Ntilde[c.offsetDensity]));
	}

	EnergyComponents Phi; //the grand free energy (with component information)
	ScalarFieldTildeArray Phi_Ntilde(nDensities); //gradients (functional derivative) w.r.t reciprocal space site densities
	nullToZero(Phi_Ntilde,gInfo);
	std::vector< vector3<> > Phi_P0(component.size()); //functional derivative w.r.t polarization density G=0
	VectorFieldTilde Phi_epsMF; //functional derivative w.r.t mean field electric field
	
	//G=0 fix for mismatch in fluid-fluid vs. fluid-electron charge kernels
	//We do this AFTER we have applied the appropriate scale factors
	if( N0Q.size() && (!useMFKernel)) //if we have charged species in our fluid, and are using mismatched charge kernels
	{
	  	for(unsigned ic=0; ic<component.size(); ic++)
		{	const FluidComponent& c = *component[ic];
		        for(unsigned i=0; i<c.molecule.sites.size(); i++)
			  { 
			    const Molecule::Site& s = *(c.molecule.sites[i]);
			    Phi["Gzero"] += Qfixed*(Ntot_c[ic]/gInfo.detR-c.idealGas->Nbulk)*s.positions.size()*s.deltaS;
			    Phi_Ntilde[c.offsetDensity+i]->data()[0] += (1.0/gInfo.dV) * (Qfixed*s.deltaS);
			  }
		}
	}

	//--------- Compute the (scaled) mean field coulomb interaction --------
	{	ScalarFieldTilde rho; //total charge density
		ScalarFieldTilde rhoMF; //effective charge density for mean-field term
		bool needRho = rhoExternal || outputs.Phi_rhoExternal;
		
		VectorFieldTilde epsMF = polarizable ? J(VectorField(&indep[nIndepIdgas])) : 0; //mean field electric field
		vector3<> P0tot;
		
		for(unsigned ic=0; ic<component.size(); ic++)
		{	const FluidComponent& c = *component[ic];
			for(unsigned i=0; i<c.molecule.sites.size(); i++)
			{	const Molecule::Site& s = *(c.molecule.sites[i]);
				if(s.chargeKernel)
				{	if(needRho) rho += s.chargeKernel * Ntilde[c.offsetDensity+i];
					rhoMF += s.chargeKernel(0) * (c.molecule.mfKernel * Ntilde[c.offsetDensity+i]);
				}
				//Polarization contributions:
				if(polarizable && s.polKernel)
				{	
					#define Polarization_Compute_Pi_Ni \
						VectorField Pi = (Cpol*s.alpha) * I(c.molecule.mfKernel*epsMF - (rhoExternal ? gradient(s.polKernel*coulomb(rhoExternal)) : 0)); \
						ScalarField Ni = I(Ntilde[c.offsetDensity+i]);
					Polarization_Compute_Pi_Ni
					
					ScalarField Phi_Ni = (0.5/(Cpol*s.alpha))*lengthSquared(Pi);
					Phi["Apol"] += gInfo.dV * dot(Ni, Phi_Ni);
					//Derivative contribution to site densities:
					Phi_Ntilde[c.offsetDensity+i] += Idag(Phi_Ni); Phi_Ni=0;
					//Update contributions to bound charge:
					VectorFieldTilde NPtilde = J(Ni * Pi); Pi=0; Ni=0;
					ScalarFieldTilde divNPbar;
					if(needRho) rho -= s.polKernel*divergence(NPtilde);
					VectorFieldTilde NPbarMF = c.molecule.mfKernel*NPtilde; NPtilde=0;
					rhoMF -= divergence(NPbarMF);
					Phi_epsMF += gInfo.nr * NPbarMF;
					P0tot += getGzero(NPbarMF);
				}
			}
			P0tot += P0[ic];
		}
		
		if(rhoMF)
		{	//External charge interaction:
			ScalarFieldTilde Phi_rho;
			ScalarFieldTilde Phi_rhoMF;
			if(needRho)
			{	if(rhoExternal)
				{	
				  ScalarFieldTilde OdExternal = O(coulomb(rhoExternal));
				  if (!useMFKernel)
				   {	
			  	       Phi["ExtCoulomb"] += dot(rho, OdExternal);
				       Phi_rho += OdExternal;
				   }
				   if (useMFKernel)
				   {
				       Phi["ExtCoulomb"] += dot(rhoMF, OdExternal);   
				       Phi_rhoMF += OdExternal; 
				   }
				}
				if(outputs.Phi_rhoExternal) 
				{
				  if (!useMFKernel) *outputs.Phi_rhoExternal = coulomb(rho);
				  if (useMFKernel) *outputs.Phi_rhoExternal = coulomb(rhoMF);
				}
			}
		
			//Mean field contributions:
			{	ScalarFieldTilde OdMF = O(coulomb(rhoMF)); //mean-field electrostatic potential
				Phi["Coulomb"] += 0.5*dot(rhoMF, OdMF);
				Phi_rhoMF += OdMF;
			}
			
			//Polarization density interactions:
			if(outputs.electricP) *outputs.electricP = P0tot * gInfo.detR;
			//--- corrections for net dipole in cell:
			vector3<> Phi_P0tot = (4*M_PI*gInfo.detR) * P0tot;
			Phi["PsqCell"] += 0.5 * dot(Phi_P0tot, P0tot); 
			//--- external electric field interactions:
			Phi["ExtCoulomb"] -= gInfo.detR * dot(Eexternal, P0tot);
			Phi_P0tot -= gInfo.detR * Eexternal;
			
			//Propagate gradients:
			for(unsigned ic=0; ic<component.size(); ic++)
			{	const FluidComponent& c = *component[ic];
				for(unsigned i=0; i<c.molecule.sites.size(); i++)
				{	const Molecule::Site& s = *(c.molecule.sites[i]);
					if(s.chargeKernel)
					{	if(Phi_rho) Phi_Ntilde[c.offsetDensity+i] += (1./gInfo.dV) * (s.chargeKernel * Phi_rho);
						Phi_Ntilde[c.offsetDensity+i] += (s.chargeKernel(0)/gInfo.dV) * (c.molecule.mfKernel * Phi_rhoMF);
					}
					//Polarization contributions:
					if(polarizable && s.polKernel)
					{	VectorFieldTilde Phi_NPtilde = gradient(c.molecule.mfKernel*Phi_rhoMF + (needRho ? s.polKernel*Phi_rho : 0));
						setGzero(Phi_NPtilde, getGzero(Phi_NPtilde) + Phi_P0tot);
						VectorField Phi_NP = Jdag(Phi_NPtilde); Phi_NPtilde=0;
						//propagate gradients from NP to N, epsMF and rhoExternal:
						Polarization_Compute_Pi_Ni
						#undef Polarization_Compute_Pi_Ni
						// --> via Ni
						ScalarField Phi_Ni; for(int k=0; k<3; k++) Phi_Ni += Phi_NP[k]*Pi[k];
						Phi_Ntilde[c.offsetDensity+i] += (1./gInfo.dV) * Idag(Phi_Ni); Phi_Ni=0;
						// --> via Pi
						VectorFieldTilde Phi_PiTilde = Idag(Phi_NP * Ni); Phi_NP=0;
						Phi_epsMF += (Cpol*s.alpha/gInfo.dV)*(c.molecule.mfKernel*Phi_PiTilde);
					}
				}
				Phi_P0[ic] += (1./gInfo.detR) * Phi_P0tot; //convert to functional derivative
			}
		}
	}
	
	//--------- Hard sphere mixture and bonding -------------
	{	//Compute the FMT weighted densities:
		ScalarFieldTilde n0tilde, n1tilde, n2tilde, n3tilde, n1vTilde, n2mTilde;
		std::vector<ScalarField> n0mol(component.size(), 0); //partial n0 for molecules that need bonding corrections
		std::vector<int> n0mult(component.size(), 0); //number of sites which contribute to n0 for each molecule
		std::vector<std::map<double,int> > bond(component.size()); //sets of bonds for each molecule
		bool bondsPresent = false; //whether bonds are present for any molecule
		for(unsigned ic=0; ic<component.size(); ic++)
		{	const FluidComponent& c = *component[ic];
			bond[ic] = c.molecule.getBonds();
			ScalarFieldTilde n0molTilde;
			for(unsigned i=0; i<c.molecule.sites.size(); i++)
			{	const Molecule::Site& s = *(c.molecule.sites[i]);
				if(s.Rhs)
				{	const ScalarFieldTilde& Nsite = Ntilde[c.offsetDensity+i];
					n0mult[ic] += s.positions.size();
					n0molTilde += s.w0  * Nsite;
					n1tilde    += s.w1  * Nsite;
					n2tilde    += s.w2  * Nsite;
					n3tilde    += s.w3  * Nsite;
					n1vTilde   += s.w1v * Nsite;
					n2mTilde   += s.w2m * Nsite;
				}
			}
			if(n0molTilde) n0tilde += n0molTilde;
			if(bond[ic].size())
			{	n0mol[ic] = I(n0molTilde);
				bondsPresent = true;
			}
		}
		if(n0tilde) //at least one sphere in the mixture
		{	ScalarField n0 = I(n0tilde); n0tilde=0;
			ScalarField n1 = I(n1tilde); n1tilde=0;
			ScalarField n2 = I(n2tilde); n2tilde=0;
			ScalarField Phi_n0, Phi_n1, Phi_n2; ScalarFieldTilde Phi_n3tilde, Phi_n1vTilde, Phi_n2mTilde;
			//Compute the sphere mixture free energy:
			Phi["MixedFMT"] += T * PhiFMT(n0, n1, n2, n3tilde, n1vTilde, n2mTilde,
				Phi_n0, Phi_n1, Phi_n2, Phi_n3tilde, Phi_n1vTilde, Phi_n2mTilde);
			//Bonding corrections if required
			if(bondsPresent)
			{	for(unsigned ic=0; ic<component.size(); ic++)
				{	const FluidComponent& c = *component[ic];
					ScalarField Phi_n0mol;
					for(const auto& b: bond[ic])
						Phi["Bonding"] += T * PhiBond(b.first, b.second*1./n0mult[ic],
							n0mol[ic], n2, n3tilde, Phi_n0mol, Phi_n2, Phi_n3tilde);
					if(Phi_n0mol)
					{	//Propagate gradient w.r.t n0mol[ic] to the site densities:
						ScalarFieldTilde Phi_n0molTilde = Idag(Phi_n0mol);
						for(unsigned i=0; i<c.molecule.sites.size(); i++)
						{	const Molecule::Site& s = *(c.molecule.sites[i]);
							if(s.Rhs)
								Phi_Ntilde[c.offsetDensity+i] += T * (s.w0  * Phi_n0molTilde);
						}
					}
				}
			}
			//Accumulate gradients w.r.t weighted densities to site densities:
			ScalarFieldTilde Phi_n0tilde = Idag(Phi_n0); Phi_n0=0;
			ScalarFieldTilde Phi_n1tilde = Idag(Phi_n1); Phi_n1=0;
			ScalarFieldTilde Phi_n2tilde = Idag(Phi_n2); Phi_n2=0;
			for(const FluidComponent* c: component)
			{	for(unsigned i=0; i<c->molecule.sites.size(); i++)
				{	const Molecule::Site& s = *(c->molecule.sites[i]);
					if(s.Rhs)
					{	ScalarFieldTilde& Phi_Nsite = Phi_Ntilde[c->offsetDensity+i];
						Phi_Nsite += T * (s.w0  * Phi_n0tilde);
						Phi_Nsite += T * (s.w1  * Phi_n1tilde);
						Phi_Nsite += T * (s.w2  * Phi_n2tilde);
						Phi_Nsite += T * (s.w3  * Phi_n3tilde);
						Phi_Nsite += T * (s.w1v * Phi_n1vTilde);
						Phi_Nsite += T * (s.w2m * Phi_n2mTilde);
					}
				}
			}
		}
	}

	//---------- Excess functionals --------------
	for(const FluidComponent* c: component) if(c->fex)
		Phi["Fex("+c->molecule.name+")"] += c->fex->compute(&Ntilde[c->offsetDensity], &Phi_Ntilde[c->offsetDensity]);

	//--------- Mixing functionals --------------
	for(const Fmix* fmix: fmixArr)
		Phi["Fmix("+fmix->getName()+")"] += fmix->compute(Ntilde, Phi_Ntilde);

	//--------- PhiNI ---------
	nullToZero(Phi_Ntilde, gInfo);
	if(outputs.N) outputs.N->resize(nDensities);
	//Put the site densities and gradients back in real space
	ScalarFieldArray N(nDensities);
	ScalarFieldArray Phi_N(nDensities);
	for(unsigned i=0; i<nDensities; i++)
	{	N[i] = I(Ntilde[i]); Ntilde[i]=0;
		Phi_N[i] = Jdag(Phi_Ntilde[i]); Phi_Ntilde[i] = 0;
		if(outputs.N) (*outputs.N)[i] = N[i]; //Link site-density to return pointer if necessary
	}
	//Estimate psiEff based on gradients, if requested
	if(outputs.psiEff)
	{	outputs.psiEff->resize(nDensities);
		for(const FluidComponent* c: component)
			for(unsigned i=0; i<c->molecule.sites.size(); i++)
			{	ScalarField& psiCur = outputs.psiEff->at(c->offsetDensity+i);
				psiCur = Phi_N[c->offsetDensity+i] + c->idealGas->V[i];
				if(i==0) psiCur -= c->idealGas->mu / c->molecule.sites[0]->positions.size();
				psiCur *= (-1./T);
			}
	}
	for(unsigned ic=0; ic<component.size(); ic++)
	{	const FluidComponent& c = *component[ic];
		Phi["PhiNI("+c.molecule.name+")"] +=
			c.idealGas->compute(&indep[c.offsetIndep], &N[c.offsetDensity], &Phi_N[c.offsetDensity], Nscale[ic], Phi_Nscale[ic]);

		//Fixed N correction to entropy:
		if(Nscale[ic]!=1.0)
		{	double deltaTs = T*log(Nscale[ic]) / c.molecule.sites[0]->positions.size();
			Phi_N[c.offsetDensity] += deltaTs;
			Phi["PhiNI("+c.molecule.name+")"] += integral(N[c.offsetDensity])*deltaTs;
		}
	}
	//Add in the implicit contributions to Phi_Nscale
	for(unsigned ic=0; ic<component.size(); ic++)
	{	const FluidComponent& ci = *component[ic];
		bool anyNonzero=false;
		for(unsigned jc=0; jc<component.size(); jc++)
			if(Nscale_N0[ic][jc])
				anyNonzero=true;
		if(anyNonzero)
		{	Phi_Nscale[ic] += gInfo.detR*dot(P0[ic], Phi_P0[ic])/ Nscale[ic];
			for(unsigned i=0; i<ci.molecule.sites.size(); i++)
				Phi_Nscale[ic] += gInfo.dV*dot(N[ci.offsetDensity+i], Phi_N[ci.offsetDensity+i])/ Nscale[ic];
		}
	}
	//Propagate gradients from Nscale to N:
	for(unsigned jc=0; jc<component.size(); jc++)
	{	const FluidComponent& cj = *component[jc];
		double Phi_Ncontrib = 0.0;
		for(unsigned ic=0; ic<component.size(); ic++)
			if(Nscale_N0[ic][jc])
				Phi_Ncontrib += Phi_Nscale[ic] * Nscale_N0[ic][jc];
		if(Phi_Ncontrib)
			Phi_N[cj.offsetDensity] += Phi_Ncontrib / (Nscale[jc] * cj.molecule.sites[0]->positions.size());
	}

	//Propagate gradients from Phi_N and Phi_P to Phi_indep
	Phi_indep.resize(get_nIndep());
	for(unsigned ic=0; ic<component.size(); ic++)
	{	const FluidComponent& c = *component[ic];
		c.idealGas->convertGradients(&indep[c.offsetIndep], &N[c.offsetDensity],
			&Phi_N[c.offsetDensity], Phi_P0[ic], &Phi_indep[c.offsetIndep], Nscale[ic]);
	}
	for(unsigned k=nIndepIdgas; k<get_nIndep(); k++) Phi_indep[k] = Jdag(Phi_epsMF[k-nIndepIdgas]);
	
	//Propagate gradients from Nscale to Qfixed / rhoExternal (Natural G=0 solution)
	if(outputs.Phi_rhoExternal)
	{	double Phi_Qfixed = 0.;
		for(unsigned ic=0; ic<component.size(); ic++)
		{
			Phi_Qfixed += Phi_Nscale[ic] * Nscale_Qfixed[ic];
			if (N0Q.size() && (!useMFKernel))
		        {
				const FluidComponent& c = *component[ic];
				for(unsigned i=0; i<c.molecule.sites.size(); i++)
				{ 
				 	//Correction to lambda from charge kernel mismatch
					  const Molecule::Site& s = *(c.molecule.sites[i]);
					  double lambda_s =  (Ntot_c[ic]/gInfo.detR-c.idealGas->Nbulk)*s.deltaS*s.positions.size();
					  if(verboseLog) logPrintf("Charge kernel mismatch correction for site %s of molecule %s: %lg\n",
					  s.name.c_str(),c.molecule.name.c_str(),lambda_s);
					  Phi_Qfixed += lambda_s;
				}
				 if(verboseLog) logPrintf("Total number of molecules of type %s: %lg\n",c.molecule.name.c_str(),Ntot_c[ic]);
		        }
		}
		nullToZero(*outputs.Phi_rhoExternal, gInfo);
		(*outputs.Phi_rhoExternal)->setGzero(Phi_Qfixed);
	}
	
	Phi["+pV"] += p * gInfo.detR; //background correction

	if(verboseLog) Phi.print(globalLog, true, "\t\t\t\t%15s = %25.16lf\n");
	if(outputs.Phi) *(outputs.Phi) = Phi;
	
	Phi_indep *= gInfo.dV; //convert functional derivative to partial derivative
	watch.stop();
	return Phi;
}
Exemple #16
0
	nil
};

static
TkStab tkcapstyle[] =
{
	"butt",	Endsquare,
	"projecting",	Endsquare,
	"round",	Enddisc,
	nil
};

static
TkOption lineopts[] =
{
	"arrow",	OPTstab,	O(TkCline, arrow),	tklines,
	"arrowshape",	OPTfrac,	O(TkCline, shape[0]),	IAUX(3),
	"width",	OPTnnfrac,	O(TkCline, width),	nil,
	"stipple",	OPTbmap,	O(TkCline, stipple),	nil,
	"smooth",	OPTstab,	O(TkCline, smooth),	tkbool,
	"splinesteps",	OPTdist,	O(TkCline, steps),	nil,
	"capstyle",	OPTstab,	O(TkCline, capstyle),	tkcapstyle,
	nil
};

static
TkOption itemopts[] =
{
	"tags",		OPTctag,	O(TkCitem, tags),	nil,
	"fill",		OPTcolr,	O(TkCitem, env),	IAUX(TkCforegnd),
	nil
Exemple #17
0
/* Scan STRING for variable references and expansion-function calls.  Only
   LENGTH bytes of STRING are actually scanned.  If LENGTH is -1, scan until
   a null byte is found.

   Write the results to LINE, which must point into 'variable_buffer'.  If
   LINE is NULL, start at the beginning of the buffer.
   Return a pointer to LINE, or to the beginning of the buffer if LINE is
   NULL.
 */
char *
variable_expand_string (char *line, const char *string, long length)
{
  struct variable *v;
  const char *p, *p1;
  char *save;
  char *o;
  unsigned int line_offset;

  if (!line)
    line = initialize_variable_output ();
  o = line;
  line_offset = line - variable_buffer;

  if (length == 0)
    {
      variable_buffer_output (o, "", 1);
      return (variable_buffer);
    }

  /* We need a copy of STRING: due to eval, it's possible that it will get
     freed as we process it (it might be the value of a variable that's reset
     for example).  Also having a nil-terminated string is handy.  */
  save = length < 0 ? xstrdup (string) : xstrndup (string, length);
  p = save;

  while (1)
    {
      /* Copy all following uninteresting chars all at once to the
         variable output buffer, and skip them.  Uninteresting chars end
         at the next $ or the end of the input.  */

      p1 = strchr (p, '$');

      o = variable_buffer_output (o, p, p1 != 0 ? (unsigned int)(p1 - p) : strlen (p) + 1);

      if (p1 == 0)
        break;
      p = p1 + 1;

      /* Dispatch on the char that follows the $.  */

      switch (*p)
        {
        case '$':
        case '\0':
          /* $$ or $ at the end of the string means output one $ to the
             variable output buffer.  */
          o = variable_buffer_output (o, p1, 1);
          break;

        case '(':
        case '{':
          /* $(...) or ${...} is the general case of substitution.  */
          {
            char openparen = *p;
            char closeparen = (openparen == '(') ? ')' : '}';
            const char *begp;
            const char *beg = p + 1;
            char *op;
            char *abeg = NULL;
            const char *end, *colon;

            op = o;
            begp = p;
            if (handle_function (&op, &begp))
              {
                o = op;
                p = begp;
                break;
              }

            /* Is there a variable reference inside the parens or braces?
               If so, expand it before expanding the entire reference.  */

            end = strchr (beg, closeparen);
            if (end == 0)
              /* Unterminated variable reference.  */
              O (fatal, *expanding_var, _("unterminated variable reference"));
            p1 = lindex (beg, end, '$');
            if (p1 != 0)
              {
                /* BEG now points past the opening paren or brace.
                   Count parens or braces until it is matched.  */
                int count = 0;
                for (p = beg; *p != '\0'; ++p)
                  {
                    if (*p == openparen)
                      ++count;
                    else if (*p == closeparen && --count < 0)
                      break;
                  }
                /* If COUNT is >= 0, there were unmatched opening parens
                   or braces, so we go to the simple case of a variable name
                   such as '$($(a)'.  */
                if (count < 0)
                  {
                    abeg = expand_argument (beg, p); /* Expand the name.  */
                    beg = abeg;
                    end = strchr (beg, '\0');
                  }
              }
            else
              /* Advance P to the end of this reference.  After we are
                 finished expanding this one, P will be incremented to
                 continue the scan.  */
              p = end;

            /* This is not a reference to a built-in function and
               any variable references inside are now expanded.
               Is the resultant text a substitution reference?  */

            colon = lindex (beg, end, ':');
            if (colon)
              {
                /* This looks like a substitution reference: $(FOO:A=B).  */
                const char *subst_beg = colon + 1;
                const char *subst_end = lindex (subst_beg, end, '=');
                if (subst_end == 0)
                  /* There is no = in sight.  Punt on the substitution
                     reference and treat this as a variable name containing
                     a colon, in the code below.  */
                  colon = 0;
                else
                  {
                    const char *replace_beg = subst_end + 1;
                    const char *replace_end = end;

                    /* Extract the variable name before the colon
                       and look up that variable.  */
                    v = lookup_variable (beg, colon - beg);
                    if (v == 0)
                      warn_undefined (beg, colon - beg);

                    /* If the variable is not empty, perform the
                       substitution.  */
                    if (v != 0 && *v->value != '\0')
                      {
                        char *pattern, *replace, *ppercent, *rpercent;
                        char *value = (v->recursive
                                       ? recursively_expand (v)
                                       : v->value);

                        /* Copy the pattern and the replacement.  Add in an
                           extra % at the beginning to use in case there
                           isn't one in the pattern.  */
                        pattern = alloca (subst_end - subst_beg + 2);
                        *(pattern++) = '%';
                        memcpy (pattern, subst_beg, subst_end - subst_beg);
                        pattern[subst_end - subst_beg] = '\0';

                        replace = alloca (replace_end - replace_beg + 2);
                        *(replace++) = '%';
                        memcpy (replace, replace_beg,
                               replace_end - replace_beg);
                        replace[replace_end - replace_beg] = '\0';

                        /* Look for %.  Set the percent pointers properly
                           based on whether we find one or not.  */
                        ppercent = find_percent (pattern);
                        if (ppercent)
                          {
                            ++ppercent;
                            rpercent = find_percent (replace);
                            if (rpercent)
                              ++rpercent;
                          }
                        else
                          {
                            ppercent = pattern;
                            rpercent = replace;
                            --pattern;
                            --replace;
                          }

                        o = patsubst_expand_pat (o, value, pattern, replace,
                                                 ppercent, rpercent);

                        if (v->recursive)
                          free (value);
                      }
                  }
              }

            if (colon == 0)
              /* This is an ordinary variable reference.
                 Look up the value of the variable.  */
                o = reference_variable (o, beg, end - beg);

            free (abeg);
          }
          break;

        default:
          if (ISSPACE (p[-1]))
            break;

          /* A $ followed by a random char is a variable reference:
             $a is equivalent to $(a).  */
          o = reference_variable (o, p, 1);

          break;
        }

      if (*p == '\0')
        break;

      ++p;
    }

  free (save);

  variable_buffer_output (o, "", 1);
  return (variable_buffer + line_offset);
}
 is_member(I f, I l, O o = O()) : first(f), last(l), compare(o) { }
Exemple #19
0
    return (PyObject *)trieobj;
}

static PyMethodDef trie_methods[] = {
    {"trie", trie_trie, METH_VARARGS,
     "trie() -> new Trie object."},
    {"load", trie_load, METH_VARARGS,
     "load(handle) -> trie object"},
    {"save", trie_save, METH_VARARGS,
     "save(handle, trie), save a trie object to a handle"},
    {NULL, NULL, 0, NULL}
};

static char trie__doc__[] =
"\
This module implements a trie data structure.  This allows an O(M)\n\
lookup of a string in a dictionary, where M is the length of the\n\
string.  It also supports approximate matches.\n\
\n\
Functions:\n\
trie    Create a new trie object.\n\
save    Save a trie to a handle.\n\
load    Load a trie from a handle.\n\
\n\
";

DL_EXPORT(void)
inittrie(void)
{
    Trie_Type.ob_type = &PyType_Type;
			void * run()
			{
				while ( true )
				{
					/* get any id from global list */
					BgzfThreadQueueElement defglob;
					try
					{
						defglob = deflatecontext.deflategloblist.deque();
					}
					catch(std::exception const & ex)
					{
						/* queue is terminated, break loop */
						break;
					}

					libmaus2_lz_bgzf_op_type op = defglob.op;
					uint64_t objectid = 0;

					{
						libmaus2::parallel::ScopePosixMutex S(deflatecontext.deflateqlock);

						switch ( op )
						{
							case libmaus2_lz_bgzf_op_compress_block:
								objectid = deflatecontext.deflatecompqueue.front();
								deflatecontext.deflatecompqueue.pop_front();
								break;
							case libmaus2_lz_bgzf_op_write_block:
							{
								BgzfThreadQueueElement const btqe = deflatecontext.deflatewritequeue.deque();
								objectid = btqe.objectid;
								libmaus2::parallel::ScopePosixMutex O(deflatecontext.deflateoutlock);
								assert ( deflatecontext.deflateB[objectid]->blockid == deflatecontext.deflatenextwriteid );
								break;
							}
							default:
								break;
						}

						assert ( op != libmaus2_lz_bgzf_op_none );
					}

					switch ( op )
					{
						case libmaus2_lz_bgzf_op_compress_block:
						{
							try
							{
								BgzfDeflateZStreamBaseFlushInfo const BDZSBFI = deflatecontext.deflateB[objectid]->flush(true /* full flush */);
								assert ( !BDZSBFI.movesize );
								deflatecontext.deflateB[objectid]->compsize = BDZSBFI.getCompressedSize();
								deflatecontext.deflateB[objectid]->flushinfo = BDZSBFI;
							}
							catch(libmaus2::exception::LibMausException const & ex)
							{
								libmaus2::parallel::ScopePosixMutex S(deflatecontext.deflateexlock);

								if ( deflatecontext.deflateB[objectid]->blockid * 2 + 0 < deflatecontext.deflateexceptionid )
								{
									deflatecontext.deflateexceptionid = deflatecontext.deflateB[objectid]->blockid * 2 + 0;
									libmaus2::exception::LibMausException::unique_ptr_type tex(ex.uclone());
									deflatecontext.deflatepse = UNIQUE_PTR_MOVE(tex);
								}

								deflatecontext.deflateB[objectid]->compsize = 0;
								deflatecontext.deflateB[objectid]->flushinfo = BgzfDeflateZStreamBaseFlushInfo();
							}
							catch(std::exception const & ex)
							{
								libmaus2::parallel::ScopePosixMutex S(deflatecontext.deflateexlock);

								if ( deflatecontext.deflateB[objectid]->blockid * 2 + 0 < deflatecontext.deflateexceptionid )
								{
									deflatecontext.deflateexceptionid = deflatecontext.deflateB[objectid]->blockid * 2 + 0;

									libmaus2::exception::LibMausException se;
									se.getStream() << ex.what() << std::endl;
									se.finish();

									libmaus2::exception::LibMausException::unique_ptr_type tex(se.uclone());
									deflatecontext.deflatepse = UNIQUE_PTR_MOVE(tex);
								}

								deflatecontext.deflateB[objectid]->compsize = 0;
								deflatecontext.deflateB[objectid]->flushinfo = BgzfDeflateZStreamBaseFlushInfo();
							}

							libmaus2::parallel::ScopePosixMutex S(deflatecontext.deflateqlock);
							deflatecontext.deflatewritequeue.enque(
								BgzfThreadQueueElement(
									libmaus2::lz::BgzfThreadOpBase::libmaus2_lz_bgzf_op_write_block,
									objectid,
									deflatecontext.deflateB[objectid]->blockid
								),
								&(deflatecontext.deflategloblist)
							);
							break;
						}
						case libmaus2_lz_bgzf_op_write_block:
						{
							libmaus2::parallel::ScopePosixMutex O(deflatecontext.deflateoutlock);
							try
							{
								#if 0
								deflatecontext.deflateout.write(
									reinterpret_cast<char const *>(deflatecontext.deflateB[objectid]->outbuf.begin()),
									deflatecontext.deflateB[objectid]->compsize
								);
								#endif
								deflatecontext.streamWrite(
									deflatecontext.deflateB[objectid]->inbuf.begin(),
									deflatecontext.deflateB[objectid]->outbuf.begin(),
									deflatecontext.deflateB[objectid]->flushinfo
								);

								deflatecontext.deflateoutbytes += deflatecontext.deflateB[objectid]->compsize;

								#if 0
								std::cerr << "compsize "
									<< deflatecontext.deflateB[objectid]->compsize
									<< " outbytes "
									<< deflatecontext.deflateoutbytes
									<< std::endl;
								#endif

								#if 0 // this test is done in streamWrite()
								if ( ! deflatecontext.deflateout )
								{
									libmaus2::exception::LibMausException se;
									se.getStream() << "BgzfDeflateParallel: output error on output stream." << std::endl;
									se.finish();
									throw se;
								}
								#endif

								if ( deflatecontext.deflateindexstr )
								{
									if ( deflatecontext.deflateB[objectid]->flushinfo.blocks == 0 )
									{

									}
									else if ( deflatecontext.deflateB[objectid]->flushinfo.blocks == 1 )
									{
										libmaus2::util::UTF8::encodeUTF8(deflatecontext.deflateB[objectid]->flushinfo.block_a_u,*(deflatecontext.deflateindexstr));
										libmaus2::util::UTF8::encodeUTF8(deflatecontext.deflateB[objectid]->flushinfo.block_a_c,*(deflatecontext.deflateindexstr));
									}
									else if ( deflatecontext.deflateB[objectid]->flushinfo.blocks == 2 )
									{
										libmaus2::util::UTF8::encodeUTF8(deflatecontext.deflateB[objectid]->flushinfo.block_a_u,*(deflatecontext.deflateindexstr));
										libmaus2::util::UTF8::encodeUTF8(deflatecontext.deflateB[objectid]->flushinfo.block_a_c,*(deflatecontext.deflateindexstr));
										libmaus2::util::UTF8::encodeUTF8(deflatecontext.deflateB[objectid]->flushinfo.block_b_u,*(deflatecontext.deflateindexstr));
										libmaus2::util::UTF8::encodeUTF8(deflatecontext.deflateB[objectid]->flushinfo.block_b_c,*(deflatecontext.deflateindexstr));
									}
								}
							}
							catch(libmaus2::exception::LibMausException const & ex)
							{
								libmaus2::parallel::ScopePosixMutex S(deflatecontext.deflateexlock);

								if ( deflatecontext.deflateB[objectid]->blockid * 2 + 1 < deflatecontext.deflateexceptionid )
								{
									deflatecontext.deflateexceptionid = deflatecontext.deflateB[objectid]->blockid * 2 + 1;
									libmaus2::exception::LibMausException::unique_ptr_type tex(ex.uclone());
									deflatecontext.deflatepse = UNIQUE_PTR_MOVE(tex);
								}
							}
							catch(std::exception const & ex)
							{
								libmaus2::parallel::ScopePosixMutex S(deflatecontext.deflateexlock);

								if ( deflatecontext.deflateB[objectid]->blockid * 2 + 1 < deflatecontext.deflateexceptionid )
								{
									deflatecontext.deflateexceptionid = deflatecontext.deflateB[objectid]->blockid * 2 + 1;

									libmaus2::exception::LibMausException se;
									se.getStream() << ex.what() << std::endl;
									se.finish();

									libmaus2::exception::LibMausException::unique_ptr_type tex(se.uclone());

									deflatecontext.deflatepse = UNIQUE_PTR_MOVE(tex);
								}
							}

							deflatecontext.deflatenextwriteid += 1;
							deflatecontext.deflatewritequeue.setReadyFor(
								BgzfThreadQueueElement(
									libmaus2::lz::BgzfThreadOpBase::libmaus2_lz_bgzf_op_write_block,
									objectid,
									deflatecontext.deflatenextwriteid
									),
								&(deflatecontext.deflategloblist)
							);
							deflatecontext.deflatefreelist.enque(objectid);
							break;
						}
						default:
						{
							break;
						}
					}
				}

				return 0;
			}
Exemple #21
0
#define MW mmix_type_memaccess_wyde
#define MT mmix_type_memaccess_tetra
#define MO mmix_type_memaccess_octa
#define M mmix_type_memaccess_block
#define J mmix_type_jsr
#define P mmix_type_pseudo

#define OP(y) XCONCAT2 (mmix_operands_,y)

/* Groups of instructions specified here must, if all are matching the
   same instruction, be consecutive, in order more-specific to
   less-specific match.  */

const struct mmix_opcode mmix_opcodes[] =
 {
   {"trap",	O (0),		OP (xyz_opt),		J},
   {"fcmp",	O (1),		OP (regs),		N},
   {"flot",	Z (8),		OP (roundregs_z),	N},

   {"fun",	O (2),		OP (regs),		N},
   {"feql",	O (3),		OP (regs),		N},
   {"flotu",	Z (10),		OP (roundregs_z),	N},

   {"fadd",	O (4),		OP (regs),		N},
   {"fix",	O (5),		OP (roundregs),		N},
   {"sflot",	Z (12),		OP (roundregs_z),	N},

   {"fsub",	O (6),		OP (regs),		N},
   {"fixu",	O (7),		OP (roundregs),		N},
   {"sflotu",	Z (14),		OP (roundregs_z),	N},
   template <class P> static
   void Apply( GenericImage<P>& image, const MorphologicalTransformationInstance& instance )
   {
      Array<AutoPointer<MorphologicalOperator> > O( 2 );

      switch ( instance.Operator() )
      {
      case MorphologicalOp::Closing:
      case MorphologicalOp::Erosion:   O[0].SetPointer( new ErosionFilter ); break;

      case MorphologicalOp::Opening:
      case MorphologicalOp::Dilation:  O[0].SetPointer( new DilationFilter ); break;

      case MorphologicalOp::Median:    O[0].SetPointer( new MedianFilter ); break;

      case MorphologicalOp::Selection: O[0].SetPointer( new SelectionFilter( instance.SelectionPoint() ) ); break;

      case MorphologicalOp::Midpoint:  O[0].SetPointer( new MidpointFilter ); break;

      default: // ?!
         return;
      }

      switch ( instance.Operator() )
      {
      case MorphologicalOp::Closing:   O[1].SetPointer( new DilationFilter ); break;
      case MorphologicalOp::Opening:   O[1].SetPointer( new ErosionFilter ); break;
      }

      String operatorName;

      switch ( instance.Operator() )
      {
      case MorphologicalOp::Closing:   operatorName = "Closing"; break;
      case MorphologicalOp::Erosion:   operatorName = "Erosion"; break;
      case MorphologicalOp::Opening:   operatorName = "Opening"; break;
      case MorphologicalOp::Dilation:  operatorName = "Dilation"; break;
      case MorphologicalOp::Median:    operatorName = "Median"; break;
      case MorphologicalOp::Selection: operatorName = "Selection"; break;
      case MorphologicalOp::Midpoint:  operatorName = "Midpoint"; break;
      }

      MTEngineStructure S( instance );
      MorphologicalTransformation T;

      T.SetStructure( S );
      T.SetInterlacingDistance( instance.InterlacingDistance() );
      T.SetLowThreshold( instance.LowThreshold() );
      T.SetHighThreshold( instance.HighThreshold() );

      image.Status().Initialize( "Morphological transformation: " + operatorName,
                                 image.NumberOfNominalSamples()*instance.NumberOfIterations() );
      image.Status().DisableInitialization();

      double a = instance.Amount();
      double a0 = 1 - a;

      GenericImage<P> img0;

      for ( int c = 0; c < image.NumberOfNominalChannels(); ++c )
      {
         image.SelectChannel( c );

         for ( int i = 0; i < instance.NumberOfIterations(); ++i )
         {
            if ( a != 1 )
               img0 = image;

            T.SetOperator( **O );
            T >> image;

            if ( O[1] )
            {
               T.SetOperator( *O[1] );
               T >> image;
            }

            if ( a != 1 )
               for ( typename P::sample* f = image[c],
                                       * fN = f + image.NumberOfPixels(),
                                       * f0 = *img0;
                     f < fN; ++f, ++f0 )
               {
                  *f = P::FloatToSample( *f*a + *f0*a0 );
               }
         }
      }
   }
Exemple #23
0
static int qesd_init_out (HWVoiceOut *hw, struct audsettings *as)
{
    ESDVoiceOut *esd = (ESDVoiceOut *) hw;
    struct audsettings obt_as = *as;
    int esdfmt = ESD_STREAM | ESD_PLAY;
    int result = -1;

    /* shut down verbose debug spew */
    if (!D_ACTIVE)
        stdio_disable();

    O("initializing EsoundD audio output");
    esdfmt |= (as->nchannels == 2) ? ESD_STEREO : ESD_MONO;
    switch (as->fmt) {
    case AUD_FMT_S8:
    case AUD_FMT_U8:
        esdfmt |= ESD_BITS8;
        obt_as.fmt = AUD_FMT_U8;
        break;
#if 0
    case AUD_FMT_S32:
    case AUD_FMT_U32:
        dolog ("Will use 16 instead of 32 bit samples\n");
#endif
    case AUD_FMT_S16:
    case AUD_FMT_U16:
    deffmt:
        esdfmt |= ESD_BITS16;
        obt_as.fmt = AUD_FMT_S16;
        break;

    default:
        dolog ("Internal logic error: Bad audio format %d\n", as->fmt);
        goto deffmt;

    }
    obt_as.endianness = AUDIO_HOST_ENDIANNESS;

    audio_pcm_init_info (&hw->info, &obt_as);

    hw->samples = conf.samples;
    esd->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);
    if (!esd->pcm_buf) {
        dolog ("Could not allocate buffer (%d bytes)\n",
               hw->samples << hw->info.shift);
        goto exit;
    }

    esd->fd = FF(esd_play_stream) (esdfmt, as->freq, conf.dac_host, NULL);
    if (esd->fd < 0) {
        if (conf.dac_host == NULL) {
            esd->fd = FF(esd_play_stream) (esdfmt, as->freq, "localhost", NULL);
        }
        if (esd->fd < 0) {
            qesd_logerr (errno, "esd_play_stream failed\n");
            goto fail2;
        }
    }

    {
        int  flags;
        flags = fcntl(esd->fd, F_GETFL);
        fcntl(esd->fd, F_SETFL, flags | O_NONBLOCK);
    }

    result = 0;  /* success */
    goto exit;

 fail2:
    qemu_free (esd->pcm_buf);
    esd->pcm_buf = NULL;

 exit:
    if (!D_ACTIVE)
        stdio_enable();

    return result;
}
Exemple #24
0
int
sti_rom_setup(struct sti_rom *rom, bus_space_tag_t iot, bus_space_tag_t memt,
    bus_space_handle_t romh, bus_addr_t *bases, u_int codebase)
{
	struct sti_dd *dd;
	int error, size, i;

	STI_ENABLE_ROM(rom->rom_softc);

	rom->iot = iot;
	rom->memt = memt;
	rom->romh = romh;
	rom->bases = bases;

	/*
	 * Get ROM header and code function pointers.
	 */

	dd = &rom->rom_dd;
	rom->rom_devtype = bus_space_read_1(memt, romh, 3);
	if (rom->rom_devtype == STI_DEVTYPE1) {
		dd->dd_type      = bus_space_read_1(memt, romh, 0x03);
		dd->dd_nmon      = bus_space_read_1(memt, romh, 0x07);
		dd->dd_grrev     = bus_space_read_1(memt, romh, 0x0b);
		dd->dd_lrrev     = bus_space_read_1(memt, romh, 0x0f);
		dd->dd_grid[0]   = parseword(0x10);
		dd->dd_grid[1]   = parseword(0x20);
		dd->dd_fntaddr   = parseword(0x30) & ~3;
		dd->dd_maxst     = parseword(0x40);
		dd->dd_romend    = parseword(0x50) & ~3;
		dd->dd_reglst    = parseword(0x60) & ~3;
		dd->dd_maxreent  = parseshort(0x70);
		dd->dd_maxtimo   = parseshort(0x78);
		dd->dd_montbl    = parseword(0x80) & ~3;
		dd->dd_udaddr    = parseword(0x90) & ~3;
		dd->dd_stimemreq = parseword(0xa0);
		dd->dd_udsize    = parseword(0xb0);
		dd->dd_pwruse    = parseshort(0xc0);
		dd->dd_bussup    = bus_space_read_1(memt, romh, 0xcb);
		dd->dd_ebussup   = bus_space_read_1(memt, romh, 0xcf);
		dd->dd_altcodet  = bus_space_read_1(memt, romh, 0xd3);
		dd->dd_eddst[0]  = bus_space_read_1(memt, romh, 0xd7);
		dd->dd_eddst[1]  = bus_space_read_1(memt, romh, 0xdb);
		dd->dd_eddst[2]  = bus_space_read_1(memt, romh, 0xdf);
		dd->dd_cfbaddr   = parseword(0xe0) & ~3;

		codebase <<= 2;
		dd->dd_pacode[0x0] = parseword(codebase + 0x000) & ~3;
		dd->dd_pacode[0x1] = parseword(codebase + 0x010) & ~3;
		dd->dd_pacode[0x2] = parseword(codebase + 0x020) & ~3;
		dd->dd_pacode[0x3] = parseword(codebase + 0x030) & ~3;
		dd->dd_pacode[0x4] = parseword(codebase + 0x040) & ~3;
		dd->dd_pacode[0x5] = parseword(codebase + 0x050) & ~3;
		dd->dd_pacode[0x6] = parseword(codebase + 0x060) & ~3;
		dd->dd_pacode[0x7] = parseword(codebase + 0x070) & ~3;
		dd->dd_pacode[0x8] = parseword(codebase + 0x080) & ~3;
		dd->dd_pacode[0x9] = parseword(codebase + 0x090) & ~3;
		dd->dd_pacode[0xa] = parseword(codebase + 0x0a0) & ~3;
		dd->dd_pacode[0xb] = parseword(codebase + 0x0b0) & ~3;
		dd->dd_pacode[0xc] = parseword(codebase + 0x0c0) & ~3;
		dd->dd_pacode[0xd] = parseword(codebase + 0x0d0) & ~3;
		dd->dd_pacode[0xe] = parseword(codebase + 0x0e0) & ~3;
		dd->dd_pacode[0xf] = parseword(codebase + 0x0f0) & ~3;
	} else {	/* STI_DEVTYPE4 */
		bus_space_read_raw_region_4(memt, romh, 0, (u_int8_t *)dd,
		    sizeof(*dd));
		/* fix pacode... */
		bus_space_read_raw_region_4(memt, romh, codebase,
		    (u_int8_t *)dd->dd_pacode, sizeof(dd->dd_pacode));
	}

	STI_DISABLE_ROM(rom->rom_softc);

#ifdef STIDEBUG
	printf("dd:\n"
	    "devtype=%x, rev=%x;%d, altt=%x, gid=%08x%08x, font=%x, mss=%x\n"
	    "end=%x, regions=%x, msto=%x, timo=%d, mont=%x, user=%x[%x]\n"
	    "memrq=%x, pwr=%d, bus=%x, ebus=%x, cfb=%x\n"
	    "code=",
	    dd->dd_type & 0xff, dd->dd_grrev, dd->dd_lrrev, dd->dd_altcodet,
	    dd->dd_grid[0], dd->dd_grid[1], dd->dd_fntaddr, dd->dd_maxst,
	    dd->dd_romend, dd->dd_reglst, dd->dd_maxreent, dd->dd_maxtimo,
	    dd->dd_montbl, dd->dd_udaddr, dd->dd_udsize, dd->dd_stimemreq,
	    dd->dd_pwruse, dd->dd_bussup, dd->dd_ebussup, dd->dd_cfbaddr);
	printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n",
	    dd->dd_pacode[0x0], dd->dd_pacode[0x1], dd->dd_pacode[0x2],
	    dd->dd_pacode[0x3], dd->dd_pacode[0x4], dd->dd_pacode[0x5],
	    dd->dd_pacode[0x6], dd->dd_pacode[0x7], dd->dd_pacode[0x8],
	    dd->dd_pacode[0x9], dd->dd_pacode[0xa], dd->dd_pacode[0xb],
	    dd->dd_pacode[0xc], dd->dd_pacode[0xd], dd->dd_pacode[0xe],
	    dd->dd_pacode[0xf]);
#endif

	/*
	 * Figure out how much bytes we need for the STI code.
	 * Note there could be fewer than STI_END entries pointer
	 * entries populated, especially on older devices.
	 */

	for (i = STI_END; !dd->dd_pacode[i]; i--)
		;
	size = dd->dd_pacode[i] - dd->dd_pacode[STI_BEGIN];
	if (rom->rom_devtype == STI_DEVTYPE1)
		size = (size + 3) / 4;
	if (size == 0) {
		printf(": no code for the requested platform\n");
		return (EINVAL);
	}

	if ((rom->rom_code = (vaddr_t)km_alloc(round_page(size), &kv_any,
	    &kp_dirty, &kd_nowait)) == 0) {
		printf(": cannot allocate %u bytes for code\n", size);
		return (ENOMEM);
	}
#ifdef STIDEBUG
	printf("code=0x%x[%x]\n", rom->rom_code, size);
#endif

	/*
	 * Copy code into memory and make it executable.
	 */

	STI_ENABLE_ROM(rom->rom_softc);

	if (rom->rom_devtype == STI_DEVTYPE1) {
		u_int8_t *p = (u_int8_t *)rom->rom_code;
		u_int32_t addr, eaddr;

		for (addr = dd->dd_pacode[STI_BEGIN], eaddr = addr + size * 4;
		    addr < eaddr; addr += 4 )
			*p++ = bus_space_read_4(memt, romh, addr) & 0xff;

	} else	/* STI_DEVTYPE4 */
		bus_space_read_raw_region_4(memt, romh,
		    dd->dd_pacode[STI_BEGIN], (u_int8_t *)rom->rom_code,
		    size);

	STI_DISABLE_ROM(rom->rom_softc);

	if ((error = uvm_map_protect(kernel_map, rom->rom_code,
	    rom->rom_code + round_page(size), UVM_PROT_RX, FALSE))) {
		printf(": uvm_map_protect failed (%d)\n", error);
		km_free((void *)rom->rom_code, round_page(size), &kv_any,
		    &kp_dirty);
		return (error);
	}

	/*
	 * Setup code function pointers.
	 */

#define	O(i) \
	(dd->dd_pacode[(i)] == 0 ? 0 : \
	    (rom->rom_code + (dd->dd_pacode[(i)] - dd->dd_pacode[0]) / \
	      (rom->rom_devtype == STI_DEVTYPE1? 4 : 1)))

	rom->init	= (sti_init_t)	O(STI_INIT_GRAPH);
	rom->mgmt	= (sti_mgmt_t)	O(STI_STATE_MGMT);
	rom->unpmv	= (sti_unpmv_t)	O(STI_FONT_UNPMV);
	rom->blkmv	= (sti_blkmv_t)	O(STI_BLOCK_MOVE);
	rom->test	= (sti_test_t)	O(STI_SELF_TEST);
	rom->exhdl	= (sti_exhdl_t)	O(STI_EXCEP_HDLR);
	rom->inqconf	= (sti_inqconf_t)O(STI_INQ_CONF);
	rom->scment	= (sti_scment_t)O(STI_SCM_ENT);
	rom->dmac	= (sti_dmac_t)	O(STI_DMA_CTRL);
	rom->flowc	= (sti_flowc_t)	O(STI_FLOW_CTRL);
	rom->utiming	= (sti_utiming_t)O(STI_UTIMING);
	rom->pmgr	= (sti_pmgr_t)	O(STI_PROC_MGR);
	rom->util	= (sti_util_t)	O(STI_UTIL);

#undef	O

	/*
	 * Set colormap entry is not implemented until 8.04, so force
	 * a NULL pointer here.
	 */
	if (dd->dd_grrev < STI_REVISION(8,4)) {
		rom->scment = NULL;
	}

	return (0);
}
vtkDataSet *
avtLegacyStreamlineFilter::ExecuteData(vtkDataSet *inDS, int, std::string)
{
    vtkPolyData        *outPD = NULL;
    vtkPolyData        *ballPD = NULL;
    vtkLineSource      *line = NULL;
    vtkPlaneSource     *plane = NULL;
    vtkSphereSource    *sphere = NULL;

    //
    // Create and initialize the streamline filter.
    //
    if(streamline != 0)
        streamline->Delete();
    streamline = vtkVisItStreamLine::New();
    streamline->SetIntegrationDirection(streamlineDirection);
    streamline->SetIntegrationStepLength(stepLength);
    streamline->SetStepLength(stepLength);
    streamline->SetSavePointInterval(stepLength);
    streamline->SetMaximumPropagationTime(maxTime);
    streamline->SetTerminalSpeed(0.01);
    vtkRungeKutta4 *integrator = vtkRungeKutta4::New();
    streamline->SetIntegrator(integrator);
    integrator->Delete();

    bool showTube = displayMethod == STREAMLINE_DISPLAY_TUBES;
    int spatialDim = GetInput()->GetInfo().GetAttributes().GetSpatialDimension();

    //
    // Create a source for the filter's streamline points.
    //
    if(sourceType == STREAMLINE_SOURCE_POINT)
    {
        double z0 = (spatialDim > 2) ? pointSource[2] : 0.;
        streamline->SetStartPosition(pointSource[0], pointSource[1], z0);
    }
    else if(sourceType == STREAMLINE_SOURCE_LINE)
    {
        line = vtkLineSource::New();
        double z0 = (spatialDim > 2) ? lineStart[2] : 0.;
        double z1 = (spatialDim > 2) ? lineEnd[2] : 0.;
        line->SetPoint1(lineStart[0], lineStart[1], z0);
        line->SetPoint2(lineEnd[0], lineEnd[1], z1);
        line->SetResolution(pointDensity);
        if(showTube && showStart)
            ballPD = line->GetOutput();

        streamline->SetSource(line->GetOutput());
    }
    else if(sourceType == STREAMLINE_SOURCE_PLANE)
    {
        plane = vtkPlaneSource::New();
        plane->SetXResolution(pointDensity);
        plane->SetYResolution(pointDensity);
        avtVector O(planeOrigin);
        avtVector U(planeUpAxis);
        avtVector N(planeNormal);
        U.normalize();
        N.normalize();
        if(spatialDim <= 2)
           N = avtVector(0.,0.,1.);
        // Determine the right vector.
        avtVector R(U % N);
        R.normalize();
        plane->SetOrigin(O.x, O.y, O.z);
        avtVector P1(U * (2./1.414214) * planeRadius + O);
        avtVector P2(R * (2./1.414214) * planeRadius + O);
        plane->SetPoint2(P1.x, P1.y, P1.z);
        plane->SetPoint1(P2.x, P2.y, P2.z);
        plane->SetNormal(N.x, N.y, N.z);
        plane->SetCenter(O.x, O.y, O.z);

        // Zero out the Z coordinate if the input dataset is only 2D.
        vtkPolyData *planePD = plane->GetOutput();
        if(spatialDim <= 2)
            SetZToZero(planePD);

        if(showTube && showStart)
            ballPD = planePD;

        streamline->SetSource(planePD);
    }
    else if(sourceType == STREAMLINE_SOURCE_SPHERE)
    {
        sphere = vtkSphereSource::New();
        sphere->SetCenter(sphereOrigin[0], sphereOrigin[1], sphereOrigin[2]);
        sphere->SetRadius(sphereRadius);
        sphere->SetLatLongTessellation(1);
        double t = double(30 - pointDensity) / 29.;
        double angle = t * 3. + (1. - t) * 30.;
        sphere->SetPhiResolution(int(angle));
        sphere->SetThetaResolution(int(angle));

        // Zero out the Z coordinate if the input dataset is only 2D.
        vtkPolyData *spherePD = sphere->GetOutput();
        if(spatialDim <= 2)
            SetZToZero(spherePD);

        if(showTube && showStart)
            ballPD = spherePD;

        streamline->SetSource(spherePD);
    }
    else if(sourceType == STREAMLINE_SOURCE_BOX)
    {
        //
        // Create polydata that contains the points that we want to streamline.
        //
        ballPD = vtkPolyData::New();
        vtkPoints *pts = vtkPoints::New();
        ballPD->SetPoints(pts);

        int npts = (pointDensity+1)*(pointDensity+1);
        int nZvals = 1;
        if(spatialDim > 2)
        {
            npts *= (pointDensity+1);
            nZvals = (pointDensity+1);
        }
        pts->SetNumberOfPoints(npts);

        float dX = boxExtents[1] - boxExtents[0];
        float dY = boxExtents[3] - boxExtents[2];
        float dZ = boxExtents[5] - boxExtents[4];
        int index = 0;
        for(int k = 0; k < nZvals; ++k)
        {
            float Z = 0.;
            if(spatialDim > 2)
                Z = (float(k) / float(pointDensity)) * dZ + boxExtents[4];
            for(int j = 0; j < pointDensity+1; ++j)
            {
                float Y = (float(j) / float(pointDensity)) * dY + boxExtents[2];
                for(int i = 0; i < pointDensity+1; ++i)
                {
                    float X = (float(i) / float(pointDensity)) * dX + boxExtents[0];
                    pts->SetPoint(index++, X, Y, Z);
                }
            }
        }
        pts->Delete();

        streamline->SetSource(ballPD);
    }

    bool doRibbons = displayMethod == STREAMLINE_DISPLAY_RIBBONS;
    if(coloringMethod == STREAMLINE_COLOR_SOLID)
    {
        // No variable coloring.
        streamline->SetSpeedScalars(1);  // hack
        streamline->SetVorticity(doRibbons?1:0);
    }
    else if(coloringMethod == STREAMLINE_COLOR_SPEED)
    {
        // Color by velocity magnitude.
        streamline->SetSpeedScalars(1);
        streamline->SetVorticity(doRibbons?1:0);
    }
    else
    {
        // Color by vorticity magnitude.
        streamline->SetSpeedScalars(0);
        streamline->SetVorticity(1);
    }

    // Set the input to the streamline filter and execute it.
    streamline->SetInput(inDS);
    streamline->Update();
    vtkPolyData *streams = streamline->GetOutput();
    if (coloringMethod == STREAMLINE_COLOR_SPEED)
        streams->GetPointData()->GetScalars()->SetName("colorVar");

    if(doRibbons)
    {
        //
        // If we're going to display the streamlines as ribbons, add the
        // streams to the ribbon filter and get the output.
        //
        if(ribbons != 0)
            ribbons->Delete();
        ribbons = vtkRibbonFilter::New();
        ribbons->SetWidth(2. * radius);
        ribbons->SetInput(streams);
        ribbons->Update();
        streams = ribbons->GetOutput();
    }

    // If we're coloring by vorticity magnitude, convert the vorticity to
    // vorticity magnitude and put it in the Scalars array.
    vtkDataArray *vorticity = streams->GetPointData()->GetVectors();
    if(vorticity != 0)
    {
        if(coloringMethod == STREAMLINE_COLOR_VORTICITY)
        {
            debug4 << "Computing vorticity magnitude." << endl;
            int n = vorticity->GetNumberOfTuples();
            vtkFloatArray *vortMag = vtkFloatArray::New();
            vortMag->SetName("colorVar");
            vortMag->SetNumberOfComponents(1);
            vortMag->SetNumberOfTuples(n);
            float *vm = (float *)vortMag->GetVoidPointer(0);
            for(int i = 0; i < n; ++i)
            {
                const double *val = vorticity->GetTuple3(i);
                *vm++ = (float)sqrt(val[0]*val[0] + val[1]*val[1] + val[2]*val[2]);
            }
            // If there is a scalar array, remove it.
            vtkDataArray *oldScalars = streams->GetPointData()->GetScalars();
            if(oldScalars != 0)
                streams->GetPointData()->RemoveArray(oldScalars->GetName());
            // Remove the vorticity array.
            streams->GetPointData()->RemoveArray(vorticity->GetName());

            // Make vorticity magnitude be the active scalar field.
            streams->GetPointData()->SetVectors(0);
            streams->GetPointData()->SetScalars(vortMag);
        }
        else
        {
            // Remove the vorticity array.
            streams->GetPointData()->RemoveArray(vorticity->GetName());
            streams->GetPointData()->SetVectors(0);
            debug4 << "Removed vorticity since we didn't need it." << endl;
        }
    }

    if(!doRibbons && showTube)
    {
        //
        // Create and initialize the tube filter.
        //
        if(tubes != 0)
            tubes->Delete();
        tubes = vtkTubeFilter::New();
        tubes->SetRadius(radius);
        tubes->SetNumberOfSides(8);
        tubes->SetRadiusFactor(2.);
        tubes->SetCapping(1);
        tubes->ReleaseDataFlagOn();

        if(showStart)
        {
            // Execute the tube filter.
            tubes->SetInput(streams);
            tubes->Update();
            vtkPolyData *tubeData = tubes->GetOutput();

            // Create an append filter that we'll use to add the start balls
            // to the tube poly data.
            vtkAppendPolyData *append = vtkAppendPolyData::New();
            append->AddInput(tubeData);
            vtkPolyData       **balls = NULL;
            int                 nballs = 0;

            // Add spheres to the start of the streamlines so we know where
            // they start.
            if(sourceType == STREAMLINE_SOURCE_POINT)
            {
                double pt[] = {pointSource[0], pointSource[1], 0.};
                if(spatialDim > 2) pt[2] = pointSource[2];
                vtkDataArray *arr = tubeData->GetPointData()->GetScalars();
                float val = arr->GetTuple1(0);
                balls = new vtkPolyData *[1];
                nballs = 1;
                balls[0] = AddStartSphere(tubeData, val, pt);
                append->AddInput(balls[0]);
            }
            else if(ballPD != NULL)
            {
                vtkCellArray *lines = streams->GetLines();
                if(lines != NULL && lines->GetNumberOfCells() > 0)
                {
                    lines->SetTraversalLocation(0);
                    nballs = ballPD->GetNumberOfPoints();
                    balls = new vtkPolyData*[nballs];
                    for(vtkIdType i = 0; i < nballs; ++i)
                    {
                        // Figure out the data value used to color the ball.
                        vtkIdType *pts = NULL, npts;
                        lines->GetNextCell(npts, pts);
                        if(pts != NULL)
                        {
                            vtkDataArray *arr = streams->GetPointData()->GetScalars();
                            double val = arr->GetTuple1(pts[0]);
                            balls[i] = AddStartSphere(tubeData, val, ballPD->GetPoint(i));
                        }
                        else
                        {
                            // There was no line for the point so add a ball 
                            // colored with zero speed.
                            balls[i] = AddStartSphere(tubeData, 0., ballPD->GetPoint(i));
                        }

                        // Add the ball to the append filter.
                        append->AddInput(balls[i]);
                    }
                }
            }

            append->Update();
            outPD = append->GetOutput();
            // Stash the polydata in the streamline filter since we keep it around for
            // the life of the filter. This keeps it from disappearing when we delete
            // the append filter.
            streamline->SetOutput(outPD);

            //
            // Delete the ball polydata.
            //
            append->Delete();
            if(nballs > 0)
            {
                for(int i = 0; i < nballs; ++i)
                    balls[i]->Delete();
                delete [] balls;
            }
        }
        else
        {
            tubes->SetInput(streams);
            tubes->Update();
            outPD = tubes->GetOutput();
        }
    }
    else
    {
        outPD = streams;
    }

    //
    // Delete any sources that we created.
    //
    if(line != NULL)
        line->Delete();
    if(plane != NULL)
        plane->Delete();
    if(sphere != NULL)
        sphere->Delete();

    return outPD;
}
Exemple #26
0
};

static
TkStab tkfill[] =
{
	"none",		0,
	"x",		Tkfillx,
	"y",		Tkfilly,
	"both",		Tkfillx|Tkfilly,
	nil
};

static
TkOption opts[] =
{
	"padx",		OPTnndist,	O(TkParam, pad.x),	nil,
	"pady",		OPTnndist,	O(TkParam, pad.y),	nil,
	"ipadx",	OPTnndist,	O(TkParam, ipad.x),	nil,
	"ipady",	OPTnndist,	O(TkParam, ipad.y),	nil,
	"side",		OPTstab,	O(TkParam, side),	tkside,
	"anchor",	OPTstab,	O(TkParam, anchor),	tkanchor,
	"fill",		OPTstab,	O(TkParam, fill),	tkfill,
	"in",		OPTwinp,	O(TkParam, in),		nil,
	"before",	OPTwinp,	O(TkParam, before),	nil,
	"after",	OPTwinp,	O(TkParam, after),	nil,
	"expand",	OPTstab,	O(TkParam, expand),	tkbool,
	nil
};

void
tkdelpack(Tk *t)
Exemple #27
0
	int	center;
	int	pix;
	int	base;
	int	flag;
	int	jump;
};

enum {
	Dragging = (1<<0),
	Autorepeat = (1<<1),
};

static
TkOption opts[] =
{
	"bigincrement",		OPTnnfrac,	O(TkScale, bigi),	nil,
	"digits",		OPTdist,	O(TkScale, digits),	nil,
	"from",			OPTfrac,	O(TkScale, from),	nil,
	"to",			OPTfrac,	O(TkScale, to),		nil,
	"length",		OPTdist,	O(TkScale, len),	nil,
	"resolution",		OPTnnfrac,	O(TkScale, res),	nil,
	"showrange",	OPTignore,	0,	nil,
	"showvalue",		OPTstab,	O(TkScale, sv),		tkbool,
	"jump",		OPTstab, O(TkScale, jump),	tkbool,
	"sliderlength",		OPTdist,	O(TkScale, sl),		nil,
	"sliderrelief",		OPTstab,	O(TkScale, relief),	tkrelief,
	"tickinterval",		OPTfrac,	O(TkScale, tick),	nil,
	"tick",		OPTfrac,	O(TkScale, tick),	nil,
	"label",		OPTtext,	O(TkScale, label),	nil,
	"command",		OPTtext,	O(TkScale, command),	nil,
	"orient",		OPTstab,	O(TkScale, orient),	tkorient,
Exemple #28
0
};

enum {
	ActiveA1	= (1<<0),	/* Scrollbar control */
	ActiveA2	= (1<<1),
	ActiveB1	= (1<<2),
	ButtonA1	= (1<<3),
	ButtonA2	= (1<<4),
	ButtonB1	= (1<<5),
	Autorepeat = (1<<6)
};

static
TkOption opts[] =
{
	"activerelief",	OPTstab,	O(TkScroll, activer),	tkrelief,
	"command",	OPTtext,	O(TkScroll, cmd),	nil,
	"jump",	OPTstab,	O(TkScroll, jump),	tkbool,
	"orient",	OPTstab,	O(TkScroll, orient),	tkorient,
	nil
};

static
TkEbind b[] = 
{
	{TkLeave,		"%W activate {}"},
	{TkEnter,		"%W activate [%W identify %x %y]"},
	{TkMotion,		"%W activate [%W identify %x %y]"},
	{TkButton1P|TkMotion,	"%W tkScrollDrag %x %y"},
	{TkButton1P,		"%W tkScrolBut1P %x %y"},
	{TkButton1P|TkDouble,	"%W tkScrolBut1P %x %y"},
Exemple #29
0
static unsigned int
bfd_h8_disassemble (bfd_vma addr, disassemble_info *info, int mach)
{
  /* Find the first entry in the table for this opcode.  */
  int regno[3] = { 0, 0, 0 };
  int dispregno[3] = { 0, 0, 0 };
  int cst[3] = { 0, 0, 0 };
  int cstlen[3] = { 0, 0, 0 };
  static bfd_boolean init = 0;
  const struct h8_instruction *qi;
  char const **pregnames = mach != 0 ? lregnames : wregnames;
  int status;
  unsigned int l;
  unsigned char data[MAX_CODE_NIBBLES];
  void *stream = info->stream;
  fprintf_ftype outfn = info->fprintf_func;

  if (!init)
    {
      bfd_h8_disassemble_init ();
      init = 1;
    }

  status = info->read_memory_func (addr, data, 2, info);
  if (status != 0)
    {
      info->memory_error_func (status, addr, info);
      return -1;
    }

  for (l = 2; status == 0 && l < sizeof (data) / 2; l += 2)
    status = info->read_memory_func (addr + l, data + l, 2, info);

  /* Find the exact opcode/arg combo.  */
  for (qi = h8_instructions; qi->opcode->name; qi++)
    {
      const struct h8_opcode *q = qi->opcode;
      const op_type *nib = q->data.nib;
      unsigned int len = 0;

      while (1)
	{
	  op_type looking_for = *nib;
	  int thisnib = data[len / 2];
	  int opnr;

	  thisnib = (len & 1) ? (thisnib & 0xf) : ((thisnib / 16) & 0xf);
	  opnr = ((looking_for & OP3) == OP3 ? 2
		  : (looking_for & DST) == DST ? 1 : 0);

	  if (looking_for < 16 && looking_for >= 0)
	    {
	      if (looking_for != thisnib)
		goto fail;
	    }
	  else
	    {
	      if ((int) looking_for & (int) B31)
		{
		  if (!((thisnib & 0x8) != 0))
		    goto fail;

		  looking_for = (op_type) ((int) looking_for & ~(int) B31);
		  thisnib &= 0x7;
		}
	      else if ((int) looking_for & (int) B30)
		{
		  if (!((thisnib & 0x8) == 0))
		    goto fail;

		  looking_for = (op_type) ((int) looking_for & ~(int) B30);
		}

	      if ((int) looking_for & (int) B21)
		{
		  if (!((thisnib & 0x4) != 0))
		    goto fail;

		  looking_for = (op_type) ((int) looking_for & ~(int) B21);
		  thisnib &= 0xb;
		}
	      else if ((int) looking_for & (int) B20)
		{
		  if (!((thisnib & 0x4) == 0))
		    goto fail;

		  looking_for = (op_type) ((int) looking_for & ~(int) B20);
		}
	      if ((int) looking_for & (int) B11)
		{
		  if (!((thisnib & 0x2) != 0))
		    goto fail;

		  looking_for = (op_type) ((int) looking_for & ~(int) B11);
		  thisnib &= 0xd;
		}
	      else if ((int) looking_for & (int) B10)
		{
		  if (!((thisnib & 0x2) == 0))
		    goto fail;

		  looking_for = (op_type) ((int) looking_for & ~(int) B10);
		}

	      if ((int) looking_for & (int) B01)
		{
		  if (!((thisnib & 0x1) != 0))
		    goto fail;

		  looking_for = (op_type) ((int) looking_for & ~(int) B01);
		  thisnib &= 0xe;
		}
	      else if ((int) looking_for & (int) B00)
		{
		  if (!((thisnib & 0x1) == 0))
		    goto fail;

		  looking_for = (op_type) ((int) looking_for & ~(int) B00);
		}

	      if (looking_for & IGNORE)
		{
		  /* Hitachi has declared that IGNORE must be zero.  */
		  if (thisnib != 0)
		    goto fail;
		}
	      else if ((looking_for & MODE) == DATA)
		{
		  ;			/* Skip embedded data.  */
		}
	      else if ((looking_for & MODE) == DBIT)
		{
		  /* Exclude adds/subs by looking at bit 0 and 2, and
                     make sure the operand size, either w or l,
                     matches by looking at bit 1.  */
		  if ((looking_for & 7) != (thisnib & 7))
		    goto fail;

		  cst[opnr] = (thisnib & 0x8) ? 2 : 1;
		}
	      else if ((looking_for & MODE) == DISP
		       || (looking_for & MODE) == ABS
		       || (looking_for & MODE) == PCREL
		       || (looking_for & MODE) == INDEXB
		       || (looking_for & MODE) == INDEXW
		       || (looking_for & MODE) == INDEXL)
		{
		  extract_immediate (stream, looking_for, thisnib, 
				     data + len / 2, cst + opnr, 
				     cstlen + opnr, q);
		  /* Even address == bra, odd == bra/s.  */
		  if (q->how == O (O_BRAS, SB))
		    cst[opnr] -= 1;
		}
	      else if ((looking_for & MODE) == REG
		       || (looking_for & MODE) == LOWREG
		       || (looking_for & MODE) == IND
		       || (looking_for & MODE) == PREINC
		       || (looking_for & MODE) == POSTINC
		       || (looking_for & MODE) == PREDEC
		       || (looking_for & MODE) == POSTDEC)
		{
		  regno[opnr] = thisnib;
		}
	      else if (looking_for & CTRL)	/* Control Register.  */
		{
		  thisnib &= 7;
		  if (((looking_for & MODE) == CCR  && (thisnib != C_CCR))
		      || ((looking_for & MODE) == EXR  && (thisnib != C_EXR))
		      || ((looking_for & MODE) == MACH && (thisnib != C_MACH))
		      || ((looking_for & MODE) == MACL && (thisnib != C_MACL))
		      || ((looking_for & MODE) == VBR  && (thisnib != C_VBR))
		      || ((looking_for & MODE) == SBR  && (thisnib != C_SBR)))
		    goto fail;
		  if (((looking_for & MODE) == CCR_EXR
		       && (thisnib != C_CCR && thisnib != C_EXR))
		      || ((looking_for & MODE) == VBR_SBR
			  && (thisnib != C_VBR && thisnib != C_SBR))
		      || ((looking_for & MODE) == MACREG
			  && (thisnib != C_MACH && thisnib != C_MACL)))
		    goto fail;
		  if (((looking_for & MODE) == CC_EX_VB_SB
		       && (thisnib != C_CCR && thisnib != C_EXR
			   && thisnib != C_VBR && thisnib != C_SBR)))
		    goto fail;

		  regno[opnr] = thisnib;
		}
	      else if ((looking_for & SIZE) == L_5)
		{
		  cst[opnr] = data[len / 2] & 31;
		  cstlen[opnr] = 5;
		}
	      else if ((looking_for & SIZE) == L_4)
		{
		  cst[opnr] = thisnib;
		  cstlen[opnr] = 4;
		}
	      else if ((looking_for & SIZE) == L_16
		       || (looking_for & SIZE) == L_16U)
		{
		  cst[opnr] = (data[len / 2]) * 256 + data[(len + 2) / 2];
		  cstlen[opnr] = 16;
		}
	      else if ((looking_for & MODE) == MEMIND)
		{
		  cst[opnr] = data[1];
		}
	      else if ((looking_for & MODE) == VECIND)
		{
		  cst[opnr] = data[1] & 0x7f;
		}
	      else if ((looking_for & SIZE) == L_32)
		{
		  int i = len / 2;

		  cst[opnr] = ((data[i] << 24) 
			       | (data[i + 1] << 16) 
			       | (data[i + 2] << 8)
			       | (data[i + 3]));

		  cstlen[opnr] = 32;
		}
	      else if ((looking_for & SIZE) == L_24)
		{
		  int i = len / 2;

		  cst[opnr] = 
		    (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
		  cstlen[opnr] = 24;
		}
	      else if (looking_for & IGNORE)
		{
		  ;
		}
	      else if (looking_for & DISPREG)
		{
		  dispregno[opnr] = thisnib & 7;
		}
	      else if ((looking_for & MODE) == KBIT)
		{
		  switch (thisnib)
		    {
		    case 9:
		      cst[opnr] = 4;
		      break;
		    case 8:
		      cst[opnr] = 2;
		      break;
		    case 0:
		      cst[opnr] = 1;
		      break;
		    default:
		      goto fail;
		    }
		}
	      else if ((looking_for & SIZE) == L_8)
		{
		  cstlen[opnr] = 8;
		  cst[opnr] = data[len / 2];
		}
	      else if ((looking_for & SIZE) == L_3
		       || (looking_for & SIZE) == L_3NZ)
		{
		  cst[opnr] = thisnib & 0x7;
		  if (cst[opnr] == 0 && (looking_for & SIZE) == L_3NZ)
		    goto fail;
		}
	      else if ((looking_for & SIZE) == L_2)
		{
		  cstlen[opnr] = 2;
		  cst[opnr] = thisnib & 0x3;
		}
	      else if ((looking_for & MODE) == MACREG)
		{
		  cst[opnr] = (thisnib == 3);
		}
	      else if (looking_for == (op_type) E)
		{
		  outfn (stream, "%s\t", q->name);

		  /* Gross.  Disgusting.  */
		  if (strcmp (q->name, "ldm.l") == 0)
		    {
		      int count, high;

		      count = (data[1] / 16) & 0x3;
		      high = regno[1];

		      outfn (stream, "@sp+,er%d-er%d", high - count, high);
		      return qi->length;
		    }

		  if (strcmp (q->name, "stm.l") == 0)
		    {
		      int count, low;

		      count = (data[1] / 16) & 0x3;
		      low = regno[0];

		      outfn (stream, "er%d-er%d,@-sp", low, low + count);
		      return qi->length;
		    }
		  if (strcmp (q->name, "rte/l") == 0
		      || strcmp (q->name, "rts/l") == 0)
		    {
		      if (regno[0] == 0)
			outfn (stream, "er%d", regno[1]);
		      else
			outfn (stream, "er%d-er%d", regno[1] - regno[0],
			       regno[1]);
		      return qi->length;
		    }
		  if (CONST_STRNEQ (q->name, "mova"))
		    {
		      const op_type *args = q->args.nib;

		      if (args[1] == (op_type) E)
			{
			  /* Short form.  */
			  print_one_arg (info, addr, args[0], cst[0], 
					 cstlen[0], dispregno[0], regno[0], 
					 pregnames, qi->length);
			  outfn (stream, ",er%d", dispregno[0]);
			}
		      else
			{
			  outfn (stream, "@(0x%x:%d,", cst[0], cstlen[0]);
			  print_one_arg (info, addr, args[1], cst[1], 
					 cstlen[1], dispregno[1], regno[1], 
					 pregnames, qi->length);
			  outfn (stream, ".%c),",
				 (args[0] & MODE) == INDEXB ? 'b' : 'w');
			  print_one_arg (info, addr, args[2], cst[2], 
					 cstlen[2], dispregno[2], regno[2], 
					 pregnames, qi->length);
			}
		      return qi->length;
		    }
		  /* Fill in the args.  */
		  {
		    const op_type *args = q->args.nib;
		    int hadone = 0;
		    int nargs;

		    /* Special case handling for the adds and subs instructions
		       since in H8 mode thay can only take the r0-r7 registers
		       but in other (higher) modes they can take the er0-er7
		       registers as well.  */
		    if (strcmp (qi->opcode->name, "adds") == 0
			|| strcmp (qi->opcode->name, "subs") == 0)
		      {
			outfn (stream, "#%d,%s", cst[0], pregnames[regno[1] & 0x7]);
			return qi->length;
		      }

		    for (nargs = 0; 
			 nargs < 3 && args[nargs] != (op_type) E;
			 nargs++)
		      {
			int x = args[nargs];

			if (hadone)
			  outfn (stream, ",");

			print_one_arg (info, addr, x,
				       cst[nargs], cstlen[nargs],
				       dispregno[nargs], regno[nargs],
				       pregnames, qi->length);

			hadone = 1;
		      }
		  }

		  return qi->length;
		}
	      else
		/* xgettext:c-format */
		outfn (stream, _("Don't understand 0x%x \n"), looking_for);
	    }

	  len++;
	  nib++;
	}

    fail:
      ;
    }

  /* Fell off the end.  */
  outfn (stream, ".word\tH'%x,H'%x", data[0], data[1]);
  return 2;
}
Exemple #30
0
Fichier : p.c Projet : 0branch/kona
Z void showx(K x){ O("[%lld,%lld,%lld] ",xt,xn,rc(x));show(x);if(6==xt)O("\n");}