コード例 #1
0
ファイル: compress_qdm.cpp プロジェクト: Ethatron/squash-ccr
static bool TextureCompressQDM(LPDIRECT3DTEXTURE *base, LPDIRECT3DTEXTURE *norm, int minlevel) {
  LPDIRECT3DTEXTURE baset;
  LPDIRECT3DTEXTURE normt;
  RESOURCEINFO based, baseo;
  RESOURCEINFO normd, normo;

  TextureInfoLevel(*base, baseo, 0);
  TextureInfoLevel(*norm, normo, 0);

#if 0
  /* Converts a height map into a normal map. The (x,y,z)
   * components of each normal are mapped to the (r,g,b)
   * channels of the output texture.
   */
  HRESULT D3DXComputeNormalMap(
    __out  LPDIRECT3DTEXTURE pTexture,
    __in   LPDIRECT3DTEXTURE pSrcTexture,
    __in   const PALETTEENTRY *pSrcPalette,
    __in   DWORD Flags,
    __in   DWORD Channel,
    __in   FLOAT Amplitude
    );
#endif

  /* they have to have the same dimension */
  if ((baseo.Width  != normo.Width ) ||
      (baseo.Height != normo.Height))
    return false;

  /* convert to ARGB8 (TODO: support at least the 16bit formats as well) */
  if ((baseo.Format != TEXFMT_A8B8G8R8) && baseo.Format = TEXFMT_A8R8G8B8, !TextureConvert(baseo, base, false))
    return false;
  if ((normo.Format != TEXFMT_A8B8G8R8) && normo.Format = TEXFMT_A8R8G8B8, !TextureConvert(normo, norm, true))
    return false;

  /* create the textures */
  int levels = TextureCalcMip(baseo.Width, baseo.Height, minlevel);
  int flags = squish::kColourIterativeClusterFit | squish::kBtc3;

#ifdef DX11
  ULONG *bases;
  ULONG *norms;

  DWORD basel = 1;
  DWORD norml = 1;
  DWORD level = max(basel, norml);
#else
  /* create the textures */
  pD3DDevice->CreateTexture(baseo.Width, baseo.Height, levels, 0, D3DFMT_DXT5, D3DPOOL_SYSTEMMEM, &baset, NULL);
  pD3DDevice->CreateTexture(normo.Width, normo.Height, levels, 0, D3DFMT_DXT5, D3DPOOL_SYSTEMMEM, &normt, NULL);

  /* damit */
  if (!baset || !normt) {
    if (baset) baset->Release();
    if (normt) normt->Release();

    return false;
  }

  ULONG bPch, *bases = TextureLock(*base, &bPch, 0);
  ULONG nPch, *norms = TextureLock(*norm, &nPch, 0);

  DWORD basel = baset->GetLevelCount();
  DWORD norml = normt->GetLevelCount();
  DWORD level = max(basel, norml);
#endif

  for (unsigned int l = 0; l < level; l++) {
    /* square dimension of this surface-level */
    /* square area of this surface-level */
    int lv = (1 << l);
    int av = lv * lv;

    TextureInfoLevel(baset, based, l);
    TextureInfoLevel(normt, normd, l);

    ULONG sPch, *baser = TextureLock(baset, l, &sPch, true);
    ULONG nPch, *normr = TextureLock(normt, l, &nPch, true);

    ULONG *sBase = (ULONG *)bases;
    ULONG *sNorm = (ULONG *)norms;
    ULONG *dBase = (ULONG *)baser;
    ULONG *dNorm = (ULONG *)normr;

    /* loop over 4x4-blocks of this level (DXT5) */
    for (unsigned int y = 0; y < based.Height; y += TY) {
      if (!(y & 0x3F)) {
//	logrf("line processed %d/%d of level %d/%d\r", y, based.Height, l, level);

//	PollProgress();
      }

    for (unsigned int x = 0; x < based.Width; x += TX) {
      UTYPE bBase[2][TY][TX];
      ULONG bNorm[2][TY][TX];
      type  fBase[2][TY][TX][DIM];
      float fNorm[2][TY][TX][DIM];

      /* generate this level's 4x4-block from the original surface */
      for (int ly = 0; ly < TY; ly += 1)
      for (int lx = 0; lx < TX; lx += 1) {
	type  bs[DIM] = {0}; int yl = ((y + ly) << l);
	/*ng  ns[DIM] = {0*/ int xl = ((x + lx) << l);
	float nn[DIM] = {0.0f};

	/* access all pixels this level's 4x4-block represents in
	 * the full dimension original surface (high quality mip-mapping)
	 */
	for (int oy = 0; oy < lv; oy += 1)
	for (int ox = 0; ox < lv; ox += 1) {
	  /* assume seamless tiling: wrap pixels around */
	  int posx = (xl + ox) % baseo.Width;
	  int posy = (yl + oy) % baseo.Height;

	  ULONG &b = sBase[(posy * sPch) + posx];
	  ULONG &n = sNorm[(posy * nPch) + posx];

	  /* transfer heightmap into the normal-map (overwrite) */
	  if (LODed)
	    n = (n & 0x00FFFFFF) + (b & 0xFF000000);

	  { static const f<TCOMPRESS_RGBH> fmt; Accu(bs, b); }
	  { static const f<TCOMPRESS_XYZD> fmt; Accu(nn, n); }

//	  AccuRGBM<ACCUMODE_LINEAR>(bs, b, level, l, colorgamma);	// += and max
#if	defined(NORMALS_INTEGER)
//	  AccuXYZD<ACCUMODE_SCALE >(ns, n, level, l, NORMALS_SCALEBYLEVEL);	// +=
#else
//	  AccuXYZD<ACCUMODE_SCALE >(nn, n, level, l, NORMALS_SCALEBYLEVEL);	// +=
#endif
	}

	/* build average of each channel */
	{ const int format = TCOMPRESS_RGBH; Norm(fBase[0][ly][lx], bs, av, levels, l); }
	{ const int format = TCOMPRESS_XYZD; Norm(fNorm[0][ly][lx], nn, av, levels, l); }

//	NormRGBM<TRGTMODE_CODING_RGB                         >(fBase[0][ly][lx], bs, av, colorgammainv);
#if	defined(NORMALS_INTEGER)
//	NormXYZD<TRGTMODE_CODING_DXDYdZt | TRGTNORM_CUBESPACE>(fNorm[0][ly][lx], ns, av);
#else
//	NormXYZD<TRGTMODE_CODING_DXDYdZt | TRGTNORM_CUBESPACE>(fNorm[0][ly][lx], nn, av);
#endif
      }

      type  br[DIM] = {0};
      /*ng  nr[DIM] = {0*/
      float rn[DIM] = {0.0f};

      /* analyze this level's 4x4-block */
      for (int ly = 0; ly < TY; ly += 1)
      for (int lx = 0; lx < TX; lx += 1) {
	{ const int format = TCOMPRESS_RGBH; Look(fBase[0][ly][lx], br); }
	{ const int format = TCOMPRESS_XYZD; Look(fNorm[0][ly][lx], rn); }

//	LookRGBH<TRGTMODE_CODING_RGB                         >(fBase[0][ly][lx], br);
#if	defined(NORMALS_INTEGER)
//	LookXYZD<TRGTMODE_CODING_DXDYdZt | TRGTNORM_CUBESPACE>(fNorm[0][ly][lx], nr);
#else
//	LookXYZD<TRGTMODE_CODING_DXDYdZt | TRGTNORM_CUBESPACE>(fNorm[0][ly][lx], rn);
#endif
      }

      /* generate this level's 4x4-block from the original surface */
      for (int ly = 0; ly < TY; ly += 1)
      for (int lx = 0; lx < TX; lx += 1) {
	/* build average of each channel an join */
	UTYPE b;
	ULONG n;

	{ const int format = TCOMPRESS_RGBH;
	Code(fBase[0][ly][lx], br, (TCOMPRESS_CHANNELS(format) +
				   (TCOMPRESS_GREYS   (format) ? 2 : 0)) == 2 ? 8 :
				   (TCOMPRESS_SWIZZL  (format) ? 6 : 5)); }
	{ const int format = TCOMPRESS_XYZD;
	Code(fNorm[0][ly][lx], rn, (TCOMPRESS_CHANNELS(format) +
				   (TCOMPRESS_GREYS   (format) ? 2 : 0)) == 2 ? 8 :
				   (TCOMPRESS_SWIZZL  (format) ? 6 : 5)); }
	{ const int format = TCOMPRESS_RGBH; b = Join(fBase[0][ly][lx], br); }
	{ const int format = TCOMPRESS_XYZD; n = Join(fNorm[0][ly][lx], rn); }

//	CodeRGBH<TRGTMODE_CODING_RGB                                                           >(fBase[0][ly][lx], br);
#if	defined(NORMALS_INTEGER)
//	CodeXYZD<TRGTMODE_CODING_DXDYdZt | TRGTNORM_CUBESPACE, TCOMPRESS_SWIZZL(format) ? 6 : 5>(fNorm[0][ly][lx], nr);
#else
//	CodeXYZD<TRGTMODE_CODING_DXDYdZt | TRGTNORM_CUBESPACE, TCOMPRESS_SWIZZL(format) ? 6 : 5>(fNorm[0][ly][lx], rn);
#endif

//	b = JoinRGBH<TRGTMODE_CODING_RGB                         >(fBase[0][ly][lx], br);
#if	defined(NORMALS_INTEGER)
//	n = JoinXYZD<TRGTMODE_CODING_DXDYdZt | TRGTNORM_CUBESPACE>(fNorm[0][ly][lx], nr);
#else
//	n = JoinXYZD<TRGTMODE_CODING_DXDYdZt | TRGTNORM_CUBESPACE>(fNorm[0][ly][lx], rn);
#endif

	/* write the result ABGR */
	bBase[0][ly][lx] = b;
	bNorm[0][ly][lx] = n;
      }

      /* compress to DXT5 */
#if 0
      stb_compress_dxt_block((unsigned char *)dBase, (unsigned char *)bBase[0], true, STB_DXT_DITHER | STB_DXT_HIGHQUAL);
      stb_compress_dxt_block((unsigned char *)dNorm, (unsigned char *)bNorm[0], true, STB_DXT_NORMAL | STB_DXT_HIGHQUAL);
#else
      squish::Compress((unsigned char *)bBase[0], dBase, flags + squish::kColourMetricPerceptual);
      squish::Compress((unsigned char *)bNorm[0], dNorm, flags + squish::kColourMetricUniform);
#endif

      /* advance pointer of compressed blocks */
      dBase += (128 / 32);
      dNorm += (128 / 32);

#if 0
      for (int ly = 0; ly < TY; ly += 1)
      for (int lx = 0; lx < TX; lx += 1) {
	dBase[((y + ly) * bPch) + (x + lx)] = bBase[0][ly][lx];
	dNorm[((y + ly) * nPch) + (x + lx)] = bNorm[0][ly][lx];
      }
#endif
    }
    }

    TextureUnlock(baset, l);
    TextureUnlock(normt, l);
  }

  TextureUnlock((*base), 0);
  TextureUnlock((*norm), 0);

  (*base)->Release();
  (*norm)->Release();

  (*base) = baset;
  (*norm) = normt;

  return true;
}
コード例 #2
0
COffscreenGLThread::~COffscreenGLThread()
{
	if (thread)
		Join();
	delete thread; thread = NULL;
}
コード例 #3
0
ファイル: Thread.cpp プロジェクト: ace13/bootil
		Thread::~Thread()
		{
			Join();
		}
コード例 #4
0
ファイル: path.cpp プロジェクト: Adhdcrazzy/Torque3D
bool Path::appendPath( const Path &p )
{
   mPath = CompressPath(Join(mPath,'/',p.getPath()));
   mIsDirtyPath = true;
   return true;
}
コード例 #5
0
/**
 * Function Magnetize
 * tests to see if there are any magnetic items within near reach of the given
 * "curpos".  If yes, then curpos is adjusted appropriately according to that
 * near magnetic item and true is returned.
 * @param frame = the current frame
 * @param aCurrentTool = the current tool id (from vertical right toolbar)
 * @param aGridSize = the current grid size
 * @param on_grid = the on grid position near initial position ( often on_grid = curpos)
 * @param curpos The initial position, and what to adjust if a change is needed.
 * @return bool - true if the position was adjusted magnetically, else false.
 */
bool Magnetize( PCB_EDIT_FRAME* frame, int aCurrentTool, wxSize aGridSize,
                wxPoint on_grid, wxPoint* curpos )
{
    bool    doCheckNet = g_MagneticPadOption != capture_always && g_Drc_On;
    bool    doTrack = false;
    bool    doPad = false;
    bool    amMovingVia = false;

    BOARD* m_Pcb = frame->GetBoard();
    TRACK*      currTrack = g_CurrentTrackSegment;
    BOARD_ITEM* currItem  = frame->GetCurItem();
    PCB_SCREEN* screen = frame->GetScreen();
    wxPoint     pos = frame->RefPos( true );

    // D( printf( "currTrack=%p currItem=%p currTrack->Type()=%d currItem->Type()=%d\n",  currTrack, currItem, currTrack ? currTrack->Type() : 0, currItem ? currItem->Type() : 0 ); )

    if( !currTrack && currItem && currItem->Type()==PCB_VIA_T && currItem->GetFlags() )
    {
        // moving a VIA
        currTrack = (TRACK*) currItem;
        amMovingVia = true;

        return false;   // comment this return out and play with it.
    }
    else if( currItem != currTrack )
    {
        currTrack = NULL;
    }

    if( g_MagneticPadOption == capture_always )
        doPad = true;

    if( g_MagneticTrackOption == capture_always )
        doTrack = true;

    if( aCurrentTool == ID_TRACK_BUTT || amMovingVia )
    {
        int q = capture_cursor_in_track_tool;

        if( g_MagneticPadOption == q )
            doPad = true;

        if( g_MagneticTrackOption == q )
            doTrack = true;
    }

    // D(printf("doPad=%d doTrack=%d aCurrentTool=%d amMovingVia=%d\n", doPad, doTrack, aCurrentTool, amMovingVia );)

    //  The search precedence order is pads, then tracks/vias

    if( doPad )
    {
        LSET    layer_mask( screen->m_Active_Layer );
        D_PAD*  pad = m_Pcb->GetPad( pos, layer_mask );

        if( pad )
        {
            if( doCheckNet && currTrack && currTrack->GetNetCode() != pad->GetNetCode() )
                return false;

            *curpos = pad->GetPosition();
            return true;
        }
    }

    // after pads, only track & via tests remain, skip them if not desired
    if( doTrack )
    {
        LAYER_ID layer = screen->m_Active_Layer;

        for( TRACK* via = m_Pcb->m_Track;
                via && (via = via->GetVia( *curpos, layer )) != NULL;
                via = via->Next() )
        {
            if( via != currTrack )   // a via cannot influence itself
            {
                if( !doCheckNet || !currTrack || currTrack->GetNetCode() == via->GetNetCode() )
                {
                    *curpos = via->GetStart();
                    // D(printf("via hit\n");)
                    return true;
                }
            }
        }

        if( !currTrack )
        {
            LSET layers( layer );

            TRACK* track = m_Pcb->GetVisibleTrack( m_Pcb->m_Track, pos, layers );

            if( !track || track->Type() != PCB_TRACE_T )
            {
                // D(printf("!currTrack and track=%p not found, layer_mask=0x%X\n", track, layer_mask );)
                return false;
            }

            // D( printf( "Project\n" ); )
            return Project( curpos, on_grid, track );
        }

        /*
         * In two segment mode, ignore the final segment if it's inside a grid square.
         */
        if( !amMovingVia && currTrack && g_TwoSegmentTrackBuild && currTrack->Back()
            && currTrack->GetStart().x - aGridSize.x < currTrack->GetEnd().x
            && currTrack->GetStart().x + aGridSize.x > currTrack->GetEnd().x
            && currTrack->GetStart().y - aGridSize.y < currTrack->GetEnd().y
            && currTrack->GetStart().y + aGridSize.y > currTrack->GetEnd().y )
        {
            currTrack = currTrack->Back();
        }


        for( TRACK* track = m_Pcb->m_Track; track; track = track->Next() )
        {
            if( track->Type() != PCB_TRACE_T )
                continue;

            if( doCheckNet && currTrack && currTrack->GetNetCode() != track->GetNetCode() )
                continue;

            if( m_Pcb->IsLayerVisible( track->GetLayer() ) == false )
                continue;

            // omit the layer check if moving a via
            if( !amMovingVia && !track->IsOnLayer( layer ) )
                continue;

            if( !track->HitTest( *curpos ) )
                continue;

            // D(printf( "have track prospect\n");)

            if( Join( curpos, track->GetStart(), track->GetEnd(), currTrack->GetStart(), currTrack->GetEnd() ) )
            {
                // D(printf( "join currTrack->Type()=%d\n", currTrack->Type() );)
                return true;
            }

            if( aCurrentTool == ID_TRACK_BUTT || amMovingVia )
            {
                // At this point we have a drawing mouse on a track, we are drawing
                // a new track and that new track is parallel to the track the
                // mouse is on. Find the nearest end point of the track under mouse
                // to the mouse and return that.
                double distStart = GetLineLength( *curpos, track->GetStart() );
                double distEnd   = GetLineLength( *curpos, track->GetEnd() );

                // if track not via, or if its a via dragging but not with its adjacent track
                if( currTrack->Type() != PCB_VIA_T ||
                    ( currTrack->GetStart() != track->GetStart() && currTrack->GetStart() != track->GetEnd() ))
                {
                    double max_dist = currTrack->GetWidth() / 2.0f;

                    if( distStart <= max_dist )
                    {
                        // D(printf("nearest end is start\n");)
                        *curpos = track->GetStart();
                        return true;
                    }

                    if( distEnd <= max_dist )
                    {
                        // D(printf("nearest end is end\n");)
                        *curpos = track->GetEnd();
                        return true;
                    }

                    // @todo otherwise confine curpos such that it stays centered within "track"
                }
            }
        }
    }

    return false;
}
コード例 #6
0
ファイル: Navigator.cpp プロジェクト: AbdelghaniDr/mirror
void Navigator::Search()
{
	sortitems.Check(sorting);
	int sc = scope.GetScroll();
	String key = scope.GetKey();
	String s = TrimBoth(~search);
	String search_name, search_nest;
	bool wholeclass = false;
	bool both = false;
	navigator_global = false;
	if(s.Find('.') >= 0) {
		Vector<String> h = Split((String)~search, '.');
		if(*s.Last() == '.')
			search_nest = Join(h, "::");
		else {
			search_name = h.Pop();
			if(h.GetCount())
				search_nest = Join(h, "::");
		}
		wholeclass = *s == '.' && search_nest.GetCount();
	}
	else {
		search_name = search_nest = ~search;
		both = true;
	}
	s = Join(Split(s, '.'), "::") + (s.EndsWith(".") ? "::" : "");
	int lineno = StrInt(s);
	gitem.Clear();
	nitem.Clear();
	if(IsNull(theide->editfile))
		return;
	int fileii = GetSourceFileIndex(theide->editfile);
	if(!IsNull(lineno)) {
		NavItem& m = nitem.Add();
		m.type = "Go to line " + AsString(lineno);
		m.kind = KIND_LINE;
		m.line = lineno;
		gitem.Add(Null).Add(&m);
	}
	else
	if(IsNull(s) && !sorting) {
		const CppBase& b = CodeBase();
		for(int i = 0; i < b.GetCount(); i++) {
			String nest = b.GetKey(i);
			const Array<CppItem>& ci = b[i];
			for(int j = 0; j < ci.GetCount(); j++) {
				const CppItem& m = ci[j];
				if(m.file == fileii) {
					NavItem& n = nitem.Add();
					n.Set(m);
					n.nest = nest;
					n.decl_line = m.line;
					n.decl_file = m.file;
					n.decl = !m.impl;
					NavLine& l = n.linefo.Add();
					l.impl = m.impl;
					l.file = m.file;
					l.line = m.line;
				}
			}
		}
		Sort(nitem, FieldRelation(&NavItem::line, StdLess<int>()));
		NavGroup(true);
	}
	else {
		navigator_global = true;
		const CppBase& b = CodeBase();
		String usearch_nest = ToUpper(search_nest);
		String usearch_name = ToUpper(search_name);
		ArrayMap<String, NavItem> imap;
		bool local = sorting && IsNull(s);
		VectorMap<String, int> nest_pass;
		for(int pass = -1; pass < 2; pass++) {
			for(int i = 0; i < b.GetCount(); i++) {
				String nest = b.GetKey(i);
				bool foundnest = (wholeclass ? pass < 0 ? false :
				                               pass ? ToUpper(nest) == usearch_nest
				                                    : nest == search_nest
				                             : pass < 0 ? nest == search_nest :
				                               (pass ? ToUpper(nest).Find(usearch_nest) >= 0
				                                     : nest.StartsWith(search_nest)))
				                 && nest.Find('@') < 0;
				if(local || foundnest || both) {
					const Array<CppItem>& ci = b[i];
					for(int j = 0; j < ci.GetCount(); j++) {
						const CppItem& m = ci[j];
						if(local ? m.file == fileii
						         : m.uname.Find('@') < 0 && (pass < 0 ? m.name == search_name :
						                               pass ? m.uname.Find(usearch_name) >= 0
						                                    : m.name.StartsWith(search_name))
						           || both && foundnest) {
							String key = nest + '\1' + m.qitem;
							int q = nest_pass.Find(nest);
							int p = pass;
							if(q < 0) // We do not want classes to be split based on pass
								nest_pass.Add(nest, pass);
							else
								p = nest_pass[q];
							q = imap.Find(key);
							if(q < 0) {
								NavItem& ni = imap.Add(key);
								ni.Set(m);
								ni.nest = nest;
								ni.decl_line = ni.line;
								ni.decl_file = ni.file;
								ni.decl = !ni.impl;
								ni.pass = p;
								NavLine& l = ni.linefo.Add();
								l.impl = m.impl;
								l.file = m.file;
								l.line = m.line;
							}
							else {
								NavItem& mm = imap[q];
								if(!m.impl &&
								  (!mm.decl
								    || CombineCompare(mm.decl_file, m.file)(mm.decl_line, m.line) < 0)) {
										mm.decl = true;
										mm.decl_line = m.line;
										mm.decl_file = m.file;
										mm.natural = m.natural;
								}
								NavLine& l = mm.linefo.Add();
								l.impl = m.impl;
								l.file = m.file;
								l.line = m.line;
							}
						}
					}
				}
			}
		}
		nitem = imap.PickValues();
		NavGroup(false);
		SortByKey(gitem);
		Vector<String> keys = gitem.PickKeys();
		Vector<Vector<NavItem *> > values = gitem.PickValues();
		IndexSort(keys, values);
		for(int i = 0; i < keys.GetCount(); i++)
			keys[i].Remove(0);
		VectorMap<String, Vector<NavItem *> > h(pick(keys), pick(values));
		gitem = pick(h);
		for(int i = 0; i < gitem.GetCount(); i++)
			Sort(gitem[i], sorting ? SortByNames : SortByLines);
	}
	scope.Clear();
	scope.Add(Null);
	Index<String> done;
	for(int i = 0; i < gitem.GetCount(); i++) {
		String s = gitem.GetKey(i);
		if(done.Find(s) < 0) {
			done.Add(s);
			scope.Add(s);
		}
	}
	scope.ScrollTo(sc);
	if(!navigator_global || !scope.FindSetCursor(key))
		scope.GoBegin();
}
コード例 #7
0
 LabelRange &Join(LabelRange LR) {
   return *this = Join(*this, LR);
 }
コード例 #8
0
ファイル: string.hpp プロジェクト: ShauryaRawat/thrill
static inline
std::string Join(const Glue& glue, const Container& parts) {
    return Join(glue, parts.begin(), parts.end());
}
コード例 #9
0
ファイル: EbookController.cpp プロジェクト: Jshauk/sumatrapdf
 virtual void Execute() {
     // let OpenMobiInWindow handle the failure case as well
     OpenMobiInWindow(doc, win);
     // the thread should already have terminated by now
     Join();
 }
コード例 #10
0
ファイル: CppBuilder.cpp プロジェクト: ultimatepp/mirror
Vector<String> CppBuilder::CustomStep(const String& pf, const String& package_, bool& error)
{
	String package = Nvl(package_, mainpackage);
	String path = (*pf == '.' && pf[1] != '.') ? target : SourcePath(package, pf);
	String file = GetHostPath(path);
	String ext = ToLower(GetFileExt(pf));
	if(ext == ".ext") {
		Vector<String> files;
		Vector<String> dirs;
		sGatherAllExt(files, dirs, GetFileFolder(path), "");
		
		Index<String> pkg_files;
		Package pkg;
		pkg.Load(PackagePath(package));
		for(int i = 0; i < pkg.GetCount(); i++)
			pkg_files.Add(pkg[i]);
		
		Index<String> out;
		Index<String> include_path;
		String f = LoadFile(path);
		try {
			CParser p(f);
			while(!p.IsEof()) {
				if(p.Id("files")) {
					Vector<String> e = ReadPatterns(p);
					for(int i = 0; i < files.GetCount(); i++)
						for(int j = 0; j < e.GetCount(); j++) {
							String f = files[i];
							if(PatternMatch(e[j], f) && pkg_files.Find(f) < 0)
								out.FindAdd(f);
						}
				}
				if(p.Id("exclude")) {
					ExtExclude(p, out);
				}
				if(p.Id("include_path")) {
					Vector<String> e = ReadPatterns(p);
					for(int j = 0; j < e.GetCount(); j++) {
						String ee = e[j];
						if(ee.Find('*') >= 0)
							for(int i = 0; i < dirs.GetCount(); i++) {
								String d = dirs[i];
								if(PatternMatch(e[j], d)) {
									include_path.FindAdd(d);
								}
							}
						else
							include_path.Add(ee);
					}
				}
				if(p.Id("exclude_path")) {
					ExtExclude(p, include_path);
				}
				if(p.Id("includes")) {
					Vector<String> e = ReadPatterns(p);
					for(int i = 0; i < files.GetCount(); i++)
						for(int j = 0; j < e.GetCount(); j++) {
							String f = files[i];
							if(PatternMatch(e[j], f) && pkg_files.Find(f) < 0)
								include_path.FindAdd(GetFileFolder(f));
						}
				}
			}
		}
		catch(CParser::Error) {
			PutConsole("Invalid .ext file");
			error = true;
			return Vector<String>();
		}
		
		for(int i = 0; i < include_path.GetCount(); i++)
			include.Add(NormalizePath(include_path[i], GetFileFolder(path)));
		
		Vector<String> o;
		for(int i = 0; i < out.GetCount(); i++)
			o.Add(SourcePath(package, out[i]));
		return o;
	}
	for(int i = 0; i < wspc.GetCount(); i++) {
		const Array< ::CustomStep >& mv = wspc.GetPackage(i).custom;
		for(int j = 0; j < mv.GetCount(); j++) {
			const ::CustomStep& m = mv[j];
			if(MatchWhen(m.when, config.GetKeys()) && m.MatchExt(ext)) {
				VectorMap<String, String> mac;
				AddPath(mac, "PATH", file);
				AddPath(mac, "RELPATH", pf);
				AddPath(mac, "DIR", GetFileFolder(PackagePath(package)));
				AddPath(mac, "FILEDIR", GetFileFolder(file));
				AddPath(mac, "PACKAGE", package);
				mac.Add("FILE", GetFileName(file));
				mac.Add("TITLE", GetFileTitle(file));
				AddPath(mac, "EXEPATH", GetHostPath(target));
				AddPath(mac, "EXEDIR", GetHostPath(GetFileFolder(target)));
				mac.Add("EXEFILE", GetFileName(target));
				mac.Add("EXETITLE", GetFileTitle(target));
				AddPath(mac, "OUTDIR", GetHostPath(outdir));
				//BW
				AddPath(mac, "OUTDIR", GetHostPath(GetFileFolder(target)));
				AddPath(mac, "OUTFILE", GetHostPath(GetFileName(target)));
				AddPath(mac, "OUTTITLE", GetHostPath(GetFileTitle(target)));

				mac.Add("INCLUDE", Join(include, ";"));

				Vector<String> out = Cuprep(m.output, mac, include);
				bool dirty = out.IsEmpty();
				for(int i = 0; !dirty && i < out.GetCount(); i++)
					dirty = (GetFileTime(file) > GetFileTime(out[i]));
				if(dirty) {
					HdependTimeDirty();
					PutConsole(GetFileName(file));
					Vector<String> cmd = Cuprep(m.command, mac, include);
					String cmdtext;
					for(int c = 0; c < cmd.GetCount(); c++) {
						PutVerbose(cmd[c]);
						if(!Cd(cmd[c]) && !Cp(cmd[c], package, error)) {
							String ctext = cmd[c];
							const char *cm = ctext;
							if(*cm == '?')
								cm++;
							if(*ctext != '?' && Execute(cm)) {
								for(int t = 0; t < out.GetCount(); t++)
									DeleteFile(out[t]);
								PutConsole("FAILED: " + ctext);
								error = true;
								return Vector<String>();
							}
						}
					}
				}
				return out;
			}
		}
	}
	Vector<String> out;
	out.Add(path);
	return out;
}
コード例 #11
0
ファイル: Directory.cpp プロジェクト: marcomagdy/aws-sdk-cpp
 Aws::String Join(const Aws::String& leftSegment, const Aws::String& rightSegment)
 {
     return Join(PATH_DELIM, leftSegment, rightSegment);
 }
コード例 #12
0
ファイル: thread.cpp プロジェクト: Frankie-666/tomita-parser
TThread::~TThread() throw () {
    Join();
}
コード例 #13
0
ファイル: MakeFile.cpp プロジェクト: guowei8412/upp-mirror
void CppBuilder::AddMakeFile(MakeFile& makefile, String package,
	const Vector<String>& all_uses, const Vector<String>& all_libraries,
	const Index<String>& common_config, bool exporting)
{
	String packagepath = PackagePath(package);
	Package pkg;
	pkg.Load(packagepath);
	String packagedir = GetFileFolder(packagepath);
	Vector<String> src = GetUppDirs();
	for(int i = 0; i < src.GetCount(); i++)
		src[i] = UnixPath(src[i]);

	bool main = HasFlag("MAIN");
	bool is_shared = HasFlag("SO");
	bool libout = !main && !HasFlag("NOLIB");
	bool win32 = HasFlag("WIN32");

	String pack_ident = MakeIdent(package);
	String outdir = "OutDir_" + pack_ident;
	String macros = "Macro_" + pack_ident;
	String macdef = "$(Macro)";
	String objext = (HasFlag("MSC") || HasFlag("EVC") ? ".obj" : ".o");

	Vector<String> x(config.GetKeys(), 1);
	Sort(x);
	for(int i = 0; i < x.GetCount(); i++) {
		if(common_config.Find(x[i]) < 0)
			macdef << " -Dflag" << x[i];
		x[i] = InitCaps(x[i]);
	}

	makefile.outdir << "$(" << outdir << ")";
	makefile.outfile << AdjustMakePath(GetFileTitle(NativePath(package)));
	if(main)
		makefile.outfile << GetTargetExt();
	else if(is_shared)
		makefile.outfile << (win32 ? ".dll" : ".so");
	else
		makefile.outfile << (win32 && HasFlag("MSC") ? ".lib" : ".a");
	makefile.output << (main ? String("$(OutDir)") : makefile.outdir) << makefile.outfile;

	if(main) {
		makefile.config << "CXX = c++\n"
			"LINKER = $(CXX)\n";
		String flags;
		if(HasFlag("DEBUG"))
			flags << " -D_DEBUG " << debug_options;
		else
			flags << ' ' << release_options;
		if(HasFlag("DEBUG_MINIMAL"))
			flags << " -ggdb -g1";
		if(HasFlag("DEBUG_FULL"))
			flags << " -ggdb -g2";
		if(is_shared && !win32)
			flags << " -fPIC ";
		flags << ' ' << Gather(pkg.option, config.GetKeys());
		makefile.config << "CFLAGS =" << flags << "\n"
			"CXXFLAGS =" << flags << "\n"
			"LDFLAGS = " << (HasFlag("DEBUG") ? debug_link : release_link) << " $(LINKOPTIONS)\n"
			"LIBPATH =";
		for(int i = 0; i < libpath.GetCount(); i++)
			makefile.config << " -L" << GetMakePath(AdjustMakePath(GetHostPathQ(libpath[i])));
		makefile.config << "\n"
			"AR = ar -sr\n\n";
		makefile.install << "\t-mkdir -p $(OutDir)\n";
		Vector<String> lib;
		String lnk;
		lnk << "$(LINKER)";
		if(!HasFlag("SHARED"))
			lnk << " -static";
		if(HasFlag("WIN32")) {
			lnk << " -mwindows";
			if(!HasFlag("GUI"))
				makefile.linkfiles << " -mconsole";
		}
		lnk << " -o $(OutFile)";
		if(HasFlag("DEBUG") || HasFlag("DEBUG_MINIMAL") || HasFlag("DEBUG_FULL"))
			lnk << " -ggdb";
		else
			lnk << (!HasFlag("OSX11") ? " -Wl,-s" : "");

		lnk << " $(LIBPATH)";
		if (!HasFlag("OSX11"))
			lnk << " -Wl,-O,2";
		lnk << " $(LDFLAGS) -Wl,--start-group ";

		makefile.linkfiles = lnk;
	}

	makefile.config << outdir << " = $(UPPOUT)"
		<< GetMakePath(AdjustMakePath(String().Cat() << package << '/' << method << '-' << Join(x, "-") << '/')) << "\n"
		<< macros << " = " << macdef << "\n";

	makefile.install << "\t-mkdir -p $(" << outdir << ")\n";

	String libdep, libfiles;

	libdep << makefile.output << ":";
	if(is_shared)
	{
		libfiles = "c++ -shared -fPIC"; // -v";
		Point p = ExtractVersion();
		if(!IsNull(p.x)) {
			libfiles << " -Xlinker --major-image-version -Xlinker " << p.x;
			if(!IsNull(p.y))
				libfiles << " -Xlinker --minor-image-version -Xlinker " << p.y;
		}
		libfiles << " -o ";
	}
	else
		libfiles = "$(AR) ";
	libfiles << makefile.output;

	Vector<String> libs = Split(Gather(pkg.library, config.GetKeys()), ' ');
	for(int i = 0; i < libs.GetCount(); i++) {
		String ln = libs[i];
		String ext = ToLower(GetFileExt(ln));
		if(ext == ".a" || ext == ".so" || ext == ".dll")
			makefile.linkfileend << " \\\n\t\t\t" << GetHostPathQ(FindInDirs(libpath, ln));
		else
			makefile.linkfileend << " \\\n\t\t\t-l" << ln;
	}
	
	for(int i = 0; i < pkg.GetCount(); i++)
		if(!pkg[i].separator) {
			String gop = Gather(pkg[i].option, config.GetKeys());
			String fn = SourcePath(package, pkg[i]);
			String ext = ToLower(GetFileExt(fn));
			bool isc = ext == ".c";
			bool isrc = (ext == ".rc" && HasFlag("WIN32"));
			bool iscpp = (ext == ".cpp" || ext == ".cc" || ext == ".cxx");
			bool isicpp = (ext == ".icpp");
			if(ext == ".brc") {
				isc = true;
				fn << "c";
			}
			if(isc || isrc || iscpp || isicpp) {
				String outfile;
				outfile << makefile.outdir << AdjustMakePath(GetFileTitle(fn)) << (isrc ? "_rc" : "") << objext;
				String srcfile = GetMakePath(MakeSourcePath(src, fn, false, exporting));
				makefile.rules << outfile << ": " << srcfile;
				Vector<String> dep = HdependGetDependencies(fn);
				Sort(dep, GetLanguageInfo());
				for(int d = 0; d < dep.GetCount(); d++) {
					String dfn = MakeSourcePath(src, dep[d], true, exporting);
					if(!IsNull(dfn))
						makefile.rules << " \\\n\t" << GetMakePath(dfn);
				}
				makefile.rules << "\n"
					"\t$(CXX) -c " << (isc ? "-x c $(CFLAGS)" : "-x c++ $(CXXFLAGS)") << " $(CINC) $(" << macros << ") "
						<< gop << " " << srcfile << " -o " << outfile << "\n\n";
				if(!libout || isicpp) {
					makefile.linkdep << " \\\n\t" << outfile;
					makefile.linkfiles << " \\\n\t\t" << outfile;
				}
				else {
					libdep << " \\\n\t" << outfile;
					libfiles << " \\\n\t\t" << outfile;
				}
			}
			else
			if(ext == ".o" || ext == ".obj" || ext == ".a" || ext == ".so" || ext == ".lib" || ext == ".dll") {
				makefile.linkdep << " \\\n\t" << fn;
				makefile.linkfiles << ' ' << fn;
			}
		}

	if(libout) {
		makefile.rules << libdep << "\n\t" << libfiles << "\n\n";
		makefile.linkdep << " \\\n\t" << makefile.output;
		makefile.linkfiles << " \\\n\t\t\t" << makefile.output;
	}
/*
	if(main) {
		if(!HasFlag("SOLARIS")&&!HasFlag("OSX11"))
			makefile.linkfiles << " \\\n\t\t-Wl,--start-group ";
		DDUMPC(all_libraries);
		for(int i = 0; i < all_libraries.GetCount(); i++) {
			String ln = all_libraries[i];
			String ext = ToLower(GetFileExt(ln));
			if(ext == ".a" || ext == ".so" || ext == ".dll")
				makefile.linkfileend << " \\\n\t\t\t" << GetHostPathQ(FindInDirs(libpath, ln));
			else
				makefile.linkfileend << " \\\n\t\t\t-l" << ln;
		}
		if(!HasFlag("SOLARIS")&&!HasFlag("OSX11"))
			makefile.linkfileend << " \\\n\t\t-Wl,--end-group\n\n";
	}
*/
}
コード例 #14
0
//++ ------------------------------------------------------------------------------------
// Details: CMIUtilThread destructor.
// Type:    Method.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMIUtilThread::~CMIUtilThread()
{
    Join();
}
コード例 #15
0
ファイル: threadno.cpp プロジェクト: Bluehorn/wxPython
// The default callback just joins the thread and throws away the result.
void wxThread::OnExit()
{
    Join();
}
コード例 #16
0
ファイル: Thread.cpp プロジェクト: jimmeny/mUI
void Thread::Join()
{
	Join(INFINITE);
}
コード例 #17
0
ファイル: Build.cpp プロジェクト: dreamsxin/ultimatepp
bool MakeBuild::BuildPackage(const Workspace& wspc, int pkindex, int pknumber, int pkcount,
	String mainparam, String outfile, Vector<String>& linkfile, String& linkopt, bool link)
{
	String package = wspc[pkindex];
	String mainpackage = wspc[0];
	const Package& pkg = wspc.package[pkindex];
	VectorMap<String, String> bm = GetMethodVars(method);
	if(bm.GetCount() == 0) {
		PutConsole("Invalid build method");
		ConsoleShow();
		return false;
	}
	One<Host> host = CreateHost(false);
	if(!IsNull(onefile)) {
		OneFileHost *h = new OneFileHost;
		h->host = host;
		h->onefile = onefile;
		host = h;
	}
	One<Builder> b = CreateBuilder(~host);
	if(!b)
		return false;
	b->config = PackageConfig(wspc, pkindex, bm, mainparam, *host, *b);
	const TargetMode& m = targetmode == 0 ? debug : release;
	b->version = m.version;
	b->method = method;
	b->outdir = OutDir(b->config, package, bm);
	host->RealizeDir(b->outdir);
	String mainfn = Null;
	Index<String> mcfg = PackageConfig(wspc, 0, bm, mainparam, *host, *b, &mainfn);
	HdependClearDependencies();
	for(int i = 0; i < pkg.GetCount(); i++) {
		const Array<OptItem>& f = pkg[i].depends;
		for(int j = 0; j < f.GetCount(); j++)
			if(MatchWhen(f[j].when, mcfg.GetKeys()))
				HdependAddDependency(SourcePath(package, pkg[i]), SourcePath(package, f[j].text));
	}
	String tout = OutDir(mcfg, mainpackage, bm, use_target);
	host->RealizeDir(tout);
	if(IsNull(mainfn))
		mainfn = GetFileTitle(mainpackage) + b->GetTargetExt();
	if(!IsNull(outfile))
		target = NormalizePath(outfile, tout);
	else {
		if(m.target_override && !IsNull(m.target) && IsFolder(m.target))
			target = host->NormalizePath(AppendFileName(m.target, mainfn));
		else
		if(m.target_override && (IsFullPath(m.target) || *m.target == '/' || *m.target == '\\'))
			target = m.target;
		else
		if(m.target_override && !IsNull(m.target))
			target = host->NormalizePath(AppendFileName(tout, m.target));
		else
		if(IsFullPath(mainfn))
			target = mainfn;
		else
			target = host->NormalizePath(AppendFileName(tout, mainfn));
	}
	b->target = target;
	b->mainpackage = mainpackage;
	if(IsNull(onefile)) {
		String out;
		out << "----- " << package << " ( " << Join(b->config.GetKeys(), " ") << " )";
		if(pkcount > 1)
			out << " (" << (pknumber + 1) << " / " << pkcount << ')';
		PutConsole(out);
	}
	else
		b->config.FindAdd("NOLIB");
	bool ok = b->BuildPackage(package, linkfile, linkopt,
		                      GetAllUses(wspc, pkindex),
		                      GetAllLibraries(wspc, pkindex, bm, mainparam, *host, *b),
		                      targetmode - 1);
	Vector<String> errors = PickErrors();
	host->DeleteFile(errors);
	if(!ok || !errors.IsEmpty())
		return false;
	if(link) {
		ok = b->Link(linkfile, linkopt, GetTargetMode().createmap);
		errors = PickErrors();
		host->DeleteFile(errors);
		if(!ok || !errors.IsEmpty())
			return false;
	}
	return true;
}
コード例 #18
0
ファイル: fsm.cpp プロジェクト: Frankie-666/tomita-parser
void Fsm::DumpState(yostream& s, size_t state) const
{
	s << "    ";

	// Fill in a 'row': Q -> exp(V) (for current state)
	yvector< ybitset<MaxChar> > row(Size());
	for (TransitionRow::const_iterator rit = m_transitions[state].begin(), rie = m_transitions[state].end(); rit != rie; ++rit)
		for (StatesSet::const_iterator sit = rit->second.begin(), sie = rit->second.end(); sit != sie; ++sit) {
			if (*sit >= Size()) {
				std::cerr << "WTF?! Transition from " << state << " on letter " << rit->first << " leads to non-existing state " << *sit << "\n";
				YASSERT(false);
			}
			if (Letters().Contains(rit->first)) {
				const yvector<Char>& letters = Letters().Klass(Letters().Representative(rit->first));
				for (yvector<Char>::const_iterator lit = letters.begin(), lie = letters.end(); lit != lie; ++lit)
					row[*sit].set(*lit);
			} else
				row[*sit].set(rit->first);
		}

	// Display each destination state
	for (yvector< ybitset<MaxChar> >::iterator rit = row.begin(), rie = row.end(); rit != rie; ++rit) {
		unsigned begin = 0, end = 0;

		bool empty = true;
		if (rit->test(Epsilon)) {
			s << "<Epsilon> ";
			empty = false;
		}
		if (rit->test(BeginMark)) {
			s << "<Begin> ";
			empty = false;
		}
		if (rit->test(EndMark)) {
			s << "<End> ";
			empty = false;
		}
		while (begin < 256) {
			for (begin = end; begin < 256 && !rit->test(begin); ++begin)
				;
			for (end = begin; end < 256 && rit->test(end); ++end)
				;
			if (begin + 1 == end) {
				s << CharDump(begin);
				empty = false;
			} else if (begin != end) {
				s << CharDump(begin) << ".." << (CharDump(end-1));
				empty = false;
			}
			if (!empty)
				s << " ";
		}
		if (!empty) {
			s << " => " << std::distance(row.begin(), rit);

			// Display outputs
			Outputs::const_iterator oit = outputs.find(state);
			if (oit != outputs.end()) {
				Outputs::value_type::second_type::const_iterator oit2 = oit->second.find(std::distance(row.begin(), rit));
				if (oit2 == oit->second.end())
					;
				else {
					yvector<int> payload;
					for (unsigned i = 0; i < sizeof(oit2->second) * 8; ++i)
						if (oit2->second & (1ul << i))
							payload.push_back(i);
					if (!payload.empty())
						s << "[" << Join(payload.begin(), payload.end(), ", ") << "]";
				}
			}
			s << "\n    ";
		}
	}
	if (Initial() == state)
		s << "[initial] ";
	if (IsFinal(state))
		s << "[final] ";
	Tags::const_iterator ti = tags.find(state);
	if (ti != tags.end())
		s << "[tags: " << ti->second << "] ";
	s << "\n";
}
コード例 #19
0
ファイル: t1outline.c プロジェクト: BackupTheBerlios/texlive
/* T1_GetMoveOutline(...): Generate the "outline" for a movement
                           */
T1_OUTLINE *T1_GetMoveOutline( int FontID, int deltax, int deltay, int modflag,
			       float size, T1_TMATRIX *transform)
{
  int i;
  FONTSIZEDEPS *font_ptr;
  struct segment *path, *tmppath;
  struct XYspace *Current_S;
  psfont *FontP;
  float length;
  

  /* We return to this if something goes wrong deep in the rasterizer */
  if ((i=setjmp( stck_state))!=0) {
    T1_errno=T1ERR_TYPE1_ABORT;
    sprintf( err_warn_msg_buf, "t1_abort: Reason: %s",
	     t1_get_abort_message( i));
    T1_PrintLog( "T1_GetMoveOutline()", err_warn_msg_buf,
	       T1LOG_ERROR);
    return( NULL);
  }


  /* First, check for a correct ID */
  i=CheckForFontID(FontID);
  if (i==-1){
    T1_errno=T1ERR_INVALID_FONTID;
    return(NULL);
  }
  /* if necessary load font into memory */
  if (i==0)
    if (T1_LoadFont(FontID))
      return(NULL);

  /* Check for valid size */
  if (size<=0.0){
    T1_errno=T1ERR_INVALID_PARAMETER;
    return(NULL);
  }

  FontP=pFontBase->pFontArray[i].pType1Data;
  
  /* font is now loaded into memory =>
     Check for size: */
  if ((font_ptr=QueryFontSize( FontID, size, NO_ANTIALIAS))==NULL){
    font_ptr=CreateNewFontSize( FontID, size, NO_ANTIALIAS);
    if (font_ptr==NULL){
      T1_errno=T1ERR_ALLOC_MEM;
      return(NULL);
    }
  }

  /* Setup an appropriate charspace matrix. Note that the rasterizer
     assumes vertical values with inverted sign! Transformation should
     create a copy of the local charspace matrix which then still has
     to be made permanent. */
  if (transform!=NULL){
    Current_S=(struct XYspace *) 
      Permanent(Scale(Transform (font_ptr->pCharSpaceLocal,
				 transform->cxx, - transform->cxy,
				 transform->cyx, - transform->cyy),
		      DeviceSpecifics.scale_x, DeviceSpecifics.scale_y));
  }
  else{
    Current_S=(struct XYspace *)
      Permanent(Scale(Transform(font_ptr->pCharSpaceLocal,
				1.0, 0.0, 0.0, -1.0),
		      DeviceSpecifics.scale_x, DeviceSpecifics.scale_y));
  }
  
  
  path=(struct segment *)ILoc( Current_S, deltax, deltay); 

  /* Take care for underlining and such */
  length=(float) deltax;
  if (modflag & T1_UNDERLINE){
    tmppath=(struct segment *)Type1Line(FontP,Current_S,
					pFontBase->pFontArray[FontID].UndrLnPos,
					pFontBase->pFontArray[FontID].UndrLnThick,
					length);
    path=(struct segment *)Join(path,tmppath);
  }
  if (modflag & T1_OVERLINE){
    tmppath=(struct segment *)Type1Line(FontP,Current_S,
					pFontBase->pFontArray[FontID].OvrLnPos,
					pFontBase->pFontArray[FontID].OvrLnThick,
					length);
    path=(struct segment *)Join(path,tmppath);
  }
  if (modflag & T1_OVERSTRIKE){
    tmppath=(struct segment *)Type1Line(FontP,Current_S,
					pFontBase->pFontArray[FontID].OvrStrkPos,
					pFontBase->pFontArray[FontID].OvrStrkThick,
					length);
    path=(struct segment *)Join(path,tmppath);
  }
      
  KillSpace( Current_S);
  
  return( (T1_OUTLINE *)path);
  
}
コード例 #20
0
ファイル: queue.c プロジェクト: irfanhudda/nachos-assign3
int
main()
{
    array = (int*)ShmAllocate(sizeof(int)*(SIZE+3));  // queue[SIZE], head, tail, count
    int x, i, j, seminit = 1, y;
    int pid[NUM_DEQUEUER+NUM_ENQUEUER];

    for (i=0; i<SIZE; i++) array[i] = -1;
    array[SIZE] = 0;
    array[SIZE+1] = 0;
    array[SIZE+2] = 0;

    semid = SemGet(SEM_KEY1);
    SemCtl(semid, SYNCH_SET, &seminit);

    stdoutsemid = SemGet(SEM_KEY2);
    SemCtl(stdoutsemid, SYNCH_SET, &seminit);

    notFullid = CondGet(COND_KEY1);
    notEmptyid = CondGet(COND_KEY2);

    int temp;
    temp = -11;
    SemCtl(semid,SYNCH_GET,&temp);
    PrintInt(temp);
    for (i=0; i<NUM_DEQUEUER; i++) {
       x = Fork();
       if (x == 0) {
          for (j=0; j<NUM_DEQUEUE_OP; j++) {
             x = Dequeue (i, &y);
             SemOp(stdoutsemid, -1);
             PrintString("Dequeuer ");
             PrintInt(i);
             PrintString(": Got ");
             PrintInt(x);
             PrintString(" from slot ");
             PrintInt(y);
             PrintChar('\n');
             SemOp(stdoutsemid, 1);
          }
          Exit(DEQUEUE_EXIT_CODE);
       }
       pid[i] = x;
    }
    
    for (i=0; i<NUM_ENQUEUER; i++) {
       x = Fork();
       if (x == 0) {
          x = i*NUM_ENQUEUE_OP;
          for (j=0; j<NUM_ENQUEUE_OP; j++) {
             y = Enqueue (x+j, i);
             SemOp(stdoutsemid, -1);
             PrintString("Enqueuer ");
             PrintInt(i);
             PrintString(": Inserted ");
             PrintInt(x+j);
             PrintString(" in slot ");
             PrintInt(y);
             PrintChar('\n');
             SemOp(stdoutsemid, 1);
          }
          Exit(ENQUEUE_EXIT_CODE);
       }
       pid[i+NUM_DEQUEUER] = x;
    }

    for (i=0; i<NUM_DEQUEUER+NUM_ENQUEUER; i++) {
       x = Join(pid[i]);
       SemOp(stdoutsemid, -1);
       PrintString("Parent joined with ");
       PrintInt(pid[i]);
       PrintString(" having exit code ");
       PrintInt(x);
       PrintChar('\n');
       SemOp(stdoutsemid, 1);
    }
    SemCtl(semid, SYNCH_REMOVE, 0);
    SemCtl(stdoutsemid, SYNCH_REMOVE, 0);
    CondRemove(notFullid);
    CondRemove(notEmptyid);

    return 0;
}
コード例 #21
0
ファイル: forkjoin_hard.c プロジェクト: arikj/NACHOS
int
main()
{
    int x, y=6;

    PrintString("Parent PID: ");
    PrintInt(GetPID());
    PrintChar('\n');
    x = Fork();
    if (x == 0) {
       PrintString("Child PID: ");
       PrintInt(GetPID());
       PrintChar('\n');
       PrintString("Child's parent PID: ");
       PrintInt(GetPPID());
       PrintChar('\n');
       PrintString("Child calling sleep at time: ");
       PrintInt(GetTime());
       PrintChar('\n');
       Sleep(100);
       PrintString("Child returned from sleep at time: ");
       PrintInt(GetTime());
       PrintChar('\n');
       y++;
       PrintString("Child y=");
       PrintInt(y);
       PrintChar('\n');
       x = Fork();
       //Exec("../test/printtest");
       if (x == 0) {
          PrintString("Child PID: ");
          PrintInt(GetPID());
          PrintChar('\n');
          y++;
          PrintString("Child2 y=");
          PrintInt(y);
          PrintChar('\n');
          Exit(20);
       }
       else {
          PrintString("Parent after fork waiting for child: ");
          PrintInt(x);
          PrintChar('\n');
          PrintString("Parent2 join value: ");
          PrintInt(Join(x));
          PrintChar('\n');
          PrintString("Parent2 y=");
          PrintInt(y);
          PrintChar('\n');
          Exit(10);
       }
    }
    else {
       PrintString("Parent after fork waiting for child: ");
       PrintInt(x);
       PrintChar('\n');
       PrintString("Parent2 join value: ");
       PrintInt(Join(x));
       PrintChar('\n');
       PrintString("Parent y=");
       PrintInt(y);
       PrintChar('\n');
       Exit(1);
    }
    return 0;
}
コード例 #22
0
ファイル: shell.c プロジェクト: weiyuhan/nachos
int
main()
{
    SpaceId newProc;
    OpenFileId input = ConsoleInput;
    OpenFileId output = ConsoleOutput;
    char prompt[2], ch, buffer[60], cmd[20], arg[40];
    char* quit, ls, exec, path, echo, mkdir, rm, create, open, cd, close, read, write; 
    int bufferSize, bufferIndex, cmdIndex, argIndex;
    OpenFileId fd;


    prompt[0] = '-';
    prompt[1] = '-';

    while( 1 )
    {
    	Print("nachos://  ", 's');

		bufferSize = 0;
		
		do 
		{
		
		    Read(&buffer[bufferSize], 1, input);

		} while( buffer[bufferSize++] != '\n' );

		buffer[--bufferSize] = '\0';


		bufferIndex = 0;
		cmdIndex = 0;
		while(bufferIndex < bufferSize && buffer[bufferIndex] != '\0' 
			&& buffer[bufferIndex] != ' ')
		{
			cmd[cmdIndex++] = buffer[bufferIndex++];
		}
		cmd[cmdIndex] = '\0';

		while(bufferIndex < bufferSize && buffer[bufferIndex] == ' ')
		{
			bufferIndex++;
		}

		argIndex = 0;
		while(bufferIndex < bufferSize && buffer[bufferIndex] != '\0' 
			&& buffer[bufferIndex] != ' ')
		{
			arg[argIndex++] = buffer[bufferIndex++];
		}
		arg[argIndex] = '\0';

		if(cmdIndex > 0) 
		{
			if(argIndex > 0 && strcmp("exec", cmd, 4) == 0)
			{
				newProc = Exec(arg);
				if(newProc < 0)
				{
					Print("unable to run ", 's');
					Println(arg, 's');
					continue;
				}
				Print("SpaceId : ", 's');
				Println(newProc, 'd');
				Join(newProc);
			}
			if(strcmp("join", cmd, 4) == 0)
			{
				if(newProc >= 0)
					Join(newProc);
			}
			if(strcmp("ls", cmd, 2) == 0)
			{
				LS();
			}
			if(strcmp("quit", cmd, 4) == 0)
			{
				Exit(0);
			}
			if(strcmp("halt", cmd, 4) == 0)
			{
				Halt();
			}
			if(strcmp("path", cmd, 4) == 0)
			{
				Path();
			}
			if(strcmp("help", cmd, 4) == 0)
			{
				Println("ls,echo,mkdir,cd,rm is the same as linux", 's');
				Println("create a new file with: create [filename]", 's');
				Println("open a file with: open [filename]", 's');
				Println("close a file with: close [filename]", 's');
				Println("write an opened file with: write [content]", 's');
				Println("read an opened file with: read", 's');
				Println("close an opened file with: close", 's');
				Println("show current path with: path", 's');
				Println("exit system with: exit", 's');
				Println("halt system with: halt", 's');
			}
			if(argIndex > 0 && strcmp("echo", cmd, 4) == 0)
			{
				Println(arg, 's');
			}
			if(argIndex > 0 && strcmp("mkdir", cmd, 5) == 0)
			{
				MKDir(arg);
			}
			if(argIndex > 0 && strcmp("cd", cmd, 2) == 0)
			{
				CDDir(arg);
			}
			if(argIndex > 0 && strcmp("rm", cmd, 2) == 0)
			{
				Remove(arg);
			}
			if(argIndex > 0 && strcmp("create", cmd, 6) == 0)
			{
				Create(arg);
			}
			if(argIndex > 0 && strcmp("open", cmd, 4) == 0)
			{
				fd = Open(arg);
			}
			if(strcmp("close", cmd, 5) == 0)
			{
				Close(fd);
			}
			if(argIndex > 0 && strcmp("write", cmd, 5) == 0)
			{
				Write(arg, argIndex, fd);
			}
			if(strcmp("read", cmd, 4) == 0)
			{
				int readNum = Read(arg, 40, fd);
				arg[readNum] = '\0';
				Println(arg, 's');
			}
			if(strcmp("send", cmd, 4) == 0)
			{
				int num = parseInt(arg, argIndex);
				PutMsg(num, newProc);
			}
			if(strcmp("get", cmd, 3) == 0)
			{
				int num = GetMsg();
				Println(num, 'd');
			}
			if(strcmp("ts", cmd, 2) == 0)
			{
				TS();
			}
		}
    }
}
コード例 #23
0
 void TileRPGGameLoop::Shutdown()
 {
     StopLoop();
     Join();
 }
コード例 #24
0
ファイル: BotClient.cpp プロジェクト: andreasabt/linux-abt
int BotClient::ChatBotFunctions(string buffer)
{
    MessageHandler data(buffer);
    int pos=0;

    if (logger)
    {
        stringstream buf;
        for(int i=0;i<(int)data.message.size();i++)
            buf << data.message[i] << " ";
        if (data.message.size() > 0)
            LogChat(data.sender, buf.str());
    }

    if( (pos=data.atPosition("-change_nick")) != -1 && (int)data.message.size() > pos+1 )
    {
        Nick(data.message[pos+1]);
        conn->Send("PRIVMSG #" + conn->GetChannel() + " :name changed\r\n");
    }
    if( (pos=data.atPosition("-join")) != -1 && (int)data.message.size() > pos+1 )
    {
        Join( data.message[pos+1] );
    }
    if( (pos=data.atPosition("-change_topic")) != -1 && (int)data.message.size() > pos+1)
    {
        ChangeTopic(data.message[pos+1]);
        conn->Send("PRIVMSG #" + conn->GetChannel() + " :topic changed\r\n");
    }
    if( (pos=data.atPosition("-leave")) != -1 && (int)data.message.size() > pos+1 )
    {
        conn->Send("PRIVMSG #" + conn->GetChannel() + " :ciao!\r\n");
        Leave( data.message[pos+1] );
    }
    if((pos=data.atPosition("-show_chatlog")) != -1 )
    {
        ShowLog();
    }
    if ((pos=data.atPosition("-last_seen_user")) != -1 && data.message.size() > pos+1)
    {
        ShowLastSeen(data.message[pos+1]);
    }
    if ((pos=data.atPosition("-quit")) != -1 )
    {
        conn->Send("PRIVMSG #" + conn->GetChannel() + " :cya!\r\n");
        conn->Send("QUIT cya\r\n");
        return -1;
    }
    if ((pos=data.atPosition("-log")) != -1 && (int)data.message.size() > pos+1 ) {
        if (data.message[pos+1] == "on" )
        {
            logger = true;
            conn->Send("PRIVMSG #" + conn->GetChannel() + " :logging on\r\n");
        } else if( data.message[pos+1] == "off" )
        {
            logger = false;
            conn->Send("PRIVMSG #" + conn->GetChannel() + " :logging off\r\n");
        }
    }

    return 0;
}
コード例 #25
0
void OSThread::StopAndWaitForThread()
{
    fStopRequested = true;
    if (!fJoined)
        Join();
}
コード例 #26
0
LongPollThread::~LongPollThread()
{
    fireTermination();

    Join();
}
コード例 #27
0
WatchDogObserver::~WatchDogObserver()
{
    TerminationEvent.SetEvent();

    Join();
}
コード例 #28
0
ファイル: threadno.cpp プロジェクト: Bluehorn/wxPython
wxThread::~wxThread()
{
    Destroy();
    Join();
    delete p_internal;
}
コード例 #29
0
ファイル: sIRC32.cpp プロジェクト: peekaye/Syllable-sIRC
void MainView::HandleMessage(Message* pcMessage)
{
	switch(pcMessage->GetCode())
	{
		case M_MENU_QUIT:
			cout << "You pressed Quit Button" << endl;
			OkToQuit();
			break;	
		
		case MSG_SEND:
			{
			cout << "You pressed Send" << endl;					
			SendMsg();
			break;
			}		
		case MSG_FROMLOOPER_NEW_MESSAGE:
			cout << "MSG_FROMLOOPER_NEW_MESSAGE received" << endl;		
			cout << "Starting Update" << endl;					
			Update();				
			cout << "Update Done" << endl;							
			break;				
			
		case M_MENU_ABO:
		    cout << "You pressed About" << endl;
			ShowAbout();
			break;
		
		case M_MENU_CONNECT:
		    cout << "You pressed Connect" << endl;
			Connect();
			break;
			
		case M_MENU_LOGIN:
		    cout << "You pressed Login" << endl;
			Login();
			break;			
			
		case MSG_JOINCHANNEL:
		    cout << "You pressed Join" << endl;
			Join();
			break;
			
		case MSG_SINGLEUPDATE:
		    cout << "You pressed Single Update" << endl;
			Update();
			break;			
			
		case MSG_UPDATE:
		    cout << "You pressed Update" << endl;
			if( m_CommThread )
				m_CommThread->PostMessage( MSG_TOLOOPER_START, m_CommThread, m_CommThread ); 	
			cout << "Message send to MSG_TOLOOPER_START" << endl;	
			break;	
					
		case M_MENU_DISCONNECT:
		    cout << "You pressed Disconnect" << endl;
			Disconnect();
			break;
		case MSG_SETTINGS:
		{
		    cout << "You pressed Settings" << endl;
			break;
		}
					
		default:
			LayoutView::HandleMessage(pcMessage);
			break;
	}
}
コード例 #30
0
ファイル: interprc.cpp プロジェクト: asir6/Colt
void IntersectionProcessor::JoinEdges(const OpsDoublePoint &intersectionPt)
{
    // join the last edge to the first if the intersection points coincides
    // with the first endpoint of the last edge, or if the edges are not
    // coincident (if these conditions are not met, then all edges must be
    // be coincident)

    WingedEdge *edge0 = m_edgeRecs[m_nEdgeRecs-1].m_edge;
    WingedEdge *edge1 = m_edgeRecs[0].m_edge;

    if (intersectionPt == *edge0->m_vert[0] || !EdgesCoincident(edge0, edge1))
        Join(intersectionPt, edge0, edge1);

    // loop through the edges in increasing polar order, joining them in
    // counter-clockwise order

    for (int i = 0; i < (m_nEdgeRecs - 1); ) {
        edge0 = m_edgeRecs[i].m_edge;
        edge1 = m_edgeRecs[i+1].m_edge;

        // join the first edge to the second edge if the intersection point
        // coincides with the first endpoint of the first edge, or if the
        // edges are not coincident

        if (intersectionPt==*edge0->m_vert[0]||!EdgesCoincident(edge0, edge1)){
            Join(intersectionPt, edge0, edge1);
            i++;
        }

        // else the intersection point coincides with the last endpoint of the
        // first edge, and the first and second edges are coincident - must
        // have a sequence of two or more coincident edges. Merge the edges
        // and mark all but the last in the sequence as deleted.

        else {
            int j = i + 1;
            BOOL minVertSideIn = edge0->SideIn(WingedEdge::MinVertSide);
            BOOL maxVertSideIn = edge0->SideIn(WingedEdge::MaxVertSide);
            WingedEdge *firstEdge = NULL, *lastEdge = NULL;

            // Check if edge0 is linked to other non-coincident edges from
            // vert[0]

            if (!EdgesCoincident(edge0, edge0->m_cwEdge[1]))
                firstEdge = edge0;
            else if (!EdgesCoincident(edge0, edge0->m_ccwEdge[0]))
                lastEdge = edge0;

            edge0->SetEdgeDeleted();

            // determine union of side-in flags and mark edges as deleted

            while (j < (m_nEdgeRecs-1) &&
                       EdgesCoincident(edge1, m_edgeRecs[j+1].m_edge)) {
                if (edge1->SideIn(WingedEdge::MinVertSide))
                    minVertSideIn = TRUE;

                if (edge1->SideIn(WingedEdge::MaxVertSide))
                    maxVertSideIn = TRUE;

                // Check if edge1 is linked to other non-coincident edges from
                // vert[0]

                if (!firstEdge && !EdgesCoincident(edge1, edge1->m_cwEdge[1]))
                     firstEdge = edge1;
                else if (!lastEdge&&!EdgesCoincident(edge1,edge1->m_ccwEdge[0]))
                     lastEdge = edge1;

                edge1->SetEdgeDeleted();
                edge1 = m_edgeRecs[++j].m_edge;
            }

            // patch up links to other edges from vert[0]

            if (firstEdge != NULL) {
                edge1->m_cwEdge[1] = firstEdge->m_cwEdge[1];
                edge1->m_cwEdge[1]->ResetWings(firstEdge, edge1);
            }
            else if (edge1->m_cwEdge[1]->EdgeDeleted())
                edge1->m_cwEdge[1] = edge1;

            if (lastEdge != NULL) {
                edge1->m_ccwEdge[0] = lastEdge->m_ccwEdge[0];
                edge1->m_ccwEdge[0]->ResetWings(lastEdge, edge1);
            }
            else if (edge1->m_ccwEdge[0]->EdgeDeleted())
                edge1->m_ccwEdge[0] = edge1;

            // patch up link to edge from vert[1] - the first edge in
            // sequence of coincident edges may have been joined to another
            // non-coincident edge

            if (edge0->m_ccwEdge[1] != edge0) {
                edge1->m_ccwEdge[1] = edge0->m_ccwEdge[1];
                edge1->m_ccwEdge[1]->ResetWings(edge0, edge1);
            }

            // update the side-in flags if necessary

            if (minVertSideIn)
                edge1->SetSideIn(WingedEdge::MinVertSide);

            if (maxVertSideIn)
                edge1->SetSideIn(WingedEdge::MaxVertSide);

            i = j;
        }
    }

} // end: JoinEdges()