• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!

[Snippet] UnitUpdatedTree

Level 31
Joined
Jul 10, 2007
Messages
6,306
Primarily to show people one way to do a tree of ordered units ^)^. Adds all units to the tree and allows you to retrieve that tree and iterate over it. Also supports closest neighbor.

JASS:
library UnitUpdatedTree uses UnitMovement, UnitRangeTree, Tt
/*
*   uses
*
*       UnitMovement        hiveworkshop.com/forums/submissions-414/system-needs-work-unit-movement-201449/
*       UnitRangeTree       hiveworkshop.com/forums/submissions-414/system-unitrangetree-213758/
*       Tt                  hiveworkshop.com/forums/jass-resources-412/system-timer-tools-201165/
*
*   function GetUnitTree takes nothing returns UnitTreeXY
*   function GetClosestNeighbor takes UnitIndex whichUnit returns UnitIndex
*
*/
    private struct UnitUpdatedTree_p extends array
        static UnitTreeXY tree
        
        private static method update takes nothing returns boolean
            local MovingUnits u = MovingUnits.first
            loop
                exitwhen 0 == u
                call tree.search(u).delete()
                call tree.add(u)
                set u = u.next
            endloop
            return true
        endmethod
        private static method onInit takes nothing returns nothing
            call Timer[.1].list.register(Condition(function thistype.update))
            set tree = UnitTreeXY.create()
        endmethod
        
        private method index takes nothing returns nothing
            call tree.add(GetIndexedUnitId())
        endmethod
        private method deindex takes nothing returns nothing
            call tree.search(GetIndexedUnitId()).delete()
        endmethod
        
        implement UnitIndexStruct
    endstruct
    
    function GetUnitTree takes nothing returns UnitTreeXY
        return UnitUpdatedTree_p.tree
    endfunction
    function GetClosestNeighbor takes UnitIndex whichUnit returns UnitIndex
        local UnitTreeXY low = GetUnitTree().searchClose(whichUnit, true)
        local UnitTreeXY high = low.next
        
        local real xlow = GetUnitX(low.index.unit)
        local real ylow = GetUnitY(low.index.unit)
        local real xhigh = GetUnitX(high.index.unit)
        local real yhigh = GetUnitY(high.index.unit)
        local real x = GetUnitX(whichUnit.unit)
        local real y = GetUnitX(whichUnit.unit)
        set xlow = xlow - x
        set ylow = ylow - y
        set xhigh = xhigh - x
        set yhigh = yhigh - y
        
        if (xlow*xlow + ylow*ylow < xhigh*high + yhigh*yhigh) then
            return low
        endif
        
        return high
    endfunction
endlibrary
 
Last edited:
Top