void BreakBlockquoteCommand::doApply()
{
    if (endingSelection().isNone())
        return;
    
    // Delete the current selection.
    if (endingSelection().isRange())
        deleteSelection(false, false);
    
    // This is a scenario that should never happen, but we want to
    // make sure we don't dereference a null pointer below.    

    ASSERT(!endingSelection().isNone());
    
    if (endingSelection().isNone())
        return;
        
    VisiblePosition visiblePos = endingSelection().visibleStart();
    
    // pos is a position equivalent to the caret.  We use downstream() so that pos will 
    // be in the first node that we need to move (there are a few exceptions to this, see below).
    Position pos = endingSelection().start().downstream();
    
    // Find the top-most blockquote from the start.
    Element* topBlockquote = 0;
    for (ContainerNode* node = pos.node()->parentNode(); node; node = node->parentNode()) {
        if (isMailBlockquote(node))
            topBlockquote = static_cast<Element*>(node);
    }
    if (!topBlockquote || !topBlockquote->parentNode())
        return;
    
    RefPtr<Element> breakNode = createBreakElement(document());

    bool isLastVisPosInNode = isLastVisiblePositionInNode(visiblePos, topBlockquote);

    // If the position is at the beginning of the top quoted content, we don't need to break the quote.
    // Instead, insert the break before the blockquote, unless the position is as the end of the the quoted content.
    if (isFirstVisiblePositionInNode(visiblePos, topBlockquote) && !isLastVisPosInNode) {
        insertNodeBefore(breakNode.get(), topBlockquote);
        setEndingSelection(VisibleSelection(Position(breakNode.get(), 0), DOWNSTREAM));
        rebalanceWhitespace();   
        return;
    }
    
    // Insert a break after the top blockquote.
    insertNodeAfter(breakNode.get(), topBlockquote);

    // If we're inserting the break at the end of the quoted content, we don't need to break the quote.
    if (isLastVisPosInNode) {
        setEndingSelection(VisibleSelection(Position(breakNode.get(), 0), DOWNSTREAM));
        rebalanceWhitespace();
        return;
    }
    
    // Don't move a line break just after the caret.  Doing so would create an extra, empty paragraph
    // in the new blockquote.
    if (lineBreakExistsAtVisiblePosition(visiblePos))
        pos = pos.next();
        
    // Adjust the position so we don't split at the beginning of a quote.  
    while (isFirstVisiblePositionInNode(VisiblePosition(pos), nearestMailBlockquote(pos.node())))
        pos = pos.previous();
    
    // startNode is the first node that we need to move to the new blockquote.
    Node* startNode = pos.node();
        
    // Split at pos if in the middle of a text node.
    if (startNode->isTextNode()) {
        Text* textNode = static_cast<Text*>(startNode);
        if ((unsigned)pos.deprecatedEditingOffset() >= textNode->length()) {
            startNode = startNode->traverseNextNode();
            ASSERT(startNode);
        } else if (pos.deprecatedEditingOffset() > 0)
            splitTextNode(textNode, pos.deprecatedEditingOffset());
    } else if (pos.deprecatedEditingOffset() > 0) {
        Node* childAtOffset = startNode->childNode(pos.deprecatedEditingOffset());
        startNode = childAtOffset ? childAtOffset : startNode->traverseNextNode();
        ASSERT(startNode);
    }
    
    // If there's nothing inside topBlockquote to move, we're finished.
    if (!startNode->isDescendantOf(topBlockquote)) {
        setEndingSelection(VisibleSelection(VisiblePosition(Position(startNode, 0))));
        return;
    }
    
    // Build up list of ancestors in between the start node and the top blockquote.
    Vector<Element*> ancestors;    
    for (Element* node = startNode->parentElement(); node && node != topBlockquote; node = node->parentElement())
        ancestors.append(node);
    
    // Insert a clone of the top blockquote after the break.
    RefPtr<Element> clonedBlockquote = topBlockquote->cloneElementWithoutChildren();
    insertNodeAfter(clonedBlockquote.get(), breakNode.get());
    
    // Clone startNode's ancestors into the cloned blockquote.
    // On exiting this loop, clonedAncestor is the lowest ancestor
    // that was cloned (i.e. the clone of either ancestors.last()
    // or clonedBlockquote if ancestors is empty).
    RefPtr<Element> clonedAncestor = clonedBlockquote;
    for (size_t i = ancestors.size(); i != 0; --i) {
        RefPtr<Element> clonedChild = ancestors[i - 1]->cloneElementWithoutChildren();
        // Preserve list item numbering in cloned lists.
        if (clonedChild->isElementNode() && clonedChild->hasTagName(olTag)) {
            Node* listChildNode = i > 1 ? ancestors[i - 2] : startNode;
            // The first child of the cloned list might not be a list item element, 
            // find the first one so that we know where to start numbering.
            while (listChildNode && !listChildNode->hasTagName(liTag))
                listChildNode = listChildNode->nextSibling();
            if (listChildNode && listChildNode->renderer())
                setNodeAttribute(static_cast<Element*>(clonedChild.get()), startAttr, String::number(toRenderListItem(listChildNode->renderer())->value()));
        }
            
        appendNode(clonedChild.get(), clonedAncestor.get());
        clonedAncestor = clonedChild;
    }
    
    // Move the startNode and its siblings.
    Node *moveNode = startNode;
    while (moveNode) {
        Node *next = moveNode->nextSibling();
        removeNode(moveNode);
        appendNode(moveNode, clonedAncestor.get());
        moveNode = next;
    }

    if (!ancestors.isEmpty()) {
        // Split the tree up the ancestor chain until the topBlockquote
        // Throughout this loop, clonedParent is the clone of ancestor's parent.
        // This is so we can clone ancestor's siblings and place the clones
        // into the clone corresponding to the ancestor's parent.
        Element* ancestor;
        Element* clonedParent;
        for (ancestor = ancestors.first(), clonedParent = clonedAncestor->parentElement();
             ancestor && ancestor != topBlockquote;
             ancestor = ancestor->parentElement(), clonedParent = clonedParent->parentElement()) {
            moveNode = ancestor->nextSibling();
            while (moveNode) {
                Node *next = moveNode->nextSibling();
                removeNode(moveNode);
                appendNode(moveNode, clonedParent);
                moveNode = next;
            }
        }
        
        // If the startNode's original parent is now empty, remove it
        Node* originalParent = ancestors.first();
        if (!originalParent->hasChildNodes())
            removeNode(originalParent);
    }
    
    // Make sure the cloned block quote renders.
    addBlockPlaceholderIfNeeded(clonedBlockquote.get());
    
    // Put the selection right before the break.
    setEndingSelection(VisibleSelection(Position(breakNode.get(), 0), DOWNSTREAM));
    rebalanceWhitespace();
}
std::map<Switch, double> PerfectPathOptimizer::Score(const Position& position) {
  return lane_scores_[position.piece()][position.end_lane()];
}
void StructureAgent::debug_showGoal()
{
	if (!isAlive()) return;

	int w = unit->getType().tileWidth() * 32 / 2;
	Broodwar->drawText(CoordinateType::Map, unit->getPosition().x() - w, unit->getPosition().y() - 10, unit->getType().getName().c_str());

	//Draw "is working" box
	int total = 0;
	int done = 0;
	string txt = "";
	Color cColor = Colors::Blue;
	int bar_h = 18;

	if (unit->isBeingConstructed())
	{
		total = unit->getType().buildTime();
		done = total - unit->getRemainingBuildTime();
		txt = "";
		bar_h = 8;
	}
	if (!unit->isBeingConstructed() && unit->getType().isResourceContainer())
	{
		total = unit->getInitialResources();
		done = unit->getResources();
		txt = "";
		cColor = Colors::Orange;
		bar_h = 8;
	}
	if (unit->isResearching())
	{
		total = unit->getTech().researchTime();
		done = total - unit->getRemainingResearchTime();
		txt = unit->getTech().getName();
	}
	if (unit->isUpgrading())
	{
		total = unit->getUpgrade().upgradeTime();
		done = total - unit->getRemainingUpgradeTime();
		txt = unit->getUpgrade().getName();
	}
	if (unit->isTraining())
	{
		if (unit->getTrainingQueue().size() > 0)
		{
			UnitType t = *(unit->getTrainingQueue().begin());
			total = t.buildTime();
			txt = t.getName();
			done = total - unit->getRemainingTrainTime();
		}
	}

	if (total > 0)
	{
		int w = unit->getType().tileWidth() * 32;
		int h = unit->getType().tileHeight() * 32;

		//Start 
		Position s = Position(unit->getPosition().x() - w/2, unit->getPosition().y() - 30);
		//End
		Position e = Position(s.x() + w, s.y() + bar_h);
		//Progress
		int prg = (int)((double)done / (double)total * w);
		Position p = Position(s.x() + prg, s.y() +  bar_h);

		Broodwar->drawBox(CoordinateType::Map,s.x(),s.y(),e.x(),e.y(),cColor,false);
		Broodwar->drawBox(CoordinateType::Map,s.x(),s.y(),p.x(),p.y(),cColor,true);

		Broodwar->drawText(CoordinateType::Map, s.x() + 5, s.y() + 2, txt.c_str());
	}

	if (!unit->isBeingConstructed() && unit->getType().getID() == UnitTypes::Terran_Bunker.getID())
	{
		int w = unit->getType().tileWidth() * 32;
		int h = unit->getType().tileHeight() * 32;

		Broodwar->drawText(CoordinateType::Map, unit->getPosition().x() - w / 2, unit->getPosition().y() - 10, unit->getType().getName().c_str());

		//Draw Loaded box
		Position a = Position(unit->getPosition().x() - w/2, unit->getPosition().y() - h/2);
		Position b = Position(a.x() + 94, a.y() + 6);
		Broodwar->drawBox(CoordinateType::Map,a.x(),a.y(),b.x(),b.y(),Colors::Green,false);

		if ((int)unit->getLoadedUnits().size() > 0)
		{
			Position a = Position(unit->getPosition().x() - w/2, unit->getPosition().y() - h/2);
			Position b = Position(a.x() + unit->getLoadedUnits().size() * 24, a.y() + 6);

			Broodwar->drawBox(CoordinateType::Map,a.x(),a.y(),b.x(),b.y(),Colors::Green,true);
		}
	}
}
Example #4
0
	virtual void						acceptAt(Position const& _pos, Named*, CodeScene* _cs)
	{
		_cs->setCurrent(_pos.place(new ThisPointer));
	}
void servoboard_main::servoPlayButtonClicked(quint8 servoNumber, quint8 servoValue)
{
    Position *p = new Position();
    p->addServoPosition(servoNumber,servoValue);
    emit this->playPosition(p);
}
Example #6
0
List<ValueDefiner*> GlobalReferencedValue::staticRefPossibilities(Position const& _p)
{
	return _p->root()->childrenOf<ValueDefiner>();
}
Example #7
0
int Solve (int nodeType, Position& board, int ply, int alpha, int beta, int depth) {

	// return score for terminal state
	if (board.HasWon(board.get_arrayOfBitboard((board.get_nPlies() - 1) & 1))) {
		return -WIN + ply;
	} else if (board.get_nPlies() == 42) {
		return DRAW;
	}

	// Mate distance pruning
	alpha = std::max (ply - WIN, alpha);
	beta = std::min (WIN - (ply + 1), beta);
	if (alpha >= beta) {
		return alpha;
	}

	TTEntry entry = TranspositionTable.probeTTable(board.get_key());
		
	if (entry.flag == EXACT
		|| entry.flag == L_BOUND && entry.evaluationScore >= beta
		|| entry.flag == U_BOUND && entry.evaluationScore <= alpha) {

		if (entry.evaluationScore >= beta) {
			updateKillers(entry.move, ply);
		}
		return entry.evaluationScore;
	}

	int hashMove = (entry.flag == L_BOUND && entry.evaluationScore < beta) ? entry.move : NO_MOVE;
	int bestScore = -INF;
	int movesMade = 0;
	bool raisedAlpha = false;
	MovePicker mPicker(board, ply, hashMove);
	int bestMove = NO_MOVE;
	
	for (int i=0; i < 7; i++) {
			
		int move = mPicker.getNextMove();
		
		if (move == NO_MOVE) {
			break;
		}

		board.MakeMove(move);
		int score = -Solve(NON_ROOT, board, ply + 1, -beta, -alpha, depth - 1);
		board.UnmakeMove();
		nodesVisited++;
		movesMade++;

		if (score >= beta) {
			TTEntry newEntry = {board.get_key(), L_BOUND, depth, score, move};
			TranspositionTable.storeTTable(board.get_key(), newEntry);
			updateKillers(move, ply);
			updateHistory(depth, ply, move);

			if (movesMade == 1) {
				fh1++;
			} else {
				fh++;
			}
			return score;
		} else if (score > bestScore) {
			bestScore = score;
			bestMove = move;
			if (score > alpha) {
				alpha = score;
				raisedAlpha = true;
			}
		} 
	}

	if (raisedAlpha) {
		TTEntry newEntry = {board.get_key(), EXACT, depth, alpha, bestMove};
		TranspositionTable.storeTTable(board.get_key(), newEntry);
	} else {
		TTEntry newEntry = {board.get_key(), U_BOUND, depth, bestScore, NO_MOVE};
		TranspositionTable.storeTTable(board.get_key(), newEntry);
	}
	
	return bestScore; 
}
Example #8
0
// 利きのある場所への取れない近接王手からの3手詰め
Move Position::weak_mate_n_ply(int ply) const
{
	// 1手詰めであるならこれを返す
	Move m = mate1ply();
	if (m)
		return m;

	// 詰まない
	if (ply <= 1)
		return MOVE_NONE;

	Color us = side_to_move();
	Color them = ~us;
	Bitboard around8 = kingEffect(king_square(them));

	// const剥がし
	Position* This = ((Position*)this);

	StateInfo si;
	StateInfo si2;

	// 近接王手で味方の利きがあり、敵の利きのない場所を探す。
	for (auto m : MoveList<CHECKS>(*this))
	{
		// 近接王手で、この指し手による駒の移動先に敵の駒がない。
		Square to = to_sq(m);
		if ((around8 & to)

#ifndef LONG_EFFECT_LIBRARY
			// toに利きがあるかどうか。mが移動の指し手の場合、mの元の利きを取り除く必要がある。
			&& (is_drop(m) ? effected_to(us, to) : (attackers_to(us, to, pieces() ^ from_sq(m)) ^ from_sq(m)))

			// 敵玉の利きは必ずtoにあるのでそれを除いた利きがあるかどうか。
			&& (attackers_to(them,to,pieces()) ^ king_square(them))
#else
			&& (is_drop(m) ? effected_to(us, to) :
					board_effect[us].effect(to) >= 2 ||
					(long_effect.directions_of(us, from_sq(m)) & Effect8::directions_of(from_sq(m), to)) != 0)

			// 敵玉の利きがあるので2つ以上なければそれで良い。
			&& (board_effect[them].effect(to) <= 1)
#endif
			)
		{
			if (!legal(m))
				continue;

			ASSERT_LV3(gives_check(m));

			This->do_move(m,si,true);

			ASSERT_LV3(in_check());

			// この局面ですべてのevasionを試す
			for (auto m2 : MoveList<EVASIONS>(*this))
			{
				if (!legal(m2))
					continue;

				// この指し手で逆王手になるなら、不詰めとして扱う
				if (gives_check(m2))
					goto NEXT_CHECK;

				This->do_move(m2, si2, false);

				ASSERT_LV3(!in_check());

				if (!weak_mate_n_ply(ply-2))
				{
					// 詰んでないので、m2で詰みを逃れている。
					This->undo_move(m2);
					goto NEXT_CHECK;
				}

				This->undo_move(m2);
			}

			// すべて詰んだ
			This->undo_move(m);

			// mによって3手で詰む。
			return m;

		NEXT_CHECK:;
			This->undo_move(m);
		}
	}
	return MOVE_NONE;
}
Example #9
0
const PositionDiff Position::operator -(const Position& other) const {
    int dx = mX - other.getX();
    int dy = mY - other.getY();

    return PositionDiff(dx, dy);
}
Example #10
0
        void UpdateAI(uint32 diff) override
        {
            if (!UpdateVictim() || !CheckInRoom())
                return;

            events.Update(diff);

            if (me->HasUnitState(UNIT_STATE_CASTING))
                return;

            while (uint32 eventId = events.ExecuteEvent())
            {
                switch (eventId)
                {
                    case EVENT_CURSE:
                        DoCastAOE(SPELL_CURSE_PLAGUEBRINGER);
                        events.ScheduleEvent(EVENT_CURSE, urand(50000, 60000));
                        return;
                    case EVENT_WARRIOR:
                        Talk(SAY_SUMMON);
                        SummonUndead(NPC_WARRIOR, RAID_MODE(2, 3));
                        events.ScheduleEvent(EVENT_WARRIOR, 30000);
                        return;
                    case EVENT_BLINK:
                        DoCastAOE(SPELL_CRIPPLE, true);
                        DoCastAOE(SPELL_BLINK);
                        DoResetThreat();
                        events.ScheduleEvent(EVENT_BLINK, 40000);
                        return;
                    case EVENT_BALCONY:
                        me->SetReactState(REACT_PASSIVE);
                        me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
                        me->AttackStop();
                        me->RemoveAllAuras();
                        me->NearTeleportTo(Teleport.GetPositionX(), Teleport.GetPositionY(), Teleport.GetPositionZ(), Teleport.GetOrientation());
                        events.Reset();
                        events.ScheduleEvent(EVENT_WAVE, urand(2000, 5000));
                        waveCount = 0;
                        return;
                    case EVENT_WAVE:
                        Talk(SAY_SUMMON);
                        switch (balconyCount)
                        {
                            case 0:
                                SummonUndead(NPC_CHAMPION, RAID_MODE(2, 4));
                                break;
                            case 1:
                                SummonUndead(NPC_CHAMPION, RAID_MODE(1, 2));
                                SummonUndead(NPC_GUARDIAN, RAID_MODE(1, 2));
                                break;
                            case 2:
                                SummonUndead(NPC_GUARDIAN, RAID_MODE(2, 4));
                                break;
                            default:
                                SummonUndead(NPC_CHAMPION, RAID_MODE(5, 10));
                                SummonUndead(NPC_GUARDIAN, RAID_MODE(5, 10));
                                break;
                        }
                        ++waveCount;
                        events.ScheduleEvent(waveCount < 2 ? EVENT_WAVE : EVENT_GROUND, urand(30000, 45000));
                        return;
                    case EVENT_GROUND:
                    {
                        ++balconyCount;
                        float x, y, z, o;
                        me->GetHomePosition(x, y, z, o);
                        me->NearTeleportTo(x, y, z, o);
                        events.ScheduleEvent(EVENT_BALCONY, 110000);
                        EnterPhaseGround();
                        return;
                    }
                }
            }

            if (me->HasReactState(REACT_AGGRESSIVE))
                DoMeleeAttackIfReady();
        }
void
GUITriggeredRerouter::GUITriggeredRerouterEdge::drawGL(const GUIVisualizationSettings& s) const {
    const SUMOReal exaggeration = s.addSize.getExaggeration(s);
    if (s.scale * exaggeration >= 3) {
        glPushName(getGlID());
        const SUMOReal prob = myParent->getProbability();
        if (myAmClosedEdge) {
            // draw closing symbol onto all lanes
            const RerouteInterval* const ri =
                myParent->getCurrentReroute(MSNet::getInstance()->getCurrentTimeStep());
            if (ri != 0 && prob > 0) {
                // draw only if the edge is closed at this time
                if (std::find(ri->closed.begin(), ri->closed.end(), myEdge) != ri->closed.end()) {
                    const size_t noLanes = myFGPositions.size();
                    for (size_t j = 0; j < noLanes; ++j) {
                        Position pos = myFGPositions[j];
                        SUMOReal rot = myFGRotations[j];
                        glPushMatrix();
                        glTranslated(pos.x(), pos.y(), 0);
                        glRotated(rot, 0, 0, 1);
                        glTranslated(0, -1.5, 0);
                        int noPoints = 9;
                        if (s.scale > 25) {
                            noPoints = (int)(9.0 + s.scale / 10.0);
                            if (noPoints > 36) {
                                noPoints = 36;
                            }
                        }
                        glTranslated(0, 0, getType());
                        //glScaled(exaggeration, exaggeration, 1);
                        glColor3d(0.7, 0, 0);
                        GLHelper::drawFilledCircle((SUMOReal) 1.3, noPoints);
                        glTranslated(0, 0, .1);
                        glColor3d(1, 0, 0);
                        GLHelper::drawFilledCircle((SUMOReal) 1.3, noPoints, 0, prob * 360);
                        glTranslated(0, 0, .1);
                        glColor3d(1, 1, 1);
                        glRotated(-90, 0, 0, 1);
                        glBegin(GL_TRIANGLES);
                        glVertex2d(0 - .3, -1.);
                        glVertex2d(0 - .3, 1.);
                        glVertex2d(0 + .3, 1.);
                        glVertex2d(0 + .3, -1.);
                        glVertex2d(0 - .3, -1.);
                        glVertex2d(0 + .3, 1.);
                        glEnd();
                        glPopMatrix();
                    }
                }
            }

        } else {
            // draw rerouter symbol onto all lanes
            for (size_t i = 0; i < myFGPositions.size(); ++i) {
                const Position& pos = myFGPositions[i];
                SUMOReal rot = myFGRotations[i];
                glPushMatrix();
                glTranslated(pos.x(), pos.y(), 0);
                glRotated(rot, 0, 0, 1);
                glTranslated(0, 0, getType());
                glScaled(exaggeration, exaggeration, 1);
                glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

                glBegin(GL_TRIANGLES);
                glColor3d(1, .8f, 0);
                // base
                glVertex2d(0 - 1.4, 0);
                glVertex2d(0 - 1.4, 6);
                glVertex2d(0 + 1.4, 6);
                glVertex2d(0 + 1.4, 0);
                glVertex2d(0 - 1.4, 0);
                glVertex2d(0 + 1.4, 6);
                glEnd();

                glTranslated(0, 0, .1);
                glColor3d(0, 0, 0);
                pfSetPosition(0, 0);
                pfSetScale(3.f);
                SUMOReal w = pfdkGetStringWidth("U");
                glRotated(180, 0, 1, 0);
                glTranslated(-w / 2., 2, 0);
                pfDrawString("U");

                glTranslated(w / 2., -2, 0);
                std::string str = toString((int)(prob * 100)) + "%";
                pfSetPosition(0, 0);
                pfSetScale(.7f);
                w = pfdkGetStringWidth(str.c_str());
                glTranslated(-w / 2., 4, 0);
                pfDrawString(str.c_str());
                glPopMatrix();
            }
        }
        glPopName();
    }
}
Example #12
0
void FirstPersonCamera::Update(double dt, vector<InteractableOBJs>&InteractablesList, vector<Building>&BuildingsList, Player &somePlayer)
{
    Vector3 boundary(1000, 1000, 1000);

    speed = 30;
    mouseSpeed = 12;

    static const float CAMERA_SPEED = 50.f;
    //if (Application::IsKeyPressed('R'))
    //{
    //	Reset();
    //}

    //view.y < 0.9396 && view.y > -09396

    //Mouse - Shania
    //int Angle = 50;
    //horizontalAngle += mouseSpeed * dt * float(1680 / 2 - Application::mouseX);
    //if (verticalAngle + mouseSpeed * dt * float(1080 / 2 - Application::mouseY) < Angle && verticalAngle + mouseSpeed * dt * float(1080 / 2 - Application::mouseY) > -Angle)
    //{
    //    verticalAngle += mouseSpeed * dt * float(1080 / 2 - Application::mouseY);
    //}

    //Vector3 view(cos(Math::DegreeToRadian(verticalAngle)) * sin(Math::DegreeToRadian(horizontalAngle)),
    //    sin(Math::DegreeToRadian(verticalAngle)),
    //    cos(Math::DegreeToRadian(verticalAngle)) * cos(Math::DegreeToRadian(horizontalAngle)));


    //Vector3 right(sin(Math::DegreeToRadian(horizontalAngle - 90)), 0, cos(Math::DegreeToRadian(horizontalAngle - 90)));

    //up = right.Cross(view);

    //target = position + view.Normalized();


    // Mouse - DonoDon
    Vector3 view = (target - position).Normalized();

    float yaw = 0;
    float pitch = 0;

    yaw = (float)(mouseSpeed  * dt * (1680 / 2 - Application::mouseX));

    pitch = (float)(mouseSpeed * dt * (1080 / 2 - Application::mouseY));

    // Mouse
    Mtx44 rotationYaw;
    rotationYaw.SetToRotation(yaw, 0, 1, 0);
    view = (target - position);
    Vector3 right = view.Cross(up);
    view = rotationYaw * view;

    target = view + position;
    up = rotationYaw * up;

    Mtx44 rotationPitch;
    view = (target - position);
    right = view.Cross(up);
    right.y = 0;
    up = right.Cross(view).Normalized();
    rotationPitch.SetToRotation(pitch, right.x, right.y, right.z);



    view = rotationPitch * view;
    target = view + position;

    view = (target - position).Normalized();

    Position camPos; // Position to check collision with

    if (Application::IsKeyPressed('W'))
    {
        camPos.Set(somePlayer.pos.x + view.Normalized().x, somePlayer.pos.y + view.Normalized().y, somePlayer.pos.z + view.Normalized().z);
        if (createBoundary(InteractablesList, BuildingsList, somePlayer, camPos))
        {
            position.x = position.x + view.Normalized().x; // position = position + view
            position.z = position.z + view.Normalized().z; // position = position + view
            target.x = target.x + view.Normalized().x; // target = target + view
            target.z = target.z + view.Normalized().z; // target = target + view

            somePlayer.pos.x += view.Normalized().x;
            somePlayer.pos.z += view.Normalized().z;
        }
    }

    if (Application::IsKeyPressed('S'))
    {
        //camPos.Set(position.x - view.x, position.Normalized().y - view.y, position.z - view.z);
        camPos.Set(somePlayer.pos.x - view.Normalized().x, somePlayer.pos.y - view.Normalized().y, somePlayer.pos.z - view.Normalized().z);
        if (createBoundary(InteractablesList, BuildingsList, somePlayer, camPos))
        {
            position.x = position.x - (target - position).Normalized().x;
            position.z = position.z - (target - position).Normalized().z;
            target.x = target.x - (target - position).Normalized().x;
            target.z = target.z - (target - position).Normalized().z;

            somePlayer.pos.x -= view.Normalized().x;
            somePlayer.pos.z -= view.Normalized().z;
        }
    }

    if (Application::IsKeyPressed('A'))
    {
        //camPos.Set(position.x - right.Normalized().x, position.Normalized().y - right.Normalized().y, position.z - right.Normalized().z);
        camPos.Set(somePlayer.pos.x - right.Normalized().x, somePlayer.pos.y - right.Normalized().y, somePlayer.pos.z - right.Normalized().z);
        if (createBoundary(InteractablesList, BuildingsList, somePlayer, camPos))
        {
            position -= right.Normalized();
            target -= right.Normalized();

            somePlayer.pos.x -= right.Normalized().x;
            somePlayer.pos.z -= right.Normalized().z;
        }
    }

    if (Application::IsKeyPressed('D'))
    {
        //camPos.Set(position.x + right.Normalized().x, position.Normalized().y + right.Normalized().y, position.z + right.Normalized().z);
        camPos.Set(somePlayer.pos.x + right.Normalized().x, somePlayer.pos.y + right.Normalized().y, somePlayer.pos.z + right.Normalized().z);
        if (createBoundary(InteractablesList, BuildingsList, somePlayer, camPos))
        {
            position += right.Normalized();
            target += right.Normalized();

            somePlayer.pos.x += right.Normalized().x;
            somePlayer.pos.z += right.Normalized().z;
        }
    }

}
void
Boundary::add(const Position& p) {
    add(p.x(), p.y());
}
bool
Boundary::around(const Position& p, SUMOReal offset) const {
    return
        (p.x() <= myXmax + offset && p.x() >= myXmin - offset) &&
        (p.y() <= myYmax + offset && p.y() >= myYmin - offset);
}
Example #15
0
void Spectator::getViewIndex(Vec2 pos, ViewIndex& index) const {
  Position position = getLevel()->getPosition(pos);
  position.getViewIndex(index, nullptr);
  if (const Creature* c = position.getCreature())
    index.insert(c->getViewObject());
}
Example #16
0
void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
{
    deleteSection (startPosition.getPosition(), endPosition.getPosition());
}
Value evaluate(const Position& pos)
{
//	margin = VALUE_ZERO;
	const Color us = pos.side_to_move();
	return Value(pos.evaluate(us));
}
Example #18
0
void CodeDocument::insertText (const Position& position, const String& text)
{
    insertText (position.getPosition(), text);
}
Example #19
0
int32 CreatureAI::VisualizeBoundary(uint32 duration, Unit* owner, bool fill) const
{
    typedef std::pair<int32, int32> coordinate;

    if (!owner)
        return -1;

    if (!_boundary || _boundary->empty())
        return LANG_CREATURE_MOVEMENT_NOT_BOUNDED;

    std::queue<coordinate> Q;
    std::unordered_set<coordinate> alreadyChecked;
    std::unordered_set<coordinate> outOfBounds;

    Position startPosition = owner->GetPosition();
    if (!CheckBoundary(&startPosition)) // fall back to creature position
    {
        startPosition = me->GetPosition();
        if (!CheckBoundary(&startPosition))
        {
            startPosition = me->GetHomePosition();
            if (!CheckBoundary(&startPosition)) // fall back to creature home position
                return LANG_CREATURE_NO_INTERIOR_POINT_FOUND;
        }
    }
    float spawnZ = startPosition.GetPositionZ() + BOUNDARY_VISUALIZE_SPAWN_HEIGHT;

    bool boundsWarning = false;
    Q.push({ 0,0 });
    while (!Q.empty())
    {
        coordinate front = Q.front();
        bool hasOutOfBoundsNeighbor = false;
        for (coordinate off : std::initializer_list<coordinate>{{1,0}, {0,1}, {-1,0}, {0,-1}})
        {
            coordinate next(front.first + off.first, front.second + off.second);
            if (next.first > BOUNDARY_VISUALIZE_FAILSAFE_LIMIT || next.first < -BOUNDARY_VISUALIZE_FAILSAFE_LIMIT || next.second > BOUNDARY_VISUALIZE_FAILSAFE_LIMIT || next.second < -BOUNDARY_VISUALIZE_FAILSAFE_LIMIT)
            {
                boundsWarning = true;
                continue;
            }
            if (alreadyChecked.find(next) == alreadyChecked.end()) // never check a coordinate twice
            {
                Position nextPos(startPosition.GetPositionX() + next.first*BOUNDARY_VISUALIZE_STEP_SIZE, startPosition.GetPositionY() + next.second*BOUNDARY_VISUALIZE_STEP_SIZE, startPosition.GetPositionZ());
                if (CheckBoundary(&nextPos))
                    Q.push(next);
                else
                {
                    outOfBounds.insert(next);
                    hasOutOfBoundsNeighbor = true;
                }
                alreadyChecked.insert(next);
            }
            else
                if (outOfBounds.find(next) != outOfBounds.end())
                    hasOutOfBoundsNeighbor = true;
        }
        if (fill || hasOutOfBoundsNeighbor)
            if (TempSummon* point = owner->SummonCreature(BOUNDARY_VISUALIZE_CREATURE, Position(startPosition.GetPositionX() + front.first*BOUNDARY_VISUALIZE_STEP_SIZE, startPosition.GetPositionY() + front.second*BOUNDARY_VISUALIZE_STEP_SIZE, spawnZ), TEMPSUMMON_TIMED_DESPAWN, duration * IN_MILLISECONDS))
            {
                point->SetObjectScale(BOUNDARY_VISUALIZE_CREATURE_SCALE);
                point->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_STUNNED | UNIT_FLAG_IMMUNE_TO_NPC);
                if (!hasOutOfBoundsNeighbor)
                    point->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
            }
        Q.pop();
    }
    return boundsWarning ? LANG_CREATURE_MOVEMENT_MAYBE_UNBOUNDED : 0;
}
Example #20
0
CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const noexcept
{
    Position p (position);
    const int maxDistance = 256;
    int i = 0;

    while (i < maxDistance
            && CharacterFunctions::isWhitespace (p.getCharacter())
            && (i == 0 || (p.getCharacter() != '\n'
                            && p.getCharacter() != '\r')))
    {
        ++i;
        p.moveBy (1);
    }

    if (i == 0)
    {
        const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());

        while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
        {
            ++i;
            p.moveBy (1);
        }

        while (i < maxDistance
                && CharacterFunctions::isWhitespace (p.getCharacter())
                && (i == 0 || (p.getCharacter() != '\n'
                                && p.getCharacter() != '\r')))
        {
            ++i;
            p.moveBy (1);
        }
    }

    return p;
}
Example #21
0
int main()
{
	time_t begin = time(0); //use time
    
	srand(static_cast<unsigned int>(time(NULL)));
    //bool bad_input = false; could check this way
    
	// Ask for the board size (between 5 and 20 in each direction) and the number of mines.
	cout << "Welcome to MineSweeper 215!" << endl;
    cout << "" << endl;
    cout << "How large should the board be (width height)? ";
    
	int width = 0;
	int height = 0;
    int mine_count = 0; //move this to here cause it was too nested
    cin >> width >> height;
    
    while (cin.fail()){
        cout << "Please enter two number seperated by a space." << endl;
        cin.clear();
        cin.ignore(200, '\n');
        cout << "How large should the board be (width height)? ";
        cin >> width >> height;
    }

        
    while (width < 5 || width > 20 || height < 5 || height > 20) { //use while loops to check
        if(width < 5)
            cout << "Sorry, the width cannot be smaller than 5." << endl;
        if(width > 20)
            cout << "Sorry, the width cannot be larger than 20." << endl;
        if(height < 5)
            cout << "Sorry, the height cannot be smaller than 5." << endl;
        if(height > 20)
            cout << "Sorry, the height cannot be larger than 20." << endl;
        
        cin.clear();
        cin.ignore(200, '\n');
        cout << "How large should the board be (width height)? ";
        cin >> width >> height;
        while (cin.fail()){
            cout << "Please enter two number seperated by a space." << endl;
            cin.clear();
            cin.ignore(200, '\n');
            cout << "How large should the board be (width height)? ";
            cin >> width >> height;
        }
    }

    

    cout << "How many mines to place (maximum " << (width*height) << ")? ";
    cin.ignore(200, '\n');
    cin.clear();
    cin >> mine_count;
    
    while (cin.fail()){
        cout << "Please enter a number";
        cin.clear();
        cin.ignore(200, '\n');
        cout << "How many mines to place (maximum " << (width*height) << ")? ";
        cin >> mine_count;
    }
    while (mine_count > (width*height)) {
        cout << "Sorry, the maximum number of mines is " << (width*height) << "." << endl;
        cout << "How many mines to place (maximum " << (width*height) << ")? ";
        cin.ignore(200, '\n');
        cin.clear();
        cin >> mine_count;
        
        while (cin.fail()){
            cout << "Please enter a number";
            cin.ignore(200, '\n');
            cout << "How many mines to place (maximum " << (width*height) << ")? ";
            cin.ignore(200, '\n');
            cin.clear();
            cin >> mine_count;
        }
        
    }
    
    
    cout << "Beginning game! Good Luck!" << endl;
	// Create a board of that size.
	MineSweeperBoard board(width, height, mine_count);
    
	while (!board.lost() || !board.won())
	{
		board.display(cout);
        bool correct_command = false;
        char command; //use a char?
        Position p;
        
		// Ask the user to [R]eveal, [F]lag, or [G]ive up. The first two commands also require a Position, so you may need to ask for x and y coordinates as well.
		cout << "[R]eveal, [F]lag, or [G]ive up? ";
        cin.clear();
        cin.ignore(200, '\n');
        cin >> command;

        if(command == 'R' || command == 'F' || command == 'G'){
            correct_command = true;
        }
        
        while (correct_command == false) {
            cout << "Unknown command" << endl;
            cout << "[R]eveal, [F]lag, or [G]ive up? ";
            cin.clear();
            cin.ignore(200, '\n');
            cin >> command;
            if(command == 'R' || command == 'F' || command == 'G'){
                correct_command = true;
            }
        }
        
        if(command == 'R' || command == 'F'){
            cout << "What position (x y)? ";
            int x, y;

            cin >> x >> y;
            
            while (cin.fail()){
                cout << "Please enter two numbers seperated by a space";
                cin.clear();
                cin.ignore(200, '\n');
                cout << "What position (x y)? " << endl;
                cin >> x >> y;
            }
            while (x > (width-1) || y > (height-1)) {
                cout << "Coordinate must be within board." << endl;
                cin.clear();
                cin.ignore(200, '\n');
                cout << "What position (x y)? " << endl;
                cin >> x >> y;
            }
            p.set_x(x);
            p.set_y(y);

        
        }else{
Example #22
0
void CodeDocument::findLineContaining  (const Position& pos, Position& s, Position& e) const noexcept
{
    s.setLineAndIndex (pos.getLineNumber(), 0);
    e.setLineAndIndex (pos.getLineNumber() + 1, 0);
}
Example #23
0
void ThreadsManager::split(Position& pos, SearchStack* ss, Value* alpha, const Value beta,
                           Value* bestValue, Depth depth, Move threatMove,
                           int moveCount, MovePicker* mp, bool pvNode) {
  assert(pos.is_ok());
  assert(*bestValue >= -VALUE_INFINITE);
  assert(*bestValue <= *alpha);
  assert(*alpha < beta);
  assert(beta <= VALUE_INFINITE);
  assert(depth > DEPTH_ZERO);
  assert(pos.thread() >= 0 && pos.thread() < activeThreads);
  assert(activeThreads > 1);

  int i, master = pos.thread();
  Thread& masterThread = threads[master];

  lock_grab(&mpLock);

  // If no other thread is available to help us, or if we have too many
  // active split points, don't split.
  if (   !available_slave_exists(master)
      || masterThread.activeSplitPoints >= MAX_ACTIVE_SPLIT_POINTS)
  {
      lock_release(&mpLock);
      return;
  }

  // Pick the next available split point object from the split point stack
  SplitPoint& splitPoint = masterThread.splitPoints[masterThread.activeSplitPoints++];

  // Initialize the split point object
  splitPoint.parent = masterThread.splitPoint;
  splitPoint.master = master;
  splitPoint.is_betaCutoff = false;
  splitPoint.depth = depth;
  splitPoint.threatMove = threatMove;
  splitPoint.alpha = *alpha;
  splitPoint.beta = beta;
  splitPoint.pvNode = pvNode;
  splitPoint.bestValue = *bestValue;
  splitPoint.mp = mp;
  splitPoint.moveCount = moveCount;
  splitPoint.pos = &pos;
  splitPoint.nodes = 0;
  splitPoint.ss = ss;
  for (i = 0; i < activeThreads; i++)
      splitPoint.is_slave[i] = false;

  masterThread.splitPoint = &splitPoint;

  // If we are here it means we are not available
  assert(masterThread.state != Thread::AVAILABLE);

  int workersCnt = 1; // At least the master is included

  // Allocate available threads setting state to THREAD_BOOKED
  for (i = 0; !Fake && i < activeThreads && workersCnt < maxThreadsPerSplitPoint; i++)
      if (i != master && threads[i].is_available_to(master))
      {
          threads[i].state = Thread::BOOKED;
          threads[i].splitPoint = &splitPoint;
          splitPoint.is_slave[i] = true;
          workersCnt++;
      }

  assert(Fake || workersCnt > 1);

  // We can release the lock because slave threads are already booked and master is not available
  lock_release(&mpLock);

  // Tell the threads that they have work to do. This will make them leave
  // their idle loop.
  for (i = 0; i < activeThreads; i++)
      if (i == master || splitPoint.is_slave[i])
      {
          assert(i == master || threads[i].state == Thread::BOOKED);

          threads[i].state = Thread::WORKISWAITING; // This makes the slave to exit from idle_loop()

          if (useSleepingThreads && i != master)
              threads[i].wake_up();
      }

  // Everything is set up. The master thread enters the idle loop, from
  // which it will instantly launch a search, because its state is
  // THREAD_WORKISWAITING.  We send the split point as a second parameter to the
  // idle loop, which means that the main thread will return from the idle
  // loop when all threads have finished their work at this split point.
  idle_loop(master, &splitPoint);

  // We have returned from the idle loop, which means that all threads are
  // finished. Update alpha and bestValue, and return.
  lock_grab(&mpLock);

  *alpha = splitPoint.alpha;
  *bestValue = splitPoint.bestValue;
  masterThread.activeSplitPoints--;
  masterThread.splitPoint = splitPoint.parent;
  pos.set_nodes_searched(pos.nodes_searched() + splitPoint.nodes);

  lock_release(&mpLock);
}
Example #24
0
void VisibleSelection::adjustSelectionToAvoidCrossingEditingBoundaries()
{
    if (m_base.isNull() || m_start.isNull() || m_end.isNull())
        return;

    Node* baseRoot = highestEditableRoot(m_base);
    Node* startRoot = highestEditableRoot(m_start);
    Node* endRoot = highestEditableRoot(m_end);

    Node* baseEditableAncestor = lowestEditableAncestor(m_base.containerNode());

    // The base, start and end are all in the same region.  No adjustment necessary.
    if (baseRoot == startRoot && baseRoot == endRoot)
        return;

    // The selection is based in editable content.
    if (baseRoot) {
        // If the start is outside the base's editable root, cap it at the start of that root.
        // If the start is in non-editable content that is inside the base's editable root, put it
        // at the first editable position after start inside the base's editable root.
        if (startRoot != baseRoot) {
            VisiblePosition first = firstEditablePositionAfterPositionInRoot(m_start, baseRoot);
            m_start = first.deepEquivalent();
            if (m_start.isNull()) {
                ASSERT_NOT_REACHED();
                m_start = m_end;
            }
        }
        // If the end is outside the base's editable root, cap it at the end of that root.
        // If the end is in non-editable content that is inside the base's root, put it
        // at the last editable position before the end inside the base's root.
        if (endRoot != baseRoot) {
            VisiblePosition last = lastEditablePositionBeforePositionInRoot(m_end, baseRoot);
            m_end = last.deepEquivalent();
            if (m_end.isNull())
                m_end = m_start;
        }
    // The selection is based in non-editable content.
    } else {
        // FIXME: Non-editable pieces inside editable content should be atomic, in the same way that editable
        // pieces in non-editable content are atomic.

        // The selection ends in editable content or non-editable content inside a different editable ancestor,
        // move backward until non-editable content inside the same lowest editable ancestor is reached.
        Node* endEditableAncestor = lowestEditableAncestor(m_end.containerNode());
        if (endRoot || endEditableAncestor != baseEditableAncestor) {

            Position p = previousVisuallyDistinctCandidate(m_end);
            Node* shadowAncestor = endRoot ? endRoot->shadowHost() : 0;
            if (p.isNull() && shadowAncestor)
                p = positionAfterNode(shadowAncestor);
            while (p.isNotNull() && !(lowestEditableAncestor(p.containerNode()) == baseEditableAncestor && !isEditablePosition(p))) {
                Node* root = editableRootForPosition(p);
                shadowAncestor = root ? root->shadowHost() : 0;
                p = isAtomicNode(p.containerNode()) ? positionInParentBeforeNode(p.containerNode()) : previousVisuallyDistinctCandidate(p);
                if (p.isNull() && shadowAncestor)
                    p = positionAfterNode(shadowAncestor);
            }
            VisiblePosition previous(p);

            if (previous.isNull()) {
                // The selection crosses an Editing boundary.  This is a
                // programmer error in the editing code.  Happy debugging!
                ASSERT_NOT_REACHED();
                m_base = Position();
                m_extent = Position();
                validate();
                return;
            }
            m_end = previous.deepEquivalent();
        }

        // The selection starts in editable content or non-editable content inside a different editable ancestor,
        // move forward until non-editable content inside the same lowest editable ancestor is reached.
        Node* startEditableAncestor = lowestEditableAncestor(m_start.containerNode());
        if (startRoot || startEditableAncestor != baseEditableAncestor) {
            Position p = nextVisuallyDistinctCandidate(m_start);
            Node* shadowAncestor = startRoot ? startRoot->shadowHost() : 0;
            if (p.isNull() && shadowAncestor)
                p = positionBeforeNode(shadowAncestor);
            while (p.isNotNull() && !(lowestEditableAncestor(p.containerNode()) == baseEditableAncestor && !isEditablePosition(p))) {
                Node* root = editableRootForPosition(p);
                shadowAncestor = root ? root->shadowHost() : 0;
                p = isAtomicNode(p.containerNode()) ? positionInParentAfterNode(p.containerNode()) : nextVisuallyDistinctCandidate(p);
                if (p.isNull() && shadowAncestor)
                    p = positionBeforeNode(shadowAncestor);
            }
            VisiblePosition next(p);

            if (next.isNull()) {
                // The selection crosses an Editing boundary.  This is a
                // programmer error in the editing code.  Happy debugging!
                ASSERT_NOT_REACHED();
                m_base = Position();
                m_extent = Position();
                validate();
                return;
            }
            m_start = next.deepEquivalent();
        }
    }

    // Correct the extent if necessary.
    if (baseEditableAncestor != lowestEditableAncestor(m_extent.containerNode()))
        m_extent = m_baseIsFirst ? m_end : m_start;
}
Example #25
0
TEST(PositionTest, Initialize) {
  Position subject;
  subject += 1,2,3;
  EXPECT_EQ(3, subject.back());
}
Example #26
0
void Thread::split(Position& pos, const Stack* ss, Value alpha, Value beta, Value* bestValue,
                   Move* bestMove, Depth depth, int moveCount,
                   MovePicker* movePicker, int nodeType, bool cutNode) {

  assert(pos.pos_is_ok());
  assert(-VALUE_INFINITE < *bestValue && *bestValue <= alpha && alpha < beta && beta <= VALUE_INFINITE);
  assert(depth >= Threads.minimumSplitDepth);
  assert(searching);
  assert(splitPointsSize < MAX_SPLITPOINTS_PER_THREAD);

  // Pick the next available split point from the split point stack
  SplitPoint& sp = splitPoints[splitPointsSize];

  sp.masterThread = this;
  sp.parentSplitPoint = activeSplitPoint;
  sp.slavesMask = 0, sp.slavesMask.set(idx);
  sp.depth = depth;
  sp.bestValue = *bestValue;
  sp.bestMove = *bestMove;
  sp.alpha = alpha;
  sp.beta = beta;
  sp.nodeType = nodeType;
  sp.cutNode = cutNode;
  sp.movePicker = movePicker;
  sp.moveCount = moveCount;
  sp.pos = &pos;
  sp.nodes = 0;
  sp.cutoff = false;
  sp.ss = ss;

  // Try to allocate available threads and ask them to start searching setting
  // 'searching' flag. This must be done under lock protection to avoid concurrent
  // allocation of the same slave by another master.
  Threads.mutex.lock();
  sp.mutex.lock();

  sp.allSlavesSearching = true; // Must be set under lock protection
  ++splitPointsSize;
  activeSplitPoint = &sp;
  activePosition = NULL;

  for (Thread* slave; (slave = Threads.available_slave(this)) != NULL; )
  {
      sp.slavesMask.set(slave->idx);
      slave->activeSplitPoint = &sp;
      slave->searching = true; // Slave leaves idle_loop()
      slave->notify_one(); // Could be sleeping
  }

  // Everything is set up. The master thread enters the idle loop, from which
  // it will instantly launch a search, because its 'searching' flag is set.
  // The thread will return from the idle loop when all slaves have finished
  // their work at this split point.
  sp.mutex.unlock();
  Threads.mutex.unlock();

  Thread::idle_loop(); // Force a call to base class idle_loop()

  // In the helpful master concept, a master can help only a sub-tree of its
  // split point and because everything is finished here, it's not possible
  // for the master to be booked.
  assert(!searching);
  assert(!activePosition);

  // We have returned from the idle loop, which means that all threads are
  // finished. Note that setting 'searching' and decreasing splitPointsSize is
  // done under lock protection to avoid a race with Thread::available_to().
  Threads.mutex.lock();
  sp.mutex.lock();

  searching = true;
  --splitPointsSize;
  activeSplitPoint = sp.parentSplitPoint;
  activePosition = &pos;
  pos.set_nodes_searched(pos.nodes_searched() + sp.nodes);
  *bestMove = sp.bestMove;
  *bestValue = sp.bestValue;

  sp.mutex.unlock();
  Threads.mutex.unlock();
}
Example #27
0
static Position focusPosition(const VisibleSelection& selection)
{
    Position focus = selection.isBaseFirst() ? selection.end() : selection.start();
    return focus.parentAnchoredEquivalent();
}
Example #28
0
bool move_is_legal(const Position& pos, const Move m, Bitboard pinned) {

    assert(pos.is_ok());
    assert(move_is_ok(m));
    assert(pinned == pos.pinned_pieces(pos.side_to_move()));

    Color us = pos.side_to_move();
    Color them = opposite_color(us);
    Square from = move_from(m);
    Square to = move_to(m);
    Piece pc = pos.piece_on(from);

    // Use a slower but simpler function for uncommon cases
    if (move_is_ep(m) || move_is_castle(m))
        return move_is_legal(pos, m);

    // If the from square is not occupied by a piece belonging to the side to
    // move, the move is obviously not legal.
    if (color_of_piece(pc) != us)
        return false;

    // The destination square cannot be occupied by a friendly piece
    if (pos.color_of_piece_on(to) == us)
        return false;

    // Handle the special case of a pawn move
    if (type_of_piece(pc) == PAWN)
    {
        // Move direction must be compatible with pawn color
        int direction = to - from;
        if ((us == WHITE) != (direction > 0))
            return false;

        // A pawn move is a promotion iff the destination square is
        // on the 8/1th rank.
        if ((  (square_rank(to) == RANK_8 && us == WHITE)
                ||(square_rank(to) == RANK_1 && us != WHITE)) != bool(move_is_promotion(m)))
            return false;

        // The promotion piece, if any, must be valid
        if (move_promotion_piece(m) > QUEEN || move_promotion_piece(m) == PAWN)
            return false;

        // Proceed according to the square delta between the origin and
        // destination squares.
        switch (direction)
        {
        case DELTA_NW:
        case DELTA_NE:
        case DELTA_SW:
        case DELTA_SE:
            // Capture. The destination square must be occupied by an enemy
            // piece (en passant captures was handled earlier).
            if (pos.color_of_piece_on(to) != them)
                return false;
            break;

        case DELTA_N:
        case DELTA_S:
            // Pawn push. The destination square must be empty.
            if (!pos.square_is_empty(to))
                return false;
            break;

        case DELTA_NN:
            // Double white pawn push. The destination square must be on the fourth
            // rank, and both the destination square and the square between the
            // source and destination squares must be empty.
            if (   square_rank(to) != RANK_4
                    || !pos.square_is_empty(to)
                    || !pos.square_is_empty(from + DELTA_N))
                return false;
            break;

        case DELTA_SS:
            // Double black pawn push. The destination square must be on the fifth
            // rank, and both the destination square and the square between the
            // source and destination squares must be empty.
            if (   square_rank(to) != RANK_5
                    || !pos.square_is_empty(to)
                    || !pos.square_is_empty(from + DELTA_S))
                return false;
            break;

        default:
            return false;
        }
        // The move is pseudo-legal, check if it is also legal
        return pos.is_check() ? pos.pl_move_is_evasion(m, pinned) : pos.pl_move_is_legal(m, pinned);
    }

    // Luckly we can handle all the other pieces in one go
    return    bit_is_set(pos.attacks_from(pc, from), to)
              && (pos.is_check() ? pos.pl_move_is_evasion(m, pinned) : pos.pl_move_is_legal(m, pinned))
              && !move_is_promotion(m);
}
void InsertParagraphSeparatorCommand::doApply()
{
    if (!endingSelection().isNonOrphanedCaretOrRange())
        return;
    
    Position insertionPosition = endingSelection().start();
        
    EAffinity affinity = endingSelection().affinity();
        
    // Delete the current selection.
    if (endingSelection().isRange()) {
        calculateStyleBeforeInsertion(insertionPosition);
        deleteSelection(false, true);
        insertionPosition = endingSelection().start();
        affinity = endingSelection().affinity();
    }
    
    // FIXME: The parentAnchoredEquivalent conversion needs to be moved into enclosingBlock.
    RefPtr<Element> startBlock = enclosingBlock(insertionPosition.parentAnchoredEquivalent().containerNode());
    Position canonicalPos = VisiblePosition(insertionPosition).deepEquivalent();
    if (!startBlock
        || !startBlock->nonShadowBoundaryParentNode()
        || isTableCell(startBlock.get())
        || isHTMLFormElement(startBlock.get())
        // FIXME: If the node is hidden, we don't have a canonical position so we will do the wrong thing for tables and <hr>. https://bugs.webkit.org/show_bug.cgi?id=40342
        || (!canonicalPos.isNull() && canonicalPos.deprecatedNode()->renderer() && canonicalPos.deprecatedNode()->renderer()->isTable())
        || (!canonicalPos.isNull() && canonicalPos.deprecatedNode()->hasTagName(hrTag))) {
        applyCommandToComposite(InsertLineBreakCommand::create(document()));
        return;
    }
    
    // Use the leftmost candidate.
    insertionPosition = insertionPosition.upstream();
    if (!insertionPosition.isCandidate())
        insertionPosition = insertionPosition.downstream();

    // Adjust the insertion position after the delete
    insertionPosition = positionAvoidingSpecialElementBoundary(insertionPosition);
    VisiblePosition visiblePos(insertionPosition, affinity);
    calculateStyleBeforeInsertion(insertionPosition);

    //---------------------------------------------------------------------
    // Handle special case of typing return on an empty list item
    if (breakOutOfEmptyListItem())
        return;

    //---------------------------------------------------------------------
    // Prepare for more general cases.

    bool isFirstInBlock = isStartOfBlock(visiblePos);
    bool isLastInBlock = isEndOfBlock(visiblePos);
    bool nestNewBlock = false;

    // Create block to be inserted.
    RefPtr<Element> blockToInsert;
    if (startBlock->isRootEditableElement()) {
        blockToInsert = createDefaultParagraphElement(document());
        nestNewBlock = true;
    } else if (shouldUseDefaultParagraphElement(startBlock.get())) 
        blockToInsert = createDefaultParagraphElement(document());
    else
        blockToInsert = startBlock->cloneElementWithoutChildren();

    //---------------------------------------------------------------------
    // Handle case when position is in the last visible position in its block,
    // including when the block is empty. 
    if (isLastInBlock) {
        if (nestNewBlock) {
            if (isFirstInBlock && !lineBreakExistsAtVisiblePosition(visiblePos)) {
                // The block is empty.  Create an empty block to
                // represent the paragraph that we're leaving.
                RefPtr<Element> extraBlock = createDefaultParagraphElement(document());
                appendNode(extraBlock, startBlock);
                appendBlockPlaceholder(extraBlock);
            }
            appendNode(blockToInsert, startBlock);
        } else {
            // We can get here if we pasted a copied portion of a blockquote with a newline at the end and are trying to paste it
            // into an unquoted area. We then don't want the newline within the blockquote or else it will also be quoted.
            if (m_pasteBlockqutoeIntoUnquotedArea) {
                if (Node* highestBlockquote = highestEnclosingNodeOfType(canonicalPos, &isMailBlockquote))
                    startBlock = toElement(highestBlockquote);
            }

            // Most of the time we want to stay at the nesting level of the startBlock (e.g., when nesting within lists).  However,
            // for div nodes, this can result in nested div tags that are hard to break out of.
            Element* siblingNode = startBlock.get();
            if (blockToInsert->hasTagName(divTag))
                siblingNode = highestVisuallyEquivalentDivBelowRoot(startBlock.get());
            insertNodeAfter(blockToInsert, siblingNode);
        }

        // Recreate the same structure in the new paragraph.
        
        Vector<RefPtr<Element> > ancestors;
        getAncestorsInsideBlock(positionOutsideTabSpan(insertionPosition).deprecatedNode(), startBlock.get(), ancestors);      
        RefPtr<Element> parent = cloneHierarchyUnderNewBlock(ancestors, blockToInsert);
        
        appendBlockPlaceholder(parent);

        setEndingSelection(VisibleSelection(firstPositionInNode(parent.get()), DOWNSTREAM, endingSelection().isDirectional()));
        return;
    }
    

    //---------------------------------------------------------------------
    // Handle case when position is in the first visible position in its block, and
    // similar case where previous position is in another, presumeably nested, block.
    if (isFirstInBlock || !inSameBlock(visiblePos, visiblePos.previous())) {
        Node *refNode;
        
        insertionPosition = positionOutsideTabSpan(insertionPosition);

        if (isFirstInBlock && !nestNewBlock)
            refNode = startBlock.get();
        else if (isFirstInBlock && nestNewBlock) {
            // startBlock should always have children, otherwise isLastInBlock would be true and it's handled above.
            ASSERT(startBlock->firstChild());
            refNode = startBlock->firstChild();
        }
        else if (insertionPosition.deprecatedNode() == startBlock && nestNewBlock) {
            refNode = startBlock->childNode(insertionPosition.deprecatedEditingOffset());
            ASSERT(refNode); // must be true or we'd be in the end of block case
        } else
            refNode = insertionPosition.deprecatedNode();

        // find ending selection position easily before inserting the paragraph
        insertionPosition = insertionPosition.downstream();
        
        insertNodeBefore(blockToInsert, refNode);

        // Recreate the same structure in the new paragraph.

        Vector<RefPtr<Element> > ancestors;
        getAncestorsInsideBlock(positionAvoidingSpecialElementBoundary(positionOutsideTabSpan(insertionPosition)).deprecatedNode(), startBlock.get(), ancestors);
        
        appendBlockPlaceholder(cloneHierarchyUnderNewBlock(ancestors, blockToInsert));
        
        // In this case, we need to set the new ending selection.
        setEndingSelection(VisibleSelection(insertionPosition, DOWNSTREAM, endingSelection().isDirectional()));
        return;
    }

    //---------------------------------------------------------------------
    // Handle the (more complicated) general case,

    // All of the content in the current block after visiblePos is
    // about to be wrapped in a new paragraph element.  Add a br before 
    // it if visiblePos is at the start of a paragraph so that the 
    // content will move down a line.
    if (isStartOfParagraph(visiblePos)) {
        RefPtr<Element> br = createBreakElement(document());
        insertNodeAt(br.get(), insertionPosition);
        insertionPosition = positionInParentAfterNode(br.get());
        // If the insertion point is a break element, there is nothing else
        // we need to do.
        if (visiblePos.deepEquivalent().anchorNode()->renderer()->isBR()) {
            setEndingSelection(VisibleSelection(insertionPosition, DOWNSTREAM, endingSelection().isDirectional()));
            return;
        }
    }
    
    // Move downstream. Typing style code will take care of carrying along the 
    // style of the upstream position.
    insertionPosition = insertionPosition.downstream();

    // At this point, the insertionPosition's node could be a container, and we want to make sure we include
    // all of the correct nodes when building the ancestor list.  So this needs to be the deepest representation of the position
    // before we walk the DOM tree.
    insertionPosition = positionOutsideTabSpan(VisiblePosition(insertionPosition).deepEquivalent());

    // If the returned position lies either at the end or at the start of an element that is ignored by editing
    // we should move to its upstream or downstream position.
    if (editingIgnoresContent(insertionPosition.deprecatedNode())) {
        if (insertionPosition.atLastEditingPositionForNode())
            insertionPosition = insertionPosition.downstream();
        else if (insertionPosition.atFirstEditingPositionForNode())
            insertionPosition = insertionPosition.upstream();
    }

    // Make sure we do not cause a rendered space to become unrendered.
    // FIXME: We need the affinity for pos, but pos.downstream() does not give it
    Position leadingWhitespace = insertionPosition.leadingWhitespacePosition(VP_DEFAULT_AFFINITY);
    // FIXME: leadingWhitespacePosition is returning the position before preserved newlines for positions
    // after the preserved newline, causing the newline to be turned into a nbsp.
    if (leadingWhitespace.isNotNull() && leadingWhitespace.deprecatedNode()->isTextNode()) {
        Text* textNode = toText(leadingWhitespace.deprecatedNode());
        ASSERT(!textNode->renderer() || textNode->renderer()->style()->collapseWhiteSpace());
        replaceTextInNodePreservingMarkers(textNode, leadingWhitespace.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
    }
    
    // Split at pos if in the middle of a text node.
    Position positionAfterSplit;
    if (insertionPosition.anchorType() == Position::PositionIsOffsetInAnchor && insertionPosition.containerNode()->isTextNode()) {
        RefPtr<Text> textNode = toText(insertionPosition.containerNode());
        bool atEnd = static_cast<unsigned>(insertionPosition.offsetInContainerNode()) >= textNode->length();
        if (insertionPosition.deprecatedEditingOffset() > 0 && !atEnd) {
            splitTextNode(textNode, insertionPosition.offsetInContainerNode());
            positionAfterSplit = firstPositionInNode(textNode.get());
            if (!textNode->previousSibling())
                return; // Bail out if mutation events detachd the split text node.
            insertionPosition.moveToPosition(textNode->previousSibling(), insertionPosition.offsetInContainerNode());
            visiblePos = VisiblePosition(insertionPosition);
        }
    }

    // If we got detached due to mutation events, just bail out.
    if (!startBlock->parentNode())
        return;

    // Put the added block in the tree.
    if (nestNewBlock)
        appendNode(blockToInsert.get(), startBlock);
    else
        insertNodeAfter(blockToInsert.get(), startBlock);

    document().updateLayoutIgnorePendingStylesheets();

    // If the paragraph separator was inserted at the end of a paragraph, an empty line must be
    // created.  All of the nodes, starting at visiblePos, are about to be added to the new paragraph 
    // element.  If the first node to be inserted won't be one that will hold an empty line open, add a br.
    if (isEndOfParagraph(visiblePos) && !lineBreakExistsAtVisiblePosition(visiblePos))
        appendNode(createBreakElement(document()).get(), blockToInsert.get());

    // Move the start node and the siblings of the start node.
    if (VisiblePosition(insertionPosition) != VisiblePosition(positionBeforeNode(blockToInsert.get()))) {
        Node* n;
        if (insertionPosition.containerNode() == startBlock)
            n = insertionPosition.computeNodeAfterPosition();
        else {
            Node* splitTo = insertionPosition.containerNode();
            if (splitTo->isTextNode() && insertionPosition.offsetInContainerNode() >= caretMaxOffset(splitTo))
                splitTo = NodeTraversal::next(splitTo, startBlock.get());
            ASSERT(splitTo);
            splitTreeToNode(splitTo, startBlock.get());

            for (n = startBlock->firstChild(); n; n = n->nextSibling()) {
                VisiblePosition beforeNodePosition = positionBeforeNode(n);
                if (!beforeNodePosition.isNull() && comparePositions(VisiblePosition(insertionPosition), beforeNodePosition) <= 0)
                    break;
            }
        }

        moveRemainingSiblingsToNewParent(n, blockToInsert.get(), blockToInsert);
    }            

    // Handle whitespace that occurs after the split
    if (positionAfterSplit.isNotNull()) {
        document().updateLayoutIgnorePendingStylesheets();
        if (!positionAfterSplit.isRenderedCharacter()) {
            // Clear out all whitespace and insert one non-breaking space
            ASSERT(!positionAfterSplit.containerNode()->renderer() || positionAfterSplit.containerNode()->renderer()->style()->collapseWhiteSpace());
            deleteInsignificantTextDownstream(positionAfterSplit);
            if (positionAfterSplit.deprecatedNode()->isTextNode())
                insertTextIntoNode(toText(positionAfterSplit.containerNode()), 0, nonBreakingSpaceString());
        }
    }

    setEndingSelection(VisibleSelection(firstPositionInNode(blockToInsert.get()), DOWNSTREAM, endingSelection().isDirectional()));
    applyStyleAfterInsertion(startBlock.get());
}
Example #30
0
    bool Execute(uint64 /*currTime*/, uint32 /*diff*/)
    {
        if (InstanceScript* instance = obj->GetInstanceScript())
        {
            if (obj)
            {
                switch (modifier)
                {
                case 0:
                {
                    std::list<Player*> pl_list;
                    obj->GetPlayerListInGrid(pl_list, 500.0f);

                    if (pl_list.empty())
                        return false;

                    for (auto itr : pl_list)
                    {
                        itr->AddAura(45066, itr);
                    }

                    Creature* lei_shen = obj->SummonCreature(CREATURE_LEI_SHEN, Lei_Shen, TEMPSUMMON_MANUAL_DESPAWN);
                    if (lei_shen)
                    {
                        lei_shen->SetObjectScale(2.5);
                        lei_shen->AI()->Talk(LEI_SHEN_TALK_01);

                        obj->m_Events.AddEvent(new tortos_bridge_Event(lei_shen, 1), obj->m_Events.CalculateTime(10000));
                    }
                    break;
                }
                case 1:
                {
                    if (Creature* lei_shen = obj->ToCreature())
                        lei_shen->AI()->Talk(LEI_SHEN_TALK_02);

                    obj->m_Events.AddEvent(new tortos_bridge_Event(obj, 2), obj->m_Events.CalculateTime(10000));
                    break;
                }
                case 2:
                {
                    if (Creature* lei_shen = obj->ToCreature())
                        lei_shen->AI()->Talk(LEI_SHEN_TALK_03);

                    obj->m_Events.AddEvent(new tortos_bridge_Event(obj, 3), obj->m_Events.CalculateTime(6000));
                    break;
                }
                case 3:
                {              
                 Creature* lightning_storm_trigger = obj->SummonCreature(TRIGGER_LIGHTNING_STORM, LightningStormTrigger, TEMPSUMMON_TIMED_DESPAWN);
                 if (lightning_storm_trigger)
                 {
                     lightning_storm_trigger->setFaction(35);
                     lightning_storm_trigger->CastSpell(lightning_storm_trigger, SPELL_COSMETIC_LIGHTNING_STORM);
                     obj->m_Events.AddEvent(new tortos_bridge_Event(obj, 4), obj->m_Events.CalculateTime(15000));
                 }
                break;
                }
                case 4:
                {
                    std::list<Player*> pl_list;
                    obj->GetPlayerListInGrid(pl_list, 500.0f);

                    if (pl_list.empty())
                        return false;

                    for (auto itr : pl_list)
                    {
                        itr->NearTeleportTo(TortosLair.GetPositionX(), TortosLair.GetPositionY(), TortosLair.GetPositionZ(), TortosLair.GetOrientation());
                    }
                    instance->DoRemoveAurasDueToSpellOnPlayers(45066);
                    instance->DoRemoveAurasDueToSpellOnPlayers(140560);
                    break;
                }
                }
            }
        }
        return true;
    }