Basic reformat, hit once, hope never again

This commit is contained in:
thatsIch
2015-04-03 08:54:31 +02:00
parent 4ff1631f89
commit d34c988c88
886 changed files with 31400 additions and 30990 deletions
File diff suppressed because it is too large Load Diff
+345 -357
View File
@@ -18,6 +18,7 @@
package appeng.me.cache;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@@ -53,96 +54,60 @@ import appeng.me.GridNode;
import appeng.me.energy.EnergyThreshold;
import appeng.me.energy.EnergyWatcher;
public class EnergyGridCache implements IEnergyGrid
{
final public TreeSet<EnergyThreshold> interests = new TreeSet<EnergyThreshold>();
final double AvgLength = 40.0;
final Set<IAEPowerStorage> providers = new LinkedHashSet<IAEPowerStorage>();
final Set<IAEPowerStorage> requesters = new LinkedHashSet<IAEPowerStorage>();
final Multiset<IEnergyGridProvider> energyGridProviders = HashMultiset.create();
final IGrid myGrid;
final private HashMap<IGridNode, IEnergyWatcher> watchers = new HashMap<IGridNode, IEnergyWatcher>();
final private Set<IEnergyGrid> localSeen = new HashSet<IEnergyGrid>();
/**
* estimated power available.
*/
int availableTicksSinceUpdate = 0;
double globalAvailablePower = 0;
double globalMaxPower = 0;
/**
* idle draw.
*/
double drainPerTick = 0;
final double AvgLength = 40.0;
double avgDrainPerTick = 0;
double avgInjectionPerTick = 0;
double tickDrainPerTick = 0;
double tickInjectionPerTick = 0;
/**
* power status
*/
boolean publicHasPower = false;
boolean hasPower = true;
long ticksSinceHasPowerChange = 900;
/**
* excess power in the system.
*/
double extra = 0;
IAEPowerStorage lastProvider;
final Set<IAEPowerStorage> providers = new LinkedHashSet<IAEPowerStorage>();
IAEPowerStorage lastRequester;
final Set<IAEPowerStorage> requesters = new LinkedHashSet<IAEPowerStorage>();
final public TreeSet<EnergyThreshold> interests = new TreeSet<EnergyThreshold>();
final private HashMap<IGridNode, IEnergyWatcher> watchers = new HashMap<IGridNode, IEnergyWatcher>();
final private Set<IEnergyGrid> localSeen = new HashSet<IEnergyGrid>();
private double buffer()
{
return this.providers.isEmpty() ? 1000.0 : 0.0;
}
private IAEPowerStorage getFirstRequester()
{
if ( this.lastRequester == null )
{
Iterator<IAEPowerStorage> i = this.requesters.iterator();
this.lastRequester = i.hasNext() ? i.next() : null;
}
return this.lastRequester;
}
private IAEPowerStorage getFirstProvider()
{
if ( this.lastProvider == null )
{
Iterator<IAEPowerStorage> i = this.providers.iterator();
this.lastProvider = i.hasNext() ? i.next() : null;
}
return this.lastProvider;
}
final Multiset<IEnergyGridProvider> energyGridProviders = HashMultiset.create();
final IGrid myGrid;
PathGridCache pgc;
double lastStoredPower = -1;
public EnergyGridCache(IGrid g) {
public EnergyGridCache( IGrid g )
{
this.myGrid = g;
}
@MENetworkEventSubscribe
public void postInit(MENetworkPostCacheConstruction pcc)
public void postInit( MENetworkPostCacheConstruction pcc )
{
this.pgc = this.myGrid.getCache( IPathingGrid.class );
}
@MENetworkEventSubscribe
public void EnergyNodeChanges(MENetworkPowerIdleChange ev)
public void EnergyNodeChanges( MENetworkPowerIdleChange ev )
{
// update power usage based on event.
GridNode node = (GridNode) ev.node;
@@ -156,88 +121,188 @@ public class EnergyGridCache implements IEnergyGrid
}
@MENetworkEventSubscribe
public void EnergyNodeChanges(MENetworkPowerStorage ev)
public void EnergyNodeChanges( MENetworkPowerStorage ev )
{
if ( ev.storage.isAEPublicPowerStorage() )
if( ev.storage.isAEPublicPowerStorage() )
{
switch (ev.type)
switch( ev.type )
{
case PROVIDE_POWER:
if ( ev.storage.getPowerFlow() != AccessRestriction.WRITE )
this.providers.add( ev.storage );
break;
case REQUEST_POWER:
if ( ev.storage.getPowerFlow() != AccessRestriction.READ )
this.requesters.add( ev.storage );
break;
case PROVIDE_POWER:
if( ev.storage.getPowerFlow() != AccessRestriction.WRITE )
this.providers.add( ev.storage );
break;
case REQUEST_POWER:
if( ev.storage.getPowerFlow() != AccessRestriction.READ )
this.requesters.add( ev.storage );
break;
}
}
else
{
(new RuntimeException( "Attempt to ask the IEnergyGrid to charge a non public energy store." )).printStackTrace();
( new RuntimeException( "Attempt to ask the IEnergyGrid to charge a non public energy store." ) ).printStackTrace();
}
}
@Override
public double getEnergyDemand(double maxRequired)
public void onUpdateTick()
{
this.localSeen.clear();
return this.getEnergyDemand( maxRequired, this.localSeen );
if( !this.interests.isEmpty() )
{
double oldPower = this.lastStoredPower;
this.lastStoredPower = this.getStoredPower();
EnergyThreshold low = new EnergyThreshold( Math.min( oldPower, this.lastStoredPower ), null );
EnergyThreshold high = new EnergyThreshold( Math.max( oldPower, this.lastStoredPower ), null );
for( EnergyThreshold th : this.interests.subSet( low, true, high, true ) )
{
( (EnergyWatcher) th.watcher ).post( this );
}
}
this.avgDrainPerTick *= ( this.AvgLength - 1 ) / this.AvgLength;
this.avgInjectionPerTick *= ( this.AvgLength - 1 ) / this.AvgLength;
this.avgDrainPerTick += this.tickDrainPerTick / this.AvgLength;
this.avgInjectionPerTick += this.tickInjectionPerTick / this.AvgLength;
this.tickDrainPerTick = 0;
this.tickInjectionPerTick = 0;
// power information.
boolean currentlyHasPower = false;
if( this.drainPerTick > 0.0001 )
{
double drained = this.extractAEPower( this.getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG );
currentlyHasPower = drained >= this.drainPerTick - 0.001;
}
else
{
currentlyHasPower = this.extractAEPower( 0.1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0;
}
// ticks since change..
if( currentlyHasPower == this.hasPower )
this.ticksSinceHasPowerChange++;
else
this.ticksSinceHasPowerChange = 0;
// update status..
this.hasPower = currentlyHasPower;
// update public status, this buffers power ups for 30 ticks.
if( this.hasPower && this.ticksSinceHasPowerChange > 30 )
this.publicPowerState( true, this.myGrid );
else if( !this.hasPower )
this.publicPowerState( false, this.myGrid );
this.availableTicksSinceUpdate++;
}
@Override
public double getEnergyDemand(double maxRequired, Set<IEnergyGrid> seen)
public double extractAEPower( double amt, Actionable mode, PowerMultiplier pm )
{
if ( !seen.add( this ) )
this.localSeen.clear();
return pm.divide( this.extractAEPower( pm.multiply( amt ), mode, this.localSeen ) );
}
@Override
public double getIdlePowerUsage()
{
return this.drainPerTick + this.pgc.channelPowerUsage;
}
private void publicPowerState( boolean newState, IGrid grid )
{
if( this.publicHasPower == newState )
return;
this.publicHasPower = newState;
( (Grid) this.myGrid ).setImportantFlag( 0, this.publicHasPower );
grid.postEvent( new MENetworkPowerStatusChange() );
}
/**
* refresh current stored power.
*/
public void refreshPower()
{
this.availableTicksSinceUpdate = 0;
this.globalAvailablePower = 0;
for( IAEPowerStorage p : this.providers )
this.globalAvailablePower += p.getAECurrentPower();
}
@Override
public double extractAEPower( double amt, Actionable mode, Set<IEnergyGrid> seen )
{
if( !seen.add( this ) )
return 0;
double required = this.buffer() - this.extra;
double extractedPower = this.extra;
Iterator<IAEPowerStorage> it = this.requesters.iterator();
while (required < maxRequired && it.hasNext())
if( mode == Actionable.SIMULATE )
{
IAEPowerStorage node = it.next();
if ( node.getPowerFlow() != AccessRestriction.READ )
required += Math.max( 0.0, node.getAEMaxPower() - node.getAECurrentPower() );
extractedPower += this.simulateExtract( extractedPower, amt );
if( extractedPower < amt )
{
Iterator<IEnergyGridProvider> i = this.energyGridProviders.iterator();
while( extractedPower < amt && i.hasNext() )
extractedPower += i.next().extractAEPower( amt - extractedPower, mode, seen );
}
return extractedPower;
}
else
{
this.extra = 0;
extractedPower = this.doExtract( extractedPower, amt );
}
Iterator<IEnergyGridProvider> ix = this.energyGridProviders.iterator();
while (required < maxRequired && ix.hasNext())
// got more then we wanted?
if( extractedPower > amt )
{
IEnergyGridProvider node = ix.next();
required += node.getEnergyDemand( maxRequired - required, seen );
this.extra = extractedPower - amt;
this.globalAvailablePower -= amt;
this.tickDrainPerTick += amt;
return amt;
}
return required;
if( extractedPower < amt )
{
Iterator<IEnergyGridProvider> i = this.energyGridProviders.iterator();
while( extractedPower < amt && i.hasNext() )
extractedPower += i.next().extractAEPower( amt - extractedPower, mode, seen );
}
// go less or the correct amount?
this.globalAvailablePower -= extractedPower;
this.tickDrainPerTick += extractedPower;
return extractedPower;
}
@Override
public double injectPower(double amt, Actionable mode)
public double injectAEPower( double amt, Actionable mode, Set<IEnergyGrid> seen )
{
this.localSeen.clear();
return this.injectAEPower( amt, mode, this.localSeen );
}
@Override
public double injectAEPower(double amt, Actionable mode, Set<IEnergyGrid> seen)
{
if ( !seen.add( this ) )
if( !seen.add( this ) )
return 0;
double ignore = this.extra;
amt += this.extra;
if ( mode == Actionable.SIMULATE )
if( mode == Actionable.SIMULATE )
{
Iterator<IAEPowerStorage> it = this.requesters.iterator();
while (amt > 0 && it.hasNext())
while( amt > 0 && it.hasNext() )
{
IAEPowerStorage node = it.next();
amt = node.injectAEPower( amt, Actionable.SIMULATE );
}
Iterator<IEnergyGridProvider> i = this.energyGridProviders.iterator();
while (amt > 0 && i.hasNext())
while( amt > 0 && i.hasNext() )
amt = i.next().injectAEPower( amt, mode, seen );
}
else
@@ -245,12 +310,12 @@ public class EnergyGridCache implements IEnergyGrid
this.tickInjectionPerTick += amt - ignore;
// totalInjectionPastTicks[0] += i;
while (amt > 0 && !this.requesters.isEmpty())
while( amt > 0 && !this.requesters.isEmpty() )
{
IAEPowerStorage node = this.getFirstRequester();
amt = node.injectAEPower( amt, Actionable.MODULATE );
if ( amt > 0 )
if( amt > 0 )
{
this.requesters.remove( node );
this.lastRequester = null;
@@ -258,7 +323,7 @@ public class EnergyGridCache implements IEnergyGrid
}
Iterator<IEnergyGridProvider> i = this.energyGridProviders.iterator();
while (amt > 0 && i.hasNext())
while( amt > 0 && i.hasNext() )
{
IEnergyGridProvider what = i.next();
Set<IEnergyGrid> listCopy = new HashSet<IEnergyGrid>();
@@ -277,275 +342,36 @@ public class EnergyGridCache implements IEnergyGrid
}
@Override
public double extractAEPower(double amt, Actionable mode, PowerMultiplier pm)
public double getEnergyDemand( double maxRequired, Set<IEnergyGrid> seen )
{
this.localSeen.clear();
return pm.divide( this.extractAEPower( pm.multiply( amt ), mode, this.localSeen ) );
}
@Override
public void addNode(IGridNode node, IGridHost machine)
{
if ( machine instanceof IEnergyGridProvider )
this.energyGridProviders.add( (IEnergyGridProvider) machine );
// idle draw...
GridNode gridNode = (GridNode) node;
IGridBlock gb = gridNode.getGridBlock();
gridNode.previousDraw = gb.getIdlePowerUsage();
this.drainPerTick += gridNode.previousDraw;
// power storage
if ( machine instanceof IAEPowerStorage )
{
IAEPowerStorage ps = (IAEPowerStorage) machine;
if ( ps.isAEPublicPowerStorage() )
{
double max = ps.getAEMaxPower();
double current = ps.getAECurrentPower();
if ( ps.getPowerFlow() != AccessRestriction.WRITE )
{
this.globalMaxPower += ps.getAEMaxPower();
}
if ( current > 0 && ps.getPowerFlow() != AccessRestriction.WRITE )
{
this.globalAvailablePower += current;
this.providers.add( ps );
}
if ( current < max && ps.getPowerFlow() != AccessRestriction.READ )
this.requesters.add( ps );
}
}
if ( machine instanceof IEnergyWatcherHost )
{
IEnergyWatcherHost swh = (IEnergyWatcherHost) machine;
EnergyWatcher iw = new EnergyWatcher( this, swh );
this.watchers.put( node, iw );
swh.updateWatcher( iw );
}
this.myGrid.postEventTo( node, new MENetworkPowerStatusChange() );
}
@Override
public void removeNode(IGridNode node, IGridHost machine)
{
if ( machine instanceof IEnergyGridProvider )
this.energyGridProviders.remove( machine );
// idle draw.
GridNode gridNode = (GridNode) node;
this.drainPerTick -= gridNode.previousDraw;
// power storage.
if ( machine instanceof IAEPowerStorage )
{
IAEPowerStorage ps = (IAEPowerStorage) machine;
if ( ps.isAEPublicPowerStorage() )
{
if ( ps.getPowerFlow() != AccessRestriction.WRITE )
{
this.globalMaxPower -= ps.getAEMaxPower();
this.globalAvailablePower -= ps.getAECurrentPower();
}
if ( this.lastProvider == machine )
this.lastProvider = null;
if ( this.lastRequester == machine )
this.lastRequester = null;
this.providers.remove( machine );
this.requesters.remove( machine );
}
}
if ( machine instanceof IStackWatcherHost )
{
IEnergyWatcher myWatcher = this.watchers.get( machine );
if ( myWatcher != null )
{
myWatcher.clear();
this.watchers.remove( machine );
}
}
}
double lastStoredPower = -1;
@Override
public void onUpdateTick()
{
if ( !this.interests.isEmpty() )
{
double oldPower = this.lastStoredPower;
this.lastStoredPower = this.getStoredPower();
EnergyThreshold low = new EnergyThreshold( Math.min( oldPower, this.lastStoredPower ), null );
EnergyThreshold high = new EnergyThreshold( Math.max( oldPower, this.lastStoredPower ), null );
for (EnergyThreshold th : this.interests.subSet( low, true, high, true ))
{
((EnergyWatcher) th.watcher).post( this );
}
}
this.avgDrainPerTick *= (this.AvgLength - 1) / this.AvgLength;
this.avgInjectionPerTick *= (this.AvgLength - 1) / this.AvgLength;
this.avgDrainPerTick += this.tickDrainPerTick / this.AvgLength;
this.avgInjectionPerTick += this.tickInjectionPerTick / this.AvgLength;
this.tickDrainPerTick = 0;
this.tickInjectionPerTick = 0;
// power information.
boolean currentlyHasPower = false;
if ( this.drainPerTick > 0.0001 )
{
double drained = this.extractAEPower( this.getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG );
currentlyHasPower = drained >= this.drainPerTick - 0.001;
}
else
{
currentlyHasPower = this.extractAEPower( 0.1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0;
}
// ticks since change..
if ( currentlyHasPower == this.hasPower )
this.ticksSinceHasPowerChange++;
else
this.ticksSinceHasPowerChange = 0;
// update status..
this.hasPower = currentlyHasPower;
// update public status, this buffers power ups for 30 ticks.
if ( this.hasPower && this.ticksSinceHasPowerChange > 30 )
this.publicPowerState( true, this.myGrid );
else if ( !this.hasPower )
this.publicPowerState( false, this.myGrid );
this.availableTicksSinceUpdate++;
}
private void publicPowerState(boolean newState, IGrid grid)
{
if ( this.publicHasPower == newState )
return;
this.publicHasPower = newState;
((Grid) this.myGrid).setImportantFlag( 0, this.publicHasPower );
grid.postEvent( new MENetworkPowerStatusChange() );
}
/**
* refresh current stored power.
*/
public void refreshPower()
{
this.availableTicksSinceUpdate = 0;
this.globalAvailablePower = 0;
for (IAEPowerStorage p : this.providers)
this.globalAvailablePower += p.getAECurrentPower();
}
@Override
public double getStoredPower()
{
if ( this.availableTicksSinceUpdate > 90 )
this.refreshPower();
return Math.max( 0.0, this.globalAvailablePower );
}
@Override
public double getMaxStoredPower()
{
return this.globalMaxPower;
}
@Override
public double extractAEPower(double amt, Actionable mode, Set<IEnergyGrid> seen)
{
if ( !seen.add( this ) )
if( !seen.add( this ) )
return 0;
double extractedPower = this.extra;
double required = this.buffer() - this.extra;
if ( mode == Actionable.SIMULATE )
Iterator<IAEPowerStorage> it = this.requesters.iterator();
while( required < maxRequired && it.hasNext() )
{
extractedPower += this.simulateExtract( extractedPower, amt );
if ( extractedPower < amt )
{
Iterator<IEnergyGridProvider> i = this.energyGridProviders.iterator();
while (extractedPower < amt && i.hasNext())
extractedPower += i.next().extractAEPower( amt - extractedPower, mode, seen );
}
return extractedPower;
}
else
{
this.extra = 0;
extractedPower = this.doExtract( extractedPower, amt );
IAEPowerStorage node = it.next();
if( node.getPowerFlow() != AccessRestriction.READ )
required += Math.max( 0.0, node.getAEMaxPower() - node.getAECurrentPower() );
}
// got more then we wanted?
if ( extractedPower > amt )
Iterator<IEnergyGridProvider> ix = this.energyGridProviders.iterator();
while( required < maxRequired && ix.hasNext() )
{
this.extra = extractedPower - amt;
this.globalAvailablePower -= amt;
this.tickDrainPerTick += amt;
return amt;
IEnergyGridProvider node = ix.next();
required += node.getEnergyDemand( maxRequired - required, seen );
}
if ( extractedPower < amt )
{
Iterator<IEnergyGridProvider> i = this.energyGridProviders.iterator();
while (extractedPower < amt && i.hasNext())
extractedPower += i.next().extractAEPower( amt - extractedPower, mode, seen );
}
// go less or the correct amount?
this.globalAvailablePower -= extractedPower;
this.tickDrainPerTick += extractedPower;
return extractedPower;
return required;
}
private double doExtract(double extractedPower, double amt)
{
while (extractedPower < amt && !this.providers.isEmpty())
{
IAEPowerStorage node = this.getFirstProvider();
double req = amt - extractedPower;
double newPower = node.extractAEPower( req, Actionable.MODULATE, PowerMultiplier.ONE );
extractedPower += newPower;
if ( newPower < req )
{
this.providers.remove( node );
this.lastProvider = null;
}
}
// totalDrainPastTicks[0] += extractedPower;
return extractedPower;
}
private double simulateExtract(double extractedPower, double amt)
private double simulateExtract( double extractedPower, double amt )
{
Iterator<IAEPowerStorage> it = this.providers.iterator();
while (extractedPower < amt && it.hasNext())
while( extractedPower < amt && it.hasNext() )
{
IAEPowerStorage node = it.next();
@@ -557,16 +383,36 @@ public class EnergyGridCache implements IEnergyGrid
return extractedPower;
}
@Override
public boolean isNetworkPowered()
private double doExtract( double extractedPower, double amt )
{
return this.publicHasPower;
while( extractedPower < amt && !this.providers.isEmpty() )
{
IAEPowerStorage node = this.getFirstProvider();
double req = amt - extractedPower;
double newPower = node.extractAEPower( req, Actionable.MODULATE, PowerMultiplier.ONE );
extractedPower += newPower;
if( newPower < req )
{
this.providers.remove( node );
this.lastProvider = null;
}
}
// totalDrainPastTicks[0] += extractedPower;
return extractedPower;
}
@Override
public double getIdlePowerUsage()
private IAEPowerStorage getFirstProvider()
{
return this.drainPerTick + this.pgc.channelPowerUsage;
if( this.lastProvider == null )
{
Iterator<IAEPowerStorage> i = this.providers.iterator();
this.lastProvider = i.hasNext() ? i.next() : null;
}
return this.lastProvider;
}
@Override
@@ -582,22 +428,164 @@ public class EnergyGridCache implements IEnergyGrid
}
@Override
public void onSplit(IGridStorage storageB)
public boolean isNetworkPowered()
{
return this.publicHasPower;
}
@Override
public double injectPower( double amt, Actionable mode )
{
this.localSeen.clear();
return this.injectAEPower( amt, mode, this.localSeen );
}
private IAEPowerStorage getFirstRequester()
{
if( this.lastRequester == null )
{
Iterator<IAEPowerStorage> i = this.requesters.iterator();
this.lastRequester = i.hasNext() ? i.next() : null;
}
return this.lastRequester;
}
private double buffer()
{
return this.providers.isEmpty() ? 1000.0 : 0.0;
}
@Override
public double getStoredPower()
{
if( this.availableTicksSinceUpdate > 90 )
this.refreshPower();
return Math.max( 0.0, this.globalAvailablePower );
}
@Override
public double getMaxStoredPower()
{
return this.globalMaxPower;
}
@Override
public double getEnergyDemand( double maxRequired )
{
this.localSeen.clear();
return this.getEnergyDemand( maxRequired, this.localSeen );
}
@Override
public void removeNode( IGridNode node, IGridHost machine )
{
if( machine instanceof IEnergyGridProvider )
this.energyGridProviders.remove( machine );
// idle draw.
GridNode gridNode = (GridNode) node;
this.drainPerTick -= gridNode.previousDraw;
// power storage.
if( machine instanceof IAEPowerStorage )
{
IAEPowerStorage ps = (IAEPowerStorage) machine;
if( ps.isAEPublicPowerStorage() )
{
if( ps.getPowerFlow() != AccessRestriction.WRITE )
{
this.globalMaxPower -= ps.getAEMaxPower();
this.globalAvailablePower -= ps.getAECurrentPower();
}
if( this.lastProvider == machine )
this.lastProvider = null;
if( this.lastRequester == machine )
this.lastRequester = null;
this.providers.remove( machine );
this.requesters.remove( machine );
}
}
if( machine instanceof IStackWatcherHost )
{
IEnergyWatcher myWatcher = this.watchers.get( machine );
if( myWatcher != null )
{
myWatcher.clear();
this.watchers.remove( machine );
}
}
}
@Override
public void addNode( IGridNode node, IGridHost machine )
{
if( machine instanceof IEnergyGridProvider )
this.energyGridProviders.add( (IEnergyGridProvider) machine );
// idle draw...
GridNode gridNode = (GridNode) node;
IGridBlock gb = gridNode.getGridBlock();
gridNode.previousDraw = gb.getIdlePowerUsage();
this.drainPerTick += gridNode.previousDraw;
// power storage
if( machine instanceof IAEPowerStorage )
{
IAEPowerStorage ps = (IAEPowerStorage) machine;
if( ps.isAEPublicPowerStorage() )
{
double max = ps.getAEMaxPower();
double current = ps.getAECurrentPower();
if( ps.getPowerFlow() != AccessRestriction.WRITE )
{
this.globalMaxPower += ps.getAEMaxPower();
}
if( current > 0 && ps.getPowerFlow() != AccessRestriction.WRITE )
{
this.globalAvailablePower += current;
this.providers.add( ps );
}
if( current < max && ps.getPowerFlow() != AccessRestriction.READ )
this.requesters.add( ps );
}
}
if( machine instanceof IEnergyWatcherHost )
{
IEnergyWatcherHost swh = (IEnergyWatcherHost) machine;
EnergyWatcher iw = new EnergyWatcher( this, swh );
this.watchers.put( node, iw );
swh.updateWatcher( iw );
}
this.myGrid.postEventTo( node, new MENetworkPowerStatusChange() );
}
@Override
public void onSplit( IGridStorage storageB )
{
this.extra /= 2;
storageB.dataObject().setDouble( "extraEnergy", this.extra );
}
@Override
public void onJoin(IGridStorage storageB)
public void onJoin( IGridStorage storageB )
{
this.extra += storageB.dataObject().getDouble( "extraEnergy" );
}
@Override
public void populateGridStorage(IGridStorage storage)
public void populateGridStorage( IGridStorage storage )
{
storage.dataObject().setDouble( "extraEnergy", this.extra );
}
}
+162 -163
View File
@@ -18,6 +18,7 @@
package appeng.me.cache;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
@@ -53,25 +54,23 @@ import appeng.me.helpers.GenericInterestManager;
import appeng.me.storage.ItemWatcher;
import appeng.me.storage.NetworkInventoryHandler;
public class GridStorageCache implements IStorageGrid
{
final private SetMultimap<IAEStack, ItemWatcher> interests = HashMultimap.create();
final public GenericInterestManager<ItemWatcher> interestManager = new GenericInterestManager<ItemWatcher>( this.interests );
final public IGrid myGrid;
final HashSet<ICellProvider> activeCellProviders = new HashSet<ICellProvider>();
final HashSet<ICellProvider> inactiveCellProviders = new HashSet<ICellProvider>();
final public IGrid myGrid;
private NetworkInventoryHandler<IAEItemStack> myItemNetwork;
final private SetMultimap<IAEStack, ItemWatcher> interests = HashMultimap.create();
final public GenericInterestManager<ItemWatcher> interestManager = new GenericInterestManager<ItemWatcher>( this.interests );
private final NetworkMonitor<IAEItemStack> itemMonitor = new NetworkMonitor<IAEItemStack>( this, StorageChannel.ITEMS );
private NetworkInventoryHandler<IAEFluidStack> myFluidNetwork;
private final NetworkMonitor<IAEFluidStack> fluidMonitor = new NetworkMonitor<IAEFluidStack>( this, StorageChannel.FLUIDS );
private final HashMap<IGridNode, IStackWatcher> watchers = new HashMap<IGridNode, IStackWatcher>();
private NetworkInventoryHandler<IAEItemStack> myItemNetwork;
private NetworkInventoryHandler<IAEFluidStack> myFluidNetwork;
public GridStorageCache(IGrid g) {
public GridStorageCache( IGrid g )
{
this.myGrid = g;
}
@@ -82,82 +81,86 @@ public class GridStorageCache implements IStorageGrid
this.fluidMonitor.onTick();
}
private class CellChangeTrackerRecord
@Override
public void removeNode( IGridNode node, IGridHost machine )
{
if( machine instanceof ICellContainer )
{
ICellContainer cc = (ICellContainer) machine;
final StorageChannel channel;
final int up_or_down;
final IItemList list;
final BaseActionSource src;
public CellChangeTrackerRecord(StorageChannel channel, int i, IMEInventoryHandler<? extends IAEStack> h, BaseActionSource actionSrc) {
this.channel = channel;
this.up_or_down = i;
this.src = actionSrc;
if ( channel == StorageChannel.ITEMS )
this.list = ((IMEInventoryHandler<IAEItemStack>) h).getAvailableItems( AEApi.instance().storage().createItemList() );
else if ( channel == StorageChannel.FLUIDS )
this.list = ((IMEInventoryHandler<IAEFluidStack>) h).getAvailableItems( AEApi.instance().storage().createFluidList() );
else
this.list = null;
this.myGrid.postEvent( new MENetworkCellArrayUpdate() );
this.removeCellProvider( cc, new CellChangeTracker() ).applyChanges();
this.inactiveCellProviders.remove( cc );
}
public void applyChanges()
if( machine instanceof IStackWatcherHost )
{
GridStorageCache.this.postChangesToNetwork( this.channel, this.up_or_down, this.list, this.src );
}
}
private class CellChangeTracker
{
final List<CellChangeTrackerRecord> data = new LinkedList<CellChangeTrackerRecord>();
public void postChanges(StorageChannel channel, int i, IMEInventoryHandler<? extends IAEStack> h, BaseActionSource actionSrc)
{
this.data.add( new CellChangeTrackerRecord( channel, i, h, actionSrc ) );
}
public void applyChanges()
{
for (CellChangeTrackerRecord rec : this.data)
rec.applyChanges();
IStackWatcher myWatcher = this.watchers.get( machine );
if( myWatcher != null )
{
myWatcher.clear();
this.watchers.remove( machine );
}
}
}
@Override
public void registerCellProvider(ICellProvider provider)
public void addNode( IGridNode node, IGridHost machine )
{
this.inactiveCellProviders.add( provider );
this.addCellProvider( provider, new CellChangeTracker() ).applyChanges();
if( machine instanceof ICellContainer )
{
ICellContainer cc = (ICellContainer) machine;
this.inactiveCellProviders.add( cc );
this.myGrid.postEvent( new MENetworkCellArrayUpdate() );
if( node.isActive() )
this.addCellProvider( cc, new CellChangeTracker() ).applyChanges();
}
if( machine instanceof IStackWatcherHost )
{
IStackWatcherHost swh = (IStackWatcherHost) machine;
ItemWatcher iw = new ItemWatcher( this, swh );
this.watchers.put( node, iw );
swh.updateWatcher( iw );
}
}
@Override
public void unregisterCellProvider(ICellProvider provider)
public void onSplit( IGridStorage storageB )
{
this.removeCellProvider( provider, new CellChangeTracker() ).applyChanges();
this.inactiveCellProviders.remove( provider );
}
public CellChangeTracker addCellProvider(ICellProvider cc, CellChangeTracker tracker)
@Override
public void onJoin( IGridStorage storageB )
{
if ( this.inactiveCellProviders.contains( cc ) )
}
@Override
public void populateGridStorage( IGridStorage storage )
{
}
public CellChangeTracker addCellProvider( ICellProvider cc, CellChangeTracker tracker )
{
if( this.inactiveCellProviders.contains( cc ) )
{
this.inactiveCellProviders.remove( cc );
this.activeCellProviders.add( cc );
BaseActionSource actionSrc = new BaseActionSource();
if ( cc instanceof IActionHost )
if( cc instanceof IActionHost )
actionSrc = new MachineSource( (IActionHost) cc );
for (IMEInventoryHandler<IAEItemStack> h : cc.getCellArray( StorageChannel.ITEMS ))
for( IMEInventoryHandler<IAEItemStack> h : cc.getCellArray( StorageChannel.ITEMS ) )
{
tracker.postChanges( StorageChannel.ITEMS, 1, h, actionSrc );
}
for (IMEInventoryHandler<IAEFluidStack> h : cc.getCellArray( StorageChannel.FLUIDS ))
for( IMEInventoryHandler<IAEFluidStack> h : cc.getCellArray( StorageChannel.FLUIDS ) )
{
tracker.postChanges( StorageChannel.FLUIDS, 1, h, actionSrc );
}
@@ -166,23 +169,23 @@ public class GridStorageCache implements IStorageGrid
return tracker;
}
public CellChangeTracker removeCellProvider(ICellProvider cc, CellChangeTracker tracker)
public CellChangeTracker removeCellProvider( ICellProvider cc, CellChangeTracker tracker )
{
if ( this.activeCellProviders.contains( cc ) )
if( this.activeCellProviders.contains( cc ) )
{
this.inactiveCellProviders.add( cc );
this.activeCellProviders.remove( cc );
BaseActionSource actionSrc = new BaseActionSource();
if ( cc instanceof IActionHost )
if( cc instanceof IActionHost )
actionSrc = new MachineSource( (IActionHost) cc );
for (IMEInventoryHandler<IAEItemStack> h : cc.getCellArray( StorageChannel.ITEMS ))
for( IMEInventoryHandler<IAEItemStack> h : cc.getCellArray( StorageChannel.ITEMS ) )
{
tracker.postChanges( StorageChannel.ITEMS, -1, h, actionSrc );
}
for (IMEInventoryHandler<IAEFluidStack> h : cc.getCellArray( StorageChannel.FLUIDS ))
for( IMEInventoryHandler<IAEFluidStack> h : cc.getCellArray( StorageChannel.FLUIDS ) )
{
tracker.postChanges( StorageChannel.FLUIDS, -1, h, actionSrc );
}
@@ -192,7 +195,7 @@ public class GridStorageCache implements IStorageGrid
}
@MENetworkEventSubscribe
public void cellUpdate(MENetworkCellArrayUpdate ev)
public void cellUpdate( MENetworkCellArrayUpdate ev )
{
this.myItemNetwork = null;
this.myFluidNetwork = null;
@@ -203,20 +206,20 @@ public class GridStorageCache implements IStorageGrid
CellChangeTracker tracker = new CellChangeTracker();
for (ICellProvider cc : ll)
for( ICellProvider cc : ll )
{
boolean Active = true;
if ( cc instanceof IActionHost )
if( cc instanceof IActionHost )
{
IGridNode node = ((IActionHost) cc).getActionableNode();
if ( node != null && node.isActive() )
IGridNode node = ( (IActionHost) cc ).getActionableNode();
if( node != null && node.isActive() )
Active = true;
else
Active = false;
}
if ( Active )
if( Active )
this.addCellProvider( cc, tracker );
else
this.removeCellProvider( cc, tracker );
@@ -228,118 +231,81 @@ public class GridStorageCache implements IStorageGrid
tracker.applyChanges();
}
@Override
public void removeNode(IGridNode node, IGridHost machine)
private void postChangesToNetwork( StorageChannel chan, int up_or_down, IItemList availableItems, BaseActionSource src )
{
if ( machine instanceof ICellContainer )
switch( chan )
{
ICellContainer cc = (ICellContainer) machine;
this.myGrid.postEvent( new MENetworkCellArrayUpdate() );
this.removeCellProvider( cc, new CellChangeTracker() ).applyChanges();
this.inactiveCellProviders.remove( cc );
}
if ( machine instanceof IStackWatcherHost )
{
IStackWatcher myWatcher = this.watchers.get( machine );
if ( myWatcher != null )
{
myWatcher.clear();
this.watchers.remove( machine );
}
}
}
@Override
public void addNode(IGridNode node, IGridHost machine)
{
if ( machine instanceof ICellContainer )
{
ICellContainer cc = (ICellContainer) machine;
this.inactiveCellProviders.add( cc );
this.myGrid.postEvent( new MENetworkCellArrayUpdate() );
if ( node.isActive() )
this.addCellProvider( cc, new CellChangeTracker() ).applyChanges();
}
if ( machine instanceof IStackWatcherHost )
{
IStackWatcherHost swh = (IStackWatcherHost) machine;
ItemWatcher iw = new ItemWatcher( this, swh );
this.watchers.put( node, iw );
swh.updateWatcher( iw );
}
}
private void buildNetworkStorage(StorageChannel chan)
{
SecurityCache security = this.myGrid.getCache( ISecurityGrid.class );
switch (chan)
{
case FLUIDS:
this.myFluidNetwork = new NetworkInventoryHandler<IAEFluidStack>( StorageChannel.FLUIDS, security );
for (ICellProvider cc : this.activeCellProviders)
{
for (IMEInventoryHandler<IAEFluidStack> h : cc.getCellArray( chan ))
this.myFluidNetwork.addNewStorage( h );
}
break;
case ITEMS:
this.myItemNetwork = new NetworkInventoryHandler<IAEItemStack>( StorageChannel.ITEMS, security );
for (ICellProvider cc : this.activeCellProviders)
{
for (IMEInventoryHandler<IAEItemStack> h : cc.getCellArray( chan ))
this.myItemNetwork.addNewStorage( h );
}
break;
default:
}
}
private void postChangesToNetwork(StorageChannel chan, int up_or_down, IItemList availableItems, BaseActionSource src)
{
switch (chan)
{
case FLUIDS:
this.fluidMonitor.postChange( up_or_down > 0, availableItems, src );
break;
case ITEMS:
this.itemMonitor.postChange( up_or_down > 0, availableItems, src );
break;
default:
case FLUIDS:
this.fluidMonitor.postChange( up_or_down > 0, availableItems, src );
break;
case ITEMS:
this.itemMonitor.postChange( up_or_down > 0, availableItems, src );
break;
default:
}
}
public IMEInventoryHandler<IAEItemStack> getItemInventoryHandler()
{
if ( this.myItemNetwork == null )
if( this.myItemNetwork == null )
this.buildNetworkStorage( StorageChannel.ITEMS );
return this.myItemNetwork;
}
private void buildNetworkStorage( StorageChannel chan )
{
SecurityCache security = this.myGrid.getCache( ISecurityGrid.class );
switch( chan )
{
case FLUIDS:
this.myFluidNetwork = new NetworkInventoryHandler<IAEFluidStack>( StorageChannel.FLUIDS, security );
for( ICellProvider cc : this.activeCellProviders )
{
for( IMEInventoryHandler<IAEFluidStack> h : cc.getCellArray( chan ) )
this.myFluidNetwork.addNewStorage( h );
}
break;
case ITEMS:
this.myItemNetwork = new NetworkInventoryHandler<IAEItemStack>( StorageChannel.ITEMS, security );
for( ICellProvider cc : this.activeCellProviders )
{
for( IMEInventoryHandler<IAEItemStack> h : cc.getCellArray( chan ) )
this.myItemNetwork.addNewStorage( h );
}
break;
default:
}
}
public IMEInventoryHandler<IAEFluidStack> getFluidInventoryHandler()
{
if ( this.myFluidNetwork == null )
if( this.myFluidNetwork == null )
this.buildNetworkStorage( StorageChannel.FLUIDS );
return this.myFluidNetwork;
}
@Override
public void postAlterationOfStoredItems(StorageChannel chan, Iterable<? extends IAEStack> input, BaseActionSource src)
public void postAlterationOfStoredItems( StorageChannel chan, Iterable<? extends IAEStack> input, BaseActionSource src )
{
if ( chan == StorageChannel.ITEMS )
if( chan == StorageChannel.ITEMS )
this.itemMonitor.postChange( true, (Iterable<IAEItemStack>) input, src );
else if ( chan == StorageChannel.FLUIDS )
else if( chan == StorageChannel.FLUIDS )
this.fluidMonitor.postChange( true, (Iterable<IAEFluidStack>) input, src );
}
@Override
public IMEMonitor<IAEFluidStack> getFluidInventory()
public void registerCellProvider( ICellProvider provider )
{
return this.fluidMonitor;
this.inactiveCellProviders.add( provider );
this.addCellProvider( provider, new CellChangeTracker() ).applyChanges();
}
@Override
public void unregisterCellProvider( ICellProvider provider )
{
this.removeCellProvider( provider, new CellChangeTracker() ).applyChanges();
this.inactiveCellProviders.remove( provider );
}
@Override
@@ -349,21 +315,54 @@ public class GridStorageCache implements IStorageGrid
}
@Override
public void onSplit(IGridStorage storageB)
public IMEMonitor<IAEFluidStack> getFluidInventory()
{
return this.fluidMonitor;
}
@Override
public void onJoin(IGridStorage storageB)
private class CellChangeTrackerRecord
{
final StorageChannel channel;
final int up_or_down;
final IItemList list;
final BaseActionSource src;
public CellChangeTrackerRecord( StorageChannel channel, int i, IMEInventoryHandler<? extends IAEStack> h, BaseActionSource actionSrc )
{
this.channel = channel;
this.up_or_down = i;
this.src = actionSrc;
if( channel == StorageChannel.ITEMS )
this.list = ( (IMEInventoryHandler<IAEItemStack>) h ).getAvailableItems( AEApi.instance().storage().createItemList() );
else if( channel == StorageChannel.FLUIDS )
this.list = ( (IMEInventoryHandler<IAEFluidStack>) h ).getAvailableItems( AEApi.instance().storage().createFluidList() );
else
this.list = null;
}
public void applyChanges()
{
GridStorageCache.this.postChangesToNetwork( this.channel, this.up_or_down, this.list, this.src );
}
}
@Override
public void populateGridStorage(IGridStorage storage)
private class CellChangeTracker
{
}
final List<CellChangeTrackerRecord> data = new LinkedList<CellChangeTrackerRecord>();
public void postChanges( StorageChannel channel, int i, IMEInventoryHandler<? extends IAEStack> h, BaseActionSource actionSrc )
{
this.data.add( new CellChangeTrackerRecord( channel, i, h, actionSrc ) );
}
public void applyChanges()
{
for( CellChangeTrackerRecord rec : this.data )
rec.applyChanges();
}
}
}
+70 -70
View File
@@ -18,6 +18,7 @@
package appeng.me.cache;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
@@ -34,94 +35,42 @@ import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList;
import appeng.me.storage.ItemWatcher;
public class NetworkMonitor<T extends IAEStack<T>> extends MEMonitorHandler<T>
{
private final static Deque<NetworkMonitor<?>> DEPTH = new LinkedList<NetworkMonitor<?>>();
final private GridStorageCache myGridCache;
final private StorageChannel myChannel;
boolean sendEvent = false;
public NetworkMonitor( GridStorageCache cache, StorageChannel chan )
{
super( null, chan );
this.myGridCache = cache;
this.myChannel = chan;
}
public void forceUpdate()
{
this.hasChanged = true;
Iterator<Entry<IMEMonitorHandlerReceiver<T>, Object>> i = this.getListeners();
while (i.hasNext())
while( i.hasNext() )
{
Entry<IMEMonitorHandlerReceiver<T>, Object> o = i.next();
IMEMonitorHandlerReceiver<T> receiver = o.getKey();
if ( receiver.isValid( o.getValue() ) )
if( receiver.isValid( o.getValue() ) )
receiver.onListUpdate();
else
i.remove();
}
}
public NetworkMonitor(GridStorageCache cache, StorageChannel chan) {
super( null, chan );
this.myGridCache = cache;
this.myChannel = chan;
}
private final static Deque<NetworkMonitor<?>> DEPTH = new LinkedList<NetworkMonitor<?>>();
@Override
protected void postChangesToListeners(Iterable<T> changes, BaseActionSource src)
{
this.postChange( true, changes, src );
}
protected void postChange(boolean Add, Iterable<T> changes, BaseActionSource src)
{
if ( DEPTH.contains( this ) )
return;
DEPTH.push( this );
this.sendEvent = true;
this.notifyListenersOfChange( changes, src );
IItemList<T> myStorageList = this.getStorageList();
for (T changedItem : changes)
{
T difference = changedItem;
if ( !Add && changedItem != null )
(difference = changedItem.copy()).setStackSize( -changedItem.getStackSize() );
if ( this.myGridCache.interestManager.containsKey( changedItem ) )
{
Collection<ItemWatcher> list = this.myGridCache.interestManager.get( changedItem );
if ( !list.isEmpty() )
{
IAEStack fullStack = myStorageList.findPrecise( changedItem );
if ( fullStack == null )
{
fullStack = changedItem.copy();
fullStack.setStackSize( 0 );
}
this.myGridCache.interestManager.enableTransactions();
for (ItemWatcher iw : list)
iw.getHost().onStackChange( myStorageList, fullStack, difference, src, this.getChannel() );
this.myGridCache.interestManager.disableTransactions();
}
}
}
final NetworkMonitor<?> last = DEPTH.pop();
if ( last != this )
throw new RuntimeException( "Invalid Access to Networked Storage API detected." );
}
public void onTick()
{
if ( this.sendEvent )
if( this.sendEvent )
{
this.sendEvent = false;
this.myGridCache.myGrid.postEvent( new MENetworkStorageEvent( this, this.myChannel ) );
@@ -131,15 +80,66 @@ public class NetworkMonitor<T extends IAEStack<T>> extends MEMonitorHandler<T>
@Override
protected IMEInventoryHandler getHandler()
{
switch (this.myChannel)
switch( this.myChannel )
{
case ITEMS:
return this.myGridCache.getItemInventoryHandler();
case FLUIDS:
return this.myGridCache.getFluidInventoryHandler();
default:
case ITEMS:
return this.myGridCache.getItemInventoryHandler();
case FLUIDS:
return this.myGridCache.getFluidInventoryHandler();
default:
}
return null;
}
@Override
protected void postChangesToListeners( Iterable<T> changes, BaseActionSource src )
{
this.postChange( true, changes, src );
}
protected void postChange( boolean Add, Iterable<T> changes, BaseActionSource src )
{
if( DEPTH.contains( this ) )
return;
DEPTH.push( this );
this.sendEvent = true;
this.notifyListenersOfChange( changes, src );
IItemList<T> myStorageList = this.getStorageList();
for( T changedItem : changes )
{
T difference = changedItem;
if( !Add && changedItem != null )
( difference = changedItem.copy() ).setStackSize( -changedItem.getStackSize() );
if( this.myGridCache.interestManager.containsKey( changedItem ) )
{
Collection<ItemWatcher> list = this.myGridCache.interestManager.get( changedItem );
if( !list.isEmpty() )
{
IAEStack fullStack = myStorageList.findPrecise( changedItem );
if( fullStack == null )
{
fullStack = changedItem.copy();
fullStack.setStackSize( 0 );
}
this.myGridCache.interestManager.enableTransactions();
for( ItemWatcher iw : list )
iw.getHost().onStackChange( myStorageList, fullStack, difference, src, this.getChannel() );
this.myGridCache.interestManager.disableTransactions();
}
}
}
final NetworkMonitor<?> last = DEPTH.pop();
if( last != this )
throw new RuntimeException( "Invalid Access to Networked Storage API detected." );
}
}
+103 -102
View File
@@ -18,6 +18,7 @@
package appeng.me.cache;
import java.util.HashMap;
import com.google.common.collect.LinkedHashMultimap;
@@ -37,37 +38,38 @@ import appeng.me.cache.helpers.TunnelCollection;
import appeng.parts.p2p.PartP2PTunnel;
import appeng.parts.p2p.PartP2PTunnelME;
public class P2PCache implements IGridCache
{
final IGrid myGrid;
final private HashMap<Long, PartP2PTunnel> inputs = new HashMap<Long, PartP2PTunnel>();
final private Multimap<Long, PartP2PTunnel> outputs = LinkedHashMultimap.create();
final private TunnelCollection NullColl = new TunnelCollection<PartP2PTunnel>( null, null );
final IGrid myGrid;
public P2PCache(IGrid g) {
public P2PCache( IGrid g )
{
this.myGrid = g;
}
@MENetworkEventSubscribe
public void bootComplete(MENetworkBootingStatusChange bootStatus)
public void bootComplete( MENetworkBootingStatusChange bootStatus )
{
ITickManager tm = this.myGrid.getCache( ITickManager.class );
for (PartP2PTunnel me : this.inputs.values())
for( PartP2PTunnel me : this.inputs.values() )
{
if ( me instanceof PartP2PTunnelME )
if( me instanceof PartP2PTunnelME )
tm.wakeDevice( me.getGridNode() );
}
}
@MENetworkEventSubscribe
public void bootComplete(MENetworkPowerStatusChange power)
public void bootComplete( MENetworkPowerStatusChange power )
{
ITickManager tm = this.myGrid.getCache( ITickManager.class );
for (PartP2PTunnel me : this.inputs.values())
for( PartP2PTunnel me : this.inputs.values() )
{
if ( me instanceof PartP2PTunnelME )
if( me instanceof PartP2PTunnelME )
tm.wakeDevice( me.getGridNode() );
}
}
@@ -78,17 +80,101 @@ public class P2PCache implements IGridCache
}
public void updateFreq(PartP2PTunnel t, long NewFreq)
@Override
public void removeNode( IGridNode node, IGridHost machine )
{
if ( this.outputs.containsValue( t ) )
if( machine instanceof PartP2PTunnel )
{
if( machine instanceof PartP2PTunnelME )
{
if( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) )
return;
}
PartP2PTunnel t = (PartP2PTunnel) machine;
// AELog.info( "rmv-" + (t.output ? "output: " : "input: ") + t.freq
// );
if( t.output )
this.outputs.remove( t.freq, t );
else
this.inputs.remove( t.freq );
this.updateTunnel( t.freq, !t.output, false );
}
}
@Override
public void addNode( IGridNode node, IGridHost machine )
{
if( machine instanceof PartP2PTunnel )
{
if( machine instanceof PartP2PTunnelME )
{
if( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) )
return;
}
PartP2PTunnel t = (PartP2PTunnel) machine;
// AELog.info( "add-" + (t.output ? "output: " : "input: ") + t.freq
// );
if( t.output )
this.outputs.put( t.freq, t );
else
this.inputs.put( t.freq, t );
this.updateTunnel( t.freq, !t.output, false );
}
}
@Override
public void onSplit( IGridStorage storageB )
{
}
@Override
public void onJoin( IGridStorage storageB )
{
}
@Override
public void populateGridStorage( IGridStorage storage )
{
}
private void updateTunnel( long freq, boolean updateOutputs, boolean configChange )
{
for( PartP2PTunnel p : this.outputs.get( freq ) )
{
if( configChange )
p.onTunnelConfigChange();
p.onTunnelNetworkChange();
}
PartP2PTunnel in = this.inputs.get( freq );
if( in != null )
{
if( configChange )
in.onTunnelConfigChange();
in.onTunnelNetworkChange();
}
}
public void updateFreq( PartP2PTunnel t, long NewFreq )
{
if( this.outputs.containsValue( t ) )
this.outputs.remove( t.freq, t );
if ( this.inputs.containsValue( t ) )
if( this.inputs.containsValue( t ) )
this.inputs.remove( t.freq );
t.freq = NewFreq;
if ( t.output )
if( t.output )
this.outputs.put( t.freq, t );
else
this.inputs.put( t.freq, t );
@@ -99,106 +185,21 @@ public class P2PCache implements IGridCache
this.updateTunnel( t.freq, !t.output, true );
}
@Override
public void addNode(IGridNode node, IGridHost machine)
{
if ( machine instanceof PartP2PTunnel )
{
if ( machine instanceof PartP2PTunnelME )
{
if ( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) )
return;
}
PartP2PTunnel t = (PartP2PTunnel) machine;
// AELog.info( "add-" + (t.output ? "output: " : "input: ") + t.freq
// );
if ( t.output )
this.outputs.put( t.freq, t );
else
this.inputs.put( t.freq, t );
this.updateTunnel( t.freq, !t.output, false );
}
}
@Override
public void removeNode(IGridNode node, IGridHost machine)
{
if ( machine instanceof PartP2PTunnel )
{
if ( machine instanceof PartP2PTunnelME )
{
if ( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) )
return;
}
PartP2PTunnel t = (PartP2PTunnel) machine;
// AELog.info( "rmv-" + (t.output ? "output: " : "input: ") + t.freq
// );
if ( t.output )
this.outputs.remove( t.freq, t );
else
this.inputs.remove( t.freq );
this.updateTunnel( t.freq, !t.output, false );
}
}
private void updateTunnel(long freq, boolean updateOutputs, boolean configChange)
{
for (PartP2PTunnel p : this.outputs.get( freq ))
{
if ( configChange )
p.onTunnelConfigChange();
p.onTunnelNetworkChange();
}
PartP2PTunnel in = this.inputs.get( freq );
if ( in != null )
{
if ( configChange )
in.onTunnelConfigChange();
in.onTunnelNetworkChange();
}
}
public TunnelCollection<PartP2PTunnel> getOutputs(long freq, Class<? extends PartP2PTunnel> c)
public TunnelCollection<PartP2PTunnel> getOutputs( long freq, Class<? extends PartP2PTunnel> c )
{
PartP2PTunnel in = this.inputs.get( freq );
if ( in == null )
if( in == null )
return this.NullColl;
TunnelCollection<PartP2PTunnel> out = this.inputs.get( freq ).getCollection( this.outputs.get( freq ), c );
if ( out == null )
if( out == null )
return this.NullColl;
return out;
}
public PartP2PTunnel getInput(long freq)
public PartP2PTunnel getInput( long freq )
{
return this.inputs.get( freq );
}
@Override
public void onSplit(IGridStorage storageB)
{
}
@Override
public void onJoin(IGridStorage storageB)
{
}
@Override
public void populateGridStorage(IGridStorage storage)
{
}
}
+177 -183
View File
@@ -18,6 +18,7 @@
package appeng.me.cache;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
@@ -55,34 +56,28 @@ import appeng.me.pathfinding.PathSegment;
import appeng.tile.networking.TileController;
import appeng.util.Platform;
public class PathGridCache implements IPathingGrid
{
boolean recalculateControllerNextTick = true;
boolean updateNetwork = true;
boolean booting = false;
final LinkedList<PathSegment> active = new LinkedList<PathSegment>();
ControllerState controllerState = ControllerState.NO_CONTROLLER;
int instance = Integer.MIN_VALUE;
int ticksUntilReady = 20;
public int channelsInUse = 0;
int lastChannels = 0;
final Set<TileController> controllers = new HashSet<TileController>();
final Set<IGridNode> requireChannels = new HashSet<IGridNode>();
final Set<IGridNode> blockDense = new HashSet<IGridNode>();
final IGrid myGrid;
private HashSet<IPathItem> semiOpen = new HashSet<IPathItem>();
public int channelsInUse = 0;
public int channelsByBlocks = 0;
public double channelPowerUsage = 0.0;
boolean recalculateControllerNextTick = true;
boolean updateNetwork = true;
boolean booting = false;
ControllerState controllerState = ControllerState.NO_CONTROLLER;
int instance = Integer.MIN_VALUE;
int ticksUntilReady = 20;
int lastChannels = 0;
private HashSet<IPathItem> semiOpen = new HashSet<IPathItem>();
public PathGridCache(IGrid g)
public PathGridCache( IGrid g )
{
this.myGrid = g;
}
@@ -90,14 +85,14 @@ public class PathGridCache implements IPathingGrid
@Override
public void onUpdateTick()
{
if ( this.recalculateControllerNextTick )
if( this.recalculateControllerNextTick )
{
this.recalcController();
}
if ( this.updateNetwork )
if( this.updateNetwork )
{
if ( !this.booting )
if( !this.booting )
this.myGrid.postEvent( new MENetworkBootingStatusChange() );
this.booting = true;
@@ -105,7 +100,7 @@ public class PathGridCache implements IPathingGrid
this.instance++;
this.channelsInUse = 0;
if ( !AEConfig.instance.isFeatureEnabled( AEFeature.Channels ) )
if( !AEConfig.instance.isFeatureEnabled( AEFeature.Channels ) )
{
int used = this.calculateRequiredChannels();
@@ -116,11 +111,11 @@ public class PathGridCache implements IPathingGrid
this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( used ) );
}
else if ( this.controllerState == ControllerState.NO_CONTROLLER )
else if( this.controllerState == ControllerState.NO_CONTROLLER )
{
int requiredChannels = this.calculateRequiredChannels();
int used = requiredChannels;
if ( requiredChannels > 8 )
if( requiredChannels > 8 )
used = 0;
int nodes = this.myGrid.getNodes().size();
@@ -132,7 +127,7 @@ public class PathGridCache implements IPathingGrid
this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( used ) );
}
else if ( this.controllerState == ControllerState.CONTROLLER_CONFLICT )
else if( this.controllerState == ControllerState.CONTROLLER_CONFLICT )
{
this.ticksUntilReady = 20;
this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 ) );
@@ -146,13 +141,13 @@ public class PathGridCache implements IPathingGrid
// myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 )
// );
for (IGridNode node : this.myGrid.getMachines( TileController.class ))
for( IGridNode node : this.myGrid.getMachines( TileController.class ) )
{
closedList.add( (IPathItem) node );
for (IGridConnection gcc : node.getConnections())
for( IGridConnection gcc : node.getConnections() )
{
GridConnection gc = (GridConnection) gcc;
if ( !(gc.getOtherSide( node ).getMachine() instanceof TileController) )
if( !( gc.getOtherSide( node ).getMachine() instanceof TileController ) )
{
List<IPathItem> open = new LinkedList<IPathItem>();
closedList.add( gc );
@@ -165,13 +160,13 @@ public class PathGridCache implements IPathingGrid
}
}
if ( !this.active.isEmpty() || this.ticksUntilReady > 0 )
if( !this.active.isEmpty() || this.ticksUntilReady > 0 )
{
Iterator<PathSegment> i = this.active.iterator();
while (i.hasNext())
while( i.hasNext() )
{
PathSegment pat = i.next();
if ( pat.step() )
if( pat.step() )
{
pat.isDead = true;
i.remove();
@@ -180,12 +175,12 @@ public class PathGridCache implements IPathingGrid
this.ticksUntilReady--;
if ( this.active.isEmpty() && this.ticksUntilReady <= 0 )
if( this.active.isEmpty() && this.ticksUntilReady <= 0 )
{
if ( this.controllerState == ControllerState.CONTROLLER_ONLINE )
if( this.controllerState == ControllerState.CONTROLLER_ONLINE )
{
final Iterator<TileController> controllerIterator = this.controllers.iterator();
if (controllerIterator.hasNext())
if( controllerIterator.hasNext() )
{
final TileController controller = controllerIterator.next();
controller.getGridNode( ForgeDirection.UNKNOWN ).beginVisit( new ControllerChannelUpdater() );
@@ -202,19 +197,142 @@ public class PathGridCache implements IPathingGrid
}
}
@Override
public void removeNode( IGridNode gridNode, IGridHost machine )
{
if( machine instanceof TileController )
{
this.controllers.remove( machine );
this.recalculateControllerNextTick = true;
}
EnumSet<GridFlags> flags = gridNode.getGridBlock().getFlags();
if( flags.contains( GridFlags.REQUIRE_CHANNEL ) )
this.requireChannels.remove( gridNode );
if( flags.contains( GridFlags.CANNOT_CARRY_COMPRESSED ) )
this.blockDense.remove( gridNode );
this.repath();
}
@Override
public void addNode( IGridNode gridNode, IGridHost machine )
{
if( machine instanceof TileController )
{
this.controllers.add( (TileController) machine );
this.recalculateControllerNextTick = true;
}
EnumSet<GridFlags> flags = gridNode.getGridBlock().getFlags();
if( flags.contains( GridFlags.REQUIRE_CHANNEL ) )
this.requireChannels.add( gridNode );
if( flags.contains( GridFlags.CANNOT_CARRY_COMPRESSED ) )
this.blockDense.add( gridNode );
this.repath();
}
@Override
public void onSplit( IGridStorage storageB )
{
}
@Override
public void onJoin( IGridStorage storageB )
{
}
@Override
public void populateGridStorage( IGridStorage storage )
{
}
private void recalcController()
{
this.recalculateControllerNextTick = false;
ControllerState old = this.controllerState;
if( this.controllers.isEmpty() )
{
this.controllerState = ControllerState.NO_CONTROLLER;
}
else
{
IGridNode startingNode = this.controllers.iterator().next().getGridNode( ForgeDirection.UNKNOWN );
if( startingNode == null )
{
this.controllerState = ControllerState.CONTROLLER_CONFLICT;
return;
}
DimensionalCoord dc = startingNode.getGridBlock().getLocation();
ControllerValidator cv = new ControllerValidator( dc.x, dc.y, dc.z );
startingNode.beginVisit( cv );
if( cv.isValid && cv.found == this.controllers.size() )
this.controllerState = ControllerState.CONTROLLER_ONLINE;
else
this.controllerState = ControllerState.CONTROLLER_CONFLICT;
}
if( old != this.controllerState )
{
this.myGrid.postEvent( new MENetworkControllerChange() );
}
}
private int calculateRequiredChannels()
{
int depth = 0;
this.semiOpen.clear();
for( IGridNode nodes : this.requireChannels )
{
if( !this.semiOpen.contains( nodes ) )
{
IGridBlock gb = nodes.getGridBlock();
EnumSet<GridFlags> flags = gb.getFlags();
if( flags.contains( GridFlags.COMPRESSED_CHANNEL ) && !this.blockDense.isEmpty() )
return 9;
depth++;
if( flags.contains( GridFlags.MULTIBLOCK ) )
{
IGridMultiblock gmb = (IGridMultiblock) gb;
Iterator<IGridNode> i = gmb.getMultiblockNodes();
while( i.hasNext() )
this.semiOpen.add( (IPathItem) i.next() );
}
}
}
return depth;
}
private void achievementPost()
{
if ( this.lastChannels != this.channelsInUse && AEConfig.instance.isFeatureEnabled( AEFeature.Channels ) )
if( this.lastChannels != this.channelsInUse && AEConfig.instance.isFeatureEnabled( AEFeature.Channels ) )
{
Achievements currentBracket = this.getAchievementBracket( this.channelsInUse );
Achievements lastBracket = this.getAchievementBracket( this.lastChannels );
if ( currentBracket != lastBracket && currentBracket != null )
if( currentBracket != lastBracket && currentBracket != null )
{
Set<Integer> players = new HashSet<Integer>();
for (IGridNode n : this.requireChannels)
for( IGridNode n : this.requireChannels )
players.add( n.getPlayerID() );
for (int id : players)
for( int id : players )
{
Platform.addStat( id, currentBracket.getAchievement() );
}
@@ -223,48 +341,43 @@ public class PathGridCache implements IPathingGrid
this.lastChannels = this.channelsInUse;
}
private Achievements getAchievementBracket(int ch)
private Achievements getAchievementBracket( int ch )
{
if ( ch < 8 )
if( ch < 8 )
return null;
if ( ch < 128 )
if( ch < 128 )
return Achievements.Networking1;
if ( ch < 2048 )
if( ch < 2048 )
return Achievements.Networking2;
return Achievements.Networking3;
}
private int calculateRequiredChannels()
@MENetworkEventSubscribe
void updateNodReq( MENetworkChannelChanged ev )
{
int depth = 0;
this.semiOpen.clear();
IGridNode gridNode = ev.node;
for (IGridNode nodes : this.requireChannels)
{
if ( !this.semiOpen.contains( nodes ) )
{
IGridBlock gb = nodes.getGridBlock();
EnumSet<GridFlags> flags = gb.getFlags();
if( gridNode.getGridBlock().getFlags().contains( GridFlags.REQUIRE_CHANNEL ) )
this.requireChannels.add( gridNode );
else
this.requireChannels.remove( gridNode );
if ( flags.contains( GridFlags.COMPRESSED_CHANNEL ) && !this.blockDense.isEmpty() )
return 9;
this.repath();
}
depth++;
@Override
public boolean isNetworkBooting()
{
return !this.active.isEmpty() && !this.booting;
}
if ( flags.contains( GridFlags.MULTIBLOCK ) )
{
IGridMultiblock gmb = (IGridMultiblock) gb;
Iterator<IGridNode> i = gmb.getMultiblockNodes();
while (i.hasNext())
this.semiOpen.add( (IPathItem) i.next() );
}
}
}
return depth;
@Override
public ControllerState getControllerState()
{
return this.controllerState;
}
@Override
@@ -276,123 +389,4 @@ public class PathGridCache implements IPathingGrid
this.channelsByBlocks = 0;
this.updateNetwork = true;
}
@Override
public void removeNode(IGridNode gridNode, IGridHost machine)
{
if ( machine instanceof TileController )
{
this.controllers.remove( machine );
this.recalculateControllerNextTick = true;
}
EnumSet<GridFlags> flags = gridNode.getGridBlock().getFlags();
if ( flags.contains( GridFlags.REQUIRE_CHANNEL ) )
this.requireChannels.remove( gridNode );
if ( flags.contains( GridFlags.CANNOT_CARRY_COMPRESSED ) )
this.blockDense.remove( gridNode );
this.repath();
}
@Override
public void addNode(IGridNode gridNode, IGridHost machine)
{
if ( machine instanceof TileController )
{
this.controllers.add( (TileController) machine );
this.recalculateControllerNextTick = true;
}
EnumSet<GridFlags> flags = gridNode.getGridBlock().getFlags();
if ( flags.contains( GridFlags.REQUIRE_CHANNEL ) )
this.requireChannels.add( gridNode );
if ( flags.contains( GridFlags.CANNOT_CARRY_COMPRESSED ) )
this.blockDense.add( gridNode );
this.repath();
}
@MENetworkEventSubscribe
void updateNodReq(MENetworkChannelChanged ev)
{
IGridNode gridNode = ev.node;
if ( gridNode.getGridBlock().getFlags().contains( GridFlags.REQUIRE_CHANNEL ) )
this.requireChannels.add( gridNode );
else
this.requireChannels.remove( gridNode );
this.repath();
}
private void recalcController()
{
this.recalculateControllerNextTick = false;
ControllerState old = this.controllerState;
if ( this.controllers.isEmpty() )
{
this.controllerState = ControllerState.NO_CONTROLLER;
}
else
{
IGridNode startingNode = this.controllers.iterator().next().getGridNode( ForgeDirection.UNKNOWN );
if ( startingNode == null )
{
this.controllerState = ControllerState.CONTROLLER_CONFLICT;
return;
}
DimensionalCoord dc = startingNode.getGridBlock().getLocation();
ControllerValidator cv = new ControllerValidator( dc.x, dc.y, dc.z );
startingNode.beginVisit( cv );
if ( cv.isValid && cv.found == this.controllers.size() )
this.controllerState = ControllerState.CONTROLLER_ONLINE;
else
this.controllerState = ControllerState.CONTROLLER_CONFLICT;
}
if ( old != this.controllerState )
{
this.myGrid.postEvent( new MENetworkControllerChange() );
}
}
@Override
public ControllerState getControllerState()
{
return this.controllerState;
}
@Override
public boolean isNetworkBooting()
{
return !this.active.isEmpty() && !this.booting;
}
@Override
public void onSplit(IGridStorage storageB)
{
}
@Override
public void onJoin(IGridStorage storageB)
{
}
@Override
public void populateGridStorage(IGridStorage storage)
{
}
}
+77 -76
View File
@@ -18,6 +18,7 @@
package appeng.me.cache;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
@@ -37,24 +38,25 @@ import appeng.api.networking.security.ISecurityProvider;
import appeng.core.WorldSettings;
import appeng.me.GridNode;
public class SecurityCache implements ISecurityGrid
{
public final IGrid myGrid;
final private List<ISecurityProvider> securityProvider = new ArrayList<ISecurityProvider>();
final private HashMap<Integer, EnumSet<SecurityPermissions>> playerPerms = new HashMap<Integer, EnumSet<SecurityPermissions>>();
private long securityKey = -1;
public SecurityCache(IGrid g) {
public SecurityCache( IGrid g )
{
this.myGrid = g;
}
private long securityKey = -1;
public final IGrid myGrid;
@MENetworkEventSubscribe
public void updatePermissions(MENetworkSecurityChange ev)
public void updatePermissions( MENetworkSecurityChange ev )
{
this.playerPerms.clear();
if ( this.securityProvider.isEmpty() )
if( this.securityProvider.isEmpty() )
return;
this.securityProvider.get( 0 ).readPermissions( this.playerPerms );
@@ -66,27 +68,90 @@ public class SecurityCache implements ISecurityGrid
}
@Override
public void onUpdateTick()
{
}
@Override
public void removeNode( IGridNode gridNode, IGridHost machine )
{
if( machine instanceof ISecurityProvider )
{
this.securityProvider.remove( machine );
this.updateSecurityKey();
}
}
private void updateSecurityKey()
{
long lastCode = this.securityKey;
if( this.securityProvider.size() == 1 )
this.securityKey = this.securityProvider.get( 0 ).getSecurityKey();
else
this.securityKey = -1;
if( lastCode != this.securityKey )
{
this.myGrid.postEvent( new MENetworkSecurityChange() );
for( IGridNode n : this.myGrid.getNodes() )
( (GridNode) n ).lastSecurityKey = this.securityKey;
}
}
@Override
public void addNode( IGridNode gridNode, IGridHost machine )
{
if( machine instanceof ISecurityProvider )
{
this.securityProvider.add( (ISecurityProvider) machine );
this.updateSecurityKey();
}
else
( (GridNode) gridNode ).lastSecurityKey = this.securityKey;
}
@Override
public void onSplit( IGridStorage destinationStorage )
{
}
@Override
public void onJoin( IGridStorage sourceStorage )
{
}
@Override
public void populateGridStorage( IGridStorage destinationStorage )
{
} @Override
public boolean isAvailable()
{
return this.securityProvider.size() == 1 && this.securityProvider.get( 0 ).isSecurityEnabled();
}
@Override
public boolean hasPermission(EntityPlayer player, SecurityPermissions perm)
public boolean hasPermission( EntityPlayer player, SecurityPermissions perm )
{
return this.hasPermission( player == null ? -1 : WorldSettings.getInstance().getPlayerID( player.getGameProfile() ), perm );
}
@Override
public boolean hasPermission(int playerID, SecurityPermissions perm)
public boolean hasPermission( int playerID, SecurityPermissions perm )
{
if ( this.isAvailable() )
if( this.isAvailable() )
{
EnumSet<SecurityPermissions> perms = this.playerPerms.get( playerID );
if ( perms == null )
if( perms == null )
{
if ( playerID == -1 ) // no default?
if( playerID == -1 ) // no default?
return false;
else
return this.hasPermission( -1, perm );
@@ -97,75 +162,11 @@ public class SecurityCache implements ISecurityGrid
return true;
}
private void updateSecurityKey()
{
long lastCode = this.securityKey;
if ( this.securityProvider.size() == 1 )
this.securityKey = this.securityProvider.get( 0 ).getSecurityKey();
else
this.securityKey = -1;
if ( lastCode != this.securityKey )
{
this.myGrid.postEvent( new MENetworkSecurityChange() );
for (IGridNode n : this.myGrid.getNodes())
((GridNode) n).lastSecurityKey = this.securityKey;
}
}
@Override
public void removeNode(IGridNode gridNode, IGridHost machine)
{
if ( machine instanceof ISecurityProvider )
{
this.securityProvider.remove( machine );
this.updateSecurityKey();
}
}
@Override
public void addNode(IGridNode gridNode, IGridHost machine)
{
if ( machine instanceof ISecurityProvider )
{
this.securityProvider.add( (ISecurityProvider) machine );
this.updateSecurityKey();
}
else
((GridNode) gridNode).lastSecurityKey = this.securityKey;
}
@Override
public void onUpdateTick()
{
}
@Override
public void onSplit(IGridStorage destinationStorage)
{
}
@Override
public void onJoin(IGridStorage sourceStorage)
{
}
@Override
public void populateGridStorage(IGridStorage destinationStorage)
{
}
@Override
public int getOwner()
{
if ( this.isAvailable() )
if( this.isAvailable() )
return this.securityProvider.get( 0 ).getOwner();
return -1;
}
}
+125 -130
View File
@@ -18,6 +18,7 @@
package appeng.me.cache;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
@@ -36,31 +37,138 @@ import appeng.me.cluster.implementations.SpatialPylonCluster;
import appeng.tile.spatial.TileSpatialIOPort;
import appeng.tile.spatial.TileSpatialPylon;
public class SpatialPylonCache implements ISpatialCache
{
final IGrid myGrid;
long powerRequired = 0;
double efficiency = 0.0;
DimensionalCoord captureMin;
DimensionalCoord captureMax;
boolean isValid = false;
List<TileSpatialIOPort> ioPorts = new LinkedList<TileSpatialIOPort>();
HashMap<SpatialPylonCluster, SpatialPylonCluster> clusters = new HashMap<SpatialPylonCluster, SpatialPylonCluster>();
boolean needsUpdate = false;
final IGrid myGrid;
public SpatialPylonCache(IGrid g) {
public SpatialPylonCache( IGrid g )
{
this.myGrid = g;
}
@Override
public long requiredPower()
@MENetworkEventSubscribe
public void bootingRender( MENetworkBootingStatusChange c )
{
return this.powerRequired;
this.reset( this.myGrid );
}
public void reset( IGrid grid )
{
int reqX = 0;
int reqY = 0;
int reqZ = 0;
int requirePylonBlocks = 1;
double minPower = 0;
double maxPower = 0;
this.clusters = new HashMap<SpatialPylonCluster, SpatialPylonCluster>();
this.ioPorts = new LinkedList<TileSpatialIOPort>();
for( IGridNode gm : grid.getMachines( TileSpatialIOPort.class ) )
{
this.ioPorts.add( (TileSpatialIOPort) gm.getMachine() );
}
IReadOnlyCollection<IGridNode> set = grid.getMachines( TileSpatialPylon.class );
for( IGridNode gm : set )
{
if( gm.meetsChannelRequirements() )
{
SpatialPylonCluster c = ( (TileSpatialPylon) gm.getMachine() ).getCluster();
if( c != null )
this.clusters.put( c, c );
}
}
this.captureMax = null;
this.captureMin = null;
this.isValid = true;
int pylonBlocks = 0;
for( SpatialPylonCluster cl : this.clusters.values() )
{
if( this.captureMax == null )
this.captureMax = cl.max.copy();
if( this.captureMin == null )
this.captureMin = cl.min.copy();
pylonBlocks += cl.tileCount();
this.captureMin.x = Math.min( this.captureMin.x, cl.min.x );
this.captureMin.y = Math.min( this.captureMin.y, cl.min.y );
this.captureMin.z = Math.min( this.captureMin.z, cl.min.z );
this.captureMax.x = Math.max( this.captureMax.x, cl.max.x );
this.captureMax.y = Math.max( this.captureMax.y, cl.max.y );
this.captureMax.z = Math.max( this.captureMax.z, cl.max.z );
}
if( this.hasRegion() )
{
this.isValid = this.captureMax.x - this.captureMin.x > 1 && this.captureMax.y - this.captureMin.y > 1 && this.captureMax.z - this.captureMin.z > 1;
for( SpatialPylonCluster cl : this.clusters.values() )
{
switch( cl.currentAxis )
{
case X:
this.isValid = this.isValid && ( ( this.captureMax.y == cl.min.y || this.captureMin.y == cl.max.y ) || ( this.captureMax.z == cl.min.z || this.captureMin.z == cl.max.z ) ) && ( ( this.captureMax.y == cl.max.y || this.captureMin.y == cl.min.y ) || ( this.captureMax.z == cl.max.z || this.captureMin.z == cl.min.z ) );
break;
case Y:
this.isValid = this.isValid && ( ( this.captureMax.x == cl.min.x || this.captureMin.x == cl.max.x ) || ( this.captureMax.z == cl.min.z || this.captureMin.z == cl.max.z ) ) && ( ( this.captureMax.x == cl.max.x || this.captureMin.x == cl.min.x ) || ( this.captureMax.z == cl.max.z || this.captureMin.z == cl.min.z ) );
break;
case Z:
this.isValid = this.isValid && ( ( this.captureMax.y == cl.min.y || this.captureMin.y == cl.max.y ) || ( this.captureMax.x == cl.min.x || this.captureMin.x == cl.max.x ) ) && ( ( this.captureMax.y == cl.max.y || this.captureMin.y == cl.min.y ) || ( this.captureMax.x == cl.max.x || this.captureMin.x == cl.min.x ) );
break;
case UNFORMED:
this.isValid = false;
break;
}
}
reqX = this.captureMax.x - this.captureMin.x;
reqY = this.captureMax.y - this.captureMin.y;
reqZ = this.captureMax.z - this.captureMin.z;
requirePylonBlocks = Math.max( 6, ( ( reqX * reqZ + reqX * reqY + reqY * reqZ ) * 3 ) / 8 );
this.efficiency = (double) pylonBlocks / (double) requirePylonBlocks;
if( this.efficiency > 1.0 )
this.efficiency = 1.0;
if( this.efficiency < 0.0 )
this.efficiency = 0.0;
minPower = (double) reqX * (double) reqY * reqZ * AEConfig.instance.spatialPowerMultiplier;
maxPower = Math.pow( minPower, AEConfig.instance.spatialPowerExponent );
}
double affective_efficiency = Math.pow( this.efficiency, 0.25 );
this.powerRequired = (long) ( affective_efficiency * minPower + ( 1.0 - affective_efficiency ) * maxPower );
for( SpatialPylonCluster cl : this.clusters.values() )
{
boolean myWasValid = cl.isValid;
cl.isValid = this.isValid;
if( myWasValid != this.isValid )
cl.updateStatus( false );
}
}
@Override
@@ -87,116 +195,10 @@ public class SpatialPylonCache implements ISpatialCache
return this.captureMax;
}
public void reset(IGrid grid)
@Override
public long requiredPower()
{
int reqX = 0;
int reqY = 0;
int reqZ = 0;
int requirePylonBlocks = 1;
double minPower = 0;
double maxPower = 0;
this.clusters = new HashMap<SpatialPylonCluster, SpatialPylonCluster>();
this.ioPorts = new LinkedList<TileSpatialIOPort>();
for (IGridNode gm : grid.getMachines( TileSpatialIOPort.class ))
{
this.ioPorts.add( (TileSpatialIOPort) gm.getMachine() );
}
IReadOnlyCollection<IGridNode> set = grid.getMachines( TileSpatialPylon.class );
for (IGridNode gm : set)
{
if ( gm.meetsChannelRequirements() )
{
SpatialPylonCluster c = ((TileSpatialPylon) gm.getMachine()).getCluster();
if ( c != null )
this.clusters.put( c, c );
}
}
this.captureMax = null;
this.captureMin = null;
this.isValid = true;
int pylonBlocks = 0;
for (SpatialPylonCluster cl : this.clusters.values())
{
if ( this.captureMax == null )
this.captureMax = cl.max.copy();
if ( this.captureMin == null )
this.captureMin = cl.min.copy();
pylonBlocks += cl.tileCount();
this.captureMin.x = Math.min( this.captureMin.x, cl.min.x );
this.captureMin.y = Math.min( this.captureMin.y, cl.min.y );
this.captureMin.z = Math.min( this.captureMin.z, cl.min.z );
this.captureMax.x = Math.max( this.captureMax.x, cl.max.x );
this.captureMax.y = Math.max( this.captureMax.y, cl.max.y );
this.captureMax.z = Math.max( this.captureMax.z, cl.max.z );
}
if ( this.hasRegion() )
{
this.isValid = this.captureMax.x - this.captureMin.x > 1 && this.captureMax.y - this.captureMin.y > 1 && this.captureMax.z - this.captureMin.z > 1;
for (SpatialPylonCluster cl : this.clusters.values())
{
switch (cl.currentAxis)
{
case X:
this.isValid = this.isValid && ((this.captureMax.y == cl.min.y || this.captureMin.y == cl.max.y) || (this.captureMax.z == cl.min.z || this.captureMin.z == cl.max.z))
&& ((this.captureMax.y == cl.max.y || this.captureMin.y == cl.min.y) || (this.captureMax.z == cl.max.z || this.captureMin.z == cl.min.z));
break;
case Y:
this.isValid = this.isValid && ((this.captureMax.x == cl.min.x || this.captureMin.x == cl.max.x) || (this.captureMax.z == cl.min.z || this.captureMin.z == cl.max.z))
&& ((this.captureMax.x == cl.max.x || this.captureMin.x == cl.min.x) || (this.captureMax.z == cl.max.z || this.captureMin.z == cl.min.z));
break;
case Z:
this.isValid = this.isValid && ((this.captureMax.y == cl.min.y || this.captureMin.y == cl.max.y) || (this.captureMax.x == cl.min.x || this.captureMin.x == cl.max.x))
&& ((this.captureMax.y == cl.max.y || this.captureMin.y == cl.min.y) || (this.captureMax.x == cl.max.x || this.captureMin.x == cl.min.x));
break;
case UNFORMED:
this.isValid = false;
break;
}
}
reqX = this.captureMax.x - this.captureMin.x;
reqY = this.captureMax.y - this.captureMin.y;
reqZ = this.captureMax.z - this.captureMin.z;
requirePylonBlocks = Math.max( 6, ((reqX * reqZ + reqX * reqY + reqY * reqZ) * 3) / 8 );
this.efficiency = (double) pylonBlocks / (double) requirePylonBlocks;
if ( this.efficiency > 1.0 )
this.efficiency = 1.0;
if ( this.efficiency < 0.0 )
this.efficiency = 0.0;
minPower = (double) reqX * (double) reqY * reqZ * AEConfig.instance.spatialPowerMultiplier;
maxPower = Math.pow( minPower, AEConfig.instance.spatialPowerExponent );
}
double affective_efficiency = Math.pow( this.efficiency, 0.25 );
this.powerRequired = (long) (affective_efficiency * minPower + (1.0 - affective_efficiency) * maxPower);
for (SpatialPylonCluster cl : this.clusters.values())
{
boolean myWasValid = cl.isValid;
cl.isValid = this.isValid;
if ( myWasValid != this.isValid )
cl.updateStatus( false );
}
return this.powerRequired;
}
@Override
@@ -205,45 +207,38 @@ public class SpatialPylonCache implements ISpatialCache
return (float) this.efficiency * 100;
}
@MENetworkEventSubscribe
public void bootingRender(MENetworkBootingStatusChange c)
{
this.reset( this.myGrid );
}
@Override
public void onUpdateTick()
{
}
@Override
public void addNode(IGridNode node, IGridHost machine)
public void removeNode( IGridNode node, IGridHost machine )
{
}
@Override
public void removeNode(IGridNode node, IGridHost machine)
public void addNode( IGridNode node, IGridHost machine )
{
}
@Override
public void onSplit(IGridStorage storageB)
public void onSplit( IGridStorage storageB )
{
}
@Override
public void onJoin(IGridStorage storageB)
public void onJoin( IGridStorage storageB )
{
}
@Override
public void populateGridStorage(IGridStorage storage)
public void populateGridStorage( IGridStorage storage )
{
}
}
+99 -101
View File
@@ -18,6 +18,7 @@
package appeng.me.cache;
import java.util.HashMap;
import java.util.PriorityQueue;
@@ -35,37 +36,35 @@ import appeng.api.networking.ticking.TickRateModulation;
import appeng.api.networking.ticking.TickingRequest;
import appeng.me.cache.helpers.TickTracker;
public class TickManagerCache implements ITickManager
{
private long currentTick = 0;
final IGrid myGrid;
public TickManagerCache(IGrid g) {
this.myGrid = g;
}
final HashMap<IGridNode, TickTracker> alertable = new HashMap<IGridNode, TickTracker>();
final HashMap<IGridNode, TickTracker> sleeping = new HashMap<IGridNode, TickTracker>();
final HashMap<IGridNode, TickTracker> awake = new HashMap<IGridNode, TickTracker>();
final PriorityQueue<TickTracker> upcomingTicks = new PriorityQueue<TickTracker>();
private long currentTick = 0;
public TickManagerCache( IGrid g )
{
this.myGrid = g;
}
public long getCurrentTick()
{
return this.currentTick;
}
public long getAvgNanoTime(IGridNode node)
public long getAvgNanoTime( IGridNode node )
{
TickTracker tt = this.awake.get( node );
if ( tt == null )
if( tt == null )
tt = this.sleeping.get( node );
if ( tt == null )
if( tt == null )
return -1;
return tt.getAvgNanos();
@@ -78,40 +77,40 @@ public class TickManagerCache implements ITickManager
try
{
this.currentTick++;
while (!this.upcomingTicks.isEmpty())
while( !this.upcomingTicks.isEmpty() )
{
tt = this.upcomingTicks.peek();
int diff = (int) (this.currentTick - tt.lastTick);
if ( diff >= tt.current_rate )
int diff = (int) ( this.currentTick - tt.lastTick );
if( diff >= tt.current_rate )
{
// remove tt..
this.upcomingTicks.poll();
TickRateModulation mod = tt.gt.tickingRequest( tt.node, diff );
switch (mod)
switch( mod )
{
case FASTER:
tt.setRate( tt.current_rate - 2 );
break;
case IDLE:
tt.setRate( tt.request.maxTickRate );
break;
case SAME:
break;
case SLEEP:
this.sleepDevice( tt.node );
break;
case SLOWER:
tt.setRate( tt.current_rate + 1 );
break;
case URGENT:
tt.setRate( 0 );
break;
default:
break;
case FASTER:
tt.setRate( tt.current_rate - 2 );
break;
case IDLE:
tt.setRate( tt.request.maxTickRate );
break;
case SAME:
break;
case SLEEP:
this.sleepDevice( tt.node );
break;
case SLOWER:
tt.setRate( tt.current_rate + 1 );
break;
case URGENT:
tt.setRate( 0 );
break;
default:
break;
}
if ( this.awake.containsKey( tt.node ) )
if( this.awake.containsKey( tt.node ) )
this.addToQueue( tt );
}
else
@@ -120,24 +119,77 @@ public class TickManagerCache implements ITickManager
}
catch( Throwable t )
{
CrashReport crashreport = CrashReport.makeCrashReport(t, "Ticking GridNode");
CrashReportCategory crashreportcategory = crashreport.makeCategory( tt.gt.getClass().getSimpleName() + " being ticked." );
tt.addEntityCrashInfo(crashreportcategory);
throw new ReportedException(crashreport);
CrashReport crashreport = CrashReport.makeCrashReport( t, "Ticking GridNode" );
CrashReportCategory crashreportcategory = crashreport.makeCategory( tt.gt.getClass().getSimpleName() + " being ticked." );
tt.addEntityCrashInfo( crashreportcategory );
throw new ReportedException( crashreport );
}
}
private void addToQueue(TickTracker tt)
private void addToQueue( TickTracker tt )
{
tt.lastTick = this.currentTick;
this.upcomingTicks.add( tt );
}
@Override
public boolean alertDevice(IGridNode node)
public void removeNode( IGridNode gridNode, IGridHost machine )
{
if( machine instanceof IGridTickable )
{
this.alertable.remove( gridNode );
this.sleeping.remove( gridNode );
this.awake.remove( gridNode );
}
}
@Override
public void addNode( IGridNode gridNode, IGridHost machine )
{
if( machine instanceof IGridTickable )
{
TickingRequest tr = ( (IGridTickable) machine ).getTickingRequest( gridNode );
if( tr != null )
{
TickTracker tt = new TickTracker( tr, gridNode, (IGridTickable) machine, this.currentTick, this );
if( tr.canBeAlerted )
this.alertable.put( gridNode, tt );
if( tr.isSleeping )
this.sleeping.put( gridNode, tt );
else
{
this.awake.put( gridNode, tt );
this.addToQueue( tt );
}
}
}
}
@Override
public void onSplit( IGridStorage storageB )
{
}
@Override
public void onJoin( IGridStorage storageB )
{
}
@Override
public void populateGridStorage( IGridStorage storage )
{
}
@Override
public boolean alertDevice( IGridNode node )
{
TickTracker tt = this.alertable.get( node );
if ( tt == null )
if( tt == null )
return false;
// throw new RuntimeException(
// "Invalid alerted device, this node is not marked as alertable, or part of this grid." );
@@ -158,9 +210,9 @@ public class TickManagerCache implements ITickManager
}
@Override
public boolean sleepDevice(IGridNode node)
public boolean sleepDevice( IGridNode node )
{
if ( this.awake.containsKey( node ) )
if( this.awake.containsKey( node ) )
{
TickTracker gt = this.awake.get( node );
this.awake.remove( node );
@@ -173,9 +225,9 @@ public class TickManagerCache implements ITickManager
}
@Override
public boolean wakeDevice(IGridNode node)
public boolean wakeDevice( IGridNode node )
{
if ( this.sleeping.containsKey( node ) )
if( this.sleeping.containsKey( node ) )
{
TickTracker gt = this.sleeping.get( node );
this.sleeping.remove( node );
@@ -187,58 +239,4 @@ public class TickManagerCache implements ITickManager
return false;
}
@Override
public void removeNode(IGridNode gridNode, IGridHost machine)
{
if ( machine instanceof IGridTickable )
{
this.alertable.remove( gridNode );
this.sleeping.remove( gridNode );
this.awake.remove( gridNode );
}
}
@Override
public void addNode(IGridNode gridNode, IGridHost machine)
{
if ( machine instanceof IGridTickable )
{
TickingRequest tr = ((IGridTickable) machine).getTickingRequest( gridNode );
if ( tr != null )
{
TickTracker tt = new TickTracker( tr, gridNode, (IGridTickable) machine, this.currentTick, this );
if ( tr.canBeAlerted )
this.alertable.put( gridNode, tt );
if ( tr.isSleeping )
this.sleeping.put( gridNode, tt );
else
{
this.awake.put( gridNode, tt );
this.addToQueue( tt );
}
}
}
}
@Override
public void onSplit(IGridStorage storageB)
{
}
@Override
public void onJoin(IGridStorage storageB)
{
}
@Override
public void populateGridStorage(IGridStorage storage)
{
}
}
@@ -18,15 +18,17 @@
package appeng.me.cache.helpers;
import appeng.api.networking.IGridConnection;
public class ConnectionWrapper
{
public IGridConnection connection;
public ConnectionWrapper(IGridConnection gc) {
public ConnectionWrapper( IGridConnection gc )
{
this.connection = gc;
}
}
+5 -4
View File
@@ -18,22 +18,24 @@
package appeng.me.cache.helpers;
import java.util.HashMap;
import java.util.concurrent.Callable;
import appeng.api.networking.IGridNode;
import appeng.parts.p2p.PartP2PTunnelME;
public class Connections implements Callable
{
final private PartP2PTunnelME me;
final public HashMap<IGridNode, TunnelConnection> connections = new HashMap<IGridNode, TunnelConnection>();
final private PartP2PTunnelME me;
public boolean create = false;
public boolean destroy = false;
public Connections(PartP2PTunnelME o) {
public Connections( PartP2PTunnelME o )
{
this.me = o;
}
@@ -56,5 +58,4 @@ public class Connections implements Callable
this.create = true;
this.destroy = false;
}
}
+16 -13
View File
@@ -18,6 +18,7 @@
package appeng.me.cache.helpers;
import net.minecraft.crash.CrashReportCategory;
import appeng.api.networking.IGridNode;
@@ -27,6 +28,7 @@ import appeng.api.util.DimensionalCoord;
import appeng.me.cache.TickManagerCache;
import appeng.parts.AEBasePart;
public class TickTracker implements Comparable<TickTracker>
{
@@ -40,44 +42,45 @@ public class TickTracker implements Comparable<TickTracker>
public long lastTick;
public int current_rate;
public TickTracker(TickingRequest req, IGridNode node, IGridTickable gt, long currentTick, TickManagerCache tickManagerCache) {
public TickTracker( TickingRequest req, IGridNode node, IGridTickable gt, long currentTick, TickManagerCache tickManagerCache )
{
this.request = req;
this.gt = gt;
this.node = node;
this.current_rate = (req.minTickRate + req.maxTickRate) / 2;
this.current_rate = ( req.minTickRate + req.maxTickRate ) / 2;
this.lastTick = currentTick;
this.host = tickManagerCache;
}
public long getAvgNanos()
{
return (this.LastFiveTicksTime / 5);
return ( this.LastFiveTicksTime / 5 );
}
public void setRate(int rate)
public void setRate( int rate )
{
this.current_rate = rate;
if ( this.current_rate < this.request.minTickRate )
if( this.current_rate < this.request.minTickRate )
this.current_rate = this.request.minTickRate;
if ( this.current_rate > this.request.maxTickRate )
if( this.current_rate > this.request.maxTickRate )
this.current_rate = this.request.maxTickRate;
}
@Override
public int compareTo(TickTracker t)
public int compareTo( TickTracker t )
{
int nextTick = (int) ((this.lastTick - this.host.getCurrentTick()) + this.current_rate);
int ts_nextTick = (int) ((t.lastTick - this.host.getCurrentTick()) + t.current_rate);
int nextTick = (int) ( ( this.lastTick - this.host.getCurrentTick() ) + this.current_rate );
int ts_nextTick = (int) ( ( t.lastTick - this.host.getCurrentTick() ) + t.current_rate );
return nextTick - ts_nextTick;
}
public void addEntityCrashInfo(CrashReportCategory crashreportcategory)
public void addEntityCrashInfo( CrashReportCategory crashreportcategory )
{
if ( this.gt instanceof AEBasePart )
if( this.gt instanceof AEBasePart )
{
AEBasePart part = (AEBasePart)this.gt;
AEBasePart part = (AEBasePart) this.gt;
part.addEntityCrashInfo( crashreportcategory );
}
@@ -89,7 +92,7 @@ public class TickTracker implements Comparable<TickTracker>
crashreportcategory.addCrashSection( "ConnectedSides", this.node.getConnectedSides() );
DimensionalCoord dc = this.node.getGridBlock().getLocation();
if ( dc != null )
if( dc != null )
crashreportcategory.addCrashSection( "Location", dc );
}
}
+14 -11
View File
@@ -18,32 +18,27 @@
package appeng.me.cache.helpers;
import java.util.Collection;
import java.util.Iterator;
import appeng.parts.p2p.PartP2PTunnel;
import appeng.util.iterators.NullIterator;
public class TunnelCollection<T extends PartP2PTunnel> implements Iterable<T>
{
final Class clz;
Collection<T> tunnelSources;
public TunnelCollection(Collection<T> src, Class c) {
public TunnelCollection( Collection<T> src, Class c )
{
this.tunnelSources = src;
this.clz = c;
}
@Override
public Iterator<T> iterator()
{
if ( this.tunnelSources == null )
return new NullIterator<T>();
return new TunnelIterator<T>( this.tunnelSources, this.clz );
}
public void setSource(Collection<T> c)
public void setSource( Collection<T> c )
{
this.tunnelSources = c;
}
@@ -53,7 +48,15 @@ public class TunnelCollection<T extends PartP2PTunnel> implements Iterable<T>
return !this.iterator().hasNext();
}
public boolean matches(Class<? extends PartP2PTunnel> c)
@Override
public Iterator<T> iterator()
{
if( this.tunnelSources == null )
return new NullIterator<T>();
return new TunnelIterator<T>( this.tunnelSources, this.clz );
}
public boolean matches( Class<? extends PartP2PTunnel> c )
{
return this.clz == c;
}
@@ -18,16 +18,19 @@
package appeng.me.cache.helpers;
import appeng.api.networking.IGridConnection;
import appeng.parts.p2p.PartP2PTunnelME;
public class TunnelConnection
{
final public PartP2PTunnelME tunnel;
final public IGridConnection c;
public TunnelConnection(PartP2PTunnelME t, IGridConnection con) {
public TunnelConnection( PartP2PTunnelME t, IGridConnection con )
{
this.tunnel = t;
this.c = con;
}
+13 -11
View File
@@ -18,11 +18,13 @@
package appeng.me.cache.helpers;
import java.util.Collection;
import java.util.Iterator;
import appeng.parts.p2p.PartP2PTunnel;
public class TunnelIterator<T extends PartP2PTunnel> implements Iterator<T>
{
@@ -30,22 +32,23 @@ public class TunnelIterator<T extends PartP2PTunnel> implements Iterator<T>
final Class targetType;
T Next;
private void findNext()
public TunnelIterator( Collection<T> tunnelSources, Class clz )
{
while (this.Next == null && this.wrapped.hasNext())
{
this.Next = this.wrapped.next();
if ( !this.targetType.isInstance( this.Next ) )
this.Next = null;
}
}
public TunnelIterator(Collection<T> tunnelSources, Class clz) {
this.wrapped = tunnelSources.iterator();
this.targetType = clz;
this.findNext();
}
private void findNext()
{
while( this.Next == null && this.wrapped.hasNext() )
{
this.Next = this.wrapped.next();
if( !this.targetType.isInstance( this.Next ) )
this.Next = null;
}
}
@Override
public boolean hasNext()
{
@@ -66,5 +69,4 @@ public class TunnelIterator<T extends PartP2PTunnel> implements Iterator<T>
{
// no.
}
}