Ejemplo n.º 1
0
NTSTATUS
DriverEntry(
	IN PDRIVER_OBJECT DriverObject,
	IN PUNICODE_STRING RegistryPath
	)
{
	NTSTATUS status;

	DebugPrint(("Yt driver loaded.\n"));

	YtDriverObject = DriverObject;

	//Inicialize spin-lock and head of list.
	time1 = (PLARGE_INTEGER) YtAlloc(NonPagedPool, sizeof(LARGE_INTEGER));
	time2 = (PLARGE_INTEGER) YtAlloc(NonPagedPool, sizeof(LARGE_INTEGER));
	time.QuadPart = 0;
	count.QuadPart = 0;

	//Save registry path
	YtRegistryPath.MaximumLength = RegistryPath->Length
									+ sizeof(UNICODE_NULL);
	YtRegistryPath.Buffer = (PWSTR) YtAlloc(NonPagedPool, YtRegistryPath.MaximumLength);
	if (YtRegistryPath.Buffer != NULL)
	{
		RtlCopyUnicodeString(&YtRegistryPath, RegistryPath);
	} else {
		YtRegistryPath.Length = 0;
		YtRegistryPath.MaximumLength = 0;
	}

	//Create dispatch points
	PDRIVER_DISPATCH *dispatch;
	ULONG i;
	for (i = 0, dispatch = DriverObject->MajorFunction;
		i <= IRP_MJ_MAXIMUM_FUNCTION;
		i++, dispatch++) {

		*dispatch = YtDispatchEmpty;
	}

	//Set up the device driver entry points.
	DriverObject->MajorFunction[IRP_MJ_CREATE]          = YtDispatchCreateClose;
	DriverObject->MajorFunction[IRP_MJ_CLOSE]           = YtDispatchCreateClose;
	DriverObject->MajorFunction[IRP_MJ_CLEANUP]         = YtDispatchCreateClose;
	DriverObject->MajorFunction[IRP_MJ_READ]            = YtDispatchRead;
	DriverObject->MajorFunction[IRP_MJ_WRITE]           = YtDispatchWrite;
	DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL]  = YtDeviceControl;
	
	DriverObject->MajorFunction[IRP_MJ_SHUTDOWN]        = YtShutdownFlush;
	DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS]   = YtShutdownFlush;
	DriverObject->MajorFunction[IRP_MJ_PNP]             = YtDispatchPnP;
	DriverObject->MajorFunction[IRP_MJ_POWER]           = YtDispatchPower;

	DriverObject->DriverExtension->AddDevice            = YtAddDevice;//YtAddDeviceStub;
	DriverObject->DriverUnload                          = YtUnload;

/*	PWSTR devlist;
	NTSTATUS dlstatus = IoGetDeviceInterfaces(
		&GUID_DEVINTERFACE_DISK,
		NULL,
		0,
		&devlist
		);

	if(NT_SUCCESS(dlstatus))
	{
		DebugPrint(("Yt: device list received successfully: %X\n", devlist));

		PWSTR buf = devlist;
		while( *buf != L'\0')
		{
			DebugPrint(("Yt: Disk device detected: %ws\n", buf));

			UNICODE_STRING DeviceName;
			RtlInitUnicodeString(&DeviceName, buf);

			PFILE_OBJECT FileObject;
			PDEVICE_OBJECT DeviceObject;

			NTSTATUS obstatus = IoGetDeviceObjectPointer(
				&DeviceName,
				FILE_READ_DATA | FILE_WRITE_DATA,
				&FileObject,
				&DeviceObject
				);

			if(NT_SUCCESS(obstatus))
			{
				DebugPrint(("Yt: Successfully got object pointer for device %ws\n", buf));

				//YtAddDevice(DriverObject, DeviceObject);
				ObDereferenceObject(FileObject);
			}
			else
			{
				DebugPrint(("Yt: Unable to get object pointer for device %ws\n", buf));
			}

			buf += wcslen(buf)+1;
		}
		ExFreePool(devlist);
	}
	else
	{
		DebugPrint(("Yt: device list receiving failed.\n"));
	}*/

#if DBG
	DebugPrint(("Yt: launching RB-tree testing...\n"));
	launch_rb_tree_testing();
#endif

	status = YtCreateFDO(DriverObject);

	return status;
}
Ejemplo n.º 2
0
int Broadcast::Bind(unsigned short port)
{
    SOCKADDR_IN addr;
    int result;
    unsigned short i;
    BOOL istrue=TRUE;

    //If called a second time reintialize
    if (m_sock != INVALID_SOCKET)
        closesocket(m_sock);

    m_sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);

    if (m_sock==INVALID_SOCKET)
    {
        result=WSAGetLastError();
        DebugPrint("Failed to create socket error<%d>\n",result);
        return result;
    }


    //Create a socket for broadcasting 
    //and that doesn't linge on close
    //should set buffer max to 512
/*
    if (setsockopt(m_sock,SOL_SOCKET,
            SO_BROADCAST,(const char *)&istrue,sizeof(istrue))) {
        result = WSAGetLastError();
        DebugPrint("Failed to setsockopt SO_BROADCAST error<%d>\n",result);
        closesocket(m_sock);
        m_sock=INVALID_SOCKET;
        return result;
    }
*/
    //remember that TCP/IP and UDP ports are seperate
    //and so even with TCP/IP ports all used we shouldn't
    //have a problem binding to a port. So no retry on port
    ZeroMemory(&addr,sizeof(SOCKADDR_IN));
    ZeroMemory(&m_addr,sizeof(SOCKADDR_IN));
    addr.sin_family=AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(port);

    //For broadcast address we don't want to bind to the port we want to send to
    for (i=10000;i<0xFFFF;i++) {
        if (i==port)
            continue;

        addr.sin_port = htons(i);
        DebugPrint("Tring to bind on port<%d>\n",i);
        if (result=bind(m_sock,(SOCKADDR *)&addr,sizeof(SOCKADDR_IN)))
        {
            result=WSAGetLastError();
            if (result!= WSAEADDRINUSE) {
                DebugPrint("Failed to bind error<%d>\n",result);
                closesocket(m_sock);
                m_sock=INVALID_SOCKET;
                return result;
            }
        }
        else
            break;
    }

    if (result) {
        DebugPrint("Failed to bind to any address\n");
        closesocket(m_sock);
        m_sock=INVALID_SOCKET;
    };    
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_BROADCAST;
    CopyMemory(&m_addr,&addr,sizeof(SOCKADDR_IN));

    //We are good to send
    return NULL;
};
Ejemplo n.º 3
0
void CPlayer::Init(/* PlayerTypes */ int type)
{
	this->Units.resize(0);
	this->FreeWorkers.resize(0);

	//  Take first slot for person on this computer,
	//  fill other with computer players.
	if (type == PlayerPerson && !NetPlayers) {
		if (!ThisPlayer) {
			ThisPlayer = this;
		} else {
			type = PlayerComputer;
		}
	}
	if (NetPlayers && NumPlayers == NetLocalPlayerNumber) {
		ThisPlayer = &Players[NetLocalPlayerNumber];
	}

	if (NumPlayers == PlayerMax) {
		static int already_warned;

		if (!already_warned) {
			DebugPrint("Too many players\n");
			already_warned = 1;
		}
		return;
	}

	//  Make simple teams:
	//  All person players are enemies.
	int team;
	switch (type) {
		case PlayerNeutral:
		case PlayerNobody:
		default:
			team = 0;
			this->SetName("Neutral");
			break;
		case PlayerComputer:
			team = 1;
			this->SetName("Computer");
			break;
		case PlayerPerson:
			team = 2 + NumPlayers;
			this->SetName("Person");
			break;
		case PlayerRescuePassive:
		case PlayerRescueActive:
			// FIXME: correct for multiplayer games?
			this->SetName("Computer");
			team = 2 + NumPlayers;
			break;
	}
	DebugPrint("CreatePlayer name %s\n" _C_ this->Name.c_str());

	this->Type = type;
	this->Race = 0;
	this->Team = team;
	this->Enemy = 0;
	this->Allied = 0;
	this->AiName = "ai-passive";

	//  Calculate enemy/allied mask.
	for (int i = 0; i < NumPlayers; ++i) {
		switch (type) {
			case PlayerNeutral:
			case PlayerNobody:
			default:
				break;
			case PlayerComputer:
				// Computer allied with computer and enemy of all persons.
				if (Players[i].Type == PlayerComputer) {
					this->Allied |= (1 << i);
					Players[i].Allied |= (1 << NumPlayers);
				} else if (Players[i].Type == PlayerPerson || Players[i].Type == PlayerRescueActive) {
					this->Enemy |= (1 << i);
					Players[i].Enemy |= (1 << NumPlayers);
				}
				break;
			case PlayerPerson:
				// Humans are enemy of all?
				if (Players[i].Type == PlayerComputer || Players[i].Type == PlayerPerson) {
					this->Enemy |= (1 << i);
					Players[i].Enemy |= (1 << NumPlayers);
				} else if (Players[i].Type == PlayerRescueActive || Players[i].Type == PlayerRescuePassive) {
					this->Allied |= (1 << i);
					Players[i].Allied |= (1 << NumPlayers);
				}
				break;
			case PlayerRescuePassive:
				// Rescue passive are allied with persons
				if (Players[i].Type == PlayerPerson) {
					this->Allied |= (1 << i);
					Players[i].Allied |= (1 << NumPlayers);
				}
				break;
			case PlayerRescueActive:
				// Rescue active are allied with persons and enemies of computer
				if (Players[i].Type == PlayerComputer) {
					this->Enemy |= (1 << i);
					Players[i].Enemy |= (1 << NumPlayers);
				} else if (Players[i].Type == PlayerPerson) {
					this->Allied |= (1 << i);
					Players[i].Allied |= (1 << NumPlayers);
				}
				break;
		}
	}

	//  Initial default incomes.
	for (int i = 0; i < MaxCosts; ++i) {
		this->Incomes[i] = DefaultIncomes[i];
	}

	//  Initial max resource amounts.
	for (int i = 0; i < MaxCosts; ++i) {
		this->MaxResources[i] = DefaultResourceMaxAmounts[i];
	}

	memset(this->UnitTypesCount, 0, sizeof(this->UnitTypesCount));

	this->Supply = 0;
	this->Demand = 0;
	this->NumBuildings = 0;
	this->Score = 0;

	this->Color = PlayerColors[NumPlayers][0];

	if (Players[NumPlayers].Type == PlayerComputer || Players[NumPlayers].Type == PlayerRescueActive) {
		this->AiEnabled = true;
	} else {
		this->AiEnabled = false;
	}
	++NumPlayers;
}
Ejemplo n.º 4
0
/**
**  Draw unit on map.
*/
void CUnit::Draw(const CViewport &vp) const
{
	int frame;
	int state;
	int constructed;
	const CConstructionFrame *cframe;
	const CUnitType *type;

	if (this->Destroyed || this->Container || this->Type->Revealer) { // Revealers are not drawn
		return;
	}

	bool IsVisible = this->IsVisible(*ThisPlayer);

	// Those should have been filtered. Check doesn't make sense with ReplayRevealMap
	Assert(ReplayRevealMap || this->Type->VisibleUnderFog || IsVisible);

	int player = this->RescuedFrom ? this->RescuedFrom->Index : this->Player->Index;
	int action = this->CurrentAction();
	PixelPos screenPos;
	if (ReplayRevealMap || IsVisible) {
		screenPos = vp.MapToScreenPixelPos(this->GetMapPixelPosTopLeft());
		type = this->Type;
		frame = this->Frame;
		state = (action == UnitActionBuilt) | ((action == UnitActionUpgradeTo) << 1);
		constructed = this->Constructed;
		// Reset Type to the type being upgraded to
		if (action == UnitActionUpgradeTo) {
			const COrder_UpgradeTo &order = *static_cast<COrder_UpgradeTo *>(this->CurrentOrder());

			type = &order.GetUnitType();
		}

		if (this->CurrentAction() == UnitActionBuilt) {
			COrder_Built &order = *static_cast<COrder_Built *>(this->CurrentOrder());

			cframe = &order.GetFrame();
		} else {
			cframe = NULL;
		}
	} else {
		screenPos = vp.TilePosToScreen_TopLeft(this->Seen.tilePos);

		screenPos.x += this->Seen.IX;
		screenPos.y += this->Seen.IY;
		frame = this->Seen.Frame;
		type = this->Seen.Type;
		constructed = this->Seen.Constructed;
		state = this->Seen.State;
		cframe = this->Seen.CFrame;
	}

#ifdef DYNAMIC_LOAD
	if (!type->Sprite) {
		LoadUnitTypeSprite(type);
	}
#endif

	if (!IsVisible && frame == UnitNotSeen) {
		DebugPrint("FIXME: Something is wrong, unit %d not seen but drawn time %lu?.\n" _C_
				   UnitNumber(*this) _C_ GameCycle);
		return;
	}


	if (state == 1 && constructed && cframe) {
		DrawConstructionShadow(*type, cframe, frame, screenPos);
	} else {
		if (action != UnitActionDie) {
			DrawShadow(*type, frame, screenPos);
		}
	}

	//
	// Show that the unit is selected
	//
	DrawUnitSelection(vp, *this);

	//
	// Adjust sprite for Harvesters.
	//
	CPlayerColorGraphic *sprite = type->Sprite;
	if (type->Harvester && this->CurrentResource) {
		ResourceInfo *resinfo = type->ResInfo[this->CurrentResource];
		if (this->ResourcesHeld) {
			if (resinfo->SpriteWhenLoaded) {
				sprite = resinfo->SpriteWhenLoaded;
			}
		} else {
			if (resinfo->SpriteWhenEmpty) {
				sprite = resinfo->SpriteWhenEmpty;
			}
		}
	}

	//
	// Now draw!
	// Buildings under construction/upgrade/ready.
	//
	if (state == 1) {
		if (constructed && cframe) {
			const PixelPos pos(screenPos + (type->GetPixelSize()) / 2);
			DrawConstruction(GameSettings.Presets[player].PlayerColor, cframe, *type, frame, pos);
		} else {
			DrawUnitType(*type, sprite, GameSettings.Presets[player].PlayerColor, frame, screenPos);
		}
		//
		// Draw the future unit type, if upgrading to it.
		//
	} else {
		DrawUnitType(*type, sprite, GameSettings.Presets[player].PlayerColor, frame, screenPos);
	}

	// Unit's extras not fully supported.. need to be decorations themselves.
	DrawInformations(*this, *type, screenPos);
}
Ejemplo n.º 5
0
/**
**  Return the value corresponding.
**
**  @param unit   Unit.
**  @param index  Index of the variable.
**  @param e      Component of the variable.
**  @param t      Which var use (0:unit, 1:Type, 2:Stats)
**
**  @return       Value corresponding
*/
UStrInt GetComponent(const CUnit &unit, int index, EnumVariable e, int t)
{
	UStrInt val;
	CVariable *var;

	Assert((unsigned int) index < UnitTypeVar.GetNumberVariable());

	switch (t) {
		case 0: // Unit:
			var = &unit.Variable[index];
			break;
		case 1: // Type:
			var = &unit.Type->MapDefaultStat.Variables[index];
			break;
		case 2: // Stats:
			var = &unit.Stats->Variables[index];
			break;
		default:
			DebugPrint("Bad value for GetComponent: t = %d" _C_ t);
			var = &unit.Variable[index];
			break;
	}

	switch (e) {
		case VariableValue:
			val.type = USTRINT_INT;
			val.i = var->Value;
			break;
		case VariableMax:
			val.type = USTRINT_INT;
			val.i = var->Max;
			break;
		case VariableIncrease:
			val.type = USTRINT_INT;
			val.i = var->Increase;
			break;
		case VariableDiff:
			val.type = USTRINT_INT;
			val.i = var->Max - var->Value;
			break;
		case VariablePercent:
			Assert(unit.Variable[index].Max != 0);
			val.type = USTRINT_INT;
			val.i = 100 * var->Value / var->Max;
			break;
		case VariableName:
			if (index == GIVERESOURCE_INDEX) {
				val.type = USTRINT_STR;
				val.i = unit.Type->GivesResource;
				val.s = DefaultResourceNames[unit.Type->GivesResource].c_str();
			} else if (index == CARRYRESOURCE_INDEX) {
				val.type = USTRINT_STR;
				val.i = unit.CurrentResource;
				val.s = DefaultResourceNames[unit.CurrentResource].c_str();
			} else {
				val.type = USTRINT_STR;
				val.i = index;
				val.s = UnitTypeVar.VariableNameLookup[index];
			}
			break;
	}
	return val;
}
Ejemplo n.º 6
0
// IRP_MJ_CREATE/IRP_MJ_CLOSE处理函数
NTSTATUS DispatchCreateClose(
    __in PDEVICE_OBJECT DeviceObject,
    __in PIRP Irp
    )
{
    PIO_STACK_LOCATION irpStack;
    NTSTATUS            status;
    PFILE_CONTEXT       fileContext;

    UNREFERENCED_PARAMETER(DeviceObject);

    PAGED_CODE();

    irpStack = IoGetCurrentIrpStackLocation(Irp);

    ASSERT(irpStack->FileObject != NULL);    

    switch (irpStack->MajorFunction)
    {
	case IRP_MJ_CREATE:
		{
			DebugPrint(("IRP_MJ_CREATE\n"));

			fileContext = (PFILE_CONTEXT)ExAllocatePoolWithQuotaTag(
				NonPagedPool, 
				sizeof(FILE_CONTEXT),
				TAG);

			if (NULL == fileContext) 
			{
				status =  STATUS_INSUFFICIENT_RESOURCES;
				break;
			}

			IoInitializeRemoveLock(&fileContext->FileRundownLock, TAG, 0, 0);

			ASSERT(irpStack->FileObject->FsContext == NULL);
			irpStack->FileObject->FsContext = (PVOID) fileContext;

			status = STATUS_SUCCESS;
			break;
		}

	case IRP_MJ_CLOSE:
		{
			DebugPrint(("IRP_MJ_CLOSE\n"));

			fileContext = irpStack->FileObject->FsContext;
			IoAcquireRemoveLock(&fileContext->FileRundownLock, 0);
			IoReleaseRemoveLockAndWait(&fileContext->FileRundownLock, 0);

			ExFreePoolWithTag(fileContext, TAG);

			status = STATUS_SUCCESS;
			break;
		}

	default:
		ASSERT(FALSE);  // should never hit this
		status = STATUS_NOT_IMPLEMENTED;
		break;
    }

    Irp->IoStatus.Status = status;
    Irp->IoStatus.Information = 0;
    IoCompleteRequest(Irp, IO_NO_INCREMENT);
    return status;
}
Ejemplo n.º 7
0
void AiNewDepotRequest(CUnit &worker)
{
#if 0
    DebugPrint("%d: Worker %d report: Resource [%d] too far from depot, returning time [%d].\n"
               _C_ worker->Player->Index _C_ worker->Slot
               _C_ worker->CurrentResource
               _C_ worker->Data.Move.Cycles);
#endif
    Assert(worker.CurrentAction() == UnitActionResource);
    COrder_Resource &order = *static_cast<COrder_Resource *>(worker.CurrentOrder());

    const Vec2i pos = order.GetHarvestLocation();

    if (pos.x != -1 && NULL != FindDepositNearLoc(*worker.Player, pos, 10, worker.CurrentResource)) {
        /*
         * New Depot has just be finished and worker just return to old depot
         * (far away) from new Deopt.
         */
        return;
    }
    CUnitType *best_type = NULL;
    int best_cost = 0;
    //int best_mask = 0;
    // Count the already made build requests.
    int counter[UnitTypeMax];

    AiGetBuildRequestsCount(*worker.Player->Ai, counter);

    const int n = AiHelpers.Depots[worker.CurrentResource - 1].size();

    for (int i = 0; i < n; ++i) {
        CUnitType &type = *AiHelpers.Depots[worker.CurrentResource - 1][i];

        if (counter[type.Slot]) { // Already ordered.
            return;
        }
        if (!AiRequestedTypeAllowed(*worker.Player, type)) {
            continue;
        }

        // Check if resources available.
        //int needmask = AiCheckUnitTypeCosts(type);
        int cost = 0;
        for (int c = 1; c < MaxCosts; ++c) {
            cost += type.Stats[worker.Player->Index].Costs[c];
        }

        if (best_type == NULL || (cost < best_cost)) {
            best_type = &type;
            best_cost = cost;
            //best_mask = needmask;
        }
    }

    if (best_type) {
        //if(!best_mask) {
        AiBuildQueue queue;

        queue.Type = best_type;
        queue.Want = 1;
        queue.Made = 0;
        queue.Pos = pos;

        worker.Player->Ai->UnitTypeBuilt.push_back(queue);

        DebugPrint("%d: Worker %d report: Requesting new depot near [%d,%d].\n"
                   _C_ worker.Player->Index _C_ UnitNumber(worker)
                   _C_ queue.Pos.x _C_ queue.Pos.y);
        /*
        } else {
        	AiPlayer->NeededMask |= best_mask;
        }
        */
    }
}
Ejemplo n.º 8
0
VOID
ScsiPortCompleteRequest(
    IN PVOID HwDeviceExtension,
    IN UCHAR PathId,
    IN UCHAR TargetId,
    IN UCHAR Lun,
    IN UCHAR SrbStatus
)

/*++

Routine Description:

    Complete all active requests for the specified logical unit.

Arguments:

    DeviceExtenson - Supplies the HBA miniport driver's adapter data storage.

    TargetId, Lun and PathId - specify device address on a SCSI bus.

    SrbStatus - Status to be returned in each completed SRB.

Return Value:

    None.

--*/

{
    PADAPTER_EXTENSION deviceExtension = GET_FDO_EXTENSION(HwDeviceExtension);
    ULONG binNumber;

    for (binNumber = 0; binNumber < NUMBER_LOGICAL_UNIT_BINS; binNumber++) {

        PLOGICAL_UNIT_BIN bin = &deviceExtension->LogicalUnitList[binNumber];
        PLOGICAL_UNIT_EXTENSION logicalUnit;
        ULONG limit = 0;

        logicalUnit = bin->List;

        DebugPrint((2, "ScsiPortCompleteRequest: Completing requests in "
                    "bin %d [%#p]\n",
                    binNumber, bin));

        for(logicalUnit = bin->List;
                logicalUnit != NULL;
                logicalUnit = logicalUnit->NextLogicalUnit) {

            PLIST_ENTRY entry;

            ASSERT(limit++ < 1000);

            //
            // See if this logical unit matches the pattern.  Check for -1
            // first since this seems to be the most popular way to complete
            // requests.
            //

            if (((PathId == SP_UNTAGGED) || (PathId == logicalUnit->PathId)) &&
                    ((TargetId == SP_UNTAGGED) ||
                     (TargetId == logicalUnit->TargetId)) &&
                    ((Lun == SP_UNTAGGED) || (Lun == logicalUnit->Lun))) {

                //
                // Complete any pending abort reqeusts.
                //

                if (logicalUnit->AbortSrb != NULL) {
                    logicalUnit->AbortSrb->SrbStatus = SrbStatus;

                    ScsiPortNotification(
                        RequestComplete,
                        HwDeviceExtension,
                        logicalUnit->AbortSrb
                    );
                }

                if(logicalUnit->CurrentUntaggedRequest != NULL) {

                    SpCompleteSrb(deviceExtension,
                                  logicalUnit->CurrentUntaggedRequest,
                                  SrbStatus);
                }

                //
                // Complete each of the requests in the queue.
                //

                entry = logicalUnit->RequestList.Flink;
                while (entry != &logicalUnit->RequestList) {
                    PSRB_DATA srbData;

                    ASSERT(limit++ < 1000);
                    srbData = CONTAINING_RECORD(entry, SRB_DATA, RequestList);
                    SpCompleteSrb(deviceExtension,  srbData, SrbStatus);
                    entry = srbData->RequestList.Flink;
                }

            }
        }
    }

    return;

} // end ScsiPortCompleteRequest()
Ejemplo n.º 9
0
ssize_t read_write_mode(int fd, OriginF fn, const char* hook_fn_name, uint32_t event, int timeout_so, Args && ... args)
{
    DebugPrint(dbg_hook, "hook %s. %s coroutine.", hook_fn_name, g_Scheduler.IsCoroutine() ? "In" : "Not in");

    if (!g_Scheduler.IsCoroutine()) {
        return fn(fd, std::forward<Args>(args)...);
    } else {
        int flags = fcntl(fd, F_GETFL, 0);
        if (flags & O_NONBLOCK)
            return fn(fd, std::forward<Args>(args)...);

        if (-1 == fcntl(fd, F_SETFL, flags | O_NONBLOCK))
            return fn(fd, std::forward<Args>(args)...);

        ssize_t n = fn(fd, std::forward<Args>(args)...);
        if (n == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
            // get timeout option.
            Task* tk = g_Scheduler.GetCurrentTask();
            uint64_t timer_id = 0;
            struct timeval timeout;
            socklen_t timeout_blen = sizeof(timeout);
            if (0 == getsockopt(fd, SOL_SOCKET, timeout_so, &timeout, &timeout_blen)) {
                if (timeout.tv_sec > 0 || timeout.tv_usec > 0) {
                    std::chrono::milliseconds duration{timeout.tv_sec * 1000 +
                        timeout.tv_usec / 1000};
                    DebugPrint(dbg_hook, "hook task(%s) %s timeout=%dms. fd=%d",
                            g_Scheduler.GetCurrentTaskDebugInfo(), hook_fn_name, (int)duration.count(), fd);
                    tk->IncrementRef(); // timer use ref.
                    timer_id = g_Scheduler.ExpireAt(duration, [=]{
                            g_Scheduler.IOBlockCancel(tk);
                            tk->DecrementRef(); // timer use ref.
                            });
                }
            }

            // add into epoll, and switch other context.
            g_Scheduler.IOBlockSwitch(fd, event);
            bool is_timeout = false;
            if (timer_id) {
                is_timeout = true;
                if (g_Scheduler.CancelTimer(timer_id)) {
                    is_timeout = false;
                    tk->DecrementRef(); // timer use ref.
                }
            }

            if (tk->wait_successful_ == 0) {
                if (is_timeout) {
                    fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
                    errno = EAGAIN;
                    return -1;
                } else {
                    fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
                    return fn(fd, std::forward<Args>(args)...);
                }
            }

            DebugPrint(dbg_hook, "continue task(%s) %s. fd=%d", g_Scheduler.GetCurrentTaskDebugInfo(), hook_fn_name, fd);
            n = fn(fd, std::forward<Args>(args)...);
        } else {
            DebugPrint(dbg_hook, "task(%s) syscall(%s) completed immediately. fd=%d",
                    g_Scheduler.GetCurrentTaskDebugInfo(), hook_fn_name, fd);
        }

        int e = errno;
        fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
        errno = e;
        return n;
    }
}
Ejemplo n.º 10
0
PVOID
ScsiPortGetLogicalUnit(
    IN PVOID HwDeviceExtension,
    IN UCHAR PathId,
    IN UCHAR TargetId,
    IN UCHAR Lun
)

/*++

Routine Description:

    Walk port driver's logical unit extension list searching
    for entry.

Arguments:

    HwDeviceExtension - The port driver's device extension follows
        the miniport's device extension and contains a pointer to
        the logical device extension list.

    PathId, TargetId and Lun - identify which logical unit on the
        SCSI buses.

Return Value:

    If entry found return miniport driver's logical unit extension.
    Else, return NULL.

--*/

{
    PADAPTER_EXTENSION deviceExtension;
    PLOGICAL_UNIT_EXTENSION logicalUnit;

    DebugPrint((3, "ScsiPortGetLogicalUnit: TargetId %d\n",
                TargetId));

    //
    // Get pointer to port driver device extension.
    //

    deviceExtension = GET_FDO_EXTENSION(HwDeviceExtension);

    //
    // Get a pointer to the logical unit.
    //

    logicalUnit = GetLogicalUnitExtension(deviceExtension,
                                          PathId,
                                          TargetId,
                                          Lun,
                                          FALSE,
                                          FALSE);

    if(logicalUnit != NULL) {

        return logicalUnit->HwLogicalUnitExtension;
    }

    return NULL;

} // end ScsiPortGetLogicalUnit()
Ejemplo n.º 11
0
VOID
ScsiPortLogError(
    IN PVOID HwDeviceExtension,
    IN PSCSI_REQUEST_BLOCK Srb OPTIONAL,
    IN UCHAR PathId,
    IN UCHAR TargetId,
    IN UCHAR Lun,
    IN ULONG ErrorCode,
    IN ULONG UniqueId
)

/*++

Routine Description:

    This routine saves the error log information, and queues a DPC if necessary.

Arguments:

    HwDeviceExtension - Supplies the HBA miniport driver's adapter data storage.

    Srb - Supplies an optional pointer to srb if there is one.

    TargetId, Lun and PathId - specify device address on a SCSI bus.

    ErrorCode - Supplies an error code indicating the type of error.

    UniqueId - Supplies a unique identifier for the error.

Return Value:

    None.

--*/

{
    PADAPTER_EXTENSION deviceExtension = GET_FDO_EXTENSION(HwDeviceExtension);
    PDEVICE_OBJECT DeviceObject = deviceExtension->CommonExtension.DeviceObject;
    PSRB_DATA srbData;
    PERROR_LOG_ENTRY errorLogEntry;

    //
    // If the error log entry is already full, then dump the error.
    //

    if (deviceExtension->InterruptData.InterruptFlags & PD_LOG_ERROR) {

#if SCSIDBG_ENABLED
        DebugPrint((1,"ScsiPortLogError: Dumping scsi error log packet.\n"));
        DebugPrint((1,
                    "PathId = %2x, TargetId = %2x, Lun = %2x, ErrorCode = %x, UniqueId = %x.",
                    PathId,
                    TargetId,
                    Lun,
                    ErrorCode,
                    UniqueId
                   ));
#endif
        return;
    }

    //
    // Save the error log data in the log entry.
    //

    errorLogEntry = &deviceExtension->InterruptData.LogEntry;

    errorLogEntry->ErrorCode = ErrorCode;
    errorLogEntry->TargetId = TargetId;
    errorLogEntry->Lun = Lun;
    errorLogEntry->PathId = PathId;
    errorLogEntry->UniqueId = UniqueId;

    //
    // Get the sequence number from the SRB data.
    //

    if (Srb != NULL) {

        srbData = Srb->OriginalRequest;

        ASSERT_SRB_DATA(srbData);

        errorLogEntry->SequenceNumber = srbData->SequenceNumber;
        errorLogEntry->ErrorLogRetryCount = srbData->ErrorLogRetryCount++;
    } else {
        errorLogEntry->SequenceNumber = 0;
        errorLogEntry->ErrorLogRetryCount = 0;
    }

    //
    // Indicate that the error log entry is in use.
    //

    deviceExtension->InterruptData.InterruptFlags |= PD_LOG_ERROR;

    //
    // Request a DPC be queued after the interrupt completes.
    //

    deviceExtension->InterruptData.InterruptFlags |= PD_NOTIFICATION_REQUIRED;

    return;

} // end ScsiPortLogError()
Ejemplo n.º 12
0
string ExactMatchingRule::ToString() const
{
  ostringstream os;
  os << "ExactMatchingRule [ " << DebugPrint(m_mwmId) << ", " << DebugPrint(m_feature) << " ]";
  return os.str();
}
Ejemplo n.º 13
0
Archivo: GSM.cpp Proyecto: fffaraz/gpst
int GSM::begin(long baud_rate){
	int response=-1;
	int cont=0;
	boolean norep=false;
	boolean turnedON=false;
	SetCommLineStatus(CLS_ATCMD);
	_cell.begin(baud_rate);
	setStatus(IDLE); 

	
	for (cont=0; cont<3; cont++){
		if (AT_RESP_ERR_NO_RESP == SendATCmdWaitResp("AT", 500, 100, "OK", 5)&&!turnedON) {		//check power
	    // there is no response => turn on the module
			#ifdef DEBUG_ON
				Serial.println("DB:NO RESP");
			#endif
			// generate turn on pulse
			digitalWrite(GSM_ON, HIGH);
			delay(1200);
			digitalWrite(GSM_ON, LOW);
			delay(10000);
			norep=true;
		}
		else{
			#ifdef DEBUG_ON
				Serial.println("DB:ELSE");
			#endif
			norep=false;
		}
	}
	
	if (AT_RESP_OK == SendATCmdWaitResp("AT", 500, 100, "OK", 5)){
		#ifdef DEBUG_ON
			Serial.println("DB:CORRECT BR");
		#endif
		turnedON=true;
	}
	if(cont==3&&norep){
		Serial.println("ERROR: SIM900 doesn't answer. Check power and serial pins in GSM.cpp");
		return 0;
	}


	if (AT_RESP_ERR_DIF_RESP == SendATCmdWaitResp("AT", 500, 100, "OK", 5)&&!turnedON){		//check OK
		#ifdef DEBUG_ON
			Serial.println("DB:DIFF RESP");
		#endif
		for (int i=1;i<8;i++){
			switch (i) {
			case 1:
			  _cell.begin(2400);
			  break;
			  
			case 2:
			  _cell.begin(4800);
			  break;
			  
			case 3:
			  _cell.begin(9600);
			  break;
			   
			case 4:
			  _cell.begin(19200);
			  break;
			  
			case 5:
			  _cell.begin(38400);
			  break;
			  
			case 6:
			  _cell.begin(57600);
			  break;
			  
			case 7:
			  _cell.begin(115200);
			  _cell.print("AT+IPR=9600\r");
			  _cell.begin(9600);
			  delay(500);
			  break;
  
			// if nothing else matches, do the default
			// default is optional
			}
					
			delay(100);

			#ifdef DEBUG_PRINT
				// parameter 0 - because module is off so it is not necessary 
				// to send finish AT<CR> here
				DebugPrint("DEBUG: Stringa ", 0);
				DebugPrint(buff, 0);
			#endif
				

			if (AT_RESP_OK == SendATCmdWaitResp("AT", 500, 100, "OK", 5)){
				#ifdef DEBUG_ON
					Serial.println("DB:FOUND PREV BR");
				#endif
				_cell.print("AT+IPR=");
				_cell.print(baud_rate);    
				_cell.print("\r"); // send <CR>
				delay(500);
				_cell.begin(baud_rate);
				delay(100);
				if (AT_RESP_OK == SendATCmdWaitResp("AT", 500, 100, "OK", 5)){
					#ifdef DEBUG_ON
						Serial.println("DB:OK BR");
					#endif
				}
				turnedON=true;
				break;					
			}
			#ifdef DEBUG_ON
				Serial.println("DB:NO BR");
			#endif			
		}
		// communication line is not used yet = free
		SetCommLineStatus(CLS_FREE);
		// pointer is initialized to the first item of comm. buffer
		p_comm_buf = &comm_buf[0];
	}

	SetCommLineStatus(CLS_FREE);

	if(turnedON){
		WaitResp(50, 50);
		InitParam(PARAM_SET_0);
		InitParam(PARAM_SET_1);//configure the module  
		Echo(0);               //enable AT echo
		setStatus(READY);
		return(1);

	}
	else{
		//just to try to fix some problems with 115200 baudrate
		_cell.begin(115200);
		delay(1000);
		_cell.print("AT+IPR=");
		_cell.print(baud_rate);    
		_cell.print("\r"); // send <CR>		
		return(0);
	}
}
Ejemplo n.º 14
0
void PatchDeformPW::BuildParamData(Object *obj, LocalPatchData *localData,PatchMesh *patch,Matrix3 patchTM,Matrix3 baseTM)
	{
	localData->numPatches = patch->numPatches;
//put our base mesh data into patch space
	Matrix3 tmFromBaseToPatch = baseTM * Inverse(patchTM);

	Matrix3 tmFromPatchToBase = patchTM * Inverse(baseTM);

	Tab<Point3> pointData;
	int pointCount = obj->NumPoints();
	pointData.SetCount(pointCount);

	Tab<int> closestPoint;
	closestPoint.SetCount(pointCount);

	localData->paramData.SetCount(pointCount);

	for (int i = 0; i < pointCount; i++)
		{
		Point3 p = obj->GetPoint(i);
		localData->paramData[i].initialLocalPoint = p;
		p = p * tmFromBaseToPatch;
		pointData[i] = p;
		closestPoint[i] = -1;
		}

	int numPatches = patch->numPatches;

//split the patches into 10x10 chunks
	Tab<Point3> patchPoints;
	patchPoints.SetCount(numPatches * 100);


	int ct = 0;
	for (int i = 0; i < numPatches; i++)
		{
		Patch *p = &patch->patches[i];

		if (p->type == PATCH_QUAD)
			{
			float u,v;
			float inc = 1.0f/(10.0f+1.0f);
			u = inc;
			v = inc;
			for (int y = 0; y < 10; y++)
				{
				u = inc;
				for (int x = 0; x < 10; x++)
					{
					Point3 pt = p->interp(patch, u, v);
					patchPoints[ct] = pt;
					ct++;
					u += inc;
					}
				v += inc;
				}

			}
		else ct += 100;
		}

	for (int i = 0; i < pointCount; i++)
		{
		int closest = -1;
		float d= 0.0f;
		for (int j = 0; j <  ct; j++)
			{
			float len = LengthSquared(patchPoints[j]-pointData[i]);
			if ((closest == -1) || (len<d))
				{
				d = len;
				closest = j;
				}
			}
		closestPoint[i] = closest/100;		
		}

	BitArray usedPatches;
	usedPatches.SetSize(numPatches);
	usedPatches.ClearAll();
	for (int i = 0; i < pointCount; i++)
		{
		usedPatches.Set(closestPoint[i]);
		}

	int sampleRate;
	Interval iv;
	iv = FOREVER;

	pblock->GetValue(pb_samplerate,0,sampleRate,iv);
	patchPoints.SetCount(sampleRate*sampleRate);

	

	for (int i = 0; i < numPatches; i++)
		{
		Patch *p = &patch->patches[i];

		if (ip)
			{
			TSTR name;
			name.printf(GetString(IDS_COMPLETED_PCT),(float) i / numPatches *100.0f);
			SetWindowText(GetDlgItem(hWnd,IDC_STATUS),name);
			}

		float inc = 1.0f/(sampleRate+1.0f);

		if ( (usedPatches[i]) && (p->type == PATCH_QUAD))
			{
			float u,v;
			
			u = inc;
			v = inc;
			ct = 0;
			for (int y = 0; y < sampleRate; y++)
				{
				u = inc;
				for (int x = 0; x < sampleRate; x++)
					{
					Point3 pt = p->interp(patch, u, v);
					patchPoints[ct] = pt;
					ct++;
					u += inc;
					}
				v += inc;
				}

			
			for (int j = 0; j < pointCount; j++)
				{

				if ((ip) && ((j%10) == 0))
					{
					TSTR name;
					name.printf(GetString(IDS_COMPLETED_PCT_W_COUNT),(float) i / numPatches *100.0f,j,pointCount);
					SetWindowText(GetDlgItem(hWnd,IDC_STATUS),name);
					}
				if (closestPoint[j] == i)
					{
					int closest = -1;
					float d= 0.0f;

					for (int k = 0; k <  sampleRate*sampleRate; k++)
						{
						float len = LengthSquared(patchPoints[k]-pointData[j]);
						if ((closest == -1) || (len<d))
							{
							d = len;
							closest = k;							
							}
						}	
					
					localData->paramData[j].uv.y = float (closest/sampleRate);
					localData->paramData[j].uv.x = float (closest - (localData->paramData[j].uv.y*sampleRate));

					localData->paramData[j].uv.y = (localData->paramData[j].uv.y +1) * inc;
					localData->paramData[j].uv.x = (localData->paramData[j].uv.x +1) * inc;		
					localData->paramData[j].patchIndex = i;

//get the u vec
					float u = localData->paramData[j].uv.x;
					float v = localData->paramData[j].uv.y;
					float delta = 1.0f/(sampleRate+1.0f)*0.5f;
					float du = u-delta;
					float dv = v-delta;

if (du <= 0.0f) DebugPrint(_T("error du 0.0f \n"));
if (dv <= 0.0f) DebugPrint(_T("error dv 0.0f \n"));
if (du >= 1.0f) DebugPrint(_T("error du 1.0f \n"));
if (dv >= 1.0f) DebugPrint(_T("error dv 1.0f \n"));

					localData->incDelta = delta;

					Patch *p = &patch->patches[i];

					Point3 uVec = Normalize(p->interp(patch, du, v)-patchPoints[closest]);
//get the v vec
					Point3 vVec = Normalize(p->interp(patch, u, dv)-patchPoints[closest]);

					Point3 xAxis,yAxis,zAxis;
					xAxis = uVec;
					zAxis = CrossProd(uVec,vVec);
					yAxis = CrossProd(xAxis,zAxis);

					Point3 center = patchPoints[closest];

					Matrix3 tm(xAxis,yAxis,zAxis,center);
/*DebugPrint(_T("init %d\n"),j);*/
/*DebugPrint(_T("%f %f %f\n"),xAxis.x,xAxis.y,xAxis.z);
DebugPrint(_T("%f %f %f\n"),yAxis.x,yAxis.y,yAxis.z);
DebugPrint(_T("%f %f %f\n"),zAxis.x,zAxis.y,zAxis.z);
DebugPrint(_T("%f %f %f\n"),center.x,center.y,center.z);*/

					localData->paramData[j].initialPoint = pointData[j]*Inverse(tm);
//DebugPrint(_T("init %d\n"),j);

					}
				}
			
			}
		}

	if (ip)
		{
		TSTR name;
		name.printf(_T("%s"),GetString(IDS_PICK));
		SetWindowText(GetDlgItem(hWnd,IDC_STATUS),name);
		}

//split the patch into sub samples chunk
	}
Ejemplo n.º 15
0
BOOLEAN
MPSetPowerLowPrivate(
    PVOID Context
    )
/*++
Routine Description:

    The section follows the steps mentioned in
    Section C.2.6.2 of the Reference Manual.


Arguments:

    Adapter     Pointer to our adapter

Return Value:

--*/
{
    CSR_FILTER_STRUC    Filter;
    USHORT              IntStatus;
    MP_PMCSR            PMCSR = {0};
    ULONG               ulResult;
    PFDO_DATA FdoData = Context;

    DebugPrint(TRACE, DBG_POWER, "-->MPSetPowerLowPrivate\n");
    RtlZeroMemory (&Filter, sizeof (Filter));

    do
    {

        //
        // Before issue the command to low power state, we should disable the
        // interrup and ack all the pending interrupts, then set the adapter's power to
        // low state.
        //
        NICDisableInterrupt(FdoData);
        NIC_ACK_INTERRUPT(FdoData, IntStatus);

        //
        // If the driver should wake up the machine
        //
        if (FdoData->AllowWakeArming)
        {
            //
            // Send the WakeUp Patter to the nic
            MPIssueScbPoMgmtCommand(FdoData, &Filter, TRUE);


            //
            // Section C.2.6.2 - The driver needs to wait for the CU to idle
            // The above function already waits for the CU to idle
            //
            ASSERT ((FdoData->CSRAddress->ScbStatus & SCB_CUS_MASK) == SCB_CUS_IDLE);
        }
        else
        {

            ulResult = FdoData->BusInterface.GetBusData(
                                    FdoData->BusInterface.Context,
                                    PCI_WHICHSPACE_CONFIG,
                                    (PVOID)&PMCSR,
                                    FIELD_OFFSET(MP_PM_PCI_SPACE, PMCSR),
                                    sizeof(PMCSR));

            if(ulResult != sizeof(PMCSR)){
                ASSERT(ulResult == sizeof(PMCSR));
                DebugPrint(ERROR, DBG_POWER, "GetBusData for PMCSR failed\n");
                return FALSE;
            }
            if (PMCSR.PME_En == 1)
            {
                //
                // PME is enabled. Clear the PME_En bit.
                // So that it is not asserted
                //
                MpClearPME_En (FdoData,PMCSR);

            }

            //
            // Set the driver to lower power state by OS
            //
        }



    } while (FALSE);

    DebugPrint(TRACE, DBG_POWER, "<--MPSetPowerLowPrivate\n");

    return TRUE;
}
Ejemplo n.º 16
0
// ARI: I knew how to write this for a unix environment,
// but am quite certain that porting this can cause you
// trouble..
int NetSocketAddr(const Socket sock, unsigned long *ips, int maxAddr)
{
	if (sock == static_cast<Socket>(-1)) {
		return 0;
	}
	char buf[4096];
	struct ifconf ifc;
	ifc.ifc_len = sizeof(buf);
	ifc.ifc_buf = buf;
	if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
		DebugPrint("SIOCGIFCONF - errno %d\n" _C_ errno);
		return 0;
	}
	// with some inspiration from routed..
	int nif = 0;
	struct ifreq *ifr = ifc.ifc_req;
	char *cplim = buf + ifc.ifc_len; // skip over if's with big ifr_addr's

	for (char *cp = buf; cp < cplim;
		 cp += sizeof(ifr->ifr_name) + sizeof(ifr->ifr_ifru)) {
		ifr = (struct ifreq *)cp;
		struct ifreq ifreq = *ifr;
		if (ioctl(sock, SIOCGIFFLAGS, (char *)&ifreq) < 0) {
			DebugPrint("%s: SIOCGIFFLAGS - errno %d\n" _C_
					   ifr->ifr_name _C_ errno);
			continue;
		}
		if ((ifreq.ifr_flags & IFF_UP) == 0 || ifr->ifr_addr.sa_family == AF_UNSPEC) {
			continue;
		}
		// argh, this'll have to change sometime
		if (ifr->ifr_addr.sa_family != AF_INET) {
			continue;
		}
		if (ifreq.ifr_flags & IFF_LOOPBACK) {
			continue;
		}
		struct sockaddr_in *sap = (struct sockaddr_in *)&ifr->ifr_addr;
		struct sockaddr_in sa = *sap;
		ips[nif] = sap->sin_addr.s_addr;
		if (ifreq.ifr_flags & IFF_POINTOPOINT) {
			if (ioctl(sock, SIOCGIFDSTADDR, (char *)&ifreq) < 0) {
				DebugPrint("%s: SIOCGIFDSTADDR - errno %d\n" _C_
						   ifr->ifr_name _C_ errno);
				// failed to obtain dst addr - ignore
				continue;
			}
			if (ifr->ifr_addr.sa_family == AF_UNSPEC) {
				continue;
			}
		}
		// avoid p-t-p links with common src
		if (nif) {
			int i;
			for (i = 0; i < nif; ++i) {
				if (sa.sin_addr.s_addr == ips[i]) {
					i = -1;
					break;
				}
			}
			if (i == -1) {
				continue;
			}
		}
		++nif;
		if (nif == maxAddr) {
			break;
		}
	}
	return nif;
}
Ejemplo n.º 17
0
NTSTATUS
MPSetUpFilterCB(
    __in PFDO_DATA FdoData
    )
{
    NTSTATUS         status = STATUS_SUCCESS;
    PCB_HEADER_STRUC    NonTxCmdBlockHdr = (PCB_HEADER_STRUC)FdoData->NonTxCmdBlock;
    PFILTER_CB_STRUC    pFilterCb = (PFILTER_CB_STRUC)NonTxCmdBlockHdr;
    ULONG               Curr = 0;
    ULONG               Next = 0;
    PLIST_ENTRY         pPatternEntry = ListNext(&FdoData->PoMgmt.PatternList) ;

    DebugPrint(TRACE, DBG_POWER, "--> MPSetUpFilterCB\n");

    RtlZeroMemory (pFilterCb, sizeof(*pFilterCb));

    // Individual Address Setup
    NonTxCmdBlockHdr->CbStatus = 0;
    NonTxCmdBlockHdr->CbCommand = CB_EL_BIT | CB_LOAD_PROG_FILTER;
    NonTxCmdBlockHdr->CbLinkPointer = DRIVER_NULL;




    // go through each filter in the list.

    while (pPatternEntry != (&FdoData->PoMgmt.PatternList))
    {
        PMP_WAKE_PATTERN            pWakeUpPattern = NULL;

        // initialize local variables
        pWakeUpPattern = CONTAINING_RECORD(pPatternEntry, MP_WAKE_PATTERN, linkListEntry);

        // increment the iterator
        pPatternEntry = ListNext (pPatternEntry);

        // Update the Curr Array Pointer
        Curr = Next;

        // Create the Programmable filter for this device.
        MPCreateProgrammableFilter (pWakeUpPattern , &pFilterCb->Pattern[Curr], &Next);

        if (Next >=16)
        {
            break;
        }

    }

    {
        // Set the EL bit on the last pattern
        PUCHAR pLastPattern = (PUCHAR) &pFilterCb->Pattern[Curr];

        // Get to bit 31
        pLastPattern[3] |= CB_FILTER_EL ;


    }

    ASSERT(FdoData->CSRAddress->ScbCommandLow == 0);

    //  Wait for the CU to Idle before giving it this command
    if(!WaitScb(FdoData))
    {
        status = STATUS_DEVICE_DATA_ERROR;
    }

    DebugPrint(TRACE, DBG_POWER, "<-- MPSetUpFilterCB\n");

    return status;


}
Ejemplo n.º 18
0
OZF2GPXMap::OZF2GPXMap(const char *fn)
{
	kGUIString ozfn;
	DataHandle dh;
	int linenum;
	kGUIString line;
	kGUIStringSplit ss;
	int index;
	int z;
	int nf;
	unsigned char *fp;
	unsigned long filesize;
	OZ2FHEADER_DEF *oh;
	double maxlat,maxlon;
	double maxx,maxy;

	m_coords=0;

	dh.SetFilename(fn);
	if(dh.Open()==false)
		return;	/* couldn't load file */

	linenum=0;
	do
	{
		dh.ReadLine(&line);
		nf=ss.Split(&line,",");

		if(linenum==2)
		{
			int sl;
			static char dirchar[]={ DIRCHAR };

			ozfn.SetString(fn);	/* extract path from filename */
			sl=ozfn.GetLen()-1;
			/* cut off last subdir */
			while(sl>0)
			{
				if(ozfn.GetChar(sl)==dirchar[0])
				{
					++sl;
					break;
				}
				--sl;
			};
			ozfn.Clip(sl);
			ozfn.Append(line.GetString());
		}
		else if(linenum==4)
		{
			/* datum */
			if(!strcmp(ss.GetWord(0)->GetString(),"WGS 84"))
			{
				/* ok */
			}
			else
			{
				dh.Close();
				return;
			}
			//if (! FindOziDatumToWGS84 (strDatum.c_str (), m_pDatumTransformation)) {
			//	m_pDatumTransformation = NULL;
			//	ReportWarning ("Some unsupported datum is used: '%s'. No datum conversion performed.", strDatum.c_str ());
		}
		else
		{
			if(!strcmp(ss.GetWord(0)->GetString(),"Map Projection"))
			{
				/* todo */
			}
			else if(!strcmp(ss.GetWord(0)->GetString(),"MMPNUM"))
			{
				m_coords=new OZF2Corners[ss.GetWord(1)->GetInt()];
			}
			else if(!strcmp(ss.GetWord(0)->GetString(),"MMPXY"))
			{
				/* pixel position */
				index=atoi(ss.GetWord(1)->GetString())-1;
				m_coords[index].x=atoi(ss.GetWord(2)->GetString());
				m_coords[index].y=atoi(ss.GetWord(3)->GetString());
			}
			else if(!strcmp(ss.GetWord(0)->GetString(),"MMPLL"))
			{
				/* latitude/longitude position */
				index=atoi(ss.GetWord(1)->GetString())-1;
				m_coords[index].lon=atof(ss.GetWord(2)->GetString());
				m_coords[index].lat=atof(ss.GetWord(3)->GetString());
			}
		}
		++linenum;
	}while(dh.Eof()==false);
	dh.Close();

	/* calculate bounding rectanle for lat/lon */
	m_minlat=m_coords[0].lat;
	maxlat=m_coords[0].lat;
	m_minlon=m_coords[0].lon;
	maxlon=m_coords[0].lon;
	m_minx=m_coords[0].x;
	maxx=m_coords[0].x;
	m_miny=m_coords[0].y;
	maxy=m_coords[0].y;
	for(index=1;index<4;++index)
	{
		if(m_coords[index].lat<m_minlat)
		{
			m_minlat=m_coords[index].lat;
			m_miny=m_coords[index].y;
		}
		if(m_coords[index].lat>maxlat)
		{
			maxlat=m_coords[index].lat;
			maxy=m_coords[index].y;
		}

		if(m_coords[index].lon<m_minlon)
		{
			m_minlon=m_coords[index].lon;
			m_minx=m_coords[index].x;
		}
		if(m_coords[index].lon>maxlon)
		{
			maxlon=m_coords[index].lon;
			maxx=m_coords[index].x;
		}
	}

	/* assume linear for now until I figure out the projection */
	m_slx=(maxlon-m_minlon)/(maxx-m_minx);
	m_sly=(maxlat-m_minlat)/(maxy-m_miny);
	m_lsx=(maxx-m_minx)/(maxlon-m_minlon);
	m_lsy=(maxy-m_miny)/(maxlat-m_minlat);

	for(index=0;index<4;++index)
	{
		GPXCoord c;
		int sx,sy;

		c.Set(m_coords[index].lat,m_coords[index].lon);
		ToMap(&c,&sx,&sy);
		DebugPrint("Coord testing %f,%f %d,%d - %d,%d",m_coords[index].lat,m_coords[index].lon,m_coords[index].x,m_coords[index].y,sx,sy);
	}

	/* load the map file with the tiles */
	fp=kGUI::LoadFile(ozfn.GetString(),&filesize);
	if(!fp)
		return;	/* couldn't load file */

	m_filedata=fp;	/* save pointer to data so destructor will free it up upon exiting */
	oh=(OZ2FHEADER_DEF *)fp;
	
	if(oh->wSignature!=0x7778)
		return;	/* not valid format */

	assert ((oh->wPlanes==1) && (oh->wBitsPerPixel==8),"Unsupported bitmap format" );

	SetTileSize(64,64);

	/* parse the tile data */

	const int dwMasterTblOffset = * reinterpret_cast<const int *> (fp + filesize - 4);
	const int * const pdwMasterTbl = reinterpret_cast<const int *> (fp + dwMasterTblOffset);

	const int zoomlevels = (filesize - 4 - dwMasterTblOffset)/4;
	SetZoomLevels(1,zoomlevels);
	m_bitmaps.Alloc(zoomlevels);
	z=zoomlevels-1;
	for (int zoomlevel = 0; zoomlevel < zoomlevels; ++ zoomlevel)
	{
		OZ2FBITMAP_DEF *ih = (OZ2FBITMAP_DEF *) (fp + pdwMasterTbl [zoomlevel]);

		m_bitmaps.SetEntry(z,ih);
		SetSize(z,ih->dwImageWidth,ih->dwImageHeight);
		--z;
	}
}
Ejemplo n.º 19
0
NTSTATUS DriverEntry(
    __in PDRIVER_OBJECT  DriverObject,
    __in PUNICODE_STRING RegistryPath
    )
{
    PDEVICE_OBJECT      deviceObject;
    PDEVICE_EXTENSION   pContext;
    UNICODE_STRING      ntDeviceName;
    UNICODE_STRING      symbolicLinkName;
    NTSTATUS            status;

    UNREFERENCED_PARAMETER(RegistryPath);

    DebugPrint(("==>DriverEntry\n"));

    // 创建设备对象
    RtlInitUnicodeString(&ntDeviceName, NTDEVICE_NAME_STRING);

    status = IoCreateDevice(DriverObject,               // DriverObject
                            sizeof(DEVICE_EXTENSION),   // DeviceExtensionSize
                            &ntDeviceName,              // DeviceName
                            FILE_DEVICE_UNKNOWN,        // DeviceType
                            FILE_DEVICE_SECURE_OPEN,    // DeviceCharacteristics
                            FALSE,                      // Not Exclusive
                            &deviceObject);             // DeviceObject
        
    if (!NT_SUCCESS(status)) {
        DebugPrint(("\tIoCreateDevice returned 0x%x\n", status));
        return(status);
    }

    DriverObject->MajorFunction[IRP_MJ_CREATE]          = DispatchCreateClose;
    DriverObject->MajorFunction[IRP_MJ_CLOSE]           = DispatchCreateClose;
    DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL]  = DispatchDispatchIoControl;
    DriverObject->DriverUnload                          = DrvUnload;

    RtlInitUnicodeString(&symbolicLinkName, SYMBOLIC_NAME_STRING);
    status = IoCreateSymbolicLink(&symbolicLinkName, &ntDeviceName);

    if (!NT_SUCCESS(status)) 
	{
        IoDeleteDevice(deviceObject);
        DebugPrint(("\tIoCreateSymbolicLink returned 0x%x\n", status));
        return(status);
    }

    pContext = deviceObject->DeviceExtension;
    RtlZeroMemory(pContext, sizeof(DEVICE_EXTENSION));

    pContext->Self = deviceObject;
	pContext->bStoppingDPC = TRUE;
	pContext->ulSampleRate = 44100; // 初始采样率。我们没有提供给用户设置采样率的接口。所以它总是固定的。

    // 初始化计时器
    KeInitializeDpc (
        &pContext->TimerDpc,
        TimerDpc,
        deviceObject
        );
	
    KeInitializeEvent (
        &pContext->StopDPCEvent,
        SynchronizationEvent,
        FALSE
        );

    KeInitializeTimer (&pContext->Timer);

    // 用户缓冲区方式
    deviceObject->Flags |= DO_BUFFERED_IO;
    return status;
}
/*!
	this function is called by the associated link. in this case, we reply with error to the last
	message we received from tpm, if there is one, and we set m_LinkID to an empty ID which points
	to no link object.
*/
void CMultiplexerClientFEClientSession::OnLinkDisconnected()
{
	DebugPrint(2,"Link Disconnected\n");
	m_LinkID	=	CMultiXLinkID();
}
Ejemplo n.º 21
0
/**
**  Build new units to reduce the food shortage.
*/
static bool AiRequestSupply()
{
    // Don't request supply if we're sleeping.  When the script starts it may
    // request a better unit than the one we pick here.  If we only have enough
    // resources for one unit we don't want to build the wrong one.
    if (AiPlayer->SleepCycles != 0) {
        /* we still need supply */
        return true;
    }

    // Count the already made build requests.
    int counter[UnitTypeMax];

    AiGetBuildRequestsCount(*AiPlayer, counter);
    struct cnode cache[16];

    memset(cache, 0, sizeof(cache));

    //
    // Check if we can build this?
    //
    int j = 0;
    const int n = AiHelpers.UnitLimit[0].size();

    for (int i = 0; i < n; ++i) {
        CUnitType &type = *AiHelpers.UnitLimit[0][i];
        if (counter[type.Slot]) { // Already ordered.
#if defined(DEBUG) && defined(DebugRequestSupply)
            DebugPrint("%d: AiRequestSupply: Supply already build in %s\n"
                       _C_ AiPlayer->Player->Index _C_ type->Name.c_str());
#endif
            return false;
        }

        if (!AiRequestedTypeAllowed(*AiPlayer->Player, type)) {
            continue;
        }

        //
        // Check if resources available.
        //
        cache[j].needmask = AiCheckUnitTypeCosts(type);

        for (int c = 1; c < MaxCosts; ++c) {
            cache[j].unit_cost += type.Stats[AiPlayer->Player->Index].Costs[c];
        }
        cache[j].unit_cost += type.Supply - 1;
        cache[j].unit_cost /= type.Supply;
        cache[j++].type = &type;
        Assert(j < 16);
    }

    if (j > 1) {
        std::sort(&cache[0], &cache[j], cnode_cmp);
    }
    if (j) {
        if (!cache[0].needmask) {
            CUnitType &type = *cache[0].type;
            Vec2i invalidPos(-1, -1);
            if (AiMakeUnit(type, invalidPos)) {
                AiBuildQueue newqueue;
                newqueue.Type = &type;
                newqueue.Want = 1;
                newqueue.Made = 1;
                AiPlayer->UnitTypeBuilt.insert(
                    AiPlayer->UnitTypeBuilt.begin(), newqueue);
#if defined( DEBUG) && defined( DebugRequestSupply )
                DebugPrint("%d: AiRequestSupply: build Supply in %s\n"
                           _C_ AiPlayer->Player->Index _C_ type->Name.c_str());
#endif
                return false;
            }
        }
        AiPlayer->NeededMask |= cache[0].needmask;
    }


#if defined( DEBUG) && defined( DebugRequestSupply )
    std::string needed("");
    for (int i = 1; i < MaxCosts; ++i) {
        if (cache[0].needmask & (1 << i)) {
            needed += ":";
            switch (i) {
            case GoldCost:
                needed += "Gold<";
                break;
            case WoodCost:
                needed += "Wood<";
                break;
            case OilCost:
                needed += "Oil<";
                break;
            default:
                needed += "unknown<";
                break;
            }
            needed += '0' + i;
            needed += ">";
        }
    }
    DebugPrint("%d: AiRequestSupply: needed build %s with %s resource\n"
               _C_ AiPlayer->Player->Index _C_ cache[0].type->Name.c_str() _C_ needed.c_str());
#endif
    return true;
}
/*!
\param	pLink	a pointer to the link that created the session object
	The link object that created the session objects, notify us that it is the one that
	handles the connection to the other peer, we keep its ID.
*/
void CMultiplexerClientFEClientSession::OnLinkConnected(CMultiplexerClientFELink *pLink)
{
	DebugPrint(2,"Link Connected\n");
	m_LinkID	=	pLink->GetID();
}
Ejemplo n.º 23
0
int jrpacman_romdecode(int offset)
{
	int addressBus = offset;
	Z80_Regs Regs;
	Z80_GetRegs(&Regs);

	{
	int m1 = !Regs.M1;//active low (supposedly means opcode read)

	/* Pal 8C (16L8) */
	int pcbe =  !(addressBus >= 0x0000 && addressBus <= 0x3fff ||
				  addressBus >= 0x8000 && addressBus <=
0xdfff);

	int sop0 =  !(addressBus >= 0x0000 && addressBus <= 0x001f ||
				  addressBus >= 0x00e0 && addressBus <=
0x00ff ||
				  addressBus >= 0x9a60 && addressBus <=
0x9a7f ||
				  addressBus >= 0x9ac0 && addressBus <=
0x9adf ||
				  addressBus >= 0x9b60 && addressBus <=
0x9b7f ||
				  addressBus >= 0x9be0 && addressBus <=
0x9bff && m1);

	int sop1 =	!(addressBus >= 0x9be0 && addressBus <= 0x9bff && m1 ||
				  addressBus >= 0x9ca0 && addressBus <=
0x9cbf);

	int sop2 =	!(addressBus >= 0x00c0 && addressBus <= 0x00df ||
				  addressBus >= 0x9a40 && addressBus <=
0x9a5f);


	/* Pal 9c (16r4) */
	int md0  = ByteBit(RAM[addressBus],0);
	int md2  = ByteBit(RAM[addressBus],2);
	int md7  = ByteBit(RAM[addressBus],7);

	int d0 =  !( s0 &&  s1 && !md0 ||
			    !s0 &&  s1 &&  md0 ||
			     s0 && !s1 && !md0 ||
			    !s0 && !s1 && !md2);

	int d2 =  !( s0 &&  s1 && !md2 ||
			    !s0 &&  s1 && !md2 ||
			     s0 && !s1 &&  md2 ||
			    !s0 && !s1 && !md0);

	int d7 =  !( s2 &&  s3  ||
			    !s2 && !md7);

	int pb1 = !( sop0 &&  s0 ||
			    !sop0 && !s0);

	int ns0 =  ( sop1 &&  s0   ||
				!sop1 && !s0   ||
				!sop0 &&  sop1);

	int ns1 =  ( sop1 &&  s1 && !pb1 ||
				!sop1 &&  s1 && !pb1 ||
				 sop1 &&  s1 &&  pb1 ||
				!sop1 && !s1 &&  pb1 ||
				!sop0 &&  sop1);

	int ns2 =  ( sop0 &&  sop1 &&  s2 ||
				 sop0 && !sop1 &&  s2 ||
				!sop0 && !sop1 &&  s2 ||
				 sop0 && !sop2);

	int ns3 =  ( !md7 );

//  DebugPrint("%04x: %02x & %02x | %02x = %02x",addressBus,RAM[addressBus],~(1<<0) & ~(1<<2) & ~(1<<7), (d0) | (d2<<2) | (d7<<7),(RAM[addressBus] & ~(1<<0) & ~(1<<2) & ~(1<<7)) | (d0) | (d2<<2) | (d7<<7));
/*  printf("%04x: %02x & %02x | %02x = %02x\n",addressBus,RAM[addressBus],~(1<<0) & ~(1<<2) & ~(1<<7), (d0) | (d2<<2) | (d7<<7),(RAM[addressBus] & ~(1<<0) & ~(1<<2) & ~(1<<7)) | (d0) | (d2<<2) | (d7<<7));
    {static int i=0;
    if (i++>100)
    {
        while (getchar()!='\n')
            {}
    }}*/
	{
		int temp= ((int)RAM[addressBus] & 0x7A) | ((d7<<7) | (d2<<2) | (d0));

//      if (Z80_Trace==1)
			if (!used[addressBus])
			{
				used[addressBus]=1;
				shadowROM[addressBus] = temp;
				numberUsed++;
			}
			else
			{
				if (shadowROM[addressBus] != temp)
					DebugPrint("Address: %04x translates to 2 different values!!!! (%02x and %02x)",addressBus,shadowROM[addressBus],temp);
			}


		if (Z80_Trace==1)
		{
			static last = 0;
			if (last + 30 <= TickCount()) /* print bnanner if we havent been called in half a second */
				printf("m1   sop0 sop1 sop2 pcbe  md7  md2 md0   d7   d2   d0    pb1   s0   s1   s2   s3    ns0  ns1  ns2  ns3\n");
			last = TickCount();
			printf("%-4d %-4d %-4d %-4d %-4d  %-4d %-4d %-4d %-4d %-4d %-4d  %-4d  %-4d %-4d %-4d %-4d  %-4d %-4d %-4d %-4d     ",
			        m1,  sop0,sop1,sop2,pcbe, md7, md2, md0,
d7,  d2,  d0,   pb1,  s0,  s1,  s2,  s3,   ns0, ns1, ns2, ns3);
			printf("%04x: %02x & %02x | %02x = %02x\n",addressBus,RAM[addressBus],~(1<<0) & ~(1<<2) & ~(1<<7), (d0) | (d2<<2) | (d7<<7),(RAM[addressBus] & ~(1<<0) & ~(1<<2) & ~(1<<7)) | (d0) | (d2<<2) | (d7<<7));
			Z80_Trace = 1; /* stop it if it was running for a count */
		}

		/* latch new flip flops on rising edge of pcbe */
		if (!pcbe)
		{
			s0 = ns0;
			s1 = ns1;
			s2 = ns2;
			s3 = ns3;
		}
		return temp;
	}
	}
}
Ejemplo n.º 24
0
BOOLEAN
VerifyProHardware(
    PFOUNDINFO pFI,
    ULONG port)
{
    UCHAR bData, bTemp;

    DebugPrint((DEBUG_LEVEL,"VerifyProHardware (proport %X,probase %X, port %X)\n",pFI->ProPort,pFI->PROBase,port));
    pFI->TranslateCode = port ^ DEFAULT_BASE;

    bData=PASX_IN (pFI, INTERRUPT_CTRL_REG);

    if (bData==0xFF) {                      // 0xFF usually means nothing there
        goto VerifyFailed;
    }
    pFI->wBoardRev= (bData >>5);            // board rev is 3 topmost bits

    switch (pFI->wBoardRev) {
#ifndef WINNT
    // winnt does not want support for old cards, this code recognizes
    // some sound blasters
    case PAS_VERSION_1:
#endif
    //case PAS_PLUS:                    // same boardrev as PAS_SIXTEEN
    case PAS_STUDIO:
    case PAS_SIXTEEN:
    case PAS_CDPC:
    case 4: // Memphis
        break;

    default:
        goto VerifyFailed;              // unknown hardware type
    }

    PASX_OUT(pFI, INTERRUPT_CTRL_REG, bData ^ 0xE0);  // try changing version bits
    bTemp=PASX_IN (pFI, INTERRUPT_CTRL_REG);           // they should be read only

    if ((bTemp & (D7+D6+D5)) != (bData & (D7+D6+D5))) {
        PASX_OUT(pFI,  INTERRUPT_CTRL_REG, bData);     // Excuse me, stranger.
        goto VerifyFailed;
    }

    if (pFI->wBoardRev==PAS_VERSION_1) {

        pFI->Caps.CapsBits.CDInterfaceType=SCSI_TYPE;

        //
        // test for Enhanced SCSI mod (U48)
        //

        PASX_OUT(pFI,  ENHANCED_SCSI_DETECT_REG, 0 );    // write to try changing version bits
        ScsiPortStallExecution(10); // wait 10 us
        bTemp=PASX_IN ( pFI, ENHANCED_SCSI_DETECT_REG );     // they should be read only

        switch (bTemp & 1) {     // bit0==1 means old SCSI PAL
        case 0:
            pFI->Caps.CapsBits.EnhancedSCSI=TRUE;
        // allow to fall thru

        case 1:
            goto ProVerified;
        }
    } else {
        // if PAS hardware installed, the reset bit can never be on

        bTemp=PASX_IN (pFI, SYSTEM_CONFIG_1);     // get PAS config register
        if (bTemp & D7) {                         // D7 is reset bit
            goto VerifyFailed;
        }

        bTemp=PASX_IN (pFI, SLAVE_MODE_READ);

        if (bTemp & SLAVE_MODE_OPL3) {
            pFI->Caps.CapsBits.OPL_3=TRUE;
        }

        if (bTemp & SLAVE_MODE_16) {
            pFI->Caps.CapsBits.DAC16=TRUE;
            pFI->Caps.CapsBits.DualDAC=TRUE;

            // if 16-bit DAC, and not a CDPC, it has a 508 chip.
            // Note: PAS 16 w/ VGA will have Mixer 508 also.

            if (pFI->wBoardRev != PAS_CDPC) {
                pFI->Caps.CapsBits.Mixer_508=TRUE;
            }
        }

        pFI->Caps.CapsBits.CDInterfaceType=(bTemp & (D1+D0));

        if (pFI->Caps.CapsBits.CDInterfaceType==SCSI_TYPE) {
            pFI->Caps.CapsBits.SCSI_IO_16=TRUE;
        }

        pFI->Caps.CapsBits.Slot16=TRUE;
        pFI->Caps.CapsBits.SoundBlaster=TRUE;

        bTemp=PASX_IN (pFI, MASTER_MODE_READ);        // get slave bits
        if ((bTemp & D0)==0) {
            pFI->Caps.CapsBits.MCA=TRUE;
        }

        if (bTemp & D2) {
            pFI->Caps.CapsBits.CDPC=TRUE;
        }

        pFI->wChipRev=PASX_IN (pFI, CHIP_REV);
    }

ProVerified:

    DebugPrint((DEBUG_LEVEL,"\n\nFound PRO hardware at %X\n", port));
    pFI->ProPort=port;                  // found at this port
    return TRUE;

////////////////////////////////

VerifyFailed:
    pFI->wBoardRev=0;               // found at this port
    pFI->Caps.dwCaps=0;             // No Board, No Caps
    return FALSE;
}
Ejemplo n.º 25
0
/* virtual */ void COrder_Follow::Execute(CUnit &unit)
{
	if (unit.Wait) {
		if (!unit.Waiting) {
			unit.Waiting = 1;
			unit.WaitBackup = unit.Anim;
		}
		//Wyrmgus start
//		UnitShowAnimation(unit, unit.Type->Animations->Still);
		UnitShowAnimation(unit, unit.GetAnimations()->Still);
		//Wyrmgus end
		unit.Wait--;
		return;
	}
	if (unit.Waiting) {
		unit.Anim = unit.WaitBackup;
		unit.Waiting = 0;
	}
	CUnit *goal = this->GetGoal();

	// Reached target
	if (this->State == State_TargetReached) {

		if (!goal || !goal->IsVisibleAsGoal(*unit.Player)) {
			DebugPrint("Goal gone\n");
			this->Finished = true;
			return ;
		}

		// Don't follow after immobile units
		if (goal && goal->CanMove() == false) {
			this->Finished = true;
			return;
		}

		//Wyrmgus start
//		if (goal->tilePos == this->goalPos) {
		if (goal->tilePos == this->goalPos && goal->MapLayer == this->MapLayer) {
		//Wyrmgus end
			// Move to the next order
			if (unit.Orders.size() > 1) {
				this->Finished = true;
				return ;
			}

			unit.Wait = 10;
			if (this->Range > 1) {
				this->Range = 1;
				this->State = State_Init;
			}
			return ;
		}
		this->State = State_Init;
	}
	if (this->State == State_Init) { // first entry
		this->State = State_Initialized;
	}
	switch (DoActionMove(unit)) { // reached end-point?
		case PF_UNREACHABLE:
			//Wyrmgus start
			if ((Map.Field(unit.tilePos, unit.MapLayer)->Flags & MapFieldBridge) && !unit.Type->BoolFlag[BRIDGE_INDEX].value && unit.Type->UnitType == UnitTypeLand) {
				std::vector<CUnit *> table;
				Select(unit.tilePos, unit.tilePos, table, unit.MapLayer);
				for (size_t i = 0; i != table.size(); ++i) {
					if (!table[i]->Removed && table[i]->Type->BoolFlag[BRIDGE_INDEX].value && table[i]->CanMove()) {
						if (table[i]->CurrentAction() == UnitActionStill) {
							CommandStopUnit(*table[i]);
							CommandMove(*table[i], this->HasGoal() ? this->GetGoal()->tilePos : this->goalPos, FlushCommands, this->HasGoal() ? this->GetGoal()->MapLayer : this->MapLayer);
						}
						return;
					}
				}
			}
			//Wyrmgus end
			// Some tries to reach the goal
			this->Range++;
			break;
		case PF_REACHED: {
			if (!goal) { // goal has died
				this->Finished = true;
				return ;
			}
			// Handle Teleporter Units
			// FIXME: BAD HACK
			// goal shouldn't be busy and portal should be alive
			if (goal->Type->BoolFlag[TELEPORTER_INDEX].value && goal->Goal && goal->Goal->IsAlive() && unit.MapDistanceTo(*goal) <= 1) {
				if (!goal->IsIdle()) { // wait
					unit.Wait = 10;
					return;
				}
				// Check if we have enough mana
				if (goal->Goal->Type->TeleportCost > goal->Variable[MANA_INDEX].Value) {
					this->Finished = true;
					return;
				} else {
					goal->Variable[MANA_INDEX].Value -= goal->Goal->Type->TeleportCost;
				}
				// Everything is OK, now teleport the unit
				unit.Remove(NULL);
				if (goal->Type->TeleportEffectIn) {
					goal->Type->TeleportEffectIn->pushPreamble();
					goal->Type->TeleportEffectIn->pushInteger(UnitNumber(unit));
					goal->Type->TeleportEffectIn->pushInteger(UnitNumber(*goal));
					goal->Type->TeleportEffectIn->pushInteger(unit.GetMapPixelPosCenter().x);
					goal->Type->TeleportEffectIn->pushInteger(unit.GetMapPixelPosCenter().y);
					goal->Type->TeleportEffectIn->run();
				}
				unit.tilePos = goal->Goal->tilePos;
				//Wyrmgus start
				unit.MapLayer = goal->Goal->MapLayer;
				//Wyrmgus end
				DropOutOnSide(unit, unit.Direction, NULL);

				// FIXME: we must check if the units supports the new order.
				CUnit &dest = *goal->Goal;
				if (dest.Type->TeleportEffectOut) {
					dest.Type->TeleportEffectOut->pushPreamble();
					dest.Type->TeleportEffectOut->pushInteger(UnitNumber(unit));
					dest.Type->TeleportEffectOut->pushInteger(UnitNumber(dest));
					dest.Type->TeleportEffectOut->pushInteger(unit.GetMapPixelPosCenter().x);
					dest.Type->TeleportEffectOut->pushInteger(unit.GetMapPixelPosCenter().y);
					dest.Type->TeleportEffectOut->run();
				}

				if (dest.NewOrder == NULL
					|| (dest.NewOrder->Action == UnitActionResource && !unit.Type->BoolFlag[HARVESTER_INDEX].value)
					//Wyrmgus start
//					|| (dest.NewOrder->Action == UnitActionAttack && !unit.Type->CanAttack)
					|| (dest.NewOrder->Action == UnitActionAttack && !unit.CanAttack(true))
					//Wyrmgus end
					|| (dest.NewOrder->Action == UnitActionBoard && unit.Type->UnitType != UnitTypeLand)) {
					this->Finished = true;
					return ;
				} else {
					if (dest.NewOrder->HasGoal()) {
						if (dest.NewOrder->GetGoal()->Destroyed) {
							delete dest.NewOrder;
							dest.NewOrder = NULL;
							this->Finished = true;
							return ;
						}
						unit.Orders.insert(unit.Orders.begin() + 1, dest.NewOrder->Clone());
						this->Finished = true;
						return ;
					}
				}
			}
			this->goalPos = goal->tilePos;
			//Wyrmgus start
			this->MapLayer = goal->MapLayer;
			//Wyrmgus end
			this->State = State_TargetReached;
		}
		// FALL THROUGH
		default:
			break;
	}

	// Target destroyed?
	if (goal && !goal->IsVisibleAsGoal(*unit.Player)) {
		DebugPrint("Goal gone\n");
		this->goalPos = goal->tilePos + goal->Type->GetHalfTileSize();
		//Wyrmgus start
		this->MapLayer = goal->MapLayer;
		//Wyrmgus end
		this->ClearGoal();
		goal = NULL;
	}

	if (unit.Anim.Unbreakable) {
		return ;
	}
	// If our leader is dead or stops or attacks:
	// Attack any enemy in reaction range.
	// If don't set the goal, the unit can than choose a
	//  better goal if moving nearer to enemy.
	//Wyrmgus start
//	if (unit.Type->CanAttack
	if (unit.CanAttack()
	//Wyrmgus end
		&& (!goal || goal->CurrentAction() == UnitActionAttack || goal->CurrentAction() == UnitActionStill)) {
		CUnit *target = AttackUnitsInReactRange(unit);
		if (target) {
			// Save current command to come back.
			COrder *savedOrder = NULL;
			if (unit.CanStoreOrder(unit.CurrentOrder())) {
				savedOrder = this->Clone();
			}

			this->Finished = true;
			//Wyrmgus start
//			unit.Orders.insert(unit.Orders.begin() + 1, COrder::NewActionAttack(unit, target->tilePos));
			unit.Orders.insert(unit.Orders.begin() + 1, COrder::NewActionAttack(unit, target->tilePos, target->MapLayer));
			//Wyrmgus end

			if (savedOrder != NULL) {
				unit.SavedOrder = savedOrder;
			}
		}
	}
}
Ejemplo n.º 26
0
void EditableMapObject::SetInternet(Internet internet)
{
  m_metadata.Set(feature::Metadata::FMD_INTERNET, DebugPrint(internet));
}
Ejemplo n.º 27
0
void CPlayer::Save(CFile &file) const
{
	const CPlayer &p = *this;
	file.printf("Player(%d,\n", this->Index);
	file.printf("  \"name\", \"%s\",\n", p.Name.c_str());
	file.printf("  \"type\", ");
	switch (p.Type) {
		case PlayerNeutral:       file.printf("\"neutral\",");         break;
		case PlayerNobody:        file.printf("\"nobody\",");          break;
		case PlayerComputer:      file.printf("\"computer\",");        break;
		case PlayerPerson:        file.printf("\"person\",");          break;
		case PlayerRescuePassive: file.printf("\"rescue-passive\","); break;
		case PlayerRescueActive:  file.printf("\"rescue-active\","); break;
		default:                  file.printf("%d,", p.Type); break;
	}
	file.printf(" \"race\", \"%s\",", PlayerRaces.Name[p.Race].c_str());
	file.printf(" \"ai-name\", \"%s\",\n", p.AiName.c_str());
	file.printf("  \"team\", %d,", p.Team);

	file.printf(" \"enemy\", \"");
	for (int j = 0; j < PlayerMax; ++j) {
		file.printf("%c", (p.Enemy & (1 << j)) ? 'X' : '_');
	}
	file.printf("\", \"allied\", \"");
	for (int j = 0; j < PlayerMax; ++j) {
		file.printf("%c", (p.Allied & (1 << j)) ? 'X' : '_');
	}
	file.printf("\", \"shared-vision\", \"");
	for (int j = 0; j < PlayerMax; ++j) {
		file.printf("%c", (p.SharedVision & (1 << j)) ? 'X' : '_');
	}
	file.printf("\",\n  \"start\", {%d, %d},\n", p.StartPos.x, p.StartPos.y);

	// Resources
	file.printf("  \"resources\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		file.printf("\"%s\", %d, ", DefaultResourceNames[j].c_str(), p.Resources[j]);
	}
	// Stored Resources
	file.printf("},\n  \"stored-resources\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		file.printf("\"%s\", %d, ", DefaultResourceNames[j].c_str(), p.StoredResources[j]);
	}
	// Max Resources
	file.printf("},\n  \"max-resources\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		file.printf("\"%s\", %d, ", DefaultResourceNames[j].c_str(), p.MaxResources[j]);
	}
	// Last Resources
	file.printf("},\n  \"last-resources\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		file.printf("\"%s\", %d, ", DefaultResourceNames[j].c_str(), p.LastResources[j]);
	}
	// Incomes
	file.printf("},\n  \"incomes\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		if (j) {
			if (j == MaxCosts / 2) {
				file.printf("\n ");
			} else {
				file.printf(" ");
			}
		}
		file.printf("\"%s\", %d,", DefaultResourceNames[j].c_str(), p.Incomes[j]);
	}
	// Revenue
	file.printf("},\n  \"revenue\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		if (j) {
			if (j == MaxCosts / 2) {
				file.printf("\n ");
			} else {
				file.printf(" ");
			}
		}
		file.printf("\"%s\", %d,", DefaultResourceNames[j].c_str(), p.Revenue[j]);
	}

	// UnitTypesCount done by load units.

	file.printf("},\n  \"%s\",\n", p.AiEnabled ? "ai-enabled" : "ai-disabled");

	// Ai done by load ais.
	// Units done by load units.
	// TotalNumUnits done by load units.
	// NumBuildings done by load units.

	file.printf(" \"supply\", %d,", p.Supply);
	file.printf(" \"unit-limit\", %d,", p.UnitLimit);
	file.printf(" \"building-limit\", %d,", p.BuildingLimit);
	file.printf(" \"total-unit-limit\", %d,", p.TotalUnitLimit);

	file.printf("\n  \"score\", %d,", p.Score);
	file.printf("\n  \"total-units\", %d,", p.TotalUnits);
	file.printf("\n  \"total-buildings\", %d,", p.TotalBuildings);
	file.printf("\n  \"total-resources\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		if (j) {
			file.printf(" ");
		}
		file.printf("%d,", p.TotalResources[j]);
	}
	file.printf("},");
	file.printf("\n  \"total-razings\", %d,", p.TotalRazings);
	file.printf("\n  \"total-kills\", %d,", p.TotalKills);

	file.printf("\n  \"speed-resource-harvest\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		if (j) {
			file.printf(" ");
		}
		file.printf("%d,", p.SpeedResourcesHarvest[j]);
	}
	file.printf("},");
	file.printf("\n  \"speed-resource-return\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		if (j) {
			file.printf(" ");
		}
		file.printf("%d,", p.SpeedResourcesReturn[j]);
	}
	file.printf("},");
	file.printf("\n  \"speed-build\", %d,", p.SpeedBuild);
	file.printf("\n  \"speed-train\", %d,", p.SpeedTrain);
	file.printf("\n  \"speed-upgrade\", %d,", p.SpeedUpgrade);
	file.printf("\n  \"speed-research\", %d,", p.SpeedResearch);

	Uint8 r, g, b;

	SDL_GetRGB(p.Color, TheScreen->format, &r, &g, &b);
	file.printf("\n  \"color\", { %d, %d, %d },", r, g, b);

	// UnitColors done by init code.
	// Allow saved by allow.

	file.printf("\n  \"timers\", {");
	for (int j = 0; j < UpgradeMax; ++j) {
		if (j) {
			file.printf(" ,");
		}
		file.printf("%d", p.UpgradeTimers.Upgrades[j]);
	}
	file.printf("}");

	file.printf(")\n\n");

	DebugPrint("FIXME: must save unit-stats?\n");
}
Ejemplo n.º 28
0
NTSTATUS
PipAcquirePortResources(
    IN PPI_BUS_EXTENSION BusExtension,
    IN PDRIVER_OBJECT DriverObject,
    IN PUNICODE_STRING RegistryPath,
    IN PHYSICAL_ADDRESS BaseAddressLow,
    IN PHYSICAL_ADDRESS BaseAddressHi,
    IN ULONG Alignment,
    IN ULONG PortLength,
    OUT PCM_RESOURCE_LIST *CmResourceList
    )

/*++

Routine Description:

    This routine acquires specified port resources.

Arguments:

    BusExtension - Supplies a pointer to the pnp bus extension.

    BaseAddressLow,
    BaseAddressHi - Supplies the read data port base address range to be mapped.

    Alignment - supplies the port allignment.

    PortLength = Number of ports required.

Return Value:

    NTSTATUS code.

--*/

{

#if 1

    PCM_RESOURCE_LIST cmResource;
    PCM_PARTIAL_RESOURCE_DESCRIPTOR cmResourceDescriptor;
    NTSTATUS status;
    ULONG size;
    PIO_RESOURCE_REQUIREMENTS_LIST ioResource;
    ULONG i;
    PHYSICAL_ADDRESS physicalAddress;

    *CmResourceList = NULL;

    //
    // Create a static Io resource requirements list and
    // Call I/O mgr to get address, command and read data port addresses assigned.
    //

    size = sizeof(IO_RESOURCE_REQUIREMENTS_LIST);
    ioResource = (PIO_RESOURCE_REQUIREMENTS_LIST) ExAllocatePool(PagedPool, size);
    RtlZeroMemory(ioResource, size);
    ioResource->ListSize = size;
    ioResource->InterfaceType = Isa;
    ioResource->AlternativeLists = 1;
    ioResource->List[0].Version = 1;
    ioResource->List[0].Revision = 1;
    ioResource->List[0].Count = 1;
    ioResource->List[0].Descriptors[0].Type = CmResourceTypePort;
    ioResource->List[0].Descriptors[0].ShareDisposition = CmResourceShareDeviceExclusive;
    ioResource->List[0].Descriptors[0].Flags = CM_RESOURCE_PORT_IO;
    ioResource->List[0].Descriptors[0].u.Port.Length = PortLength;
    ioResource->List[0].Descriptors[0].u.Port.Alignment = Alignment;
    ioResource->List[0].Descriptors[0].u.Port.MinimumAddress = BaseAddressLow;
    ioResource->List[0].Descriptors[0].u.Port.MaximumAddress = BaseAddressHi;

    status = IoAssignResources(RegistryPath,
                               NULL,
                               DriverObject,
                               NULL,
                               ioResource,
                               &cmResource);
    ExFreePool(ioResource);
    if (!NT_SUCCESS(status)) {
        DebugPrint((DEBUG_MESSAGE,"PnpIsa: IoAssignResources failed\n"));
        return status;
    }

    //
    // Map port addr to memory addr if necessary.
    //

    if (PipAddressPort == NULL) {
        physicalAddress.LowPart = ADDRESS_PORT;
        physicalAddress.HighPart = 0;
        BusExtension->AddressPort =
        PipAddressPort = PipGetMappedAddress(
                             Isa,             // InterfaceType
                             0,               // BusNumber,
                             physicalAddress,
                             1,
                             CM_RESOURCE_PORT_IO,
                             &BusExtension->AddrPortMapped
                             );
        if (PipAddressPort == NULL) {
            goto exit0;
        }
    }
    if (PipCommandPort == NULL) {
        physicalAddress.LowPart = COMMAND_PORT;
        physicalAddress.HighPart = 0;
        BusExtension->CommandPort =
        PipCommandPort = PipGetMappedAddress(
                             Isa,             // InterfaceType
                             0,               // BusNumber,
                             physicalAddress,
                             1,
                             CM_RESOURCE_PORT_IO,
                             &BusExtension->CmdPortMapped
                             );
        if (PipCommandPort == NULL) {
            goto exit0;
        }
    }
    cmResourceDescriptor =
        &cmResource->List->PartialResourceList.PartialDescriptors[0];
    if ((cmResourceDescriptor->u.Port.Start.LowPart & 0xf) == 0) {

        //
        // Some cards (e.g. 3COM elnkiii) do not response to 0xyy3 addr.
        //

        DebugPrint((DEBUG_BREAK, "PnpIsa:ReadDataPort is at yy3\n"));
        goto exit0;
    }
    if (PipReadDataPort && BusExtension->DataPortMapped) {
        MmUnmapIoSpace(PipReadDataPort - 3, 4);
        PipReadDataPort = NULL;
        BusExtension->DataPortMapped = FALSE;
    }
    PipReadDataPort = PipGetMappedAddress(
                             Isa,             // InterfaceType
                             0,               // BusNumber,
                             cmResourceDescriptor->u.Port.Start,
                             cmResourceDescriptor->u.Port.Length,
                             cmResourceDescriptor->Flags,
                             &BusExtension->DataPortMapped
                             );
    if (PipReadDataPort) {
        PipReadDataPort += 3;
        PipBusExtension.ReadDataPort = PipReadDataPort;
    }
exit0:
    //ExFreePool(cmResource);
    if (PipReadDataPort && PipCommandPort && PipAddressPort) {
        *CmResourceList = cmResource;
        return STATUS_SUCCESS;
    } else {
        return STATUS_INSUFFICIENT_RESOURCES;
    }

#else

    PCM_RESOURCE_LIST cmResource;
    PCM_PARTIAL_RESOURCE_DESCRIPTOR cmResourceDescriptor;
    NTSTATUS status;
    ULONG size;
    PIO_RESOURCE_REQUIREMENTS_LIST ioResource;
    ULONG i;

    //
    // Create a static Io resource requirements list and
    // Call I/O mgr to get address, command and read data port addresses assigned.
    //

    size = sizeof(IO_RESOURCE_REQUIREMENTS_LIST) +
           sizeof (IO_RESOURCE_DESCRIPTOR) * 2;
    ioResource = (PIO_RESOURCE_REQUIREMENTS_LIST) ExAllocatePool(PagedPool, size);
    RtlZeroMemory(ioResource, size);
    ioResource->ListSize = size;
    ioResource->InterfaceType = Isa;
    ioResource->AlternativeLists = 1;
    ioResource->List[0].Version = 1;
    ioResource->List[0].Revision = 1;
    ioResource->List[0].Count = 3;
    ioResource->List[0].Descriptors[0].Type = CmResourceTypePort;
    ioResource->List[0].Descriptors[0].ShareDisposition = CmResourceShareDeviceExclusive;
    ioResource->List[0].Descriptors[0].Flags = CM_RESOURCE_PORT_IO;
    ioResource->List[0].Descriptors[0].u.Port.Length = PortLength;
    ioResource->List[0].Descriptors[0].u.Port.Alignment = Alignment;
    ioResource->List[0].Descriptors[0].u.Port.MinimumAddress = BaseAddressLow;
    ioResource->List[0].Descriptors[0].u.Port.MaximumAddress = BaseAddressHi;
    ioResource->List[0].Descriptors[1].Type = CmResourceTypePort;
    ioResource->List[0].Descriptors[1].ShareDisposition = CmResourceShareDeviceExclusive;
    ioResource->List[0].Descriptors[1].Flags = CM_RESOURCE_PORT_IO;
    ioResource->List[0].Descriptors[1].u.Port.Length = 1;
    ioResource->List[0].Descriptors[1].u.Port.Alignment = 1;
    ioResource->List[0].Descriptors[1].u.Port.MinimumAddress.LowPart = ADDRESS_PORT;
    ioResource->List[0].Descriptors[1].u.Port.MaximumAddress.LowPart = ADDRESS_PORT;
    ioResource->List[0].Descriptors[2].Type = CmResourceTypePort;
    ioResource->List[0].Descriptors[2].ShareDisposition = CmResourceShareDeviceExclusive;
    ioResource->List[0].Descriptors[2].Flags = CM_RESOURCE_PORT_IO;
    ioResource->List[0].Descriptors[2].u.Port.Length = 1;
    ioResource->List[0].Descriptors[2].u.Port.Alignment = 1;
    ioResource->List[0].Descriptors[2].u.Port.MinimumAddress.LowPart = COMMAND_PORT;
    ioResource->List[0].Descriptors[2].u.Port.MaximumAddress.LowPart = COMMAND_PORT;

    status = IoAssignResources(RegistryPath,
                               NULL,
                               DriverObject,
                               NULL,
                               ioResource,
                               &cmResource);
    ExFreePool(ioResource);
    if (!NT_SUCCESS(status)) {
        DebugPrint((DEBUG_MESSAGE,"PnpIsa: IoAssignResources failed\n"));
        return status;
    }

    //
    // Map port addr to memory addr if necessary.
    //

    ASSERT(cmResource->List->PartialResourceList.Count == 3);
    for (i = 0; i < cmResource->List->PartialResourceList.Count; i++) {
        cmResourceDescriptor =
            &cmResource->List->PartialResourceList.PartialDescriptors[i];
        ASSERT(cmResourceDescriptor->Type == CmResourceTypePort);
        if (cmResourceDescriptor->u.Port.Start.LowPart == ADDRESS_PORT) {
            if (PipAddressPort == NULL) {
                BusExtension->AddressPort =
                PipAddressPort = PipGetMappedAddress(
                                     Isa,             // InterfaceType
                                     0,               // BusNumber,
                                     cmResourceDescriptor->u.Port.Start,
                                     cmResourceDescriptor->u.Port.Length,
                                     cmResourceDescriptor->Flags,
                                     &BusExtension->AddrPortMapped
                                     );
            }
        } else if (cmResourceDescriptor->u.Port.Start.LowPart == COMMAND_PORT) {
            if (PipCommandPort == NULL) {
                BusExtension->CommandPort =
                PipCommandPort = PipGetMappedAddress(
                                     Isa,             // InterfaceType
                                     0,               // BusNumber,
                                     cmResourceDescriptor->u.Port.Start,
                                     cmResourceDescriptor->u.Port.Length,
                                     cmResourceDescriptor->Flags,
                                     &BusExtension->CmdPortMapped
                                     );
            }
        } else {
            if ((cmResourceDescriptor->u.Port.Start.LowPart & 0xf) == 0) {

                //
                // Some cards (e.g. 3COM elnkiii) do not response to 0xyy3 addr.
                //

                DebugPrint((DEBUG_BREAK, "PnpIsa:ReadDataPort is at yy3\n"));
                goto exit0;
            }
            if (PipReadDataPort && BusExtension->DataPortMapped) {
                MmUnmapIoSpace(PipReadDataPort, 4);
                PipReadDataPort = NULL;
                BusExtension->DataPortMapped = FALSE;
            }
            PipReadDataPort = PipGetMappedAddress(
                                     Isa,             // InterfaceType
                                     0,               // BusNumber,
                                     cmResourceDescriptor->u.Port.Start,
                                     cmResourceDescriptor->u.Port.Length,
                                     cmResourceDescriptor->Flags,
                                     &BusExtension->DataPortMapped
                                     );
            if (PipReadDataPort) {
                PipReadDataPort += 3;
                PipBusExtension.ReadDataPort = PipReadDataPort;
            }
        }
    }
exit0:
    ExFreePool(cmResource);
    if (PipReadDataPort && PipCommandPort && PipAddressPort) {
        return STATUS_SUCCESS;
    } else {
        IoAssignResources(RegistryPath,
                          NULL,
                          DriverObject,
                          NULL,
                          NULL,
                          NULL);
        return STATUS_INSUFFICIENT_RESOURCES;
    }
#endif // 1
}
Ejemplo n.º 29
0
//------------------------------------------------------------------------
void CTooltipSupport::showTooltip ()
{
	if (currentView)
	{
		CRect r (currentView->getVisibleSize ());
		CPoint p;
		currentView->localToFrame (p);
		r.offset (p.x, p.y);

		char* tooltip = getTooltipFromView (currentView);
		
		if (tooltip)
		{
			state = kForceVisible;
			#if MAC_COCOA
			if (frame->getNSView ())
			{
				nsViewSetTooltip (currentView, tooltip);
				free (tooltip);
				return;
			}
			#endif

			#if MAC_CARBON
			CCoord x, y;
			currentView->getFrame ()->getPosition (x,y);
			r.offset (x, y);

			HMHelpContentRec helpContent = {0};
			helpContent.version = 0;
			helpContent.absHotRect.left = r.left;
			helpContent.absHotRect.right = r.right;
			helpContent.absHotRect.top = r.top;
			helpContent.absHotRect.bottom = r.bottom;
			helpContent.tagSide = kHMDefaultSide;
			helpContent.content[0].contentType = kHMCFStringContent;
			helpContent.content[0].u.tagCFString = CFStringCreateWithCString (0, tooltip, kCFStringEncodingUTF8);
			HMDisplayTag(&helpContent);
			CFRelease (helpContent.content[0].u.tagCFString);
			#endif // MAC_CARBON
			
			#if WINDOWS
			UTF8StringHelper tooltipText (tooltip);
			if (platformObject)
			{
				RECT rc;
				rc.left = (LONG)r.left;
				rc.top = (LONG)r.top;
				rc.right = (LONG)r.right;
				rc.bottom = (LONG)r.bottom;
				TOOLINFO ti = {0};
			    ti.cbSize = sizeof(TOOLINFO);
				ti.hwnd = (HWND)frame->getSystemWindow ();
				ti.uId = 0;
				ti.rect = rc;
				ti.lpszText = (TCHAR*)(const TCHAR*)tooltipText;
				SendMessage ((HWND)platformObject, TTM_UPDATETIPTEXT, 0, (LPARAM)&ti);
				SendMessage ((HWND)platformObject, TTM_NEWTOOLRECT, 0, (LPARAM)&ti);
 				SendMessage ((HWND)platformObject, TTM_POPUP, 0, 0);
			}
			#endif // WINDOWS
			free (tooltip);
			#if DEBUGLOG
			DebugPrint ("CTooltipSupport::showTooltip (%s)\n", currentView->getClassName ());
			#endif
		}
	}
}
Ejemplo n.º 30
0
void
UniformGrid::LoadPoints(Point3 *p, int count)
{
    int dx,dy;
    bounds.Init();
    pointBase.SetCount(count);

    for (int i = 0; i < count; i++)
    {
        pointBase[i] = p[i];
        bounds += p[i];
    }

    if (count == 1)
        bounds.EnlargeBy(0.5);


//need to do some bounds check to check for bounds that are to small
    float expandBy = 0.0f;

    if (((bounds.pmax.x - bounds.pmin.x)/width) < 0.0001f)
        expandBy += 0.1f * width;
    if (((bounds.pmax.y - bounds.pmin.y)/width) < 0.0001f)
        expandBy += 0.1f * width;
    if (((bounds.pmax.z - bounds.pmin.z)/width) < 0.0001f)
        expandBy += 0.1f * width;

    bounds.EnlargeBy(expandBy);


    fXWidth = bounds.pmax.x - bounds.pmin.x;
    fYWidth = bounds.pmax.y - bounds.pmin.y;
    fZWidth = bounds.pmax.z - bounds.pmin.z;

    for (i = 0; i < count; i++)
    {

        //do XGrid
        //find out which cell we are in
        int index;

        if (activeGrid == 0)
        {
            index = FindCell(p[i].y,p[i].z,0,dx,dy);

            if ((index < 0) || (index >= widthXwidth))
                DebugPrint("XGrid Error cell out of range %d\n",i);
            else
            {
                //see if cell exists
                if (xGrid[index] == NULL)
                    xGrid[index] = new Grid();
                //add that vertex to the cell
                xGrid[index]->index.Append(1,&i);
//			xGrid[index]->hit=FALSE;
            }
        }

        //do yGrid
        //find out which cell we are in
        if (activeGrid == 1)
        {

            index = FindCell(p[i].x,p[i].z,1,dx,dy);

            if ((index < 0) || (index >= widthXwidth))
                DebugPrint("YGrid Error cell out of range %d\n",i);
            else
            {
                //see if cell exists
                if (yGrid[index] == NULL)
                    yGrid[index] = new Grid();
                //add that vertex to the cell
                yGrid[index]->index.Append(1,&i);
                //			yGrid[index]->hit=FALSE;
            }
        }


        //do ZGrid
        //find out which cell we are in
        if (activeGrid == 2)
        {

            index = FindCell(p[i].x,p[i].y,2,dx,dy);

            if ((index < 0) || (index >= widthXwidth))
                DebugPrint("ZGrid Error cell out of range %d\n",i);
            else
            {
                //see if cell exists
                if (zGrid[index] == NULL)
                    zGrid[index] = new Grid();
                //add that vertex to the cell
                zGrid[index]->index.Append(1,&i);
//				zGrid[index]->hit=FALSE;
            }
        }


    }

    xHitList.SetSize(count);
    yHitList.SetSize(count);
    zHitList.SetSize(count);

    numberOfHits = 0;
    numberOfChecks = 0;

    largestCellCount = 0;
    whichLargestCell = -1;
    for (i = 0; i < widthXwidth; i++)
    {
        Grid *g;
        if (activeGrid == 0)
            g = xGrid[i];
        else if (activeGrid == 1)
            g = yGrid[i];
        else if (activeGrid == 2)
            g = zGrid[i];

        if (g)
        {
            int ct = g->index.Count();
            if ((ct > largestCellCount) || (whichLargestCell == -1))
            {
                largestCellCount = ct;
                whichLargestCell = i;
            }
        }
    }


}