Example #1
0
File: T08.cpp Project: saggita/r5ge
void TestApp::Run()
{
	if (*mCore << "Config/T08.txt")
	{
		mCore->Lock();

		// First we need to create a heightmap we'll use to create the terrain. R5 has a fairly flexible
		// noise library with a variety of simple filters that we can use for just that purpose.

		Noise noise;

		// We want to generate a 256x256 heightmap
		noise.SetSize(256, 256);

		// You can combine a variety of filters to create the terrain's "final" look, but for the sake
		// of simplicity, let's only use one -- a perlin noise. The numbers that follow are optional
		// parameters. In this case '8' means generate an 8-octave noise, and 0.65 means that the noise
		// with values above 0.65 will be mirrored, turning high peaks into volcano-like crevices.
		// This type of noise is also known as ridged multifractal due to the ridges it tends to produce.

		noise.ApplyFilter("Perlin").Set(8.0f, 0.65f);

		// Now that we have our heightmap, we should create our terrain.
		mTerrain = mCore->GetRoot()->AddObject<Terrain>("First Terrain");

		// We want to partition our terrain into an 8 by 8 grid. This will create 64 subdivisions
		// that the terrain will use together with frustum culling to automatically discard portions
		// of the terrain that are not visible. We can actually see what percentage of the terrain
		// is being rendered by using the Terrain::GetVisibility() function after the scene has been
		// culled... but more on that later.

		mTerrain->PartitionInto(8, 8);

		// In order to fill the terrain's partitions with geometry we need to provide additional
		// information about the heightmap that will be used and how it will be used to begin with.
		// Terrain::Heightmap struct exists for just this purpose.

		// Provide the heightmap itself
		Terrain::Heightmap hm (noise.GetBuffer(), noise.GetWidth(), noise.GetHeight());

		// We want each subdivided mesh to be 32 by 32 quads. As you might recall there are 64 subdivisions
		// in total, and now each of those 64 will contain (32 x 32) = 1024 quads, or 2048 triangles.
		// When the terrain is generated the provided heightmap will be sampled using bicubic filtering,
		// so you can make the mesh much more tessellated than the heightmap, if you wish.

		hm.mMeshSize.Set(32, 32);

		// By default the terrain will be generated with dimensions of (0, 0, 0) to (1, 1, 1). Of course
		// that's not what we want. Let's apply a different scaling property here, stretching the terrain
		// along the horizontal plane (and a little bit along the vertical as well).
		hm.mTerrainScale.Set(20.0f, 20.0f, 4.0f);

		// By default the terrain starts at (0, 0, 0). Let's somwhat-center it instead.
		hm.mTerrainOffset.Set(-10.0f, -10.0f, -3.0f);

		// Time to fill the actual geometry. One last important thing to note is the optional bounding
		// box padding parameter that QuadTree::Fill function accepts. This parameter is used to extrude
		// the height of the bounding box vertically in both directions so that child objects can
		// fit easier. Objects that "fit" into the bounding box of the terrain's subdivisioned
		// nodes will get culled faster, speeding up your game. I recommend setting this property to
		// the height of the tallest building or tree you expect to place on your map. In this
		// example we don't have any objects placed as children of the terrain, but it's worth
		// noting nonetheless.

		mTerrain->FillGeometry(&hm, 0.0f);

		// And now... we need to be able to see the terrain we've just created.
		// The best way to visualize a terrain without any textures on it is to display it in wireframe.
		// You can easily do that in R5 by using a material that has a "Wireframe" technique as one of
		// its draw methods. As long as you won't forget to use that technique in the OnDraw function,
		// your wireframe object will show up in your scene. In this case it will be used for our terrain.

		// Wireframe is an R5-recognized technique so we don't need to set up any states.
		ITechnique* wireframe = mGraphics->GetTechnique("Wireframe");

		// Save it for our Draw function
		//mTechniques.Expand() = wireframe;

		// We'll be using a custom material to draw our terrain. Let's just give it the same name.
		IMaterial* mat = mGraphics->GetMaterial("Terrain");

		// Se need to change the material's color as all newly created materials start invisible (alpha of 0)
		mat->SetDiffuse( Color4ub(255, 255, 255, 255) );

		// Add this technique to the material
		mat->GetDrawMethod(wireframe, true);

		// Tell the terrain to use this material
		mTerrain->SetMaterial(mat);

		// Last thing we should do is find the label I've added to the "T08.txt" configuration file.
		// The reason it's not created via code is to simplify this tutorial. If you're curious,
		// have a look at that resource file and see how it was created inside. Since the label is
		// part of the configuration file that we've loaded at the top of this function, it's already
		// in memory and all we have to do is find it using this handy template:

		mLabel = mUI->FindWidget<UILabel>("Status");

		// Add a custom draw function that will update the label showing us how much of the terrain is
		// actually visible at any given time. Look below to see exactly what it does.
		mCore->AddOnDraw( bind(&TestApp::OnDraw, this) );

		// Enter the message processing loop
		mCore->Unlock();
		while (mCore->Update());

		//*mCore >> "Config/T08.txt";
	}
}
Example #2
0
/// Try and compile a fragment starting at the specified address. Returns
/// true if successful setting \a nextAddress to the first instruction after
/// the fragment. If unsuccessful returns false and sets \a nextAddress to the
/// address after the current function. \a endOfBlock is set to true if the
/// next address is in a new basic block.
bool JITImpl::
compileOneFragment(Core &core, JITCoreInfo &coreInfo, uint32_t startPc,
                   bool &endOfBlock, uint32_t &pcAfterFragment)
{
  assert(initialized);
  resetPerFunctionState();

  auto infoIt = coreInfo.functionMap.find(startPc);
  JITFunctionInfo *info =
    (infoIt == coreInfo.functionMap.end()) ? 0 : infoIt->second;
  if (info && !info->isStub) {
    endOfBlock = true;
    return false;
  }

  std::vector<InstructionOpcode> opcode;
  std::vector<Operands> operands;
  if (!getFragmentToCompile(core, core.fromRamPc(startPc), opcode, operands,
                            endOfBlock, pcAfterFragment)) {
    pcAfterFragment = core.toRamPc(pcAfterFragment);
    return false;
  }
  std::queue<std::pair<uint32_t,MemoryCheck*> > checks;
  placeMemoryChecks(opcode, operands, checks);

  LLVMValueRef f;
  if (info) {
    f = info->value;
    info->func = 0;
    info->isStub = false;
    deleteFunctionBody(f);
  } else {
    info = new JITFunctionInfo(startPc);
    coreInfo.functionMap.insert(std::make_pair(startPc, info));
    // Create function to contain the code we are about to add.
    info->value = f = LLVMAddFunction(module, "", jitFunctionType);
    LLVMSetFunctionCallConv(f, LLVMFastCallConv);
  }
  threadParam = LLVMGetParam(f, 0);
  LLVMValueRef ramBase =
    LLVMConstInt(LLVMInt32TypeInContext(context), core.getRamBase(), false);
  ramSizeLog2Param =
    LLVMConstInt(LLVMInt32TypeInContext(context), core.getRamSizeLog2(), false);
  LLVMBasicBlockRef entryBB =
    LLVMAppendBasicBlockInContext(context, f, "entry");
  LLVMPositionBuilderAtEnd(builder, entryBB);
  uint32_t pc = startPc;
  bool needsReturn = true;
  for (unsigned i = 0, e = opcode.size(); i != e; ++i) {
    InstructionOpcode opc = opcode[i];
    const Operands &ops = operands[i];
    InstructionProperties *properties = &instructionProperties[opc];
    uint32_t nextPc = pc + properties->size / 2;
    emitMemoryChecks(i, checks);

    // Lookup function to call.
    LLVMValueRef callee = LLVMGetNamedFunction(module, properties->function);
    assert(callee && "Function for instruction not found in module");
    LLVMTypeRef calleeType = LLVMGetElementType(LLVMTypeOf(callee));
    const unsigned fixedArgs = 4;
    const unsigned maxOperands = 6;
    unsigned numArgs = properties->getNumExplicitOperands() + fixedArgs;
    assert(LLVMCountParamTypes(calleeType) == numArgs);
    LLVMTypeRef paramTypes[fixedArgs + maxOperands];
    assert(numArgs <= (fixedArgs + maxOperands));
    LLVMGetParamTypes(calleeType, paramTypes);
    // Build call.
    LLVMValueRef args[fixedArgs + maxOperands];
    args[0] = threadParam;
    args[1] = LLVMConstInt(paramTypes[1], nextPc, false);
    args[2] = ramBase;
    args[3] = ramSizeLog2Param;
    for (unsigned i = fixedArgs; i < numArgs; i++) {
      uint32_t value =
      properties->getNumExplicitOperands() <= 3 ? ops.ops[i - fixedArgs] :
      ops.lops[i - fixedArgs];
      args[i] = LLVMConstInt(paramTypes[i], value, false);
    }
    LLVMValueRef call = emitCallToBeInlined(callee, args, numArgs);
    checkReturnValue(call, *properties);
    if (properties->mayBranch() && properties->function &&
        emitJumpToNextFragment(opc, ops, coreInfo, nextPc, info)) {
      needsReturn = false;
    }
    pc = nextPc;
  }
  assert(checks.empty() && "Not all checks emitted");
  if (needsReturn) {
    LLVMValueRef args[] = {
      threadParam
    };
    emitCallToBeInlined(functions.jitUpdateExecutionFrequency, args, 1);
    // Build return.
    LLVMBuildRet(builder,
                 LLVMConstInt(LLVMGetReturnType(jitFunctionType),
                              JIT_RETURN_CONTINUE, 0));
  }
  // Add incoming phi values.
  if (earlyReturnBB) {
    LLVMAddIncoming(earlyReturnPhi, &earlyReturnIncomingValues[0],
                    &earlyReturnIncomingBlocks[0],
                    earlyReturnIncomingValues.size());
  }
  if (DEBUG_JIT) {
    LLVMDumpValue(f);
    LLVMVerifyFunction(f, LLVMAbortProcessAction);
  }
  // Optimize.
  for (LLVMValueRef call : calls) {
    LLVMExtraInlineFunction(call);
  }
  LLVMRunFunctionPassManager(FPM, f);
  if (DEBUG_JIT) {
    LLVMDumpValue(f);
  }
  // Compile.
  JITInstructionFunction_t compiledFunction =
    reinterpret_cast<JITInstructionFunction_t>(
      LLVMRecompileAndRelinkFunction(executionEngine, f));
  info->isStub = false;
  info->func = compiledFunction;
  core.setOpcode(startPc, getFunctionThunk(*info), (pc - startPc) * 2);
  return true;
}
Example #3
0
int BootSequenceStepElf::execute(ExecutionState &state)
{
  SystemState &sys = state.sys;
  BreakpointManager &BM = state.breakpointManager;
  const LoadedElf &loadedElf = state.elfManager.load(*core, elfSector);
  Elf *e = loadedElf.getElf();
  const char *buf = loadedElf.getBuf();
  if (elf_kind(e) != ELF_K_ELF) {
    std::cerr << "ELF section is not an ELF object" << std::endl;
    std::exit(1);
  }
  GElf_Ehdr ehdr;
  if (gelf_getehdr(e, &ehdr) == NULL) {
    std::cerr << "Reading ELF header failed: " << elf_errmsg(-1) << std::endl;
    std::exit(1);
  }
  if (ehdr.e_machine != XCORE_ELF_MACHINE &&
      ehdr.e_machine != XCORE_ELF_MACHINE_OLD) {
    std::cerr << "Not a XCore ELF" << std::endl;
    std::exit(1);
  }
  uint32_t entryPoint = core->getRamBase();
  if (ehdr.e_entry != 0) {
    if (core->isValidRamAddress(ehdr.e_entry)) {
      entryPoint = ehdr.e_entry;
    } else {
      std::cout << "Warning: invalid ELF entry point 0x";
      std::cout << std::hex << ehdr.e_entry << std::dec << "\n";
    }
  }
  uint32_t ram_base = core->getRamBase();
  uint32_t ram_size = core->getRamSize();
  if (loadImage) {
    unsigned num_phdrs = ehdr.e_phnum;
    if (num_phdrs == 0) {
      std::cerr << "No ELF program headers" << std::endl;
      std::exit(1);
    }
    for (unsigned i = 0; i < num_phdrs; i++) {
      GElf_Phdr phdr;
      if (gelf_getphdr(e, i, &phdr) == NULL) {
        std::cerr << "Reading ELF program header " << i << " failed: ";
        std::cerr << elf_errmsg(-1) << std::endl;
        std::exit(1);
      }
      if (phdr.p_filesz == 0) {
        continue;
      }
      if (phdr.p_offset > elfSector->getElfSize()) {
        std::cerr << "Invalid offet in ELF program header" << i << std::endl;
        std::exit(1);
      }
      if (core->isValidRamAddress(phdr.p_paddr) &&
          core->isValidRamAddress(phdr.p_paddr + phdr.p_memsz)) {
        core->writeMemory(phdr.p_paddr, &buf[phdr.p_offset], phdr.p_filesz);
      } else if (!hasValidVirtualAddress(phdr, *core)) {
        std::cerr << "Error data from ELF program header " << i;
        std::cerr << " does not fit in memory" << std::endl;
        std::exit(1);
      }
    }
  }

  std::unique_ptr<CoreSymbolInfo> CSI;
  readSymbols(e, ram_base, ram_base + ram_size, CSI);
  SymbolInfo &SI = sys.getSymbolInfo();
  SI.add(core, std::move(CSI));

  // Patch in syscall instruction at the syscall address.
  if (const ElfSymbol *syscallSym = SI.getGlobalSymbol(core, "_DoSyscall")) {
    if (!BM.setBreakpoint(*core, syscallSym->value, BreakpointType::Syscall)) {
      std::cout << "Warning: invalid _DoSyscall address "
      << std::hex << syscallSym->value << std::dec << "\n";
    }
  }
  // Patch in exception instruction at the exception address
  if (const ElfSymbol *doExceptionSym = SI.getGlobalSymbol(core, "_DoException")) {
    if (!BM.setBreakpoint(*core, doExceptionSym->value,
                          BreakpointType::Exception)) {
      std::cout << "Warning: invalid _DoException address "
      << std::hex << doExceptionSym->value << std::dec << "\n";
    }
  }
  if (useElfEntryPoint) {
    sys.schedule(core->getThread(0));
    core->getThread(0).setPcFromAddress(entryPoint);
  }

  return 0;
}
Example #4
0
void PrivacyForm::onEncryptLogsUpdated()
{
    Core* core = Core::getInstance();

    if (bodyUI->cbEncryptHistory->isChecked())
    {
        if (!core->isPasswordSet(Core::ptHistory))
        {
            if (setChatLogsPassword())
            {
                bodyUI->cbEncryptHistory->setChecked(true);
                bodyUI->changeLogsPwButton->setEnabled(true);
                return;
            }
        }
    }
    else
    {
        QMessageBox::StandardButton button = QMessageBox::warning(
            Widget::getInstance(),
            tr("Old encrypted chat history", "title"),
            tr("Would you like to decrypt your chat history?\nOtherwise it will be deleted."),
            QMessageBox::Ok | QMessageBox::No | QMessageBox::Cancel,
            QMessageBox::Cancel
        );

        if (button == QMessageBox::Ok)
        {
            QList<HistoryKeeper::HistMessage> oldMessages = HistoryKeeper::exportMessagesDeleteFile(true);
            core->clearPassword(Core::ptHistory);
            Settings::getInstance().setEncryptLogs(false);
            HistoryKeeper::getInstance()->importMessages(oldMessages);
        }
        else if (button == QMessageBox::No)
        {
            if (QMessageBox::critical(
                    Widget::getInstance(),
                    tr("Old encrypted chat history", "title"),
                    tr("Are you sure you want to lose your entire chat history?"),
                    QMessageBox::Yes | QMessageBox::Cancel,
                    QMessageBox::Cancel
                    )
                == QMessageBox::Yes)
            {
                HistoryKeeper::removeHistory(true);
            }
            else
            {
                bodyUI->cbEncryptHistory->setChecked(true);
                return;
            }
        }
        else
        {
            bodyUI->cbEncryptHistory->setChecked(true);
            return;
        }
    }

    core->clearPassword(Core::ptHistory);
    Settings::getInstance().setEncryptLogs(false);
    bodyUI->cbEncryptHistory->setChecked(false);
    bodyUI->changeLogsPwButton->setEnabled(false);
    HistoryKeeper::resetInstance();
}
Example #5
0
ChatForm::ChatForm(Friend* chatFriend)
    : f(chatFriend)
    , isTyping{false}
{
    Core* core = Core::getInstance();
    coreav = core->getAv();

    nameLabel->setText(f->getDisplayedName());

    avatar->setPixmap(QPixmap(":/img/contact_dark.svg"), Qt::transparent);

    statusMessageLabel = new CroppingLabel();
    statusMessageLabel->setObjectName("statusLabel");
    statusMessageLabel->setFont(Style::getFont(Style::Medium));
    statusMessageLabel->setMinimumHeight(Style::getFont(Style::Medium).pixelSize());
    statusMessageLabel->setTextFormat(Qt::PlainText);

    callConfirm = nullptr;
    offlineEngine = new OfflineMsgEngine(f);

    typingTimer.setSingleShot(true);

    callDurationTimer = nullptr;
    disableCallButtonsTimer = nullptr;

    chatWidget->setTypingNotification(ChatMessage::createTypingNotification());

    headTextLayout->addWidget(statusMessageLabel);
    headTextLayout->addStretch();
    callDuration = new QLabel();
    headTextLayout->addWidget(callDuration, 1, Qt::AlignCenter);
    callDuration->hide();

    chatWidget->setMinimumHeight(160);
    connect(this, &GenericChatForm::messageInserted, this, &ChatForm::onMessageInserted);

    loadHistoryAction = menu.addAction(QString(), this, SLOT(onLoadHistory()));

    connect(core, &Core::fileSendStarted, this, &ChatForm::startFileSend);
    connect(sendButton, &QPushButton::clicked, this, &ChatForm::onSendTriggered);
    connect(fileButton, &QPushButton::clicked, this, &ChatForm::onAttachClicked);
    connect(screenshotButton, &QPushButton::clicked, this, &ChatForm::onScreenshotClicked);
    connect(callButton, &QPushButton::clicked, this, &ChatForm::onCallTriggered);
    connect(videoButton, &QPushButton::clicked, this, &ChatForm::onVideoCallTriggered);
    connect(msgEdit, &ChatTextEdit::enterPressed, this, &ChatForm::onSendTriggered);
    connect(msgEdit, &ChatTextEdit::textChanged, this, &ChatForm::onTextEditChanged);
    connect(core, &Core::fileSendFailed, this, &ChatForm::onFileSendFailed);
    connect(this, &ChatForm::chatAreaCleared, getOfflineMsgEngine(), &OfflineMsgEngine::removeAllReciepts);
    connect(&typingTimer, &QTimer::timeout, this, [=]{
        Core::getInstance()->sendTyping(f->getFriendID(), false);
        isTyping = false;
    } );
    connect(nameLabel, &CroppingLabel::editFinished, this, [=](const QString& newName)
    {
        nameLabel->setText(newName);
        emit aliasChanged(newName);
    } );

    setAcceptDrops(true);

    retranslateUi();
    Translator::registerHandler(std::bind(&ChatForm::retranslateUi, this), this);
}
Example #6
0
bool
Script::_ExecuteAction(action_node* act)
{
#if DEBUG_SCRIPTS
	printf("SCRIPT: %s (%d 0x%x)\n", IDTable::ActionAt(act->id).c_str(), act->id, act->id);
	act->Print();
#endif
	Core* core = Core::Get();
	Actor* thisActor = dynamic_cast<Actor*>(fTarget.Target());

	switch (act->id) {
		case 0x03:
		{
			/* Attack(O:Target*) */
			Object* targetObject = FindObject(act);
			if (targetObject != NULL) {
				Actor* targetActor = dynamic_cast<Actor*>(targetObject);
				if (thisActor != NULL && targetActor != NULL) {
					Attack* attackAction = new Attack(thisActor, targetActor);
					thisActor->AddAction(attackAction);
				}
			}
			break;
		}
		case 0x07:
		{
			/* CreateCreature(S:NewObject*,P:Location*,I:Face*) */
			// TODO: If point is (-1, -1) we should put the actor near
			// the active creature. Which one is the active creature?
			IE::point point = act->where;
			if (point.x == -1 && point.y == -1) {
				point = Game::Get()->Party()->ActorAt(0)->Position();
				point.x += Core::RandomNumber(-20, 20);
				point.y += Core::RandomNumber(-20, 20);
			}

			Actor* actor = new Actor(act->string1, point, act->integer1);
			RoomContainer::Get()->ActorEnteredArea(actor);

			// TODO: Add actor to the current area
			break;
		}

		case 0x8:
		{
			/*	DIALOGUE(O:OBJECT*) (8 0x8) */
			Actor* actor = dynamic_cast<Actor*>(FindObject(act));
			if (actor != NULL) {
				Dialogue* dialogueAction = new Dialogue(thisActor, actor);
				thisActor->AddAction(dialogueAction);
			}
			break;
		}
		case 0xA:
		{
			/* ENEMY() (10 0xa) */
			uint32 id = IDTable::EnemyAllyValue("ENEM");
			thisActor->SetEnemyAlly(id);
			break;
		}
		case 22:
		{
			// MoveToObject
			Object* object = FindObject(act);
			if (object != NULL) {
				WalkTo* walkTo = new WalkTo(thisActor, object->Position());
				fTarget.Target()->AddAction(walkTo);
			}

			break;
		}
		case 23:
		{
			// MoveToPoint
			Actor* actor = dynamic_cast<Actor*>(fTarget.Target());
			if (actor != NULL) {
				WalkTo* walkTo = new WalkTo(actor, act->where);
				actor->AddAction(walkTo);
				actor->StopCheckingConditions();
			}
			break;
		}
		case 29:
		{
			/* RunAwayFrom(O:Creature*,I:Time*) */
			Actor* targetActor = dynamic_cast<Actor*>(FindObject(act));
			if (targetActor != NULL && thisActor != NULL) {
				RunAwayFrom* run = new RunAwayFrom(thisActor, targetActor);
				fTarget.Target()->AddAction(run);
			}
			break;
		}
		case 36:
		{
			/*
			 * 36 Continue()
			 * This action instructs the script parser to continue looking
			 * for actions in the active creatures action list.
			 * This is mainly included in scripts for efficiency.
			 * Continue should also be appended to any script blocks added
			 * to the top of existing scripts, to ensure correct functioning
			 * of any blocks which include the OnCreation trigger.
			 * Continue may prevent actions being completed until the script
			 * parser has finished its execution cycle. Continue() must be
			 * the last command in an action list to function correctly.
			 * Use of continue in a script block will cause the parser
			 * to treater subsequent empty response blocks as though they
			 * contained a Continue() command - this parsing can be stopped
			 * by including a NoAction() in the empty response block.
			 */
			// TODO: Implement
			break;
		}
		case 61:
		{
			/* 61 StartTimer(I:ID*,I:Time*)
			This action starts a timer local to the active creature.
			The timer is measured in seconds, and the timer value is
			not saved in save games. The timer is checked with the
			TimerExpired trigger.*/

			// TODO: We should add the timer local to the active creature,
			// whatever that means
			if (fTarget.Target() == NULL)
				printf("NULL TARGET\n");
			std::ostringstream stringStream;
			stringStream << fTarget.Target()->Name() << " " << act->integer1;

			GameTimer::Add(stringStream.str().c_str(), act->integer2);

			break;
		}
		case 85:
		{
			/* 85 RandomWalk */
			if (thisActor != NULL && thisActor->IsInterruptable())
				core->RandomWalk(thisActor);
			break;
		}
		case 86:
		{
			/* 86 SetInterrupt(I:State*Boolean) */
			if (thisActor != NULL)
				thisActor->SetInterruptable(act->integer1 == 1);
			break;
		}
		case 0x1E:
		{
			std::string variableScope;
			variableScope.append(act->string1, 6);
			std::string variableName;
			variableName.append(&act->string1[6]);

			if (variableScope.compare("LOCALS") == 0) {
				if (fTarget != NULL)
					fTarget.Target()->SetVariable(variableName.c_str(),
							act->integer1);
			} else {
				// TODO: Check for AREA variables
				core->SetVariable(variableName.c_str(),
						act->integer1);
			}
			break;
		}
		case 0x53:
		{
			/* 83 SmallWait(I:Time*) */
			// TODO: The time is probably wrong
			Wait* wait = new Wait(thisActor, act->integer1);
			fTarget.Target()->AddAction(wait);
			break;
		}

		case 106:
		{
			/* Shout */
			// Check if target is silenced
			if (thisActor != NULL)
				thisActor->Shout(act->integer1);
			break;
		}
		case 0x64:
		{
			/* 100 RandomFly */
			if (thisActor != NULL && thisActor->IsInterruptable())
				core->RandomFly(thisActor);
			break;
		}
		case 0x65:
		{
			/* 101 FlyToPoint(Point, Time) */
			if (thisActor != NULL && thisActor->IsInterruptable()) {
				FlyTo* flyTo = new FlyTo(thisActor, act->where, act->integer1);
				thisActor->AddAction(flyTo);
			}
			break;
		}
		case 111:
		{
			/* DESTROYSELF() (111 0x6f) */
			// TODO: Delete it for real
			fTarget.Target()->SetStale(true);
			return false;
		}
		case 0x73:
		{
			/* SETGLOBALTIMER(S:NAME*,S:AREA*,I:TIME*GTIMES) (115 0x73)*/
			std::string timerName;
			// TODO: We append the timer name to the area name,
			// check if it's okay
			timerName.append(act->string2).append(act->string1);
			GameTimer::Add(timerName.c_str(), act->integer1);
			break;
		}
		case 0x97:
		{
			/* 151 DisplayString(O:Object*,I:StrRef*)
			 * This action displays the strref specified by the StrRef parameter
			 * in the message window, attributing the text to
			 * the specified object.
			 */
			core->DisplayMessage(act->integer1);
			break;
		}
		case 0xA7:
		{
			core->PlayMovie(act->string1);
			break;
		}

		case 134:
		{
			/* AttackReevaluate(O:Target*,I:ReevaluationPeriod*)
			 *  (134 0x86)
			 */
			Actor* targetActor = dynamic_cast<Actor*>(FindObject(act));
			if (thisActor != NULL && targetActor != NULL) {
				IE::point point = targetActor->NearestPoint(thisActor->Position());
				WalkTo* walkToAction = new WalkTo(thisActor, point);
				thisActor->AddAction(walkToAction);
				Attack* attackAction = new Attack(thisActor, targetActor);
				thisActor->AddAction(attackAction);
			}

			break;
		}
		case 198: // 0xc6
		{
			/* STARTDIALOGNOSET(O:OBJECT*) (198 0xc6) */
			// TODO: Implement more correctly.
			Actor* actor = dynamic_cast<Actor*>(FindObject(act));
			if (actor != NULL) {
				Dialogue* dialogueAction = new Dialogue(thisActor, actor);
				thisActor->AddAction(dialogueAction);
			}
			break;
		}
		case 207:
		{
			/* 207 MoveToPointNoInterrupt(P:Point*)
			 * This action causes the active creature to move to the specified coordinates.
			 * The action will update the position of creatures as stored in ARE files
			 * (first by setting the coordinates of the destination point, then by setting
			 * the coordinates of the current point once the destination is reached).
			 * Conditions are not checked until the destination point is reached.*/
			Actor* actor = dynamic_cast<Actor*>(fTarget.Target());
			if (actor != NULL) {
				WalkTo* walkTo = new WalkTo(actor, act->where);
				actor->AddAction(walkTo);
				actor->StopCheckingConditions();
			}
			break;
		}
		case 228: // 0xe4
		{
			/* CreateCreatureImpassable(S:NewObject*,P:Location*,I:Face*) (228 0xe4) */
			/* This action creates the specified creature
			 * on a normally impassable surface (e.g. on a wall,
			 * on water, on a roof). */
			Actor* actor = new Actor(act->string1, act->where, act->integer1);
			std::cout << "Created actor " << act->string1 << " on ";
			std::cout << act->where.x << ", " << act->where.y << std::endl;
			actor->SetDestination(act->where);
			RoomContainer::Get()->ActorEnteredArea(actor);
			break;
		}
		default:
			printf("SCRIPT: UNIMPLEMENTED ACTION!!!\n");
			printf("SCRIPT: %s (%d 0x%x)\n", IDTable::ActionAt(act->id).c_str(), act->id, act->id);
			act->Print();
			break;
	}

	return true;
}
Example #7
0
/**
@brief Saves the current settings back to file
*/
void SettingsSerializer::save()
{
    QSaveFile f(path);
    if (!f.open(QIODevice::Truncate | QIODevice::WriteOnly))
    {
        qWarning() << "Couldn't open file";
        return;
    }

    QByteArray data(magic, 4);
    QDataStream stream(&data, QIODevice::ReadWrite | QIODevice::Append);
    stream.setVersion(QDataStream::Qt_5_0);

    for (int g=-1; g<groups.size(); g++)
    {
        // Save the group name, if any
        if (g!=-1)
        {
            writeStream(stream, RecordTag::GroupStart);
            writeStream(stream, groups[g].toUtf8());
        }

        // Save all the arrays of this group
        for (const Array& a : arrays)
        {
            if (a.group != g)
                continue;
            if (a.size <= 0)
                continue;
            writeStream(stream, RecordTag::ArrayStart);
            writeStream(stream, a.name.toUtf8());
            writeStream(stream, vintToData(a.size));

            for (int vi : a.values)
            {
                const Value& v = values[vi];
                writeStream(stream, RecordTag::ArrayValue);
                writeStream(stream, vintToData(values[vi].arrayIndex));
                writeStream(stream, v.key.toUtf8());
                writePackedVariant(stream, v.value);
            }
            writeStream(stream, RecordTag::ArrayEnd);
        }

        // Save all the values of this group that aren't in an array
        for (const Value& v : values)
        {
            if (v.group != g || v.array != -1)
                continue;
            writeStream(stream, RecordTag::Value);
            writeStream(stream, v.key.toUtf8());
            writePackedVariant(stream, v.value);
        }
    }

    // Encrypt
    if (!password.isEmpty())
    {
        Core* core = Nexus::getCore();
        auto passkey = core->createPasskey(password);
        data = core->encryptData(data, *passkey);
    }

    f.write(data);

    // check if everything got written
    if (f.flush())
    {
        f.commit();
    }
    else
    {
        f.cancelWriting();
        qCritical() << "Failed to write, can't save!";
    }
}
 static Node* uncle(Node* n) {
   return sibling(parent(n));
 }
Example #9
0
File: umr.cpp Project: obmun/moab
ErrorCode get_max_volume(Core &mb,  EntityHandle fileset, int dim, double &vmax)
{
  ErrorCode error;
  VerdictWrapper vw(&mb);
  QualityType q;

  switch (dim) {
    case 1: q = MB_LENGTH; break;
    case 2: q = MB_AREA; break;
    case 3: q = MB_VOLUME; break;
    default: return MB_FAILURE; break;
    }

  //Get all entities of the highest dimension which is passed as a command line argument.
  Range allents, owned;
  error = mb.get_entities_by_handle(fileset, allents);MB_CHK_ERR(error);
  owned = allents.subset_by_dimension(dim);MB_CHK_ERR(error);

  //Get all owned entities
#ifdef MOAB_HAVE_MPI
  int size = 1;
  MPI_Comm_size( MPI_COMM_WORLD, &size );
  int mpi_err;
  if (size>1)
    {
      // filter the entities not owned, so we do not process them more than once
      ParallelComm* pcomm = moab::ParallelComm::get_pcomm(&mb, 0);
      Range current = owned;
      owned.clear();
      error = pcomm->filter_pstatus(current, PSTATUS_NOT_OWNED, PSTATUS_NOT, -1, &owned);
      if (error != MB_SUCCESS)
        {
          MPI_Finalize();
          return MB_FAILURE;
        }
    }
#endif

  double vmax_local=0;
  //Find the maximum volume of an entity in the owned mesh
  for (Range::iterator it=owned.begin(); it != owned.end(); it++)
    {
      double volume;
      error = vw.quality_measure(*it, q, volume);MB_CHK_ERR(error);
      if (volume >vmax_local)
        vmax_local = volume;
    }

  //Get the global maximum
  double vmax_global = vmax_local;
#ifdef MOAB_HAVE_MPI
  mpi_err = MPI_Reduce(&vmax_local, &vmax_global, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
  if (mpi_err)
      {
        MPI_Finalize();
        return MB_FAILURE;
      }
#endif

  vmax = vmax_global;

  return MB_SUCCESS;
}
 /*
    Non primary traits
  */
 static bool is_red(Node* n) {
   return !is_black(n);
 }
 static bool is_left(Node* n) {
   return left_child(parent(n)) == n;
 }
Example #12
0
File: os.cpp Project: yb-kim/osSim
void OS::executeCore(unsigned int n, unsigned int unitTick) {
    Core *core = env->getCore(n);
    core->run(unitTick);
}
int Think::Bestmove(
	Core			core			,
	int				color			,
	Board*			pBoard			,
	LibertyOfNodes*	pLibertyOfNodes
)
{
#ifdef CHECK_LOG
	core.PRT( _T("Bestmove開始☆! \n"));
#endif

#ifdef ENABLE_MOVE_RETRY
	int retry = 0;
	// 異常回避☆! リトライ☆!
	gt_Retry:
		;
#endif


	int maxScore;	// 今まで読んだ手で一番高かった評価値
	int bestmoveNode;

	// 実行するたびに違う値が得られるように現在の時刻で乱数を初期化
	srand((unsigned)clock());

	//----------------------------------------
	// 石を置く位置1つずつ、その手の評価値を算出します。
	//----------------------------------------
	maxScore = -1;
	bestmoveNode = 0; // 0 ならパス。

	pBoard->ForeachAllNodesWithoutWaku([color,&maxScore,&bestmoveNode,&pBoard,&pLibertyOfNodes, &core](int node, bool& isBreak) {
		//{
			//int x, y;
			//AbstractBoard::ConvertToXy(x, y, node);
			//core.PRT(_T("#(%d,%d) "), x, y);
		//}

		// この局面で、石を置いたときの評価値
		int flgAbort = 0;
		int score;		// 読んでいる手の評価値
		score = Evaluation::EvaluateAtNode(core, flgAbort, color, node, pBoard, pLibertyOfNodes);
		if (flgAbort)
		{
			goto gt_Next;
		}

		// ベストムーブを更新します。
		// PRT("x,y=(%d,%d)=%d\n",x,y,score);
		if (maxScore < score) {
			maxScore = score;
			bestmoveNode = node;
		}
	gt_Next:
		;
	});

#ifdef ENABLE_MOVE_RETRY

	int x, y;
	AbstractBoard::ConvertToXy(x, y, bestmoveNode);

	// 異常回避☆! リトライ☆!
	if (bestmoveNode==0)
	{
		// パスは正常です。
		goto gt_EndMethod;
	}
	else if (400<retry)
	{
		// 諦めてパスにします。
		bestmoveNode = 0;
		goto gt_EndMethod;
	}
	else if (pBoard->ValueOf(bestmoveNode) == BLACK || pBoard->ValueOf(bestmoveNode) == WHITE) {
		// 石があるなら
		core.PRT(_T("(%d,%d) 石がある。 リトライ☆! [%d]\n"), x,y, retry);
		retry++;
		goto gt_Retry;
	}
	else if (pBoard->ValueOf(bestmoveNode) == WAKU) {
		// 枠なら
		core.PRT(_T("(%d,%d) 枠だった。 リトライ☆! [%d]\n"), x, y, retry);
		retry++;
		goto gt_Retry;
	}
	else if (bestmoveNode == pBoard->kouNode) {
		// コウになる位置なら
		core.PRT(_T("(%d,%d) コウになる。 リトライ☆! [%d]\n"), x, y, retry);
		retry++;
		goto gt_Retry;
	}

	Liberty liberties[4];// 上隣 → 右隣 → 下隣 → 左隣
	pBoard->ForeachArroundDirAndNodes(bestmoveNode, [&pBoard, &liberties](int iDir, int adjNode, bool& isBreak) {
		int adjColor = pBoard->ValueOf(adjNode);			// 上下左右隣(adjacent)の石の色
		liberties[iDir].Count(adjNode, adjColor, pBoard);	// 隣の石(または連)の呼吸点 の数を数えます。
	});

	// 自分の眼潰しチェック
	{
		NoHitOwnEye	noHitOwnEye;		// 自分の眼に打たない仕組み。
		if (noHitOwnEye.IsThis(color, bestmoveNode, liberties, pBoard)) {// 自分の眼に打ち込む状況か調査
			core.PRT(_T("(%d,%d) 自分の眼に打ち込む。 リトライ☆! [%d]\n"), x, y, retry);
			retry++;
			goto gt_Retry;
		}
	}

	// 自殺手チェック
	{
		NoHitSuicide			noHitSuicide;		// 自殺手を打たないようにする仕組み。

		if (noHitSuicide.IsThis(core, color, bestmoveNode, liberties, pBoard)) {// 自殺手になる状況でないか調査。
			core.PRT(_T("(%d,%d) 自殺手になる。 リトライ☆! [%d]\n"), x, y, retry);
			retry++;
			goto gt_Retry;
		}
	}
#endif

gt_EndMethod:
	return bestmoveNode;
}
Example #14
0
void loop()
{
    core.CabeiriLoop();
}
Example #15
0
static void readElf(const char *filename, const XEElfSector *elfSector,
                    Core &core, std::auto_ptr<CoreSymbolInfo> &SI,
                    std::map<Core*,uint32_t> &entryPoints)
{
  uint64_t ElfSize = elfSector->getElfSize();
  const scoped_array<char> buf(new char[ElfSize]);
  if (!elfSector->getElfData(buf.get())) {
    std::cerr << "Error reading elf data from \"" << filename << "\"" << std::endl;
    std::exit(1);
  }

  if (elf_version(EV_CURRENT) == EV_NONE) {
    std::cerr << "ELF library intialisation failed: "
              << elf_errmsg(-1) << std::endl;
    std::exit(1);
  }
  Elf *e;
  if ((e = elf_memory(buf.get(), ElfSize)) == NULL) {
    std::cerr << "Error reading ELF: " << elf_errmsg(-1) << std::endl;
    std::exit(1);
  }
  if (elf_kind(e) != ELF_K_ELF) {
    std::cerr << filename << " is not an ELF object" << std::endl;
    std::exit(1);
  }
  GElf_Ehdr ehdr;
  if (gelf_getehdr(e, &ehdr) == NULL) {
    std::cerr << "Reading ELF header failed: " << elf_errmsg(-1) << std::endl;
    std::exit(1);
  }
  if (ehdr.e_machine != XCORE_ELF_MACHINE) {
    std::cerr << "Not a XCore ELF" << std::endl;
    std::exit(1);
  }
  if (ehdr.e_entry != 0) {
    entryPoints.insert(std::make_pair(&core, (uint32_t)ehdr.e_entry));
  }
  unsigned num_phdrs = ehdr.e_phnum;
  if (num_phdrs == 0) {
    std::cerr << "No ELF program headers" << std::endl;
    std::exit(1);
  }
  core.resetCaches();
  uint32_t ram_base = core.ram_base;
  uint32_t ram_size = core.getRamSize();
  for (unsigned i = 0; i < num_phdrs; i++) {
    GElf_Phdr phdr;
    if (gelf_getphdr(e, i, &phdr) == NULL) {
      std::cerr << "Reading ELF program header " << i << " failed: " << elf_errmsg(-1) << std::endl;
      std::exit(1);
    }
    if (phdr.p_filesz == 0) {
      continue;
    }
    if (phdr.p_offset > ElfSize) {
    	std::cerr << "Invalid offet in ELF program header" << i << std::endl;
    	std::exit(1);
    }
    if (!core.isValidAddress(phdr.p_paddr) ||
        !core.isValidAddress(phdr.p_paddr + phdr.p_memsz)) {
      std::cerr << "Error data from ELF program header " << i;
      std::cerr << " does not fit in memory" << std::endl;
      std::exit(1);
    }
    core.writeMemory(phdr.p_paddr, &buf[phdr.p_offset], phdr.p_filesz);
  }

  readSymbols(e, ram_base, ram_base + ram_size, SI);

  elf_end(e);
}
Example #16
0
int main(int args, char **argp)
{
	Core* core = new Core();
	core->CoreEntry();
}
Example #17
0
bool
Script::_EvaluateTrigger(trigger_node* trig)
{
	Actor* actor = dynamic_cast<Actor*>(fTarget.Target());
	if (actor != NULL && actor->SkipConditions())
		return false;

#if DEBUG_SCRIPTS
	printf("SCRIPT: %s%s (%d 0x%x) ? ",
			trig->flags != 0 ? "!" : "",
			IDTable::TriggerAt(trig->id).c_str(),
			trig->id, trig->id);
	trig->Print();
#endif

	Core* core = Core::Get();
	bool returnValue = false;
	try {
		switch (trig->id) {
			case 0x0002:
			{
				/* 0x0002 AttackedBy(O:Object*,I:Style*AStyles)
				 * Returns true only if the active CRE was attacked in the style
				 * specified (not necessarily hit) or had an offensive spell cast
				 * on it by the specified object in the last script round.
				 * The style parameter is non functional - this trigger is triggered
				 * by any attack style.
				 */
				object_node* node = FindObjectNode(trig);
				if (node == NULL)
					break;
				node->Print();
				ScriptResults* results = fTarget.Target()->LastScriptRoundResults();
				if (results != NULL) {
					Object* object = Object::GetMatchingObjectFromList(
							results->Attackers(), node);

					returnValue = object != NULL;
				}
				break;
			}
			case 0x400A:
			{
				//ALIGNMENT(O:OBJECT*,I:ALIGNMENT*Align) (16395 0x400A)
				Object* object = FindObject(trig);
				if (object != NULL)
					returnValue = object->IsAlignment(trig->parameter1);

				break;
			}
			case 0x400B:
			{
				//ALLEGIANCE(O:OBJECT*,I:ALLEGIENCE*EA) (16395 0x400b)
				Object* object = FindObject(trig);
				if (object != NULL)
					returnValue = object->IsEnemyAlly(trig->parameter1);

				break;
			}
			case 0x400C:
			{
				/*0x400C Class(O:Object*,I:Class*Class)*/
				Object* object = FindObject(trig);
				if (object != NULL)
					returnValue = object->IsClass(trig->parameter1);
				break;
			}
			case 0x400E:
			{
				/* GENERAL(O:OBJECT*,I:GENERAL*GENERAL) (16398 0x400e)*/
				Object* object = FindObject(trig);
				if (object != NULL)
					returnValue = object->IsGeneral(trig->parameter1);
				break;
			}
			case 0x400F:
			{
				/*0x400F Global(S:Name*,S:Area*,I:Value*)
				Returns true only if the variable with name 1st parameter
				of type 2nd parameter has value 3rd parameter.*/
				std::string variableScope;
				variableScope.append(trig->string1, 6);
				std::string variableName;
				variableName.append(&trig->string1[6]);

				int32 variableValue = 0;
				if (variableScope.compare("LOCALS") == 0) {
					variableValue = fTarget.Target()->GetVariable(variableName.c_str());
				} else {
					// TODO: Check for AREA variables, currently we
					// treat AREA variables as global variables
					variableValue = Core::Get()->GetVariable(variableName.c_str());
				}
				returnValue = variableValue == trig->parameter1;
				break;
			}
			case 0x0020:
			{
				// HitBy
				// Returns true on first Script launch, IOW initial area load
				if (!Processed()) {
					returnValue = true;
					break;
				}
				//object_node* object = FindObjectNode(trig);
				//returnValue = Object::CheckIfNodeInList(object,
				//		fTarget->LastScriptRoundResults()->Hitters());
				break;
			}
			case 0x0022:
			{
				/* TimerExpired(I:ID*) */
				std::ostringstream stringStream;
				stringStream << fTarget.Target()->Name() << " " << trig->parameter1;
				printf("TimerExpired %s\n", stringStream.str().c_str());
				GameTimer* timer = GameTimer::Get(stringStream.str().c_str());
				if (timer != NULL && timer->Expired()) {
					returnValue = true;
				}
				break;
			}
			case 0x002F:
			{
				/* 0x002F Heard(O:Object*,I:ID*SHOUTIDS)
				Returns true only if the active CRE was within 30 feet
				of the specified object and the specified object shouted
				the specified number (which does not have to be in
				SHOUTIDS.ids) in the last script round.
				NB. If the object is specified as a death variable,
				the trigger will only return true if the corresponding
				object shouting also has an Enemy-Ally flag of NEUTRAL. */
				Object* object = FindObject(trig);
				if (object != NULL && core->Distance(fTarget.Target(), object) <= 30
						&& object->LastScriptRoundResults()->Shouted()
						== trig->parameter1) {
					returnValue = true;
				}
				break;
			}


			case 0x4017:
			{
				// Race()
				Object* object = FindObject(trig);
				if (object != NULL)
					returnValue = object->IsRace(trig->parameter1);

				break;
			}

			case 0x4018:
			{
				/* 0x4018 Range(O:Object*,I:Range*)
				Returns true only if the specified object
				is within distance given (in feet) of the active CRE. */
				Object* object = FindObject(trig);
				if (object != NULL)
					returnValue = core->Distance(object, fTarget.Target()) <= trig->parameter1;
				break;
			}

			case 0x401C:
			{
				/* See(O:Object*)
				 * Returns true only if the active CRE can see
				 * the specified object which must not be hidden or invisible.
				 */
				Object* object = FindObject(trig);
				if (object != NULL)
					returnValue = core->See(fTarget.Target(), object);
				break;
			}
			case 0x401E:
			{
				/* Time(I:Time*Time)
				 * Returns true only if the period of day matches the period
				 * in the 2nd parameter (taken from Time.ids).
				 * Hours are offset by 30 minutes, e.g. Time(1) is true
				 * between 00:30 and 01:29.
				 */
				break;
			}

			case 0x4023:
				/* 0x4023 True() */
				returnValue = true;
				break;
			case 0x4027:
			{
				//DELAY(I:DELAY*) (16423 0x4027)
				// TODO: Implement
				returnValue = true;
				break;
			}
			case 0x402b:
			{
				/* ACTIONLISTEMPTY() (16427 0x402b)*/
				returnValue = fTarget.Target()->IsActionListEmpty();
				break;
			}
			case 0x4034:
			{
				/*0x4034 GlobalGT(S:Name*,S:Area*,I:Value*)
				See Global(S:Name*,S:Area*,I:Value*) except the variable
				must be greater than the value specified to be true.
				*/
				returnValue = core->GetVariable(trig->string1) > trig->parameter1;
				break;
			}
			case 0x4035:
			{	/*
				0x4035 GlobalLT(S:Name*,S:Area*,I:Value*)
				As above except for less than. */
				returnValue = core->GetVariable(trig->string1) < trig->parameter1;
				break;
			}
			case 0x0036:
			{
				/*0x0036 OnCreation()
				Returns true if the script is processed for the first time this session,
				e.g. when a creature is created (for CRE scripts) or when the player
				enters an area (for ARE scripts).*/
				returnValue = !Processed();
				break;
			}
			case 0x4037:
			{
				/* StateCheck(O:Object*,I:State*State)
				 * Returns true only if the specified object
				 * is in the state specified.
				 */
				Object* object = FindObject(trig);
				if (object != NULL)
					returnValue = object->IsState(trig->parameter1);
				break;
			}
			case 0x4039:
			{
				/* NUMBEROFTIMESTALKEDTO(I:NUM*) (16441 0x4039) */
				if (actor->NumTimesTalkedTo() == (uint32)trig->parameter1)
					returnValue = true;
				break;
			}
			case 0x4040:
			{
				/* GlobalTimerExpired(S:Name*,S:Area*) (16448 0x4040) */
				// TODO: Merge Name and Area before passing them to the
				// Timer::Get() method (also below)
				std::string timerName;
				timerName.append(trig->string2).append(trig->string1);
				GameTimer* timer = GameTimer::Get(timerName.c_str());
				returnValue = timer != NULL && timer->Expired();
				break;
			}
			case 0x4041:
			{
				/* GlobalTimerNotExpired(S:Name*,S:Area*) */
				std::string timerName;
				timerName.append(trig->string2).append(trig->string1);
				GameTimer* timer = GameTimer::Get(timerName.c_str());
				returnValue = timer == NULL || !timer->Expired();
				break;
			}
			case 0x4043:
			{
				// InParty
				const Actor* actor = dynamic_cast<const Actor*>(FindObject(trig));
				if (actor != NULL)
					returnValue = Game::Get()->Party()->HasActor(actor);

				break;
			}
			case 0x4051:
			{
				/*
				 * 0x4051 Dead(S:Name*)
				 * Returns only true if the creature with the specified script name
				 * has its death variable set to 1. Not every form of death sets this,
				 * but most do. So it's an almost complete test for death.
				 * The creature must have existed for this to be true.
				 * Note that SPRITE_IS_DEAD variables are not set if the creature is
				 * killed by a neutral creature.
				 */
				/*Script* actorScript = fScripts[trig->string1];
				if (actorScript != NULL) {
					// TODO: More NULL checking
					const char* deathVariable = actorScript->Target()->CRE()->DeathVariable();
					returnValue = fVariables[deathVariable] == 1;
				}*/
				break;
			}
			case 0x52:
			{
				/* OPENED(O:OBJECT*) (82 0x52) */
				object_node* objectNode = FindObjectNode(trig);
				if (objectNode == NULL)
					break;
				// TODO: We assume this is a door, but also
				// containers can be opened/closed
				Door* door = dynamic_cast<Door*>(fTarget.Target());
				if (door == NULL)
					break;
				if (!door->Opened())
					break;

				Object* object = core->GetObject(
						door->CurrentScriptRoundResults()->fOpenedBy.c_str());
				if (object != NULL)
					returnValue = object->MatchNode(objectNode);

				break;
			}
			case 0x4063:
			{
				/*INWEAPONRANGE(O:OBJECT*) (16483 0x4063) */
				int range = 40;
				// TODO: Check weapon range
				Object* object = FindObject(trig);
				if (object != NULL)
					returnValue = core->Distance(object, fTarget.Target()) <= range;

				break;
			}

#if 0
			case 0x4068:
			{
				/* TimeGT(I:Time*Time)
				 * Returns true only if the current time is greater than
				 * that specified. Hours are offset by 30 minutes,
				 * e.g. TimeGT(1) is true between 01:30 and 02:29.
				 */
				break;
			}

			case 0x4069:
			{
				//TIMELT(I:TIME*TIME) (16489 0x4069)
				break;
			}
#endif
			case 0x0070:
			{
				/* 0x0070 Clicked(O:Object*)
				 *	Only for trigger regions.
				 *	Returns true if the specified object
				 *	clicked on the trigger region running this script.
				 */
				object_node* objectNode = FindObjectNode(trig);
				returnValue = fTarget.Target()->LastScriptRoundResults()->Clicker()
						->MatchNode(objectNode);
				//objectNode->Print();
				fTarget.Target()->LastScriptRoundResults()->Clicker()->Print();

				// TODO: When to set this, other than now ?
				if (returnValue)
					fLastTrigger = fTarget;
				break;
			}

			case 0x4074:
			{
				/*
				 * 0x4074 Detect(O:Object*)
				 * Returns true if the the specified object
				 * is detected by the active CRE in any way
				 * (hearing or sight). Neither Move Silently
				 * and Hide in Shadows prevent creatures
				 * being detected via Detect().
				 * Detect ignores Protection from Creature
				 * type effects for static objects.
				 */
				Object* object = core->GetObject(fTarget.Target(), FindObjectNode(trig));
				if (object != NULL)
					returnValue = core->See(fTarget.Target(), object);
					// || core->Hear(fTarget, object);
				break;
			}

			case 0x4076:
			{
				/*
				 * 0x4076 OpenState(O:Object*,I:Open*BOOLEAN)
				 * NT Returns true only if the open state of the specified door
				 * matches the state specified in the 2nd parameter.
				 */
				object_node* doorObj = FindObjectNode(trig);
				Door *door = dynamic_cast<Door*>(
								core->GetObject(doorObj->name));
				if (door != NULL) {
					bool openState = trig->parameter1 == 1;
					returnValue = door->Opened() == openState;
				}
				break;
			}
			case 0x407D:
			{
				/* ISOVERME(O:Object*)
				 * Only for trigger regions. Returns true only if the specified
				 * object is over the trigger running the script
				 */
				object_node* object = FindObjectNode(trig);
				if (object != NULL) {
					Object* objectOverRegion = core->GetObject(
							dynamic_cast<Region*>(fTarget.Target()));
					if (objectOverRegion != NULL)
						returnValue = objectOverRegion->MatchNode(object);
				}

				break;
			}
			case 0x407E:
			{
				/* 0x407E AreaCheck(S:ResRef*)
				 * Returns true only if the active CRE
				 * is in the area specified.
				 */
				// TODO: We only check the active area
				returnValue = !strcmp(RoomContainer::Get()->Name(), trig->string1);
				break;
			}
			case 0x4086:
			{
				// AREATYPE(I:NUMBER*AREATYPE) (16518 0x4086)

				// TODO: We only check the active area
				const uint16 areaType = RoomContainer::Get()->AREA()->Type();
				returnValue = areaType & trig->parameter1;
				break;
			}
			case 0x4089:
			{
				/*0x4089 OR(I:OrCount*)*/
				fOrTriggers = trig->parameter1;
				returnValue = true;
				break;
			}
			case 0x401b:
			{
				/* REPUTATIONLT(O:OBJECT*,I:REPUTATION*) (16411 0x401b) */
				Actor* actor = dynamic_cast<Actor*>(FindObject(trig));
				if (actor != NULL) {
					returnValue = actor->CRE()->Reputation() < trig->parameter1;
				}
				break;
			}

			case 0x4c:
			{
				// Entered(O:Object)
				object_node* node = FindObjectNode(trig);
				Region* region = dynamic_cast<Region*>(fTarget.Target());
				//std::vector<std::string>::const_iterator i;
				Object* object = Object::GetMatchingObjectFromList(
										region->
										LastScriptRoundResults()->
										EnteredActors(), node);
				if (object != NULL) {
					fLastTrigger = object;
					returnValue = true;
				}
				break;
			}
			default:
			{
				printf("SCRIPT: UNIMPLEMENTED TRIGGER!!!\n");
				printf("SCRIPT: %s (%d 0x%x)\n", IDTable::TriggerAt(trig->id).c_str(),
								trig->id, trig->id);
				trig->Print();
				break;
			}
		}
	} catch (...) {
		printf("SCRIPT: EvaluateTrigger() caught exception");
	}
	if (trig->flags != 0)
		returnValue = !returnValue;
#if DEBUG_SCRIPTS
	printf("SCRIPT: (%s)\n", returnValue ? "TRUE" : "FALSE");
#endif
	return returnValue;
}
Example #18
0
File: core.cpp Project: Pik-9/qTox
void Core::onGroupAction(Tox*, int groupnumber, int peernumber, const uint8_t *action, uint16_t length, void* _core)
{
    Core* core = static_cast<Core*>(_core);
    emit core->groupMessageReceived(groupnumber, peernumber, CString::toString(action, length), true);
}
Example #19
0
ErrorCode ScdInterface::construct_box(HomCoord low, HomCoord high, const double * const coords, unsigned int num_coords,
                                      ScdBox *& new_box, int * const lperiodic, ScdParData *par_data,
                                      bool assign_gids, int tag_shared_ents)
{
    // create a rectangular structured mesh block
  ErrorCode rval;

  int tmp_lper[3] = {0, 0, 0};
  if (lperiodic) std::copy(lperiodic, lperiodic+3, tmp_lper);
  
#ifndef MOAB_HAVE_MPI
  if (-1 != tag_shared_ents) ERRORR(MB_FAILURE, "Parallel capability requested but MOAB not compiled parallel.");
  if (-1 == tag_shared_ents && !assign_gids) assign_gids = true; // need to assign gids in order to tag shared verts
#else
  if (par_data && low == high && ScdParData::NOPART != par_data->partMethod) {
      // requesting creation of parallel mesh, so need to compute partition
    if (!par_data->pComm) {
        // this is a really boneheaded way to have to create a PC
      par_data->pComm = ParallelComm::get_pcomm(mbImpl, 0);
      if (NULL == par_data->pComm) par_data->pComm = new ParallelComm(mbImpl, MPI_COMM_WORLD);
    }
    int ldims[6];
    rval = compute_partition(par_data->pComm->size(), par_data->pComm->rank(), *par_data, 
                             ldims, tmp_lper, par_data->pDims);
    ERRORR(rval, "Error returned from compute_partition.");
    low.set(ldims[0],ldims[1],ldims[2]);
    high.set(ldims[3],ldims[4],ldims[5]);
    if (par_data->pComm->get_debug_verbosity() > 0) {
      std::cout << "Proc " << par_data->pComm->rank() << ": " << *par_data;
      std::cout << "Proc " << par_data->pComm->rank() << " local dims: " 
                << low << "-" << high << std::endl;
    }
  }
#endif
  
  HomCoord tmp_size = high - low + HomCoord(1, 1, 1, 0);
  if ((tmp_size[1] && num_coords && (int)num_coords < tmp_size[0]) ||
      (tmp_size[2] && num_coords && (int)num_coords < tmp_size[0]*tmp_size[1]))
    return MB_FAILURE;

  rval = create_scd_sequence(low, high, MBVERTEX, 0, new_box);
  ERRORR(rval, "Trouble creating scd vertex sequence.");

    // set the vertex coordinates
  double *xc, *yc, *zc;
  rval = new_box->get_coordinate_arrays(xc, yc, zc);
  ERRORR(rval, "Couldn't get vertex coordinate arrays.");

  if (coords && num_coords) {
    unsigned int i = 0;
    for (int kl = low[2]; kl <= high[2]; kl++) {
      for (int jl = low[1]; jl <= high[1]; jl++) {
        for (int il = low[0]; il <= high[0]; il++) {
          xc[i] = coords[3*i];
          if (new_box->box_size()[1])
            yc[i] = coords[3*i+1];
          if (new_box->box_size()[2])
            zc[i] = coords[3*i+2];
          i++;
        }
      }
    }
  }
  else {
    unsigned int i = 0;
    for (int kl = low[2]; kl <= high[2]; kl++) {
      for (int jl = low[1]; jl <= high[1]; jl++) {
        for (int il = low[0]; il <= high[0]; il++) {
          xc[i] = (double) il;
          if (new_box->box_size()[1])
            yc[i] = (double) jl;
          else yc[i] = 0.0;
          if (new_box->box_size()[2])
            zc[i] = (double) kl;
          else zc[i] = 0.0;
          i++;
        }
      }
    }
  }

    // create element sequence
  Core *mbcore = dynamic_cast<Core*>(mbImpl);
  SequenceManager *seq_mgr = mbcore->sequence_manager();

  EntitySequence *tmp_seq;
  EntityHandle start_ent;

    // construct the sequence
  EntityType this_tp = MBHEX;
  if (1 >= tmp_size[2]) this_tp = MBQUAD;
  if (1 >= tmp_size[2] && 1 >= tmp_size[1]) this_tp = MBEDGE;
  rval = seq_mgr->create_scd_sequence(low, high, this_tp, 0, start_ent, tmp_seq, 
                                      tmp_lper);
  ERRORR(rval, "Trouble creating scd element sequence.");

  new_box->elem_seq(tmp_seq);
  new_box->start_element(start_ent);

    // add vertex seq to element seq, forward orientation, unity transform
  rval = new_box->add_vbox(new_box,
                             // p1: imin,jmin
                           low, low, 
                             // p2: imax,jmin
                           low + HomCoord(1, 0, 0),
                           low + HomCoord(1, 0, 0),
                             // p3: imin,jmax
                           low + HomCoord(0, 1, 0),
                           low + HomCoord(0, 1, 0));
  ERRORR(rval, "Error constructing structured element sequence.");

    // add the new hexes to the scd box set; vertices were added in call to create_scd_sequence
  Range tmp_range(new_box->start_element(), new_box->start_element() + new_box->num_elements() - 1);
  rval = mbImpl->add_entities(new_box->box_set(), tmp_range);
  ERRORR(rval, "Couldn't add new hexes to box set.");

  if (par_data) new_box->par_data(*par_data);
  

  if (assign_gids) {
    rval = assign_global_ids(new_box);
    ERRORR(rval, "Trouble assigning global ids");
  }

#ifdef MOAB_HAVE_MPI
  if (par_data && -1 != tag_shared_ents) {
    rval = tag_shared_vertices(par_data->pComm, new_box);
  }
#endif
  
  return MB_SUCCESS;
}
Example #20
0
File: core.cpp Project: Pik-9/qTox
void Core::onGroupMessage(Tox*, int groupnumber, int peernumber, const uint8_t * message, uint16_t length, void *_core)
{
    Core* core = static_cast<Core*>(_core);
    emit core->groupMessageReceived(groupnumber, peernumber, CString::toString(message, length), false);
}
Example #21
0
void SettingsSerializer::readSerialized()
{
    QFile f(path);
    if (!f.open(QIODevice::ReadOnly))
    {
        qWarning() << "Couldn't open file";
        return;
    }
    QByteArray data = f.readAll();
    f.close();

    // Decrypt
    if (tox_is_data_encrypted(reinterpret_cast<uint8_t*>(data.data())))
    {
        if (password.isEmpty())
        {
            qCritical() << "The settings file is encrypted, but we don't have a password!";
            return;
        }

        Core* core = Nexus::getCore();

        uint8_t salt[TOX_PASS_SALT_LENGTH];
        tox_get_salt(reinterpret_cast<uint8_t *>(data.data()), salt);
        auto passkey = core->createPasskey(password, salt);

        data = core->decryptData(data, *passkey);
        if (data.isEmpty())
        {
            qCritical() << "Failed to decrypt the settings file";
            return;
        }
    }
    else
    {
        if (!password.isEmpty())
            qWarning() << "We have a password, but the settings file is not encrypted";
    }

    if (memcmp(data.data(), magic, 4))
    {
        qWarning() << "Bad magic!";
        return;
    }
    data = data.mid(4);

    QDataStream stream(&data, QIODevice::ReadOnly);
    stream.setVersion(QDataStream::Qt_5_0);

    while (!stream.atEnd())
    {
        RecordTag tag;
        readStream(stream, tag);
        if (tag == RecordTag::Value)
        {
            QByteArray key;
            QByteArray value;
            readStream(stream, key);
            readStream(stream, value);
            setValue(QString::fromUtf8(key), QVariant(QString::fromUtf8(value)));
        }
        else if (tag == RecordTag::GroupStart)
        {
            QByteArray prefix;
            readStream(stream, prefix);
            beginGroup(QString::fromUtf8(prefix));
        }
        else if (tag == RecordTag::ArrayStart)
        {
            QByteArray prefix;
            readStream(stream, prefix);
            beginReadArray(QString::fromUtf8(prefix));
            QByteArray sizeData;
            readStream(stream, sizeData);
            if (sizeData.isEmpty())
            {
                qWarning("The personal save file is corrupted!");
                return;
            }
            int size = dataToVInt(sizeData);
            arrays[array].size = qMax(size, arrays[array].size);
        }
        else if (tag == RecordTag::ArrayValue)
        {
            QByteArray indexData;
            readStream(stream, indexData);
            if (indexData.isEmpty())
            {
                qWarning("The personal save file is corrupted!");
                return;
            }
            setArrayIndex(dataToVInt(indexData));
            QByteArray key;
            QByteArray value;
            readStream(stream, key);
            readStream(stream, value);
            setValue(QString::fromUtf8(key), QVariant(QString::fromUtf8(value)));
        }
        else if (tag == RecordTag::ArrayEnd)
        {
            endArray();
        }
    }

    group = array = -1;
}
Example #22
0
int main(int argc, char** argv){
  // verif M unit
#ifdef CORE_DBG
  verif_m_unit();
#endif

  if(argc < 2)
  {
    return 0;
  }

  Core *pCore = Core::start();
  pCore->init();
  COFF_parser parser(argv[1]);
  pCore->set_mode(BK_AT_MAIN);

  if(argc >= 3)
  {
    core_mode_t mode = (core_mode_t)strtoul(argv[2],NULL,10);
    pCore->set_mode(mode);
  }

  if(argc >= 4)
  {
    word_t thres = strtoul(argv[3],NULL,10);
    Profiler::set_jit_threshold_times(thres);
  }

  if(argc >= 5)
  {
    word_t thres = strtoul(argv[4],NULL,10);
    Profiler::set_jit_threshold_len(thres);
  }

  parser.connect(pCore);
  parser.set_reverse(false);
  parser.parse();
  
  pCore->init();
#if 0
  pCore->reg_write(0,0,2); // A0 = 2
  pCore->reg_write(1,0,3); // B0 = 3

  llvm::Function *func = llvm::cast<llvm::Function>(Core::get_llvm_module().getOrInsertFunction("func",
    Type::getInt32Ty(getGlobalContext()),(Type*)0));
  llvm::BasicBlock* bb = llvm::BasicBlock::Create(getGlobalContext(),"entry",func);
  Core::get_llvm_builder().SetInsertPoint(bb);
  llvm::Constant* a_side_addr = llvm::ConstantInt::get(llvm::Type::getInt32Ty(getGlobalContext())
    ,(uint64_t)pCore->get_reg_a());
  llvm::Constant* b_side_addr = llvm::ConstantInt::get(llvm::Type::getInt32Ty(getGlobalContext())
    ,(uint64_t)pCore->get_reg_b());
  llvm::Constant* dst_addr = llvm::ConstantInt::get(llvm::Type::getInt32Ty(getGlobalContext())
    ,(uint64_t)(pCore->get_reg_b()+1)); // B1
  llvm::Value* a_side = llvm::ConstantExpr::getIntToPtr(a_side_addr,
    llvm::PointerType::getUnqual(llvm::Type::getInt32Ty(getGlobalContext())));
  llvm::Value* b_side = llvm::ConstantExpr::getIntToPtr(b_side_addr,
    llvm::PointerType::getUnqual(llvm::Type::getInt32Ty(getGlobalContext())));

  llvm::Value* b1 = llvm::ConstantExpr::getIntToPtr(dst_addr,
    llvm::PointerType::getUnqual(llvm::Type::getInt32Ty(getGlobalContext())));

  llvm::Value* left = Core::get_llvm_builder().CreateLoad(a_side);
  llvm::Value* right = Core::get_llvm_builder().CreateLoad(b_side);
  llvm::Value* re = Core::get_llvm_builder().CreateAdd(left,right);
  Core::get_llvm_builder().CreateStore(re,b1,true);

  Core::get_llvm_builder().CreateRet(re);

  ExecutionEngine* EE = EngineBuilder(&Core::get_llvm_module()).create();

  // Call the `foo' function with no arguments:
  //std::vector<GenericValue> noargs;
  //GenericValue gv = EE->runFunction(func, noargs);
  void* FPtr = EE->getPointerToFunction(func);
  int (*FP)() = (int (*)())(intptr_t)FPtr;
  FP();

  // Import result of execution:
  std::cout << "Result: " << pCore->reg_read(B_SIDE,1) << "\n";
  //outs() << "re: " << gv.IntVal << "\n";
#endif

#if 0
  pCore->reg_write(A_SIDE,3,0xFF);
  de_func_t de_func = JIT::gen_su_de_32bit_1or2_src_shl_f2_nc(pCore,0x018d0ca0);

  c6x::Instruction inst;

  pCore->reg_ch_num = 1;
  de_func(pCore,&inst);
  pCore->step();

  std::cout << to_hex_str(pCore->reg_read(A_SIDE,3)) << "\n";

  system("pause");
#endif
  pCore->run();

  return 0;
} 
Example #23
0
int main(int argc, char *argv[])
{
    QCoreApplication application(argc, argv);

    application.setOrganizationName("guh");
    application.setApplicationName("coap-cli");
    application.setApplicationVersion("1.0.0");

    QCommandLineParser parser;
    parser.addHelpOption();
    QString applicationDescription = QString("\ncoap-cli is a command line tool which allowes to interact with a CoAP server.\n"
                                     "Version: %1\n"
                                     "Copyright %2 2016 Simon Stürz <*****@*****.**>\n"
                                     "Released under the GNU GENERAL PUBLIC LICENSE Version 3.").arg(application.applicationVersion()).arg(QChar(0xA9));
    parser.setApplicationDescription(applicationDescription);
    QCommandLineOption payloadOption(QStringList() << "p" << "payload", "The payload data you want to send.", "payload");
    parser.addOption(payloadOption);
    QCommandLineOption observeOption(QStringList() << "o" << "observe", "Observe the given resource.");
    parser.addOption(observeOption);
    QCommandLineOption discoverOption(QStringList() << "d" << "discover", "Discover the resources of the server.");
    parser.addOption(discoverOption);
    QCommandLineOption verboseOption(QStringList() << "v" << "verbose", "Print the whole communication process.");
    parser.addOption(verboseOption);

    parser.addPositionalArgument("method", "Method you want to use. Possible values are:\n    get (default)\n    put\n    post\n    delete", "[method]");
    parser.addPositionalArgument("url", "URL of the CoAP resource.");
    parser.process(application);

    QString urlString;
    QString methodString = "get";
    QByteArray payload;

    // check positional arguments
    QStringList positionalArguments = parser.positionalArguments();
    if (positionalArguments.isEmpty()) {
        qWarning() << "Argument 'url' missing.\n";
        parser.showHelp();
    }

    // get positional arguments
    if (positionalArguments.count() == 1) {
        urlString = positionalArguments.first();
    } else if (positionalArguments.count() == 2) {
        methodString = positionalArguments.first();
        urlString = positionalArguments.last();
    }

    // Check given URL
    QUrl url = QUrl(urlString);
    if (!url.isValid() || url.isEmpty()) {
        qWarning() << "Invalid url" << urlString;
        exit(-1);
    }
    if (url.scheme() != "coap" && !url.scheme().isEmpty()) {
        qWarning() << "Invalid url scheme" << url.scheme() << endl;
        exit(-1);
    }

    if (url.scheme().isEmpty()) {
        qWarning() << "Warning: Missing url scheme -> using 'coap'";
        url.setScheme("coap");
    }

    if (parser.isSet(verboseOption)) {
        s_loggingFilters.insert("CoAP", true);
    } else {
        s_loggingFilters.insert("CoAP", false);
    }

    // install logging filter
    QLoggingCategory::installFilter(loggingCategoryFilter);

    Core core;

    // pars options
    if (parser.isSet(payloadOption)) {
        payload = parser.value(payloadOption).toUtf8();
    }

    if (parser.isSet(observeOption) && parser.isSet(discoverOption)) {
        qWarning() << "Error: The resource can not be discovered and observed." << endl << "Please use either '-d' or '-o', not both." << endl;
        parser.showHelp();
    }

    if (parser.isSet(observeOption)) {
        core.observe(url);
    } else if (parser.isSet(discoverOption)) {
        core.discover(url);
    } else {
        core.performRequest(url, methodString, payload);
    }

    return application.exec();
}
Example #24
0
void test_leaf_merge()
{
  ErrorCode err;
  Core mb;
  AdaptiveKDTree tool(&mb);
  Tag data;
  const EntityHandle root = create_tree( tool, DEPTH, INTERVALS, &data );
  
  // reduce tree depth to DEPTH-1 by merging adjacent leaf pairs, 
  // make new "leaf" have smaller of two data values on original pair
  AdaptiveKDTreeIter iter;
  for (err = tool.get_tree_iterator( root, iter ); !err; err = iter.step()) {
    // get data for first leaf
    int data1;
    EntityHandle leaf = iter.handle();
    err = mb.tag_get_data( data, &leaf, 1, &data1 );
    CHECK_ERR(err);
    // tree traversal is always such that two leaves with same parent are consective
    err = iter.step();
    CHECK_ERR(err);
    // get data for sibling
    int data2;
    leaf = iter.handle();
    err = mb.tag_get_data( data, &leaf, 1, &data2 );
    CHECK_ERR(err);
    // as we stored increasing values, these had better be increasing
    CHECK_EQUAL( 1, data2 - data1 );
    // merge leaf pair (iter can be at either one)
    err = tool.merge_leaf( iter );  // changes iter to be new "merged" leaf
    CHECK_ERR(err);
    // store smaller of two values on new leaf
    leaf = iter.handle();
    err = mb.tag_set_data( data, &leaf, 1, &data1 );
    CHECK_ERR(err);
  }

  
  // Iterate over tree, verifying leaves and checking data
  // Initial leaves had volume of 1 : merged pairs of leaves so volume should now be 2.
  // Initial leaves were enumerated in order : merged pairs so new leaves should
  //   have data incrementing in steps of 2.
  int counter = 1;
  for (err = tool.get_tree_iterator( root, iter ); !err; err = iter.step()) {
    // store integer value on leaf
    int data1;
    EntityHandle leaf = iter.handle();
    err = mb.tag_get_data( data, &leaf, 1, &data1 );
    CHECK_ERR(err);
    CHECK_EQUAL( counter, data1 );
    counter += 2;
      
    // check size of leaf
    const double* min = iter.box_min();
    const double* max = iter.box_max();
    double dims[] = { max[0] - min[0], max[1] - min[1], max[2] - min[2] };
    double volume = dims[0] * dims[1] * dims[2];
    CHECK_REAL_EQUAL( 2.0, volume, DBL_EPSILON );  
    
    // check depth of leaf
    CHECK_EQUAL( DEPTH-1, iter.depth() );
  }
}
Example #25
0
void LyapunovExponent::calculateData() {
	
	// get program core
	Core *core = Core::getInstance();
	
	// get network
	ModularNeuralNetwork *network = getCurrentNetwork();
	QList<NeuralNetworkElement*> networkElements;
	network->getNetworkElements(networkElements);
	QList<DoubleValue*> networkValues =
		DynamicsPlotterUtil::getNetworkValues(networkElements);

	// Get parameters for varied element
	QString variedElement = mVariedElement->get();
	if(variedElement.isEmpty()) {
		reportProblem("LyapunovExponent: No element to vary.");
		return;
	}

	DoubleValue *variedValue = 
			DynamicsPlotterUtil::getElementValue(variedElement, networkElements);
	
	if(variedValue == 0) {
		reportProblem("LyapunovExponent: Invalid value or specifier.");
		return;
	}
	
	QList<double> variedRange = 
				DynamicsPlotterUtil::getDoublesFromString(mVariedRange->get());
				
	if(variedRange.size() != 2) {
		reportProblem("LyapunovExponent: Invalid parameter range.");
		return;
	}

		
	int resolutionX = mResolutionX->get();
	int resolutionY = mResolutionY->get();
	
	//avoid division by zero!
	if(resolutionX < 2 || resolutionY < 2) {
		reportProblem("LyapunovExponent: Invalid resolution given.");
		return;
	}

	
	// Let costraint resolver run properly (order matters!)
	storeNetworkConfiguration();
	storeCurrentNetworkActivities();
	triggerReset();
	restoreCurrentNetworkActivites();
	restoreNetworkConfiguration();
	notifyNetworkParametersChanged(network);

	// save original value
	double originalValue = variedValue->get();

	
	double valStep = (variedRange.at(1) - variedRange.at(0)) / (double) (resolutionX - 1);
	QList<double> variedValues;
	
	// prepare data matrix
	{
		//Thread safety of matrix.
		QMutexLocker guard(mDynamicsPlotManager->getMatrixLocker());

		mData->clear();
		mData->resize(resolutionX + 1, resolutionY + 1, 1);
		mData->fill(0);

		

		for(int x = 1; x <= resolutionX; ++x) {
			double val = variedRange.at(0) + (x-1) * valStep;
			variedValues.append(val);
			
			mData->set(val, x, 0, 0);
		}
	}
	
	int stepsPrePlot = mStepsPrePlot->get();
	int stepsToPlot = mStepsToPlot->get();

	bool drawNL = mDrawNL->get();

	QList<double> ynum;
	double eps = pow(10,-9);
	for(int x = 0; x < variedValues.size(); ++x) {

		// set initial conditions of this run/trajectory
		variedValue->set(variedValues.at(x));
		notifyNetworkParametersChanged(network);
		
		// calculate activation after X PrePlot-Steps
		for(int s = 0; s < stepsPrePlot && mActiveValue->get(); ++s) {
			triggerNetworkStep();
		}
		
		// list for states			
		QList< QList<double> > networkStates;

		for(int s = 0; s < stepsToPlot && mActiveValue->get(); ++s) {

			triggerNetworkStep();
			
			// get current state of the network
			QList<double> networkState = 
					DynamicsPlotterUtil::getNetworkState(networkValues);
			
			// save to list
			networkStates.append(networkState);
		}

		double ljanum = 0;
		int c = 0;
		for(int i = 0; i < networkStates.size() - 1; ++i) {
			double dy = 10000000, df = 100000000;
			bool found = false;

			for(int j = 0; j < networkStates.size() - 1; ++j) {

				double d = DynamicsPlotterUtil::getDistance(
								networkStates.at(i), networkStates.at(j));

				if(d < dy && d > eps) {
					dy = d;
					df = DynamicsPlotterUtil::getDistance(
								networkStates.at(i + 1), networkStates.at(j + 1));
					found = true;
				}
				
			}
			
			if(found && dy != 0 && df != 0) {
				ljanum += log(df / dy);
				c++;
			}

		}

		// save current hightest exponent
		ynum.append(ljanum / c);

		// find smallest and biggest exponent
		double ymin = ynum.first(); double ymax = ynum.first();
		for(int i = 1; i < ynum.size(); ++i) {
			double y = ynum.at(i);
			if(y < ymin) {
				ymin = y;
			}
			if(y > ymax) {
				ymax = y;
			}
		}
		double ystep = (ymax - ymin) / (double)(resolutionY - 1);
		if(ystep == 0) {
			reportProblem("LyapunovExponent: No suitable data found.");
			ymin = 1;
			ymax = 1;
		}

		{
			//Thread safety of matrix.
			QMutexLocker guard(mDynamicsPlotManager->getMatrixLocker());
			
			// clear data matrix
			mData->fill(0);

			// rescale
			for(int y = 1; y <= resolutionY; ++y) {
				double v = ymin + (y-1) * ystep;
				mData->set(Math::round(v, 5), 0, y, 0);
			}
			
			// fill rescaled matrix again
			for(int x = 1; x <= ynum.size(); ++x) {
				double v = min(max(ymin, ynum.at(x - 1)), ymax);
				int y = ceil(((v - ymin) / ystep) + 1);
				mData->set(1, x, y, 0);
			}

			// find null position (if any)
			int ny = ceil(((-ymin)/ystep)+1);
			// and draw red line indicating y=0
			if(drawNL && ny < resolutionY && ny > 0) {
				for(int x = 0; x < resolutionX; ++x) {
					if(mData->get(x, ny, 0) == 0) {
						mData->set(2, x, ny, 0);
					}
				}
			}
		}

		// runtime maintencance
		if(core->isShuttingDown()) {
			return;
		}
		core->executePendingTasks();
	
	}
	
	// re-set original parameter value
	variedValue->set(originalValue);
	// CLEAN UP
	notifyNetworkParametersChanged(network);
	triggerReset();
	restoreNetworkConfiguration();
	restoreCurrentNetworkActivites();

}
Example #26
0
bool Console::screen() {
	ISolver* SOLVE = nullptr;
	HINSTANCE hinstLib;
	PROCFUN Func;
	BOOL fFreeResult, fRunTimeLinkSuccess;
	Core core;

	string c; // every line in batch.txt
	Array<string> tokens; // splitted command
	char cmd_type;

	while (true) {
		system("cls");
		outputAll(core);
		cout << "a. Add graph primitive" << endl;
		cout << "b. Add restriction" << endl;
		cout << "c. Choose your side of the darkness!" << endl;
		cout << "s. Select by point" << endl;
		cout << "r. Select by rect" << endl;
		cout << "d. Delete selected" << endl;
		cout << "l. Load from batch" << endl;
		cout << "m. Matlab file" << endl;
		cout << "*. Clear state" << endl;
		cout << "q. Exit" << endl;

		do {
			getline(cin, c);
		} while (c.length() != 1);

		cmd_type = c[0];
		List<unsigned> objId; // List to store objects
		Array< double* > restrParams;

		switch (cmd_type) {
		case 'q':
			return 0;
		case 'a': {
			system("cls");
			outputAll(core);
			cout << "a. Point" << endl;
			cout << "b. Segment" << endl;
			cout << "c. Circle" << endl;
			cout << "q. Cancel" << endl;

			do {
				getline(cin, c);
			} while (c.length() != 1);

			cmd_type = c[0];

			switch (cmd_type) {
			case 'a': {
				system("cls");
				outputAll(core);
				cout << "Write coordinates: x and y" << endl;
				cout << "(q to cancel)" << endl;
				double x, y;

				bool flag;
				do {
					flag = true;
					getline(cin, c);
					tokens = stringSplit(c);
					if (tokens.size() != 2)
						flag = false;
					try {
						if (tokens[0] == "q")
							break;
						x = stod(tokens[0]);
						y = stod(tokens[1]);
					}
					catch (exception) {
						std::cout << "Error: point coordinates must be 2 doubles" << std::endl;
						flag = false;
					}
				} while (!flag);

				if (tokens[0] == "q")
					break;

				Array <double> Arr;
				Arr.push_back(x);
				Arr.push_back(y);
				core.addObject(Arr, IsPoint);
			} break;

			case 'b': {
				system("cls");
				outputAll(core);
				cout << "Write coordinates: x1, y1, x2 and y2" << endl;
				cout << "(q to cancel)" << endl;
				double x1, y1, x2, y2;

				bool flag;
				do {
					flag = true;
					getline(cin, c);
					tokens = stringSplit(c);
					if (tokens.size() != 4)
						flag = false;
					try {
						if (tokens[0] == "q")
							break;
						x1 = stod(tokens[0]);
						y1 = stod(tokens[1]);
						x2 = stod(tokens[2]);
						y2 = stod(tokens[3]);
					}
					catch (exception) {
						std::cout << "Error: segment coordinates must be 4 doubles" << std::endl;
						flag = false;
					}
				} while (!flag);

				if (tokens[0] == "q")
					break;

				Array <double> Arr;
				Arr.push_back(x1);
				Arr.push_back(y1);
				Arr.push_back(x2);
				Arr.push_back(y2);
				core.addObject(Arr, IsSegment);
			} break;

			case 'c': {
				system("cls");
				outputAll(core);
				cout << "Write coordinates: x1, y1 and radius" << endl;
				cout << "(q to cancel)" << endl;
				double x, y, r;

				bool flag;
				do {
					flag = true;
					getline(cin, c);
					tokens = stringSplit(c);
					if (tokens.size() != 3)
						flag = false;
					try {
						if (tokens[0] == "q")
							break;
						x = stod(tokens[0]);
						y = stod(tokens[1]);
						r = stod(tokens[2]);
					}
					catch (exception) {
						std::cout << "Error: circle coordinates must be 2 doubles, s"
							"radius must be double" << std::endl;
						flag = false;
					}
				} while (!flag);

				if (tokens[0] == "q")
					break;

				Array <double> Arr;
				Arr.push_back(x);
				Arr.push_back(y);
				Arr.push_back(r);
				core.addObject(Arr, IsCircle);
			} break;
			case 'q': {
				break;
			} break;

			default: {
				cout << "Invalid command." << endl;
			}
			}
			core.backupState();
		} break; //end of addition

		case 'b': {

			if (SOLVE == nullptr) {
				system("cls");
				outputAll(core);
				cout << endl;
				cout << "Choose your side first!" << endl;
				system("pause");
				break;
			}

			if (core.sizeListObj() == 0) {
				system("cls");
				outputAll(core);
				cout << endl;
				cout << "No objects yet!" << endl;
				system("pause");
				break;
			}

			objId.deleteAll();

			system("cls");
			outputAll(core);

			cout << "a. RT_FIX" << endl;
			cout << "b. RT_P2PDIST" << endl;
			cout << "c. RT_P2SDIST" << endl;
			cout << "d. RT_P2SDISTEX" << endl;
			cout << "e. RT_S2SANGLE" << endl;
			cout << "f. RT_S2SEQUALS" << endl;
			cout << "g. RT_S2SPARAL" << endl;
			cout << "h. RT_S2SORTHO" << endl;
			cout << "q. Cancel" << endl;

			getline(cin, c);
			switch (c[0]) {
			case 'a': {
				system("cls");
				outputAll(core);
				unsigned id;
				double d = 0;
				cout << "Write id of object" << endl;
				cout << "(q to cancel)" << endl;

				bool flag;
				do {
					flag = true;
					getline(cin, c);
					tokens = stringSplit(c);
					if (tokens.size() != 1)
						flag = false;
					try {
						if (tokens[0] == "q")
							break;
						id = stoi(tokens[0]);
					}
					catch (exception) {
						std::cout << "Error: id of a point must be an integer" << std::endl;
						flag = false;
					}
				} while (!flag);

				if (tokens[0] == "q")
					break;

				objId.push_back(id);
				core.addRestriction(&objId, &d, RT_FIX, SOLVE);
			} break;
			case 'b': {
				system("cls");

				if (core.sizeListObj() < 2) {
					system("cls");
					outputAll(core);
					cout << endl;
					cout << "Not enough objects!" << endl;
					system("pause");
					break;
				}

				outputAll(core);
				unsigned id1, id2;
				cout << "Write id of 2 points and distance" << endl;
				cout << "(q to cancel)" << endl;

				restrParams.push_back(new double);
				bool flag;
				do {
					flag = true;
					getline(cin, c);
					tokens = stringSplit(c);
					if (tokens.size() != 3)
						flag = false;
					try {
						if (tokens[0] == "q")
							break;
						id1 = stoi(tokens[0]);
						id2 = stoi(tokens[1]);
						*(restrParams[restrParams.size() - 1]) = stod(tokens[2]);
					}
					catch (exception) {
						std::cout << "Error: id of a point must be an integer, "
							"distance must be double" << std::endl;
						flag = false;
					}
				} while (!flag);

				if (tokens[0] == "q")
					break;
				if (core.searchID(id1)->object_type() != 1 || core.searchID(id2)->object_type() != 1) {
					cout << "It's not IDs of points" << endl;
					system("pause");
					break;
				}
				objId.push_back(id1);
				objId.push_back(id2);
				core.addRestriction(&objId, restrParams[restrParams.size() - 1], RT_P2PDIST, SOLVE);
			} break;
			case 'c': {
				system("cls");

				if (core.sizeListObj() < 3) {
					system("cls");
					outputAll(core);
					cout << endl;
					cout << "Not enough objects!" << endl;
					system("pause");
					break;
				}

				outputAll(core);
				unsigned id1, id2, id3;
				cout << "Write id of 3 points and distance" << endl;
				cout << "(q to cancel)" << endl;

				restrParams.push_back(new double);
				bool flag;
				do {
					flag = true;
					getline(cin, c);
					tokens = stringSplit(c);
					if (tokens.size() != 4)
						flag = false;
					try {
						if (tokens[0] == "q")
							break;
						id1 = stoi(tokens[0]);
						id2 = stoi(tokens[1]);
						id3 = stoi(tokens[2]);
						*(restrParams[restrParams.size() - 1]) = stod(tokens[3]);
					}
					catch (exception) {
						std::cout << "Error: id of a point and segment must be an integer, "
							"distance must be double" << std::endl;
						flag = false;
					}
				} while (!flag);

				if (tokens[0] == "q")
					break;
				if (core.searchID(id1)->object_type() != 1 || core.searchID(id2)->object_type() != 1 || core.searchID(id3)->object_type() != 1) {
					cout << "It's not IDs of points" << endl;
					system("pause");
					break;
				}
				objId.push_back(id1);
				objId.push_back(id2);
				objId.push_back(id3);
				core.addRestriction(&objId, restrParams[restrParams.size() - 1], RT_P2SDIST, SOLVE);
			} break;
			case 'd': {
				system("cls");

				if (core.sizeListObj() < 3) {
					system("cls");
					outputAll(core);
					cout << endl;
					cout << "Not enough objects!" << endl;
					system("pause");
					break;
				}

				outputAll(core);
				unsigned id1, id2, id3;
				cout << "Write id of 3 points and distance" << endl;
				cout << "(q to cancel)" << endl;

				restrParams.push_back(new double);
				bool flag;
				do {
					flag = true;
					getline(cin, c);
					tokens = stringSplit(c);
					if (tokens.size() != 4)
						flag = false;
					try {
						if (tokens[0] == "q")
							break;
						id1 = stoi(tokens[0]);
						id2 = stoi(tokens[1]);
						id3 = stoi(tokens[2]);
						*(restrParams[restrParams.size() - 1]) = stod(tokens[3]);
					}
					catch (exception) {
						std::cout << "Error: id of point must be an integer, "
							"distance must be double" << std::endl;
						flag = false;
					}
				} while (!flag);

				if (tokens[0] == "q")
					break;
				if (core.searchID(id1)->object_type() != 1 || core.searchID(id2)->object_type() != 1 || core.searchID(id3)->object_type() != 1) {
					cout << "It's not IDs of points" << endl;
					system("pause");
					break;
				}
				objId.push_back(id1);
				objId.push_back(id2);
				objId.push_back(id3);
				core.addRestriction(&objId, restrParams[restrParams.size() - 1], RT_P2SDISTEX, SOLVE);
			} break;
			case 'e': {
				system("cls");

				if (core.sizeListObj() < 6) {
					system("cls");
					outputAll(core);
					cout << endl;
					cout << "Not enough objects!" << endl;
					system("pause");
					break;
				}

				outputAll(core);
				int id1, id2;
				cout << "Write id of two segments and angle" << endl;
				cout << "(q to cancel)" << endl;

				restrParams.push_back(new double);
				bool flag;
				do {
					flag = true;
					getline(cin, c);
					tokens = stringSplit(c);
					if (tokens.size() != 3)
						flag = false;
					try {
						if (tokens[0] == "q")
							break;
						id1 = stoi(tokens[0]);
						id2 = stoi(tokens[1]);
						*(restrParams[restrParams.size() - 1]) = stod(tokens[2]);
					}
					catch (exception) {
						std::cout << "Error: id of segment must be an integer, "
							"angle must be in radians" << std::endl;
						flag = false;
					}
				} while (!flag);

				if (tokens[0] == "q")
					break;
				if (core.searchID(id1)->object_type() != 2 || core.searchID(id2)->object_type() != 2) {
					cout << "It's not IDs of segments" << endl;
					system("pause");
					break;
				}
				objId.push_back(id1);
				objId.push_back(id2);
				core.addRestriction(&objId, restrParams[restrParams.size() - 1], RT_S2SANGLE, SOLVE);
			} break;
			case 'f': {
				system("cls");

				if (core.sizeListObj() < 6) {
					system("cls");
					outputAll(core);
					cout << endl;
					cout << "Not enough objects!" << endl;
					system("pause");
					break;
				}

				outputAll(core);
				double d = 0;
				int id1, id2;

				cout << "Write id of two segments" << endl;
				cout << "(q to cancel)" << endl;

				restrParams.push_back(new double);
				bool flag;
				do {
					flag = true;
					getline(cin, c);
					tokens = stringSplit(c);
					if (tokens.size() != 2)
						flag = false;
					try {
						if (tokens[0] == "q")
							break;
						id1 = stoi(tokens[0]);
						id2 = stoi(tokens[1]);
					}
					catch (exception) {
						std::cout << "Error: id of segment must be an integer" << std::endl;
						flag = false;
					}
				} while (!flag);

				if (tokens[0] == "q")
					break;
				if (core.searchID(id1)->object_type() != 2 || core.searchID(id2)->object_type() != 2) {
					cout << "It's not IDs of segments" << endl;
					system("pause");
					break;
				}
				objId.push_back(id1);
				objId.push_back(id2);
				core.addRestriction(&objId, &d, RT_S2SEQUALS, SOLVE);
			} break;
			case 'g': {
				system("cls");

				if (core.sizeListObj() < 6) {
					system("cls");
					outputAll(core);
					cout << endl;
					cout << "Not enough objects!" << endl;
					system("pause");
					break;
				}

				outputAll(core);
				int id1, id2;
				double d = 0;
				cout << "Write id of two segments" << endl;
				cout << "(q to cancel)" << endl;

				restrParams.push_back(new double);
				bool flag;
				do {
					flag = true;
					getline(cin, c);
					tokens = stringSplit(c);
					if (tokens.size() != 2)
						flag = false;
					try {
						if (tokens[0] == "q")
							break;
						id1 = stoi(tokens[0]);
						id2 = stoi(tokens[1]);
					}
					catch (exception) {
						std::cout << "Error: id of segment must be an integer" << std::endl;
						flag = false;
					}
				} while (!flag);

				if (tokens[0] == "q")
					break;
				if (core.searchID(id1)->object_type() != 2 || core.searchID(id2)->object_type() != 2) {
					cout << "It's not IDs of segments" << endl;
					system("pause");
					break;
				}
				objId.push_back(id1);
				objId.push_back(id2);
				core.addRestriction(&objId, &d, RT_S2SPARAL, SOLVE);
			} break;
			case 'h': {
				system("cls");

				if (core.sizeListObj() < 6) {
					system("cls");
					outputAll(core);
					cout << endl;
					cout << "Not enough objects!" << endl;
					system("pause");
					break;
				}

				outputAll(core);
				int id1, id2;
				double d = 0;
				cout << "Write id of two segments" << endl;
				cout << "(q to cancel)" << endl;

				restrParams.push_back(new double);
				bool flag;
				do {
					flag = true;
					getline(cin, c);
					tokens = stringSplit(c);
					if (tokens.size() != 2)
						flag = false;
					try {
						if (tokens[0] == "q")
							break;
						id1 = stoi(tokens[0]);
						id2 = stoi(tokens[1]);
					}
					catch (exception) {
						std::cout << "Error: id of segment must be an integer" << std::endl;
						flag = false;
					}
				} while (!flag);

				if (tokens[0] == "q")
					break;
				if (core.searchID(id1)->object_type() != 2 || core.searchID(id2)->object_type() != 2) {
					cout << "It's not IDs of segments" << endl;
					system("pause");
					break;
				}
				objId.push_back(id1);
				objId.push_back(id2);
				core.addRestriction(&objId, &d, RT_S2SORTHO, SOLVE);
			} break;
			case 'q': {
				break;
			}
			default: {
				cout << "Invalid command." << endl;
				system("pause");
			}
			}
		} break;

		case 'c': {
			system("cls");
			outputAll(core);
			cout << endl;
			cout << "Write type of solver H or G" << endl;
			getline(cin, c);
			switch (c[0]) {
			case 'H': {
				fRunTimeLinkSuccess = FALSE;
				hinstLib = LoadLibrary(TEXT("HJdll.dll"));
				if (hinstLib != nullptr) {
					cout << "Lib Load" << endl;
					Func = (PROCFUN)GetProcAddress(hinstLib, "getMethod");

					if (nullptr != Func) {
						fRunTimeLinkSuccess = TRUE;
						cout << "O.K." << endl;
						system("pause");
						SOLVE = Func();
					}

				}
				if (!fRunTimeLinkSuccess) {
					fFreeResult = FreeLibrary(hinstLib);
					cout << "Hook J: 404 not found" << endl;
					system("pause");
					return 0;
				}
			} break;
			case 'G': {
				fRunTimeLinkSuccess = FALSE;
				hinstLib = LoadLibrary(TEXT("dllGD.dll"));
				if (hinstLib != nullptr) {
					cout << "Lib Load" << endl;
					Func = (PROCFUN)GetProcAddress(hinstLib, "getMethod");

					if (nullptr != Func) {
						fRunTimeLinkSuccess = TRUE;
						cout << "O.K." << endl;
						system("pause");
						SOLVE = Func();
					}

				}
				if (!fRunTimeLinkSuccess) {
					fFreeResult = FreeLibrary(hinstLib);
					cout << "Grad D: 404 not found" << endl;
					system("pause");
					return 0;
				}
			} break;
			default: {
				cout << "Choose your side!" << endl;
			}
			}
		} break;

		case'm': {
			system("cls");
			outputAll(core);
			string _resultfilename = "Batch.m";
			ofstream out(_resultfilename);
			out.close();
			MatlabRenderer matlab(_resultfilename, 10);
			matlab.drawSketch(core.getInfoObj());
			cout << "Your state is saved to .m file." << endl;
			system("pause");
		} break;
		
		case'*': {
			core.clearState();
		} break;

		case'l': {
			system("cls");
			outputAll(core);
			if (core.sizeListObj() != 0) {
				cout << endl << "Only initial state is supported." << endl;
				system("pause");
				break;
			}
			cout << endl;
			string input;
			cout << "Enter batch file" << endl;
			cin >> input;
			BatchProcessor newbatch(input, &core, "matlab");
			newbatch.generateCode();
			system("pause");
		} break;
		case's': {
			system("cls");
			outputAll(core);
			if (core.sizeListObj() == 0) {
				cout << endl << "No objects yet!" << endl;
				system("pause");
				break;
			}
			unsigned id;
			cout << endl << "Enter id" << endl;
			cout << "(q to cancel)" << endl;

			bool flag;
			do {
				flag = true;
				getline(cin, c);
				tokens = stringSplit(c);
				if (tokens.size() != 1)
					flag = false;
				try {
					if (tokens[0] == "q")
						break;
					id = stoi(tokens[0]);
				}
				catch (exception) {
					std::cout << "Error: id of point must be an integer" << std::endl;
					flag = false;
				}
			} while (!flag);

			if (tokens[0] == "q")
				break;

			if (!core.searchID(id)) {
				cout << endl << "Wrong id!" << endl;
				system("pause");
				break;
			}
			if (core.searchID(id)->object_type() != IsPoint) {
				cout << endl << "It's not id of a point!" << endl;
				system("pause");
				break;
			}
			Point *newp = 0;
			newp = dynamic_cast<Point*>(core.searchID(id));
			if (newp != nullptr)
				core.selectByPoint(*newp);
		} break;
		case'r': {
			system("cls");
			outputAll(core);
			if (core.sizeListObj() == 0) {
				cout << endl << "No objects yet!" << endl;
				system("pause");
				break;
			}
			double x1, y1, x2, y2;
			cout << endl << "Enter 4 double coords of a rect (x y x y)" << endl;
			cout << "(q to cancel)" << endl;

			bool flag;
			do {
				flag = true;
				getline(cin, c);
				tokens = stringSplit(c);
				if (tokens.size() != 4)
					flag = false;
				try {
					if (tokens[0] == "q")
						break;
					x1 = stoi(tokens[0]);
					y1 = stoi(tokens[1]);
					x2 = stoi(tokens[2]);
					y2 = stoi(tokens[3]);
				}
				catch (exception) {
					std::cout << "Error: coords must be 4 doubles" << std::endl;
					flag = false;
				}
			} while (!flag);

			if (tokens[0] == "q")
				break;
			core.selectByRect(x1, y1, x2, y2);
		} break;

		case'd': {
			system("cls");
			outputAll(core);
			if (core.sizeListObj() == 0) {
				cout << endl << "No objects yet!" << endl;
				system("pause");
				break;
			}
			while (core.getPicked().size())
				core.deleteSelected();
		} break;

		default: {
			cout << "Invalid command" << endl;
			system("pause");
		}
		}

	}

}
Example #27
0
static bool hasValidVirtualAddress(const GElf_Phdr &phdr, const Core &core)
{
  return core.isValidRamAddress(phdr.p_vaddr) &&
         core.isValidRamAddress(phdr.p_vaddr + phdr.p_memsz);
 }
Example #28
0
void Console::outputAll(Core &core)
{
	cout << "OBJECTS:" << endl;
	if (core.sizeListObj() == 0)
		cout << "	No objects yet." << endl;
	for (size_t i = 0; i < core.sizeListObj(); ++i) {
		Point * newp = 0; Circle *newc = 0; Segment * news = 0;
		switch (core.searchID(core.getObjIDs()[i])->object_type()) {
		case IsPoint: {
			newp = dynamic_cast<Point*>(core.searchID(core.getObjIDs()[i]));
			cout.precision(2);
			cout << setw(8);
			newp->isFixed() ? cout << "(fixed) " : cout << "";
			cout << setw(8) << "POINT ";
			cout << setw(3) << "ID: " << setw(2) << newp->showId();
			cout << setw(6) << "X: " << setw(8) << newp->getX();
			cout << setw(6) << "Y: " << setw(8) << newp->getY();
			newp->isPicked() ? cout << "  <-" : cout << "";
			cout << endl;
		} break;
		case IsSegment: {
			news = dynamic_cast<Segment*>(core.searchID(core.getObjIDs()[i]));
			cout.precision(2);
			cout << setw(8);
			news->isFixed() ? cout << "(fixed) " : cout << "";
			cout << setw(8) << "SEGMENT ";
			cout << setw(3) << "ID: " << setw(2) << news->showId();
			cout << setw(6) << news->getP1()->showId();
			cout << "-----" << news->getP2()->showId();
			news->isPicked() ? cout << setw(16) << "<-" : cout << "";
			cout << endl << endl;
		} break;
		case IsCircle: {
			newc = dynamic_cast<Circle*>(core.searchID(core.getObjIDs()[i]));
			cout.precision(2);
			cout << setw(8);
			Point t = newc->getCenter();
			newc->isFixed() ? cout << "(fixed) " : cout << "";
			cout << setw(8) << "CIRCLE ";
			cout << setw(3) << "ID: " << setw(2) << newc->showId();
			cout << setw(6) << "O: " << setw(8) << newc->getCenter().showId();
			cout << setw(6) << "R: " << setw(8) << newc->getRadius();
			newc->isPicked() ? cout << "  <-" : cout << "";
			cout << endl << endl;
		} break;
		}
	}
	cout << "RESTRICTIONS:" << endl;
	if (core.sizeListRestr() == 0)
		cout << "	No restrictions yet." << endl;
	for (size_t i = 0; i < core.sizeListRestr(); ++i) {
		switch (core.searchIDRestr(core.getRestrIDs()[i])->get_type()) {

		case RT_P2PDIST: {
			auto restr = dynamic_cast<RestrP2PDIST*>(core.searchIDRestr(core.getRestrIDs()[i]));
			cout.precision(2);
			cout << setw(16) << "P2PDIST " << setw(3) << "ID: " << setw(2) << restr->showId();
			cout << setw(13) << "violation: " << setw(8) << restr->violation();
			cout << setw(8) << restr->getP1()->showId() << "---" << restr->getP2()->showId() << endl;
		} break;
		case RT_P2SDIST: {
			auto restr = dynamic_cast<RestrP2SDIST*>(core.searchIDRestr(core.getRestrIDs()[i]));
			cout.precision(2);
			cout << setw(16) << "P2SDIST " << setw(3) << "ID: " << setw(2) << restr->showId();
			cout << setw(13) << "violation: " << setw(8) << restr->violation();
			cout << setw(8) << restr->getP1()->showId() << "---" << restr->getP2()->showId();
			cout << "==" << restr->getP3()->showId() << endl;
		} break;
		case RT_P2SDISTEX: {
			auto restr = dynamic_cast<RestrP2SDISTEX*>(core.searchIDRestr(core.getRestrIDs()[i]));
			cout.precision(2);
			cout << setw(16) << "P2SDISTEX " << setw(3) << "ID: " << setw(2) << restr->showId();
			cout << setw(13) << "violation: " << setw(8) << restr->violation();
			cout << setw(8) << restr->getP1()->showId() << "---" << restr->getP2()->showId();
			cout << "==" << restr->getP3()->showId() << endl;
		} break;
		case RT_S2SANGLE: {
			auto restr = dynamic_cast<RestrS2SANGLE*>(core.searchIDRestr(core.getRestrIDs()[i]));
			cout.precision(2);
			cout << setw(16) << "S2SANGLE " << setw(3) << "ID: " << setw(2) << restr->showId();
			cout << setw(13) << "violation: " << setw(8) << restr->violation();
			cout << setw(8) << restr->getS1()->showId() << "---" << restr->getS2()->showId() << endl;
		} break;
		case RT_S2SORTHO: {
			auto restr = dynamic_cast<RestrS2SORTHO*>(core.searchIDRestr(core.getRestrIDs()[i]));
			cout.precision(2);
			cout << setw(16) << "S2SORTHO " << setw(3) << "ID: " << setw(2) << restr->showId();
			cout << setw(13) << "violation: " << setw(8) << restr->violation();
			cout << setw(8) << restr->getS1()->showId() << "---" << restr->getS2()->showId() << endl;
		} break;
		case RT_S2SPARAL: {
			auto restr = dynamic_cast<RestrS2SPARAL*>(core.searchIDRestr(core.getRestrIDs()[i]));
			cout.precision(2);
			cout << setw(16) << "S2SPARAL " << setw(3) << "ID: " << setw(2) << restr->showId();
			cout << setw(13) << "violation: " << setw(8) << restr->violation();
			cout << setw(8) << restr->getS1()->showId() << "---" << restr->getS2()->showId() << endl;
		} break;
		case RT_S2SEQUALS: {
			auto restr = dynamic_cast<RestrS2SEQUALS*>(core.searchIDRestr(core.getRestrIDs()[i]));
			cout.precision(2);
			cout << setw(16) << "S2SEQUALS " << setw(3) << "ID: " << setw(2) << restr->showId();
			cout << setw(13) << "violation: " << setw(8) << restr->violation();
			cout << setw(8) << restr->getS1()->showId() << "---" << restr->getS2()->showId() << endl;
		} break;
		}
	}
	core.ShowRestr();
}
Example #29
0
void BasinPlotter::calculateData() {
	
	// get program core
	Core *core = Core::getInstance();
	
	// get network
	ModularNeuralNetwork *network = getCurrentNetwork();
	if(network == 0) {
		Core::log("BasinPlotter: Could not find a neural network to work with! Aborting.", true);
		return;
	}
	
	QList<NeuralNetworkElement*> networkElements;
	network->getNetworkElements(networkElements);
	QList<DoubleValue*> networkValues =
						DynamicsPlotterUtil::getNetworkValues(networkElements);

	// Get parameters for varied elements
	QString variedX = mVariedX->get();
	QString variedY = mVariedY->get();
	if(variedX.isEmpty() || variedY.isEmpty()) {
		reportProblem("BasinPlotter: No elements to vary.");
		return;
	}
	

	DoubleValue *variedValX = DynamicsPlotterUtil::getElementValue(
		variedX, networkElements, &mNeuronsWithActivationsToTransfer);
	DoubleValue *variedValY = DynamicsPlotterUtil::getElementValue(
		variedY, networkElements, &mNeuronsWithActivationsToTransfer);
	
	if(variedValX == 0 || variedValY == 0) {
		reportProblem("BasinPlotter: NULL pointer for varied element. Aborting.");
		return;
	}
	
	QList<double> variedRangeX = 
				DynamicsPlotterUtil::getDoublesFromString(mVariedRangeX->get());
	QList<double> variedRangeY = 
				DynamicsPlotterUtil::getDoublesFromString(mVariedRangeY->get());
				
	if(variedRangeX.size() != 2 || variedRangeY.size() != 2) {
		reportProblem("BasinPlotter: Not a valid range given.");
		return;
	}
		

	int resolutionX = mResolutionX->get();
	int resolutionY = mResolutionY->get();
	
	//avoid division by zero!
	if(resolutionX < 2 || resolutionY < 2) {
		reportProblem("BasinPlotter: Invalid resolution given.");
		return;
	}


	// projected elements
	int nrProjections = 0;
	QString projectionsX = mProjectionsX->get();
	QString projectionsY = mProjectionsY->get();
	QList< QList<DoubleValue*> > projectionValuesX;
	QList< QList<DoubleValue*> > projectionValuesY;
	QList<double> projectionRangesX;
	QList<double> projectionRangesY;

	if(projectionsX != "0" && projectionsY != "0") {

		QList<QStringList> projectionListX = 
				DynamicsPlotterUtil::parseElementString(projectionsX);
		QList<QStringList> projectionListY =
				DynamicsPlotterUtil::parseElementString(projectionsY);

		projectionValuesX =
				DynamicsPlotterUtil::getElementValues(projectionListX, networkElements);
		projectionValuesY =
				DynamicsPlotterUtil::getElementValues(projectionListY, networkElements);

		if(projectionValuesX.isEmpty() || projectionValuesY.isEmpty()) {
			reportProblem("BasinPlotter: Could not find specified elements to project onto.");
			return;
		}

		if(projectionValuesX.size() != projectionValuesY.size()) {
			reportProblem("BasinPlotter: Mismatching number of projected elements for the two axes.");
			return;
		}

		projectionRangesX =
				DynamicsPlotterUtil::getDoublesFromString(mProjectionRangesX->get());
		projectionRangesY =
				DynamicsPlotterUtil::getDoublesFromString(mProjectionRangesY->get());

		if(projectionRangesX.size() != 2*projectionValuesX.size() ||
		   projectionRangesY.size() != 2*projectionValuesY.size()) {
			reportProblem("BasinPlotter: Given ranges for projection don't match number of elements.");
			return;
		}

		nrProjections = projectionValuesX.size();

	}
	

	// save original values for clean-up
	QList<double> variedValuesOrig;
	variedValuesOrig.append(QList<double>() << variedValX->get()
											<< variedValY->get());

	bool resetNetworkActivation = mResetNetworkActivation->get();
	storeCurrentNetworkActivities();
	
	/* store network configuration (bias terms, synapse weights,
			observable parameters of TFs, AFs, SFs. */
	bool restoreNetConfiguration = mRestoreNetworkConfiguration->get();
	storeNetworkConfiguration();
	
	//This is important when the physical simulator is activated!
	bool resetSimulation = mResetSimulator->get();
	triggerReset();
	

	// PREPARE data matrix
	double xStart = variedRangeX.first();
	double xEnd = variedRangeX.last();
	double xStepSize = (xEnd - xStart) / (double) (resolutionX - 1);
	int roundDigits = mRoundDigits->get();
	double xVal;
	QList<double> xValues;
		
	double yStart = variedRangeY.first();
	double yEnd = variedRangeY.last();
	double yStepSize = (yEnd - yStart) / (double) (resolutionY - 1);
	double yVal;
	QList<double> yValues;
	
	{
		//Thread safety of matrix.
		QMutexLocker guard(mDynamicsPlotManager->getMatrixLocker());
		
		mData->clear();
		mData->resize(resolutionX + 1, resolutionY + 1, 3 + nrProjections);
		mData->fill(0);

		// calculate values and draw axes
		for(int x = 1; x <= resolutionX; ++x) {
			xVal = xStart + (x - 1) * xStepSize;
			mData->set(Math::round(xVal, 5), x, 0, 0);
			mData->set(Math::round(xVal, 5), x, 0, 1);
			mData->set(Math::round(xVal, 5), x, 0, 2);
			
			if(roundDigits >= 0) {
				xVal = Math::round(xVal, roundDigits);
			}
			xValues.append(xVal);
		}
		
		for(int y = 1; y <= resolutionY; ++y) {
			yVal = yStart + (y - 1) * yStepSize;
			mData->set(Math::round(yVal, 5), 0, y, 0);
			mData->set(Math::round(yVal, 5), 0, y, 1);
			mData->set(Math::round(yVal, 5), 0, y, 2);
			
			if(roundDigits >= 0) {
				yVal = Math::round(yVal, roundDigits);
			}
			yValues.append(yVal);
		}

		// same for additional projections
		for(int currProj = 0; currProj < nrProjections; ++currProj) {
			double pStartX = projectionRangesX.at(currProj * 2);
			double pEndX = projectionRangesX.at(currProj * 2 + 1);
			double pStepX = (pEndX - pStartX) / (double) (resolutionX - 1);
			for(int x = 1; x <= resolutionX; ++x) {
				mData->set(Math::round((pStartX + (x - 1) * pStepX), 5), x, 0, 3 + currProj);
			}
			double pStartY = projectionRangesY.at(currProj * 2);
			double pEndY = projectionRangesY.at(currProj * 2 + 1);
			double pStepY = (pEndY - pStartY) / (double) (resolutionY - 1);
			for(int y = 1; y <= resolutionY; ++y) {
				mData->set(Math::round((pStartY + (y - 1) * pStepY), 5), 0, y, 3 + currProj);
			}
		}
	}

	// MAIN LOOP over x parameter points
		
	int stepsRun = mStepsToRun->get();
	int stepsCheck = mStepsToCheck->get();
	double accuracy = mAccuracy->get();
	
	QList< QList<double> > attractors;
		
	for(int x = 1; x <= resolutionX && mActiveValue->get(); ++x) {
			
		mProgressPercentage->set((double)(100 * x / resolutionX));

		// INNER LOOP over y parameter points
		for(int y = 1; y <= resolutionY && mActiveValue->get(); ++y) {
			
			if(resetSimulation) {
				triggerReset();
			}
			
			if(restoreNetConfiguration) {
				restoreNetworkConfiguration();
			}
			
			if(resetNetworkActivation) {
				restoreCurrentNetworkActivites();
			}
			
			// set x parameter
			variedValX->set(xValues.at(x - 1));
			// set y parameter
			variedValY->set(yValues.at(y - 1));
			
			if(!notifyNetworkParametersChanged(network)) {
				return;
			}

			for(int runStep = 0; runStep < stepsRun && mActiveValue->get(); ++runStep) {
				// let the network run for 1 timestep
				triggerNetworkStep();
			}
			
			QList< QList<double> > networkStates;
			QList<double> networkState;
			QList< QPair<double,double> > variedPositions;

			QList< QPair< QList<double>, QList<double> > > projectionPositions;

			bool foundMatch = false;
			int attrPeriod = 0;

			for(int checkStep = 0; checkStep <= stepsCheck && !foundMatch && mActiveValue->get(); ++checkStep) {
				triggerNetworkStep();
				
				// get current network state
				networkState = DynamicsPlotterUtil::getNetworkState(networkValues);
				
				// abort on empty state
				if(networkState.isEmpty()) {
					reportProblem("BasinPlotter: Encountered empty network state.");
					return;
				}
				
				// compare states to find attractors
				for(int period = 1; period <= checkStep && !foundMatch; ++period) {
					foundMatch = DynamicsPlotterUtil::compareNetworkStates(
							networkStates.at(checkStep-period),
							networkState,
							accuracy);
					attrPeriod = period;
				}
				
				// save current state as last one
				networkStates.append(networkState);

				variedPositions.append(QPair<double,double>(variedValX->get(), variedValY->get()));

				if(nrProjections > 0) {
					QPair< QList<double>, QList<double> > currentPositions;
					currentPositions.first = DynamicsPlotterUtil::getMeanValues(projectionValuesX);
					currentPositions.second = DynamicsPlotterUtil::getMeanValues(projectionValuesY);
					projectionPositions.append(currentPositions);
				}

			}
			
			// at this point, either an attractor has been found
			if(foundMatch && mActiveValue->get()) {
				
				// check for past attractors
				bool attrMatch = false;
				int attrNo = 1;
				while(attrNo <= attractors.size() && !attrMatch) {
					for(int state = 1; state <= attrPeriod && !attrMatch; ++state) {
						attrMatch = DynamicsPlotterUtil::compareNetworkStates(
								attractors.at(attrNo-1),
								networkStates.at(networkStates.size()-state),
									// was: size()-1-state
								accuracy);
					}
					attrNo++;
				}
				
				
				//Thread safety of matrix.
				QMutexLocker guard(mDynamicsPlotManager->getMatrixLocker());
				
				// write matrix
				mData->set(attrNo, x, y, 0);
				mData->set(attrPeriod, x, y, 1);

				// calculate and plot attractor position
				int nrPositions = variedPositions.size();
				for(int periodPos = 1; periodPos <= attrPeriod; ++periodPos) {
					int currPosition = nrPositions - periodPos;

					double currValX = variedPositions.at(currPosition).first;
					double currValY = variedPositions.at(currPosition).second;
				
					int attrPosX = ceil((currValX - xStart) / xStepSize + 1);
					int attrPosY = ceil((currValY - yStart) / yStepSize + 1);
				
					mData->set(attrNo, attrPosX, attrPosY, 2);

					for(int currProj = 0; currProj < nrProjections; ++currProj) {
						double xVal = projectionPositions.at(currPosition).first.at(currProj);
						double yVal = projectionPositions.at(currPosition).second.at(currProj);

						double pStartX = projectionRangesX.at(currProj * 2);
						double pEndX = projectionRangesX.at(currProj * 2 + 1);
						double pStepX = (pEndX - pStartX) / (double) (resolutionX - 1);
						double pStartY = projectionRangesY.at(currProj * 2);
						double pEndY = projectionRangesY.at(currProj * 2 + 1);
						double pStepY = (pEndY - pStartY) / (double) (resolutionY - 1);
						
						int xPos = floor((xVal - pStartX) / pStepX + 1);
						int yPos = floor((yVal - pStartY) / pStepY + 1);

						mData->set(attrNo, xPos, yPos, 3 + currProj);
					}
				}
				
				if(!attrMatch) {
					attractors.append(networkStates.last());
				}
			}
			
			// or not, but then there's nothing to do :D
			
			// runtime maintencance
			if(core->isShuttingDown()) {
				return;
			}
			core->executePendingTasks();
		}
	}
	
	// CLEAN UP
	variedValX->set(variedValuesOrig.at(0));
	variedValY->set(variedValuesOrig.at(1));
	notifyNetworkParametersChanged(network);

	triggerReset();
	restoreNetworkConfiguration();
	restoreCurrentNetworkActivites();

}
Example #30
0
static void connectWaveformTracer(Core &core, WaveformTracer &waveformTracer)
{
  for (Port *port : core.getPorts()) {
    waveformTracer.add(core.getCoreName(), port);
  }
}