コード例 #1
0
ファイル: Texture.cpp プロジェクト: biddyweb/ewol
void ewol::resource::Texture::flush() {
	std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
	// request to the manager to be call at the next update ...
	getManager().update(std::dynamic_pointer_cast<gale::Resource>(shared_from_this()));
}
コード例 #2
0
bool PopupWindow::onProcessMessage(Message* msg)
{
  switch (msg->type()) {

    // There are cases where startFilteringMessages() is called when a
    // kCloseMessage for this same PopupWindow is enqueued. Processing
    // the kOpenMessage we ensure that the popup will be filtering
    // messages if it's needed when it's visible (as kCloseMessage and
    // kOpenMessage must be enqueued in the correct order).
    case kOpenMessage:
      if (!isMoveable())
        startFilteringMessages();
      break;

    case kCloseMessage:
      stopFilteringMessages();
      break;

    case kMouseLeaveMessage:
      if (m_hotRegion.isEmpty() && !isMoveable())
        closeWindow(nullptr);
      break;

    case kKeyDownMessage:
      if (m_filtering) {
        KeyMessage* keymsg = static_cast<KeyMessage*>(msg);
        KeyScancode scancode = keymsg->scancode();

        if (scancode == kKeyEsc)
          closeWindow(nullptr);

        if (m_enterBehavior == kCloseOnEnter &&
            (scancode == kKeyEnter ||
             scancode == kKeyEnterPad)) {
          closeWindow(this);
          return true;
        }
      }
      break;

    case kMouseDownMessage:
      if (m_filtering) {
        gfx::Point mousePos = static_cast<MouseMessage*>(msg)->position();

        switch (m_clickBehavior) {

          // If the user click outside the window, we have to close
          // the tooltip window.
          case kCloseOnClickInOtherWindow: {
            Widget* picked = pick(mousePos);
            if (!picked || picked->getRoot() != this) {
              closeWindow(NULL);
            }
            break;
          }

          case kCloseOnClickOutsideHotRegion:
            if (!m_hotRegion.contains(mousePos)) {
              closeWindow(NULL);
            }
            break;
        }
      }
      break;

    case kMouseMoveMessage:
      if (!isMoveable() &&
          !m_hotRegion.isEmpty() &&
          getManager()->getCapture() == NULL) {
        gfx::Point mousePos = static_cast<MouseMessage*>(msg)->position();

        // If the mouse is outside the hot-region we have to close the
        // window.
        if (!m_hotRegion.contains(mousePos))
          closeWindow(NULL);
      }
      break;

  }

  return Window::onProcessMessage(msg);
}
コード例 #3
0
void GoldpotView::draw(const GameTime& gameTime)
{
	FBXRenderer::draw(model, gameTime, getManager(), getController().getWorld());
}
コード例 #4
0
ファイル: TUICore.hpp プロジェクト: gogo1207/QuadAssault
bool TUICore<T>::isFocus()
{
    assert( getManager() );
    return getManager()->getFocusUI() == this;
}
コード例 #5
0
ファイル: TUICore.hpp プロジェクト: gogo1207/QuadAssault
T& TUICore<T>::setFocus()
{
    getManager()->setFocusUI( this );
    return *_this();
}
コード例 #6
0
ファイル: Model.cpp プロジェクト: steelstyle/CoreRender
	bool Model::parseNode(TiXmlElement *xml, Model::Node *parent)
	{
		// Get name
		const char *name = xml->Attribute("name");
		if (!name)
		{
			getManager()->getLog()->error("%s: Node name missing.",
			                              getName().c_str());
			return false;
		}
		// Add node
		Node *currentnode = addNode(name, parent);
		// Read transformation
		TiXmlElement *transelem = xml->FirstChildElement("Transformation");
		math::Matrix4 transmat = math::Matrix4::Identity();
		if (transelem)
		{
			std::istringstream matstream(transelem->GetText());
			for (unsigned int i = 0; i < 16; i++)
			{
				matstream >> transmat.m[i];
				char separator;
				matstream >> separator;
			}
		}
		currentnode->setTransformation(transmat);
		// Read meshes
		for (TiXmlElement *element = xml->FirstChildElement("Mesh");
		     element != 0;
		     element = element->NextSiblingElement("Mesh"))
		{
			// Read mesh info
			const char *indexstr = element->Attribute("index");
			if (!indexstr)
			{
				getManager()->getLog()->warning("%s: Mesh index missing.",
				                                getName().c_str());
				continue;
			}
			const char *materialfile = element->Attribute("material");
			if (!materialfile)
			{
				getManager()->getLog()->warning("%s: Mesh material missing.",
				                                getName().c_str());
				continue;
			}
			unsigned int batchindex = atoi(indexstr);
			if (batchindex >= batches.size())
			{
				getManager()->getLog()->warning("%s: Invalid batch index %d.",
				                                getName().c_str(),
				                                batchindex);
				continue;
			}
			// Create and add mesh
			std::string path = getPath();
			std::string directory = core::FileSystem::getDirectory(path);
			res::ResourceManager *rmgr = getManager();
			core::FileSystem::Ptr fs = rmgr->getFileSystem();
			Mesh mesh;
			mesh.batch = batchindex;
			std::string materialpath = fs->getPath(materialfile, directory);
			mesh.material = rmgr->getOrLoad<Material>("Material", materialpath);
			mesh.node = currentnode;
			addMesh(mesh);
		}
		// Read child nodes
		for (TiXmlElement *element = xml->FirstChildElement("Node");
		     element != 0;
		     element = element->NextSiblingElement("Node"))
		{
			if (!parseNode(element, currentnode))
				return false;
		}
		return true;
	}
コード例 #7
0
ファイル: unit.cpp プロジェクト: FrostHand/TiGa
void Unit::useDevice(int device,int port,int action,IOBuffer *buffer)
{
//	LogFunction(*g_logger);
	getManager()->useDevice(this,device,port,action,buffer);
}
コード例 #8
0
// ######################################################################
void EndPointChannel::buildSubChans()
{
GVX_TRACE(__PRETTY_FUNCTION__);
  // kill any subchans we may have had...
  this->removeAllSubChans();

  LINFO("Using %d orientations spanning [0..360]deg", itsNumOrients.getVal());
  for (uint ori = 0; ori < 8; )
    {
      switch (ori)
        {
        case 0:
          addSubChan(makeSharedComp
                     (new JunctionChannel(getManager(), itsOriChan,
                                          visualFeature(),
                                          1,0,0,0,0,0,0,0 )),
                     "", 1.0, /* exportOpts = */ true);
          break;
        case 1:
          addSubChan(makeSharedComp
                     (new JunctionChannel(getManager(), itsOriChan,
                                          visualFeature(),
                                          0,1,0,0,0,0,0,0 )),
                     "", 1.0, /* exportOpts = */ true);
          break;
        case 2:
          addSubChan(makeSharedComp
                     (new JunctionChannel(getManager(), itsOriChan,
                                          visualFeature(),
                                          0,0,1,0,0,0,0,0 )),
                     "", 1.0, /* exportOpts = */ true);
          break;
        case 3:
          addSubChan(makeSharedComp
                     (new JunctionChannel(getManager(), itsOriChan,
                                          visualFeature(),
                                          0,0,0,1,0,0,0,0 )),
                     "", 1.0, /* exportOpts = */ true);
          break;
        case 4:
          addSubChan(makeSharedComp
                     (new JunctionChannel(getManager(), itsOriChan,
                                          visualFeature(),
                                          0,0,0,0,1,0,0,0 )),
                     "", 1.0, /* exportOpts = */ true);
          break;
        case 5:
          addSubChan(makeSharedComp
                     (new JunctionChannel(getManager(), itsOriChan,
                                          visualFeature(),
                                          0,0,0,0,0,1,0,0 )),
                     "", 1.0, /* exportOpts = */ true);
          break;
        case 6:
          addSubChan(makeSharedComp
                     (new JunctionChannel(getManager(), itsOriChan,
                                          visualFeature(),
                                          0,0,0,0,0,0,1,0 )),
                     "", 1.0, /* exportOpts = */ true);
          break;
        case 7:
          addSubChan(makeSharedComp
                     (new JunctionChannel(getManager(), itsOriChan,
                                          visualFeature(),
                                          0,0,0,0,0,0,0,1 )),
                     "", 1.0, /* exportOpts = */ true);
          break;
        default:
          break;
        }
      ori += 8 / itsNumOrients.getVal();
    }
}
コード例 #9
0
Error TextureAtlasResource::load(const ResourceFilename& filename, Bool async)
{
	XmlDocument doc;
	ANKI_CHECK(openFileParseXml(filename, doc));

	XmlElement rootel, el;

	//
	// <textureAtlas>
	//
	ANKI_CHECK(doc.getChildElement("textureAtlas", rootel));

	//
	// <texture>
	//
	ANKI_CHECK(rootel.getChildElement("texture", el));
	CString texFname;
	ANKI_CHECK(el.getText(texFname));
	ANKI_CHECK(getManager().loadResource<TextureResource>(texFname, m_tex, async));

	m_size[0] = m_tex->getWidth();
	m_size[1] = m_tex->getHeight();

	//
	// <subTextureMargin>
	//
	ANKI_CHECK(rootel.getChildElement("subTextureMargin", el));
	I64 margin = 0;
	ANKI_CHECK(el.getNumber(margin));
	if(margin >= I(m_tex->getWidth()) || margin >= I(m_tex->getHeight()) || margin < 0)
	{
		ANKI_RESOURCE_LOGE("Too big margin %d", U(margin));
		return Error::USER_DATA;
	}
	m_margin = margin;

	//
	// <subTextures>
	//

	// Get counts
	PtrSize namesSize = 0;
	PtrSize subTexesCount = 0;
	XmlElement subTexesEl, subTexEl;
	ANKI_CHECK(rootel.getChildElement("subTextures", subTexesEl));
	ANKI_CHECK(subTexesEl.getChildElement("subTexture", subTexEl));
	do
	{
		ANKI_CHECK(subTexEl.getChildElement("name", el));
		CString name;
		ANKI_CHECK(el.getText(name));

		if(name.getLength() < 1)
		{
			ANKI_RESOURCE_LOGE("Something wrong with the <name> tag. Probably empty");
			return Error::USER_DATA;
		}

		namesSize += name.getLength() + 1;
		++subTexesCount;

		ANKI_CHECK(subTexEl.getNextSiblingElement("subTexture", subTexEl));
	} while(subTexEl);

	// Allocate
	m_subTexNames.create(getAllocator(), namesSize);
	m_subTexes.create(getAllocator(), subTexesCount);

	// Iterate again and populate
	subTexesCount = 0;
	char* names = &m_subTexNames[0];
	ANKI_CHECK(subTexesEl.getChildElement("subTexture", subTexEl));
	do
	{
		ANKI_CHECK(subTexEl.getChildElement("name", el));
		CString name;
		ANKI_CHECK(el.getText(name));

		memcpy(names, &name[0], name.getLength() + 1);

		m_subTexes[subTexesCount].m_name = names;

		ANKI_CHECK(subTexEl.getChildElement("uv", el));
		Vec4 uv;
		ANKI_CHECK(el.getVec4(uv));
		m_subTexes[subTexesCount].m_uv = {{uv[0], uv[1], uv[2], uv[3]}};

		names += name.getLength() + 1;
		++subTexesCount;

		ANKI_CHECK(subTexEl.getNextSiblingElement("subTexture", subTexEl));
	} while(subTexEl);

	return Error::NONE;
}
コード例 #10
0
	//---------------------------------------------------------------------
	void PagedWorldSection::setStrategy(const String& stratName)
	{
		setStrategy(getManager()->getStrategy(stratName));
	}
コード例 #11
0
ファイル: IPCPipeBase.cpp プロジェクト: EasyCoding/desura-app
void PipeBase::processEvents()
{
	DWORD dwWait = WaitForMultipleObjects(getNumEvents(), m_hEventsArr, FALSE, 500);

	if (isStopped())
		return;

	if (dwWait == WAIT_TIMEOUT)
		return;

	if (dwWait == WAIT_FAILED)
	{
		DWORD lErr = GetLastError();
		return;
	}

	// dwWait shows which pipe completed the operation.
	size_t i = dwWait - WAIT_OBJECT_0;  // determines which pipe
	if (i < 0 || i > (getNumEvents() - 1))
	{
		printf("Index out of range.\n");
		return;
	}

	PipeData* data = getData(i);
	DWORD cbRet = 0;

#ifdef IPC_DEBUG
	if (fh)
	{
		fprintf(fh, "Triggered event %d\n", i);
		fflush(fh);
	}
#endif
	//printf("Event %d, P: %d\n", i, data->fPendingIO);


	// Get the result if the operation was pending.
	if (data->fPendingIO)
	{
		BOOL fSuccess = GetOverlappedResult(data->hPipe, &data->oOverlap, &cbRet, FALSE);

		//printf("Pending S: %d A: %d P: %d\n", fSuccess, cbRet, data->pendingConnection);

		if (data->pendingConnection)
		{
			if (!fSuccess)
				throw gcException(ERR_PIPE, GetLastError(), gcString("Error {0}.\n", GetLastError()));

			data->pendingConnection = false;
			data->fPendingIO = FALSE;
		}
		else
		{
			DWORD err = GetLastError();

			//Buffer is full. Wait for space
			if (err == ERROR_IO_INCOMPLETE)
				fSuccess = GetOverlappedResult(data->hPipe, &data->oOverlap, &cbRet, TRUE);

			if (!fSuccess || (cbRet == 0 && data->sender == false)) // || (cbRet != data->size && data->sender == true)
			{
				disconnectAndReconnect(i);
				ResetEvent(m_hEventsArr[i]);
				printf("Disconnect pending!\n");
				return;
			}

			if (!data->sender)
			{
				data->size = cbRet;
				finishRead(data, getManager(i));
			}
		}
	}

	bool res = false;

	// The pipe state determines which operation to do next.
	if (data->sender)
		res = performWrite(data, getManager(i));
	else
		res = performRead(data, getManager(i));

	if (res)
		ResetEvent(m_hEventsArr[i]);
}
コード例 #12
0
const sf::Texture TextureManager::getTexture(std::string texture)
{
	//Påkalla funktionen med namnet till rätt animationen
		return getManager().mTextureMap[texture];
};
コード例 #13
0
int TransferManagerAdapter::verifyTicket(string ticket){
  return getManager()->verifyTicket(ticket);
}
コード例 #14
0
string TransferManagerAdapter::createTicket(int userId, int time) {
	return getManager()->createTicket(userId, time);
}
コード例 #15
0
ファイル: Model.cpp プロジェクト: steelstyle/CoreRender
	bool Model::load()
	{
		std::string path = getPath();
		std::string directory = core::FileSystem::getDirectory(path);
		// Open XML file
		TiXmlDocument xml(path.c_str());
		if (!loadResourceFile(xml))
		{
			finishLoading(false);
			return false;
		}
		// Load XML file
		TiXmlNode *root = xml.FirstChild("Model");
		if (!root || !root->ToElement())
		{
			getManager()->getLog()->error("%s: <Model> not found.",
			                              getName().c_str());
			finishLoading(false);
			return false;
		}
		// Get geometry file
		const char *geofilename = root->ToElement()->Attribute("geometry");
		if (!geofilename)
		{
			getManager()->getLog()->error("%s: No geometry file specified.",
			                              getName().c_str());
			finishLoading(false);
			return false;
		}
		// Open geometry file
		core::FileSystem::Ptr fs = getManager()->getFileSystem();
		if (!loadGeometryFile(fs->getPath(geofilename, directory)))
		{
			finishLoading(false);
			return false;
		}
		// Load nodes
		TiXmlElement *rootnodeelem = root->FirstChildElement("Node");
		if (!rootnodeelem)
		{
			getManager()->getLog()->error("%s: No node available.",
			                              getName().c_str());
			finishLoading(false);
			return false;
		}
		if (!parseNode(rootnodeelem, 0))
		{
			finishLoading(false);
			return false;
		}
		// Load joints
		for (TiXmlElement *element = root->FirstChildElement("Armature");
		     element != 0;
		     element = element->NextSiblingElement("Armature"))
		{
			// Get batch index
			const char *batchstr = element->Attribute("batch");
			if (!batchstr)
			{
				getManager()->getLog()->warning("%s: Armature batch missing.",
				                                getName().c_str());
				continue;
			}
			unsigned int batchidx = atoi(batchstr);
			if (batchidx >= batches.size())
			{
				getManager()->getLog()->warning("%s: Invalid armature batch.",
				                                getName().c_str());
				continue;
			}
			// Load joints
			for (TiXmlElement *jointelem = element->FirstChildElement("Joint");
			     jointelem != 0;
			     jointelem = jointelem->NextSiblingElement("Joint"))
			{
				// Get and check joint index
				const char *indexstr = jointelem->Attribute("index");
				if (!indexstr)
				{
					getManager()->getLog()->warning("%s: Joint index missing.",
					                                getName().c_str());
					continue;
				}
				unsigned int index = atoi(indexstr);
				if (index >= batches[batchidx].joints.size())
				{
					getManager()->getLog()->warning("%s: Joint index invalid.",
					                                getName().c_str());
					continue;
				}
				// Get and check joint name
				const char *name = jointelem->Attribute("name");
				if (!name)
				{
					getManager()->getLog()->warning("%s: Joint name missing.",
					                                getName().c_str());
					continue;
				}
				Node *node = getNode(name);
				if (!node)
				{
					getManager()->getLog()->warning("%s: Joint node \"%s\" not found.",
					                                getName().c_str(), name);
					continue;
				}
				batches[batchidx].joints[index].name = name;
				batches[batchidx].joints[index].node = node;
			}
		}
		finishLoading(true);
		return true;
	}
コード例 #16
0
bool ProtocolUDPGeneric::init_derived()
{
    if (!peerIface) {
        HAGGLE_ERR("%s No peer interface\n", getName());
        return false;
    }

    if (!localIface) {
        HAGGLE_ERR("%s No local interface\n", getName());
        return false;
    }

    SOCKET sockets[2];
    if (0 > socketpair(AF_UNIX, SOCK_DGRAM, 0, sockets)) {
        HAGGLE_ERR("%s Could not create socket pair for receiver: %s\n", getName(), STRERROR(ERRNO));
        HAGGLE_ERR("FATAL ERROR - EMERGENCY SHUTDOWN INITIATED\n"); // MOS
	getKernel()->setFatalError();
	getKernel()->shutdown();
        return false;
    }
    else
      {
        HAGGLE_DBG2("%s Opening socketpair (%d,%d)\n", getName(), sockets[0], sockets[1]);
      }

    writeEndOfReceiveSocket =
        new SocketWrapper(getKernel(), getManager(), sockets[0]);

    if (!writeEndOfReceiveSocket) {
        HAGGLE_ERR("%s Could not allocate write end\n", getName());
        return false;
    }

    if (!writeEndOfReceiveSocket->multiplySndBufferSize(2)) {
        HAGGLE_ERR("%s Could not multiply buffer size.\n", getName());
        return false;
    }

    readEndOfReceiveSocket =
        new SocketWrapper(getKernel(), getManager(), sockets[1]);

    if (!readEndOfReceiveSocket) {
        HAGGLE_ERR("%s Could not allocate read end\n", getName());
        return false;
    }

    if (!readEndOfReceiveSocket->multiplyRcvBufferSize(2)) {
        HAGGLE_ERR("%s Could not multiply buffer size.\n", getName());
        return false;
    }

    srcIP = interfaceToIP(localIface);

    if (0 == srcIP) {
        HAGGLE_ERR("%s Could not get source IP.\n");
        return false;
    }

    destIP = interfaceToIP(peerIface);

    if (0 == destIP) {
        HAGGLE_ERR("%s Could not get dest IP.\n");
        return false;
    }

    return initbase();
}
コード例 #17
0
ファイル: Model.cpp プロジェクト: steelstyle/CoreRender
	bool Model::loadGeometryFile(std::string filename)
	{
		// Open file
		core::FileSystem::Ptr fs = getManager()->getFileSystem();
		core::File::Ptr file = fs->open(filename, core::FileAccess::Read);
		if (!file)
		{
			getManager()->getLog()->error("Could not open file \"%s\".",
			                              filename.c_str());
			return false;
		}
		// Read header
		// TODO: Adapt all this to big-endian
		GeometryFile::Header header;
		if (file->read(sizeof(header), &header) != sizeof(header))
		{
			getManager()->getLog()->error("%s: Could not read geometry header.",
			                              getName().c_str());
			return false;
		}
		if (header.tag != GeometryFile::tag
		 || header.version != GeometryFile::version)
		{
			getManager()->getLog()->error("%s: Invalid geometry file.",
			                              getName().c_str());
			return false;
		}
		// Read vertex and index data
		void *vertexdata = malloc(header.vertexdatasize);
		if (file->read(header.vertexdatasize, vertexdata) != (int)header.vertexdatasize)
		{
			getManager()->getLog()->error("%s: Could not read vertex data.",
			                              getName().c_str());
			free(vertexdata);
			return false;
		}
		void *indexdata = malloc(header.indexdatasize);
		if (file->read(header.indexdatasize, indexdata) != (int)header.indexdatasize)
		{
			getManager()->getLog()->error("%s: Could not read index data.",
			                              getName().c_str());
			free(vertexdata);
			free(indexdata);
			return false;
		}
		// Construct vertex/index buffers
		res::ResourceManager *rmgr = getManager();
		vertexbuffer = rmgr->createResource<VertexBuffer>("VertexBuffer");
		indexbuffer = rmgr->createResource<IndexBuffer>("IndexBuffer");
		if (!vertexbuffer || !indexbuffer)
		{
			getManager()->getLog()->error("%s: Could not create buffers.",
			                              getName().c_str());
			free(vertexdata);
			free(indexdata);
			return false;
		}
		vertexbuffer->set(header.vertexdatasize,
		                  vertexdata,
		                  VertexBufferUsage::Static,
		                  false);
		indexbuffer->set(header.indexdatasize, indexdata, false);
		// Read batch info
		std::vector<GeometryFile::Batch> batchdata(header.batchcount, GeometryFile::Batch());
		for (unsigned int i = 0; i < header.batchcount; i++)
		{
			GeometryFile::AttribInfo &attribs = batchdata[i].attribs;
			GeometryFile::GeometryInfo &geom = batchdata[i].geom;
			if (file->read(sizeof(attribs), &attribs) != sizeof(attribs)
			 || file->read(sizeof(geom), &geom) != sizeof(geom))
			{
				getManager()->getLog()->error("%s: Could not read batch.",
				                              getName().c_str());
				return false;
			}
			// Joint matrices
			if (geom.jointcount == 0)
				continue;
			int jointsize = sizeof(float) * geom.jointcount * 16;
			batchdata[i].jointmatrices = std::vector<float>(geom.jointcount * 16);
			if (file->read(jointsize, &batchdata[i].jointmatrices[0]) != jointsize)
			{
				getManager()->getLog()->error("%s: Could not joint matrices.",
				                              getName().c_str());
				return false;
			}
		}
		// Construct batch info
		std::vector<Batch> batches(header.batchcount);
		for (unsigned int i = 0; i < header.batchcount; i++)
		{
			batches[i].layout = createVertexLayout(batchdata[i].attribs);
			if (!batches[i].layout)
			{
				getManager()->getLog()->error("%s: Could not create vertex layout.",
				                              getName().c_str());
				return false;
			}
			GeometryFile::AttribInfo &attribs = batchdata[i].attribs;
			GeometryFile::GeometryInfo &geom = batchdata[i].geom;
			batches[i].basevertex = geom.basevertex;
			batches[i].indextype = geom.indextype;
			batches[i].indexcount = geom.indexcount;
			batches[i].startindex = geom.indexoffset / geom.indextype;
			batches[i].vertexoffset = geom.vertexoffset;
			batches[i].vertexcount = geom.vertexsize / attribs.stride;
			// Create joints
			batches[i].joints = std::vector<Joint>(batchdata[i].geom.jointcount);
			for (unsigned int j = 0; j < batchdata[i].geom.jointcount; j++)
			{
				math::Matrix4 &jointmat = batches[i].joints[j].jointmat;
				memcpy(&jointmat.m[0],
				       &batchdata[i].jointmatrices[j * 16],
				       sizeof(float) * 16);
			}
		}
		this->batches = batches;
		return true;
	}
コード例 #18
0
ProtocolEvent ProtocolUDPGeneric::sendDataObjectNowNoControl(
    const DataObjectRef& dObj)
{
    NodeRef currentPeer;
    { Mutex::AutoLocker l(mutex); currentPeer = peerNode; } // MOS

    NodeRef actualPeer = getManager()->getKernel()->getNodeStore()->retrieve(currentPeer, true);
    if (!actualPeer) {
        HAGGLE_ERR("%s Peer not in node store\n", getName());
        return PROT_EVENT_ERROR;
    }

    // check if already in peers bloomfilter
    if (actualPeer->hasThisOrParentDataObject(dObj)) { // MOS
        HAGGLE_DBG("%s Peer already had data object.\n", getName());
        return PROT_EVENT_SUCCESS;
    }
    // done

    // SW: we move the hook here to minimize race condition where we send
    // too many redundant node descriptions
    // TODO: we may want to synchronize on the dObj or have some serial
    // queue so this is not probabilistic
    sendDataObjectNowSuccessHook(dObj);

    HAGGLE_DBG("%s Sending data object [%s] to peer \'%s\'\n", 
        getName(), dObj->getIdStr(), peerDescription().c_str());

    DataObjectDataRetrieverRef retriever = dObj->getDataObjectDataRetriever();
    if (!retriever || !retriever->isValid()) {
        HAGGLE_ERR("%s unable to start reading data\n", getName());
        return PROT_EVENT_ERROR;
    }

    ProtocolEvent pEvent = PROT_EVENT_SUCCESS;

    ssize_t len = retriever->retrieve(buffer, bufferSize, false);

    if (0 == len) {
        HAGGLE_ERR("%s DataObject is empty\n", getName());
        return PROT_EVENT_ERROR;
    }

    if (len < 0) {
        HAGGLE_ERR("%s Could not retrieve data from data object\n", getName());
        return PROT_EVENT_ERROR;
    }

    if ((size_t) len == bufferSize) {
        HAGGLE_ERR("%s Buffer is too small for message\n", getName());
        return PROT_EVENT_ERROR;
    }

    Timeval t_start;
    t_start.setNow();

    setSessionNo(dObj->getId()); // MOS
    setSeqNo(0); // MOS

    size_t bytesSent = 0;

    // MOS - simple way to increase udp redundancy
    for(int i = 0; i <= getConfiguration()->getRedundancy(); i++) {

    pEvent = sendData(buffer, (size_t) len, 0, &bytesSent);
    if (bytesSent != (size_t) len) {
        pEvent = PROT_EVENT_ERROR;
    }

    if (pEvent != PROT_EVENT_SUCCESS) {
        HAGGLE_ERR("%s Broadcast - Error\n", getName());
        return pEvent;
    }
    }

#ifdef DEBUG
    Timeval tx_time = Timeval::now() - t_start;

    HAGGLE_DBG("%s Sent %lu bytes data in %.3lf seconds, average speed = %.2lf kB/s\n", 
        getName(), len, tx_time.getTimeAsSecondsDouble(), 
        (double)len / (1000*tx_time.getTimeAsSecondsDouble()));
#endif

    dataObjectsOutgoing += 1; // MOS
    dataObjectsSent += 1; // MOS
    if(!dObj->isControlMessage()) dataObjectsOutgoingNonControl += 1; // MOS
    dataObjectBytesOutgoing += bytesSent; // MOS
    dataObjectBytesSent += len; // MOS
    if(dObj->isNodeDescription()) { nodeDescSent += 1; nodeDescBytesSent += len; } // MOS

    return PROT_EVENT_SUCCESS;
}
コード例 #19
0
ファイル: Image.cpp プロジェクト: atria-soft/ewol
ememory::SharedPtr<ewol::resource::TextureFile> ewol::resource::TextureFile::create(const std::string& _filename, ivec2 _size, ivec2 _sizeRegister) {
	EWOL_VERBOSE("KEEP: TextureFile: '" << _filename << "' size=" << _size << " sizeRegister=" << _sizeRegister);
	if (_filename == "") {
		ememory::SharedPtr<ewol::resource::TextureFile> object(new ewol::resource::TextureFile());
		if (object == nullptr) {
			EWOL_ERROR("allocation error of a resource : ??TEX??");
			return nullptr;
		}
		object->init();
		getManager().localAdd(object);
		return object;
	}
	if (_size.x() == 0) {
		_size.setX(-1);
		//EWOL_ERROR("Error Request the image size.x() =0 ???");
	}
	if (_size.y() == 0) {
		_size.setY(-1);
		//EWOL_ERROR("Error Request the image size.y() =0 ???");
	}
	std::string tmpFilename = _filename;
	if (etk::end_with(_filename, ".svg") == false) {
		_size = ewol::resource::TextureFile::sizeAuto;
	}
	if (_size.x()>0 && _size.y()>0) {
		EWOL_VERBOSE("     == > specific size : " << _size);
		#if    defined(__TARGET_OS__Android) \
		    || defined(__TARGET_OS__MacOs) \
		    || defined(__TARGET_OS__IOs)
			_size.setValue(nextP2(_size.x()), nextP2(_size.y()));
		#endif
		if (_sizeRegister != ewol::resource::TextureFile::sizeAuto) {
			if (_sizeRegister != ewol::resource::TextureFile::sizeDefault) {
				tmpFilename += ":";
				tmpFilename += etk::to_string(_size.x());
				tmpFilename += "x";
				tmpFilename += etk::to_string(_size.y());
			}
		}
	}
	
	EWOL_VERBOSE("KEEP: TextureFile: '" << tmpFilename << "' new size=" << _size);
	ememory::SharedPtr<ewol::resource::TextureFile> object = nullptr;
	ememory::SharedPtr<gale::Resource> object2 = getManager().localKeep(tmpFilename);
	if (object2 != nullptr) {
		object = ememory::dynamicPointerCast<ewol::resource::TextureFile>(object2);
		if (object == nullptr) {
			EWOL_CRITICAL("Request resource file : '" << tmpFilename << "' With the wrong type (dynamic cast error)");
			return nullptr;
		}
	}
	if (object != nullptr) {
		return object;
	}
	EWOL_INFO("CREATE: TextureFile: '" << tmpFilename << "' size=" << _size);
	// need to crate a new one ...
	object = ememory::SharedPtr<ewol::resource::TextureFile>(new ewol::resource::TextureFile());
	if (object == nullptr) {
		EWOL_ERROR("allocation error of a resource : " << _filename);
		return nullptr;
	}
	object->init(tmpFilename, _filename, _size);
	getManager().localAdd(object);
	return object;
}
コード例 #20
0
void
CacheStrategyUtility::_onConfig(
    const Metadata& m)
{
    const char *param;
    const Metadata *dm;

    if (m.getName() != getName()) {
        HAGGLE_ERR("Wrong config.\n");
        return;
    }

    // load knapsack optimizer

    param = m.getParameter("knapsack_optimizer");

    if (!param) {
        HAGGLE_DBG("No knapsack optimizer specified, using default.\n");
        ksOptimizer = CacheKnapsackOptimizerFactory::getNewKnapsackOptimizer(getManager()->getKernel());
    } 
    else {
        ksOptimizer = CacheKnapsackOptimizerFactory::getNewKnapsackOptimizer(getManager()->getKernel(), param);
    }

    if (!ksOptimizer) {
        HAGGLE_ERR("Could not initialize knapsack optimizer.\n");
        return;
    }

    dm = m.getMetadata(param);
    if (dm) {
        ksOptimizer->onConfig(*dm);
    }

    // load global optimizer 

    param = m.getParameter("global_optimizer");
    if (!param) {
        HAGGLE_DBG("No  specified, using default.\n");
        globalOptimizer = CacheGlobalOptimizerFactory::getNewGlobalOptimizer(getManager()->getKernel());
    } 
    else {
        globalOptimizer = CacheGlobalOptimizerFactory::getNewGlobalOptimizer(getManager()->getKernel(), param);
    }

    if (!globalOptimizer) {
        HAGGLE_ERR("Could not initialize global optimizer.\n");
        return;
    }

    dm = m.getMetadata(param);
    if (dm) {
        globalOptimizer->onConfig(*dm);
    }

    // load utility function

    param = m.getParameter("utility_function");
    if (!param) {
        HAGGLE_DBG("No utility function specified, using default.\n");
        utilFunction = CacheUtilityFunctionFactory::getNewUtilityFunction(getManager(), globalOptimizer);
    } 
    else {
        utilFunction = CacheUtilityFunctionFactory::getNewUtilityFunction(getManager(), globalOptimizer, param);
    }

    if (!utilFunction) {
        HAGGLE_ERR("Could not initialize utility function.\n");
        return;
    }

    dm = m.getMetadata(param);
    if (dm) {
        utilFunction->onConfig(*dm);
    }

    param = m.getParameter("max_capacity_kb");
    if (!param) {
        HAGGLE_ERR("No maximum capacity specified\n");
        return;
    }

    max_capacity_kb = atoi(param);

    if (max_capacity_kb < 0) {
        HAGGLE_ERR("Invalid max capacity.\n");
        return;
    }

    param = m.getParameter("watermark_capacity_kb");
    if (!param) {
        HAGGLE_ERR("No watermark capacity specified\n");
        return;
    }

    watermark_capacity_kb = atoi(param);

    if ((watermark_capacity_kb < 0) || (watermark_capacity_kb > max_capacity_kb)) {
        HAGGLE_ERR("Invalid watermark capacity.\n");
        return;
    }

    param = m.getParameter("compute_period_ms");
    if (param) {
        computePeriodMs = atoi(param);
    }

    if (computePeriodMs  < 0) {
        HAGGLE_ERR("Invalid compute period.\n");
        return;
    }

    param = m.getParameter("purge_poll_period_ms");
    if (param) {
        pollPeriodMs = atoi(param);
    }

    if (pollPeriodMs < 0) {
        HAGGLE_ERR("Invalid poll period.\n");
        return;
    }

    param = m.getParameter("purge_on_insert");
    if (param) {
        purgeOnInsert = (0 == strcmp("true", param));
    }

    param = m.getParameter("manage_only_remote_files");
    if (param) {
        manage_only_remote_files = (0 == strcmp("true", param));
    }

    param = m.getParameter("manage_locally_sent_files");
    if (param) {
        manage_locally_sent_files = (0 == strcmp("true", param));
    }

    param = m.getParameter("publish_stats_dataobject");
    if (param) {
        publish_stats_dataobject = (0 == strcmp("true", param));
    }

    param = m.getParameter("keep_in_bloomfilter");
    if (param) {
        keep_in_bloomfilter = (0 == strcmp("true", param));
    }

    param = m.getParameter("handle_zero_size");
    if (param) {
        handle_zero_size = (0 == strcmp("true", param));
    }

//JM: START DB 
    param = m.getParameter("manage_db_purging");
    if (param) {
        allow_db_purging = (0 == strcmp("true", param));
    }

    param = m.getParameter("db_size_threshold");
    if (param) {
        db_size_threshold = atoll(param);
    }

    param = m.getParameter("self_benchmark_test");
    if (param) {
        self_test = (0 == strcmp("true", param));
    }
//JM: END
    param = m.getParameter("bloomfilter_remove_delay_ms");
    if (param) {
        bloomfilter_remove_delay_ms = atoi(param);
    }

// SW: START: remove from local bloomfilter.
    if (bloomfilter_remove_delay_ms >= 0) {
        bloomfilterRemoveDelayEventType = registerEventType("BFRemoveDelay", onBloomfilterRemoveDelay);
        if (bloomfilterRemoveDelayEventType <= 0) {
            HAGGLE_ERR("Could not register bloomfilter remove delay event.\n");
        }
    }
//SW: END: remove from local bloomfilter.

    if (publish_stats_dataobject) {
        CacheReplacementTotalOrder *replacement = 
            new CacheReplacementTotalOrder(
                getManager(),
                "Timestamp",
                "PublisherID",
                "CacheStrategyUtility",
                "stats");
        // only keep the most up to date stats in the data base
        stats_replacement_strat =
            new CacheStrategyReplacementPurger(
                getManager(),
                replacement,
                NULL,
                false);

        if (!stats_replacement_strat) {
            HAGGLE_ERR("Could not allocate replacement strat\n");
        }
        else {
            stats_replacement_strat->start();
        }
    }

    periodicPurgeEventType = registerEventType("periodic purge event", onPeriodicEvent);
    periodicPurgeEvent = new Event(periodicPurgeEventType);
    // we re-use the event
	periodicPurgeEvent->setAutoDelete(false);

    firePeriodic();

    if (!purgeOnInsert && (pollPeriodMs <= 0)) {
        HAGGLE_DBG("WARNING: All purging is disabled, was this intended?\n");
    }

    // add debug printing 

    HAGGLE_DBG("Successfully initialized utiltiy cache strategy, knapsack optimizer: %s, global optimizer: %s, utiltiy function: %s,  max capacity kb: %lld, watermark capacity kb: %lld, compute period ms: %d, purge poll period ms: %d, purge on insert; %s, manage only remote files: %s, publish stats dataobject: %s, db_purge: %s (%lld), self test:%s \n", getKnapsackOptimizer()->getName().c_str(), getGlobalOptimizer()->getName().c_str(), getUtilityFunction()->getName().c_str(),  max_capacity_kb, watermark_capacity_kb, computePeriodMs, pollPeriodMs, purgeOnInsert ? "yes" : "no", manage_only_remote_files ? "yes" : "no", publish_stats_dataobject ? "yes (CacheStrategyUtility=stats)" : "no", allow_db_purging ? "yes" : "no", db_size_threshold, self_test ? "yes" : "no");
}
コード例 #21
0
ファイル: entry.cpp プロジェクト: 1007650105/aseprite
bool Entry::onProcessMessage(Message* msg)
{
  switch (msg->type()) {

    case kTimerMessage:
      if (hasFocus() && static_cast<TimerMessage*>(msg)->timer() == &m_timer) {
        // Blinking caret
        m_state = m_state ? false: true;
        invalidate();
      }
      break;

    case kFocusEnterMessage:
      m_timer.start();

      m_state = true;
      invalidate();

      if (m_lock_selection) {
        m_lock_selection = false;
      }
      else {
        selectAllText();
        m_recent_focused = true;
      }
      break;

    case kFocusLeaveMessage:
      invalidate();

      m_timer.stop();

      if (!m_lock_selection)
        deselectText();

      m_recent_focused = false;
      break;

    case kKeyDownMessage:
      if (hasFocus() && !isReadOnly()) {
        // Command to execute
        EntryCmd cmd = EntryCmd::NoOp;
        KeyMessage* keymsg = static_cast<KeyMessage*>(msg);
        KeyScancode scancode = keymsg->scancode();

        switch (scancode) {

          case kKeyLeft:
            if (msg->ctrlPressed() || msg->altPressed())
              cmd = EntryCmd::BackwardWord;
            else if (msg->cmdPressed())
              cmd = EntryCmd::BeginningOfLine;
            else
              cmd = EntryCmd::BackwardChar;
            break;

          case kKeyRight:
            if (msg->ctrlPressed() || msg->altPressed())
              cmd = EntryCmd::ForwardWord;
            else if (msg->cmdPressed())
              cmd = EntryCmd::EndOfLine;
            else
              cmd = EntryCmd::ForwardChar;
            break;

          case kKeyHome:
            cmd = EntryCmd::BeginningOfLine;
            break;

          case kKeyEnd:
            cmd = EntryCmd::EndOfLine;
            break;

          case kKeyDel:
            if (msg->shiftPressed())
              cmd = EntryCmd::Cut;
            else
              cmd = EntryCmd::DeleteForward;
            break;

          case kKeyInsert:
            if (msg->shiftPressed())
              cmd = EntryCmd::Paste;
            else if (msg->ctrlPressed())
              cmd = EntryCmd::Copy;
            break;

          case kKeyBackspace:
            cmd = EntryCmd::DeleteBackward;
            break;

          default:
            // Map common Windows shortcuts for Cut/Copy/Paste
#if defined __APPLE__
            if (msg->onlyCmdPressed())
#else
            if (msg->onlyCtrlPressed())
#endif
            {
              switch (scancode) {
                case kKeyX: cmd = EntryCmd::Cut; break;
                case kKeyC: cmd = EntryCmd::Copy; break;
                case kKeyV: cmd = EntryCmd::Paste; break;
                case kKeyA: cmd = EntryCmd::SelectAll; break;
              }
            }
            else if (getManager()->isFocusMovementKey(msg)) {
              break;
            }
            else if (keymsg->unicodeChar() >= 32) {
              // Ctrl and Alt must be unpressed to insert a character
              // in the text-field.
              if ((msg->keyModifiers() & (kKeyCtrlModifier | kKeyAltModifier)) == 0) {
                cmd = EntryCmd::InsertChar;
              }
            }
            break;
        }

        if (cmd == EntryCmd::NoOp)
          break;

        executeCmd(cmd, keymsg->unicodeChar(),
                   (msg->shiftPressed()) ? true: false);
        return true;
      }
      break;

    case kMouseDownMessage:
      captureMouse();

    case kMouseMoveMessage:
      if (hasCapture()) {
        gfx::Point mousePos = static_cast<MouseMessage*>(msg)->position();
        base::utf8_const_iterator utf8_begin = base::utf8_const_iterator(getText().begin());
        base::utf8_const_iterator utf8_end = base::utf8_const_iterator(getText().end());
        int textlen = base::utf8_length(getText());
        int c, x;

        bool move = true;
        bool is_dirty = false;

        // Backward scroll
        if (mousePos.x < getBounds().x) {
          if (m_scroll > 0) {
            m_caret = --m_scroll;
            move = false;
            is_dirty = true;
            invalidate();
          }
        }
        // Forward scroll
        else if (mousePos.x >= getBounds().x2()) {
          if (m_scroll < textlen - getAvailableTextLength()) {
            m_scroll++;
            x = getBounds().x + this->border_width.l;
            for (c=m_scroll; utf8_begin != utf8_end; ++c) {
              int ch = (c < textlen ? *(utf8_begin+c) : ' ');

              x += getFont()->charWidth(ch);
              if (x > getBounds().x2()-this->border_width.r) {
                c--;
                break;
              }
            }
            m_caret = c;
            move = false;
            is_dirty = true;
            invalidate();
          }
        }

        c = getCaretFromMouse(static_cast<MouseMessage*>(msg));

        if (static_cast<MouseMessage*>(msg)->left() ||
            (move && !isPosInSelection(c))) {
          // Move caret
          if (move) {
            if (m_caret != c) {
              m_caret = c;
              is_dirty = true;
              invalidate();
            }
          }

          // Move selection
          if (m_recent_focused) {
            m_recent_focused = false;
            m_select = m_caret;
          }
          else if (msg->type() == kMouseDownMessage)
            m_select = m_caret;
        }

        // Show the caret
        if (is_dirty) {
          m_timer.start();
          m_state = true;
        }

        return true;
      }
      break;

    case kMouseUpMessage:
      if (hasCapture()) {
        releaseMouse();

        MouseMessage* mouseMsg = static_cast<MouseMessage*>(msg);
        if (mouseMsg->right()) {
          // This flag is disabled in kFocusEnterMessage message handler.
          m_lock_selection = true;

          showEditPopupMenu(mouseMsg->position());
          requestFocus();
        }
      }
      return true;

    case kDoubleClickMessage:
      forwardWord();
      m_select = m_caret;
      backwardWord();
      invalidate();
      return true;

    case kMouseEnterMessage:
    case kMouseLeaveMessage:
      // TODO theme stuff
      if (isEnabled())
        invalidate();
      break;
  }

  return Widget::onProcessMessage(msg);
}
コード例 #22
0
/*
 * Callback when a new data object is inserted. Updates the utility strategy
 * state and notifies the utility functions.
 */
void
CacheStrategyUtility::_handleNewDataObject(
    DataObjectRef &dObj)
{
    if (!isResponsibleForDataObject(dObj)) {
        //HAGGLE_DBG("Ignoring data object, in-eligible for caching\n");
        return;
    }

    if (stats_replacement_strat && stats_replacement_strat->isResponsibleForDataObject(dObj)) {
        stats_replacement_strat->handleNewDataObject(dObj);
        return;
    }

    string id = string(dObj->getIdStr());

    if (utilMetadata.find(id) != utilMetadata.end()) {
        // the DO is already in the cache!
        HAGGLE_DBG("Received data object already in the cache: %s\n", id.c_str());
        current_dupe_do_recv++;
        return;
    }

    getUtilityFunction()->notifyInsertion(dObj);

    int cost = dObj->getOrigDataLen();
    // NOTE: we handle zero sized data objects by "faking"
    // a size of 1.
    if (cost == 0) {
        cost = 1; 
    }

    string strResults="";
    if (Trace::trace.getTraceType() == TRACE_TYPE_DEBUG2) {
        strResults.append(id);
        strResults.append("[I]=");
    }
    double utiltiy = getUtilityFunction()->compute(id, strResults);
    HAGGLE_DBG2("%s --> %f\n", strResults.c_str(), utiltiy);
    Timeval now = Timeval::now();

    bool purgeNow = false;
    if (utiltiy < getGlobalOptimizer()->getMinimumThreshold()) {
        HAGGLE_DBG("Minimum threshold for incoming data object %s is insufficient: %f < %f\n", id.c_str(), utiltiy, getGlobalOptimizer()->getMinimumThreshold());
        current_drop_on_insert++;
        purgeNow = true;
    }

    if (!purgeOnInsert && ((current_size + cost) > max_capacity_kb*1024))  {
        HAGGLE_DBG("Cache is full and purge on insert is disabled, evicting new data object!\n");
        purgeNow = true;
        total_do_hard_evicted++;
        total_do_hard_evicted_bytes += cost;
    }

    if (purgeNow) {
        // we need to properly remove from bloomfilter even when capacity is violated
        getUtilityFunction()->notifyDelete(dObj);

        // CBMEN, HL - Begin
        // Remove any pending send events for this data object
        HAGGLE_STAT("purging send events for dObj %s\n", dObj->getIdStr());
        getManager()->getKernel()->cancelEvents(EVENT_TYPE_DATAOBJECT_SEND, dObj);
        // CBMEN, HL, End

        // delayed delete (although never inserted)
        if (!keep_in_bloomfilter) {
            int delay = (bloomfilter_remove_delay_ms <= 0) ? 1000 : bloomfilter_remove_delay_ms;
            DataObjectId_t *heapId = (DataObjectId_t *)malloc(sizeof(DataObjectId_t));
            DataObject::idStrToId(id, *heapId);
            getManager()->getKernel()->addEvent(new Event(bloomfilterRemoveDelayEventType, heapId, delay/(double)1000));
        }

        return;
    }

    DataObjectUtilityMetadata *do_metadata = new DataObjectUtilityMetadata(
        dObj,
        id,
        cost,
        utiltiy,
        now,
        dObj->getCreateTime());

    if (purgeOnInsert) {
        do_metadata->setEnableDeletion(false);
    }

    if (false == utilMetadata.insert(make_pair(id, do_metadata)).second) {
        HAGGLE_ERR("Somehow data object already in cache\n"); 
        delete do_metadata;
        return;
    }

    current_size += cost;
    current_num_do++;
    total_do_inserted++;
    total_do_inserted_bytes += cost;

    if (!purgeOnInsert) {
        getManager()->insertDataObjectIntoDataStore(dObj);
        return;
    }

    bool was_deleted = false;
    _purgeCache(id, &was_deleted);

    if (was_deleted) {
        HAGGLE_DBG("Purged incoming data object %s on insert.\n", id.c_str());
        current_drop_on_insert++;
        return;
    }

    // DO still in cache, mark to allow deletion in future
    do_metadata->setEnableDeletion(true);
    getManager()->insertDataObjectIntoDataStore(dObj);
}
コード例 #23
0
ファイル: TUICore.hpp プロジェクト: gogo1207/QuadAssault
bool TUICore<T>::isTopUI()
{
    return getManager()->isTopUI( this );
}
コード例 #24
0
/**
 * The main function to purge the cache and recompute utilities. 
 * If HAGGLE_DEBUG2 is set, this will add a new debug printout per utility computation,
 * which wills how the results of each individual utility value per data object.
 * Useful for verifying new utilities are acting correctly, not recommended for production
 * run.   To use this feature, pass any non empty string to getUtilityFunction()->compute(id, string).
 * The compute() routines will append current values and status for the data object identified by 'id'
 * only if the string being passed is non empty.   If the string is empty, the routines ignore it.
 *
 */
void
CacheStrategyUtility::_purgeCache(string doid, bool *o_was_deleted)
{
    List<DataObjectUtilityMetadata *> process_dos;
    List<DataObjectUtilityMetadata *> delete_dos;
    long long total_size = 0;
    // iterate across data objects and compute utilities for
    // DOS that have not been computed recently
    for (do_util_metadata_t::iterator it = utilMetadata.begin(); it != utilMetadata.end(); it++) {
        DataObjectUtilityMetadata *do_info = (*it).second;
        Timeval now = Timeval::now();
        if (!do_info) {
            HAGGLE_ERR("NULL DO in cache\n");
            continue;
        }
        total_size += do_info->getCost();
        // was the utility recently computed?
        double delta = now.getTimeAsMilliSecondsDouble() - do_info->getComputedTime().getTimeAsMilliSecondsDouble();
        if (delta > computePeriodMs) {
            string strResults="";
            if (Trace::trace.getTraceType() == TRACE_TYPE_DEBUG2) {
              strResults.append(do_info->getId());
              strResults.append("[T]=");
            }
            double new_utility = getUtilityFunction()->compute(do_info->getId(), strResults);
            do_info->setUtility(new_utility, now);
            HAGGLE_DBG2("%s --> %f\n", strResults.c_str(), new_utility);
        }

        // does the utility meet the threshold?
        if (do_info->getUtility() < getGlobalOptimizer()->getMinimumThreshold()) {
            delete_dos.push_front(do_info);
        }
        else {
            process_dos.push_front(do_info);
        }
    }

    if (total_size != current_size) {
        HAGGLE_ERR("Fatal error: count mismatch of cache sizes! (%lld != %lld)\n", total_size, current_size);
        return;
    }

    if (total_size > (watermark_capacity_kb*1024)) {
        CacheKnapsackOptimizerResults results = getKnapsackOptimizer()->solve(&process_dos, &delete_dos, watermark_capacity_kb*1024 );
        if (results.getHadError()) {
            HAGGLE_ERR("Knapsack optimizer failed\n");
        }
    }
    else {
        //HAGGLE_DBG("High water mark short-circuit, bypassing knapsack...\n");
    }


    int num_deleted = 0;
    long long bytes_freed = 0;

    while (!delete_dos.empty()) {
        DataObjectUtilityMetadata *to_delete = delete_dos.front();
        delete_dos.pop_front();
        if (!to_delete) {
            HAGGLE_ERR("NULL utility\n");
            continue;
        }
        DataObjectId_t id;
        DataObject::idStrToId(to_delete->getId(), id);
		bool deletionEnabled = to_delete->getEnableDeletion();

        if (to_delete->getId() == doid && o_was_deleted) {
            *o_was_deleted = true;
        }

        bytes_freed += to_delete->getCost();

        num_deleted++;

        // some DOs should not be deleted immedaitely 
        // (they may not even be inserted yet)
        if (deletionEnabled) {
            getManager()->getKernel()->getDataStore()->deleteDataObject(id, true);
        }

        DataObjectRef stale_dobj = to_delete->getDataObject();
        // SW: this will delete "to_delete"
        _handleDeletedDataObject(stale_dobj);
    }

    // sanity check
    if (current_size > (watermark_capacity_kb*1024)) {
        HAGGLE_ERR("Optimizer failed (did not remove enough bytes)\n");
        return;
    }

//JM: start mem purging
    if (allow_db_purging && (current_num_do > db_size_threshold)) {
        CacheKnapsackOptimizerResults results = getKnapsackOptimizer()->solve(&process_dos, &delete_dos, db_size_threshold+1, true );
        if (results.getHadError()) {
            HAGGLE_ERR("Knapsack optimizer failed\n");
        }
    }
    unsigned int db_num_deleted = 0;

    while (!delete_dos.empty()) {
        DataObjectUtilityMetadata *to_delete = delete_dos.front();
        delete_dos.pop_front();
        if (!to_delete) {
            HAGGLE_ERR("NULL utility\n");
            continue;
        }
        DataObjectId_t id;
        DataObject::idStrToId(to_delete->getId(), id);
		bool deletionEnabled = to_delete->getEnableDeletion();

        if (to_delete->getId() == doid && o_was_deleted) {
            *o_was_deleted = true;
        }

        db_num_deleted++;

        // some DOs should not be deleted immedaitely 
        // (they may not even be inserted yet)
        if (deletionEnabled) {
            getManager()->getKernel()->getDataStore()->deleteDataObject(id, true);
        }

        DataObjectRef stale_dobj = to_delete->getDataObject();
        // SW: this will delete "to_delete"
        _handleDeletedDataObject(stale_dobj, true);
    }

    // JM: End

    if (publish_stats_dataobject) {
        _publishStatsDataObject();
    }

	// SW: NOTE: these numbers will be updated when the delete callbacks occur
    HAGGLE_DBG("Removed %d data objects, freed: %lld bytes: total capacity: %.2f\%, watermark capacity: %.2f\% , Purged %d DB entries\n", num_deleted, bytes_freed, 100*current_size/((double)max_capacity_kb * 1024), 100*current_size/((double)watermark_capacity_kb * 1024), db_num_deleted);
}
コード例 #25
0
	//---------------------------------------------------------------------
	PageContent* SimplePageContentCollection::createContent(const String& typeName)
	{
		PageContent* c = getManager()->createContent(typeName);
		mContentList.push_back(c);
		return c;
	}
コード例 #26
0
void ItemController::collectItem(unsigned itemType)
{
	((LuckyLeprechauns&)getManager()).getPlayer().getLeprechaun().collectItem(itemType);
	setEnabled(false);
}